Source for file strings.php

Documentation is available at strings.php

  1. <?php
  2. /**
  3. * strings.php
  4. *
  5. * This code provides various string manipulation functions that are
  6. * used by the rest of the SquirrelMail code.
  7. *
  8. * @copyright 1999-2020 The SquirrelMail Project Team
  9. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  10. * @version $Id: strings.php 14840 2020年01月07日 07:42:38Z pdontthink $
  11. * @package squirrelmail
  12. */
  13. /**
  14. * SquirrelMail version number -- DO NOT CHANGE
  15. */
  16. global $version;
  17. $version = '1.4.23 [SVN]';
  18. /**
  19. * SquirrelMail internal version number -- DO NOT CHANGE
  20. * $sm_internal_version = array (release, major, minor)
  21. */
  22. global $SQM_INTERNAL_VERSION;
  23. $SQM_INTERNAL_VERSION = array(1, 4, 23);
  24. /**
  25. * There can be a circular issue with includes, where the $version string is
  26. * referenced by the include of global.php, etc. before it's defined.
  27. * For that reason, bring in global.php AFTER we define the version strings.
  28. */
  29. require_once(SM_PATH . 'functions/global.php');
  30. if (file_exists (SM_PATH . 'plugins/compatibility/functions.php')) {
  31. include_once(SM_PATH . 'plugins/compatibility/functions.php');
  32. }
  33. /**
  34. * Wraps text at $wrap characters
  35. *
  36. * Has a problem with special HTML characters, so call this before
  37. * you do character translation.
  38. *
  39. * Specifically, &#039 comes up as 5 characters instead of 1.
  40. * This should not add newlines to the end of lines.
  41. */
  42. function sqWordWrap (&$line, $wrap, $charset=null) {
  43. global $languages , $squirrelmail_language;
  44. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  45. function_exists ($languages[$squirrelmail_language]['XTRA_CODE'])) {
  46. if (mb_detect_encoding ($line) != 'ASCII') {
  47. $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
  48. return;
  49. }
  50. }
  51. preg_match ('/^([\t >]*)([^\t >].*)?$/', $line, $regs);
  52. $beginning_spaces = $regs[1];
  53. if (isset($regs[2])) {
  54. $words = explode (' ', $regs[2]);
  55. } else {
  56. $words = array();
  57. }
  58. $i = 0;
  59. $line = $beginning_spaces;
  60. while ($i < count ($words)) {
  61. /* Force one word to be on a line (minimum) */
  62. $line .= $words[$i];
  63. $line_len = strlen ($beginning_spaces) + sq_strlen ($words[$i],$charset) + 2;
  64. if (isset($words[$i + 1]))
  65. $line_len += sq_strlen ($words[$i + 1],$charset);
  66. $i ++;
  67. /* Add more words (as long as they fit) */
  68. while ($line_len < $wrap && $i < count ($words)) {
  69. $line .= ' ' . $words[$i];
  70. $i++;
  71. if (isset($words[$i]))
  72. $line_len += sq_strlen ($words[$i],$charset) + 1;
  73. else
  74. $line_len += 1;
  75. }
  76. /* Skip spaces if they are the first thing on a continued line */
  77. while (!isset($words[$i]) && $i < count ($words)) {
  78. $i ++;
  79. }
  80. /* Go to the next line if we have more to process */
  81. if ($i < count ($words)) {
  82. $line .= "\n";
  83. }
  84. }
  85. }
  86. /**
  87. * Does the opposite of sqWordWrap()
  88. * @param string body the text to un-wordwrap
  89. * @return void
  90. */
  91. function sqUnWordWrap (&$body) {
  92. global $squirrelmail_language;
  93. if ($squirrelmail_language == 'ja_JP') {
  94. return;
  95. }
  96. $lines = explode ("\n", $body);
  97. $body = '';
  98. $PreviousSpaces = '';
  99. $cnt = count ($lines);
  100. for ($i = 0; $i < $cnt; $i ++) {
  101. preg_match ("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
  102. $CurrentSpaces = $regs[1];
  103. if (isset($regs[2])) {
  104. $CurrentRest = $regs[2];
  105. } else {
  106. $CurrentRest = '';
  107. }
  108. if ($i == 0) {
  109. $PreviousSpaces = $CurrentSpaces;
  110. $body = $lines[$i];
  111. } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
  112. && (strlen ($lines[$i - 1]) > 65) /* Over 65 characters long */
  113. && strlen ($CurrentRest)) { /* and there's a line to continue with */
  114. $body .= ' ' . $CurrentRest;
  115. } else {
  116. $body .= "\n" . $lines[$i];
  117. $PreviousSpaces = $CurrentSpaces;
  118. }
  119. }
  120. $body .= "\n";
  121. }
  122. /**
  123. * Truncates the given string so that it has at
  124. * most $max_chars characters. NOTE that a "character"
  125. * may be a multibyte character, or (optionally), an
  126. * HTML entity, so this function is different than
  127. * using substr() or mb_substr().
  128. *
  129. * NOTE that if $elipses is given and used, the returned
  130. * number of characters will be $max_chars PLUS the
  131. * length of $elipses
  132. *
  133. * @param string $string The string to truncate
  134. * @param int $max_chars The maximum allowable characters
  135. * @param string $elipses A string that will be added to
  136. * the end of the truncated string
  137. * (ONLY if it is truncated) (OPTIONAL;
  138. * default not used)
  139. * @param boolean $html_entities_as_chars Whether or not to keep
  140. * HTML entities together
  141. * (OPTIONAL; default ignore
  142. * HTML entities)
  143. *
  144. * @return string The truncated string
  145. *
  146. * @since 1.4.20 and 1.5.2 (replaced truncateWithEntities())
  147. *
  148. */
  149. function sm_truncate_string ($string, $max_chars, $elipses='',
  150. $html_entities_as_chars=FALSE)
  151. {
  152. // if the length of the string is less than
  153. // the allowable number of characters, just
  154. // return it as is (even if it contains any
  155. // HTML entities, that would just make the
  156. // actual length even smaller)
  157. //
  158. $actual_strlen = sq_strlen ($string, 'auto');
  159. if ($max_chars <= 0 || $actual_strlen <= $max_chars)
  160. return $string;
  161. // if needed, count the number of HTML entities in
  162. // the string up to the maximum character limit,
  163. // pushing that limit up for each entity found
  164. //
  165. $adjusted_max_chars = $max_chars;
  166. if ($html_entities_as_chars)
  167. {
  168. // $loop_count is needed to prevent an endless loop
  169. // which is caused by buggy mbstring versions that
  170. // return 0 (zero) instead of FALSE in some rare
  171. // cases. Thanks, PHP.
  172. // see: http://bugs.php.net/bug.php?id=52731
  173. // also: tracker 3053349ドル
  174. //
  175. $loop_count = 0;
  176. $entity_pos = $entity_end_pos = -1;
  177. while ($entity_end_pos + 1 < $actual_strlen
  178. && ($entity_pos = sq_strpos ($string, '&', $entity_end_pos + 1)) !== FALSE
  179. && ($entity_end_pos = sq_strpos ($string, ';', $entity_pos)) !== FALSE
  180. && $entity_pos <= $adjusted_max_chars
  181. && $loop_count++ < $max_chars)
  182. {
  183. $adjusted_max_chars += $entity_end_pos - $entity_pos;
  184. }
  185. // this isn't necessary because sq_substr() would figure this
  186. // out anyway, but we can avoid a sq_substr() call and we
  187. // know that we don't have to add an elipses (this is now
  188. // an accurate comparison, since $adjusted_max_chars, like
  189. // $actual_strlen, does not take into account HTML entities)
  190. //
  191. if ($actual_strlen <= $adjusted_max_chars)
  192. return $string;
  193. }
  194. // get the truncated string
  195. //
  196. $truncated_string = sq_substr ($string, 0, $adjusted_max_chars);
  197. // return with added elipses
  198. //
  199. return $truncated_string . $elipses;
  200. }
  201. /**
  202. * If $haystack is a full mailbox name and $needle is the mailbox
  203. * separator character, returns the last part of the mailbox name.
  204. *
  205. * @param string haystack full mailbox name to search
  206. * @param string needle the mailbox separator character
  207. * @return string the last part of the mailbox name
  208. */
  209. function readShortMailboxName ($haystack, $needle) {
  210. if ($needle == '') {
  211. $elem = $haystack;
  212. } else {
  213. $parts = explode ($needle, $haystack);
  214. $elem = array_pop ($parts);
  215. while ($elem == '' && count ($parts)) {
  216. $elem = array_pop ($parts);
  217. }
  218. }
  219. return( $elem );
  220. }
  221. /**
  222. * php_self
  223. *
  224. * Attempts to determine the path and filename and any arguments
  225. * for the currently executing script. This is usually found in
  226. * $_SERVER['REQUEST_URI'], but some environments may differ, so
  227. * this function tries to standardize this value.
  228. *
  229. * @since 1.2.3
  230. * @return string The path, filename and any arguments for the
  231. * current script
  232. */
  233. function php_self () {
  234. $request_uri = '';
  235. // first try $_SERVER['PHP_SELF'], which seems most reliable
  236. // (albeit it usually won't include the query string)
  237. //
  238. $request_uri = '';
  239. if (!sqgetGlobalVar ('PHP_SELF', $request_uri, SQ_SERVER )
  240. || empty($request_uri)) {
  241. // well, then let's try $_SERVER['REQUEST_URI']
  242. //
  243. $request_uri = '';
  244. if (!sqgetGlobalVar ('REQUEST_URI', $request_uri, SQ_SERVER )
  245. || empty($request_uri)) {
  246. // TODO: anyone have any other ideas? maybe $_SERVER['SCRIPT_NAME']???
  247. //
  248. return '';
  249. }
  250. }
  251. // we may or may not have any query arguments, depending on
  252. // which environment variable was used above, and the PHP
  253. // version, etc., so let's check for it now
  254. //
  255. $query_string = '';
  256. if (strpos ($request_uri, '?') === FALSE
  257. && sqgetGlobalVar ('QUERY_STRING', $query_string, SQ_SERVER )
  258. && !empty($query_string)) {
  259. $request_uri .= '?' . $query_string;
  260. }
  261. return $request_uri;
  262. }
  263. /**
  264. * Find out where squirrelmail lives and try to be smart about it.
  265. * The only problem would be when squirrelmail lives in directories
  266. * called "src", "functions", or "plugins", but people who do that need
  267. * to be beaten with a steel pipe anyway.
  268. *
  269. * @return string the base uri of squirrelmail installation.
  270. */
  271. function sqm_baseuri (){
  272. global $base_uri, $PHP_SELF;
  273. /**
  274. * If it is in the session, just return it.
  275. */
  276. if (sqgetGlobalVar ('base_uri',$base_uri,SQ_SESSION )){
  277. return $base_uri;
  278. }
  279. $dirs = array('|src/.*|', '|plugins/.*|', '|functions/.*|');
  280. $repl = array('', '', '');
  281. $base_uri = preg_replace ($dirs, $repl, $PHP_SELF);
  282. return $base_uri;
  283. }
  284. /**
  285. * get_location
  286. *
  287. * Determines the location to forward to, relative to your server.
  288. * This is used in HTTP Location: redirects.
  289. * If set, it uses $config_location_base as the first part of the URL,
  290. * specifically, the protocol, hostname and port parts. The path is
  291. * always autodetected.
  292. *
  293. * @return string the base url for this SquirrelMail installation
  294. */
  295. function get_location () {
  296. $is_secure_connection, $sq_ignore_http_x_forwarded_headers;
  297. /* Get the path, handle virtual directories */
  298. if(strpos (php_self (), '?')) {
  299. $path = substr (php_self (), 0, strpos (php_self (), '?'));
  300. } else {
  301. $path = php_self ();
  302. }
  303. $path = substr ($path, 0, strrpos ($path, '/'));
  304. // proto+host+port are already set in config:
  305. if ( !empty($config_location_base) ) {
  306. // register it in the session just in case some plugin depends on this
  307. sqsession_register ($config_location_base . $path, 'sq_base_url');
  308. return $config_location_base . $path ;
  309. }
  310. // we computed it before, get it from the session:
  311. if ( sqgetGlobalVar ('sq_base_url', $full_url, SQ_SESSION ) ) {
  312. return $full_url . $path;
  313. }
  314. // else: autodetect
  315. /* Check if this is a HTTPS or regular HTTP request. */
  316. $proto = 'http://';
  317. if ($is_secure_connection)
  318. $proto = 'https://';
  319. /* Get the hostname from the Host header or server config. */
  320. if ($sq_ignore_http_x_forwarded_headers
  321. || !sqgetGlobalVar ('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER )
  322. || empty($host)) {
  323. if ( !sqgetGlobalVar ('HTTP_HOST', $host, SQ_SERVER ) || empty($host) ) {
  324. if ( !sqgetGlobalVar ('SERVER_NAME', $host, SQ_SERVER ) || empty($host) ) {
  325. $host = '';
  326. }
  327. }
  328. }
  329. $port = '';
  330. if (strpos ($host, ':') === FALSE) {
  331. // Note: HTTP_X_FORWARDED_PROTO could be sent from the client and
  332. // therefore possibly spoofed/hackable - for now, the
  333. // administrator can tell SM to ignore this value by setting
  334. // $sq_ignore_http_x_forwarded_headers to boolean TRUE in
  335. // config/config_local.php, but in the future we may
  336. // want to default this to TRUE and make administrators
  337. // who use proxy systems turn it off (see 1.5.2+).
  338. global $sq_ignore_http_x_forwarded_headers;
  339. if ($sq_ignore_http_x_forwarded_headers
  340. || !sqgetGlobalVar ('HTTP_X_FORWARDED_PROTO', $forwarded_proto, SQ_SERVER ))
  341. $forwarded_proto = '';
  342. if (sqgetGlobalVar ('SERVER_PORT', $server_port, SQ_SERVER )) {
  343. if (($server_port != 80 && $proto == 'http://') ||
  344. ($server_port != 443 && $proto == 'https://' &&
  345. strcasecmp ($forwarded_proto, 'https') !== 0)) {
  346. $port = sprintf (':%d', $server_port);
  347. }
  348. }
  349. }
  350. /* this is a workaround for the weird macosx caching that
  351. causes Apache to return 16080 as the port number, which causes
  352. SM to bail */
  353. if ($imap_server_type == 'macosx' && $port == ':16080') {
  354. $port = '';
  355. }
  356. /* Fallback is to omit the server name and use a relative */
  357. /* URI, although this is not RFC 2616 compliant. */
  358. $full_url = ($host ? $proto . $host . $port : '');
  359. sqsession_register ($full_url, 'sq_base_url');
  360. return $full_url . $path;
  361. }
  362. /**
  363. * Encrypts password
  364. *
  365. * These functions are used to encrypt the password before it is
  366. * stored in a cookie. The encryption key is generated by
  367. * OneTimePadCreate();
  368. *
  369. * @param string string the (password)string to encrypt
  370. * @param string epad the encryption key
  371. * @return string the base64-encoded encrypted password
  372. */
  373. function OneTimePadEncrypt ($string, $epad) {
  374. $pad = base64_decode ($epad);
  375. if (strlen ($pad)>0) {
  376. // make sure that pad is longer than string
  377. while (strlen ($string)>strlen ($pad)) {
  378. $pad.=$pad;
  379. }
  380. } else {
  381. // FIXME: what should we do when $epad is not base64 encoded or empty.
  382. }
  383. $encrypted = '';
  384. for ($i = 0; $i < strlen ($string); $i++) {
  385. $encrypted .= chr (ord ($string[$i]) ^ ord ($pad[$i]));
  386. }
  387. return base64_encode ($encrypted);
  388. }
  389. /**
  390. * Decrypts a password from the cookie
  391. *
  392. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  393. * This uses the encryption key that is stored in the session.
  394. *
  395. * @param string string the string to decrypt
  396. * @param string epad the encryption key from the session
  397. * @return string the decrypted password
  398. */
  399. function OneTimePadDecrypt ($string, $epad) {
  400. $pad = base64_decode ($epad);
  401. if (strlen ($pad)>0) {
  402. // make sure that pad is longer than string
  403. while (strlen ($string)>strlen ($pad)) {
  404. $pad.=$pad;
  405. }
  406. } else {
  407. // FIXME: what should we do when $epad is not base64 encoded or empty.
  408. }
  409. $encrypted = base64_decode ($string);
  410. $decrypted = '';
  411. for ($i = 0; $i < strlen ($encrypted); $i++) {
  412. $decrypted .= chr (ord ($encrypted[$i]) ^ ord ($pad[$i]));
  413. }
  414. return $decrypted;
  415. }
  416. /**
  417. * Randomizes the mt_rand() function.
  418. *
  419. * Toss this in strings or integers and it will seed the generator
  420. * appropriately. With strings, it is better to get them long.
  421. * Use md5() to lengthen smaller strings.
  422. *
  423. * @param mixed val a value to seed the random number generator
  424. * @return void
  425. */
  426. function sq_mt_seed ($Val) {
  427. /* if mt_getrandmax() does not return a 2^n - 1 number,
  428. this might not work well. This uses $Max as a bitmask. */
  429. $Max = mt_getrandmax ();
  430. if (! is_int ($Val)) {
  431. $Val = crc32 ($Val);
  432. }
  433. if ($Val < 0) {
  434. $Val *= -1;
  435. }
  436. if ($Val == 0) {
  437. return;
  438. }
  439. mt_srand (($Val ^ mt_rand (0, $Max)) & $Max);
  440. }
  441. /**
  442. * Init random number generator
  443. *
  444. * This function initializes the random number generator fairly well.
  445. * It also only initializes it once, so you don't accidentally get
  446. * the same 'random' numbers twice in one session.
  447. *
  448. * @return void
  449. */
  450. function sq_mt_randomize () {
  451. static $randomized;
  452. if ($randomized) {
  453. return;
  454. }
  455. /* Global. */
  456. sqgetGlobalVar ('REMOTE_PORT', $remote_port, SQ_SERVER );
  457. sqgetGlobalVar ('REMOTE_ADDR', $remote_addr, SQ_SERVER );
  458. sq_mt_seed ((int)((double) microtime () * 1000000));
  459. sq_mt_seed (md5 ($remote_port . $remote_addr . getmypid ()));
  460. /* getrusage */
  461. if (function_exists ('getrusage')) {
  462. /* Avoid warnings with Win32 */
  463. $dat = @getrusage ();
  464. if (isset($dat) && is_array ($dat)) {
  465. $Str = '';
  466. foreach ($dat as $k => $v)
  467. {
  468. $Str .= $k . $v;
  469. }
  470. sq_mt_seed (md5 ($Str));
  471. }
  472. }
  473. if(sqgetGlobalVar ('UNIQUE_ID', $unique_id, SQ_SERVER )) {
  474. sq_mt_seed (md5 ($unique_id));
  475. }
  476. $randomized = 1;
  477. }
  478. /**
  479. * Creates encryption key
  480. *
  481. * Creates an encryption key for encrypting the password stored in the cookie.
  482. * The encryption key itself is stored in the session.
  483. *
  484. * @param int length optional, length of the string to generate
  485. * @return string the encryption key
  486. */
  487. function OneTimePadCreate ($length=100) {
  488. $pad = '';
  489. for ($i = 0; $i < $length; $i++) {
  490. $pad .= chr (mt_rand (0,255));
  491. }
  492. return base64_encode ($pad);
  493. }
  494. /**
  495. * Returns a string showing the size of the message/attachment.
  496. *
  497. * @param int bytes the filesize in bytes
  498. * @return string the filesize in human readable format
  499. */
  500. function show_readable_size ($bytes) {
  501. $bytes /= 1024;
  502. $type = 'k';
  503. if ($bytes / 1024 > 1) {
  504. $bytes /= 1024;
  505. $type = 'M';
  506. }
  507. if ($bytes < 10) {
  508. $bytes *= 10;
  509. settype ($bytes, 'integer');
  510. $bytes /= 10;
  511. } else {
  512. settype ($bytes, 'integer');
  513. }
  514. return $bytes . '<small>&nbsp;' . $type . '</small>';
  515. }
  516. /**
  517. * Generates a random string from the caracter set you pass in
  518. *
  519. * @param int size the size of the string to generate
  520. * @param string chars a string containing the characters to use
  521. * @param int flags a flag to add a specific set to the characters to use:
  522. * Flags:
  523. * 1 = add lowercase a-z to $chars
  524. * 2 = add uppercase A-Z to $chars
  525. * 4 = add numbers 0-9 to $chars
  526. * @return string the random string
  527. */
  528. function GenerateRandomString ($size, $chars, $flags = 0) {
  529. if ($flags & 0x1) {
  530. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  531. }
  532. if ($flags & 0x2) {
  533. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  534. }
  535. if ($flags & 0x4) {
  536. $chars .= '0123456789';
  537. }
  538. if (($size < 1) || (strlen ($chars) < 1)) {
  539. return '';
  540. }
  541. sq_mt_randomize (); /* Initialize the random number generator */
  542. $String = '';
  543. $j = strlen ( $chars ) - 1;
  544. while (strlen ($String) < $size) {
  545. $String .= $chars{mt_rand (0, $j)};
  546. }
  547. return $String;
  548. }
  549. /**
  550. * Escapes special characters for use in IMAP commands.
  551. *
  552. * @param string the string to escape
  553. * @return string the escaped string
  554. */
  555. function quoteimap ($str) {
  556. // FIXME use this performance improvement (not changing because this is STABLE branch): return str_replace(array('\\', '"'), array('\\\\', '\\"'), $str);
  557. return preg_replace ("/([\"\\\\])/", "\\\\1ドル", $str);
  558. }
  559. /**
  560. * Trims array
  561. *
  562. * Trims every element in the array, ie. remove the first char of each element
  563. * Obsolete: will probably removed soon
  564. * @param array array the array to trim
  565. * @obsolete
  566. */
  567. function TrimArray (&$array) {
  568. foreach ($array as $k => $v) {
  569. global $$k;
  570. if (is_array ($$k)) {
  571. foreach ($$k as $k2 => $v2) {
  572. $$k[$k2] = substr ($v2, 1);
  573. }
  574. } else {
  575. $$k = substr ($v, 1);
  576. }
  577. /* Re-assign back to array. */
  578. $array[$k] = $$k;
  579. }
  580. }
  581. /**
  582. * Removes slashes from every element in the array
  583. */
  584. function RemoveSlashes (&$array) {
  585. foreach ($array as $k => $v) {
  586. global $$k;
  587. if (is_array ($$k)) {
  588. foreach ($$k as $k2 => $v2) {
  589. $newArray[stripslashes ($k2)] = stripslashes ($v2);
  590. }
  591. $$k = $newArray;
  592. } else {
  593. $$k = stripslashes ($v);
  594. }
  595. /* Re-assign back to the array. */
  596. $array[$k] = $$k;
  597. }
  598. }
  599. /**
  600. * Create compose link
  601. *
  602. * Returns a link to the compose-page, taking in consideration
  603. * the compose_in_new and javascript settings.
  604. * @param string url the URL to the compose page
  605. * @param string text the link text, default "Compose"
  606. * @return string a link to the compose page
  607. */
  608. function makeComposeLink ($url, $text = null, $target='')
  609. {
  610. global $compose_new_win,$javascript_on;
  611. if(!$text) {
  612. $text = _ ("Compose");
  613. }
  614. // if not using "compose in new window", make
  615. // regular link and be done with it
  616. if($compose_new_win != '1') {
  617. return makeInternalLink ($url, $text, $target);
  618. }
  619. // build the compose in new window link...
  620. // if javascript is on, use onClick event to handle it
  621. if($javascript_on) {
  622. sqgetGlobalVar ('base_uri', $base_uri, SQ_SESSION );
  623. return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
  624. }
  625. // otherwise, just open new window using regular HTML
  626. return makeInternalLink ($url, $text, '_blank');
  627. }
  628. /**
  629. * Print variable
  630. *
  631. * sm_print_r($some_variable, [$some_other_variable [, ...]]);
  632. *
  633. * Debugging function - does the same as print_r, but makes sure special
  634. * characters are converted to htmlentities first. This will allow
  635. * values like <[email protected]> to be displayed.
  636. * The output is wrapped in <<pre>> and <</pre>> tags.
  637. *
  638. * @return void
  639. */
  640. function sm_print_r () {
  641. ob_start (); // Buffer output
  642. foreach(func_get_args () as $var) {
  643. print_r ($var);
  644. echo "\n";
  645. }
  646. $buffer = ob_get_contents (); // Grab the print_r output
  647. ob_end_clean (); // Silently discard the output & stop buffering
  648. print '<pre>';
  649. print htmlentities ($buffer);
  650. print '</pre>';
  651. }
  652. /**
  653. * version of fwrite which checks for failure
  654. */
  655. function sq_fwrite ($fp, $string) {
  656. // write to file
  657. $count = @fwrite ($fp,$string);
  658. // the number of bytes written should be the length of the string
  659. if($count != strlen ($string)) {
  660. return FALSE;
  661. }
  662. return $count;
  663. }
  664. /**
  665. * Tests if string contains 8bit symbols.
  666. *
  667. * If charset is not set, function defaults to default_charset.
  668. * $default_charset global must be set correctly if $charset is
  669. * not used.
  670. * @param string $string tested string
  671. * @param string $charset charset used in a string
  672. * @return bool true if 8bit symbols are detected
  673. * @since 1.5.1 and 1.4.4
  674. */
  675. function sq_is8bit ($string,$charset='') {
  676. if ($charset=='') $charset=$default_charset;
  677. /**
  678. * Don't use 240円 in ranges. Sometimes RH 7.2 doesn't like it.
  679. * Don't use 200円-237円 for iso-8859-x charsets. This ranges
  680. * stores control symbols in those charsets.
  681. * Use preg_match instead of ereg in order to avoid problems
  682. * with mbstring overloading
  683. */
  684. if (preg_match ("/^iso-8859/i",$charset)) {
  685. $needle='/240円|[241円-377円]/';
  686. } else {
  687. $needle='/[200円-237円]|240円|[241円-377円]/';
  688. }
  689. return preg_match ("$needle",$string);
  690. }
  691. /**
  692. * Function returns number of characters in string.
  693. *
  694. * Returned number might be different from number of bytes in string,
  695. * if $charset is multibyte charset. Detection depends on mbstring
  696. * functions. If mbstring does not support tested multibyte charset,
  697. * vanilla string length function is used.
  698. * @param string $str string
  699. * @param string $charset charset
  700. * @since 1.5.1 and 1.4.6
  701. * @return integer number of characters in string
  702. */
  703. function sq_strlen ($string, $charset=NULL){
  704. // NULL charset? Just use strlen()
  705. //
  706. if (is_null ($charset))
  707. return strlen ($string);
  708. // use current character set?
  709. //
  710. if ($charset == 'auto')
  711. {
  712. //FIXME: this may or may not be better as a session value instead of a global one
  713. global $sq_string_func_auto_charset;
  714. if (!isset($sq_string_func_auto_charset))
  715. {
  716. global $default_charset , $squirrelmail_language;
  717. $sq_string_func_auto_charset = $default_charset;
  718. if ($squirrelmail_language == 'ja_JP') $sq_string_func_auto_charset = 'euc-jp';
  719. }
  720. $charset = $sq_string_func_auto_charset;
  721. }
  722. // standardize character set name
  723. //
  724. $charset = strtolower ($charset);
  725. /* ===== FIXME: this list is not used in 1.5.x, but if we need it, unless this differs between all our string function wrappers, we should store this info in the session
  726. // only use mbstring with the following character sets
  727. //
  728. $sq_strlen_mb_charsets = array(
  729. 'utf-8',
  730. 'big5',
  731. 'gb2312',
  732. 'gb18030',
  733. 'euc-jp',
  734. 'euc-cn',
  735. 'euc-tw',
  736. 'euc-kr'
  737. );
  738. // now we can use mb_strlen() if needed
  739. //
  740. if (in_array($charset, $sq_strlen_mb_charsets)
  741. && in_array($charset, sq_mb_list_encodings()))
  742. ===== */
  743. //FIXME: is there any reason why this cannot be a static global array used by all string wrapper functions?
  744. if (in_array ($charset, sq_mb_list_encodings ()))
  745. return mb_strlen ($string, $charset);
  746. // else use normal strlen()
  747. //
  748. return strlen ($string);
  749. }
  750. /**
  751. * This is a replacement for PHP's strpos() that is
  752. * multibyte-aware.
  753. *
  754. * @param string $haystack The string to search within
  755. * @param string $needle The substring to search for
  756. * @param int $offset The offset from the beginning of $haystack
  757. * from which to start searching
  758. * (OPTIONAL; default none)
  759. * @param string $charset The charset of the given string. A value of NULL
  760. * here will force the use of PHP's standard strpos().
  761. * (OPTIONAL; default is "auto", which indicates that
  762. * the user's current charset should be used).
  763. *
  764. * @return mixed The integer offset of the next $needle in $haystack,
  765. * if found, or FALSE if not found
  766. *
  767. */
  768. function sq_strpos ($haystack, $needle, $offset=0, $charset='auto')
  769. {
  770. // NULL charset? Just use strpos()
  771. //
  772. if (is_null ($charset))
  773. return strpos ($haystack, $needle, $offset);
  774. // use current character set?
  775. //
  776. if ($charset == 'auto')
  777. {
  778. //FIXME: this may or may not be better as a session value instead of a global one
  779. global $sq_string_func_auto_charset;
  780. if (!isset($sq_string_func_auto_charset))
  781. {
  782. global $default_charset , $squirrelmail_language;
  783. $sq_string_func_auto_charset = $default_charset;
  784. if ($squirrelmail_language == 'ja_JP') $sq_string_func_auto_charset = 'euc-jp';
  785. }
  786. $charset = $sq_string_func_auto_charset;
  787. }
  788. // standardize character set name
  789. //
  790. $charset = strtolower ($charset);
  791. /* ===== FIXME: this list is not used in 1.5.x, but if we need it, unless this differs between all our string function wrappers, we should store this info in the session
  792. // only use mbstring with the following character sets
  793. //
  794. $sq_strpos_mb_charsets = array(
  795. 'utf-8',
  796. 'big5',
  797. 'gb2312',
  798. 'gb18030',
  799. 'euc-jp',
  800. 'euc-cn',
  801. 'euc-tw',
  802. 'euc-kr'
  803. );
  804. // now we can use mb_strpos() if needed
  805. //
  806. if (in_array($charset, $sq_strpos_mb_charsets)
  807. && in_array($charset, sq_mb_list_encodings()))
  808. ===== */
  809. //FIXME: is there any reason why this cannot be a static global array used by all string wrapper functions?
  810. if (in_array ($charset, sq_mb_list_encodings ()))
  811. return mb_strpos ($haystack, $needle, $offset, $charset);
  812. // else use normal strpos()
  813. //
  814. return strpos ($haystack, $needle, $offset);
  815. }
  816. /**
  817. * This is a replacement for PHP's substr() that is
  818. * multibyte-aware.
  819. *
  820. * @param string $string The string to operate upon
  821. * @param int $start The offset at which to begin substring extraction
  822. * @param int $length The number of characters after $start to return
  823. * NOTE that if you need to specify a charset but
  824. * want to achieve normal substr() behavior where
  825. * $length is not specified, use NULL (OPTIONAL;
  826. * default from $start to end of string)
  827. * @param string $charset The charset of the given string. A value of NULL
  828. * here will force the use of PHP's standard substr().
  829. * (OPTIONAL; default is "auto", which indicates that
  830. * the user's current charset should be used).
  831. *
  832. * @return string The desired substring
  833. *
  834. * Of course, you can use more advanced (e.g., negative) values
  835. * for $start and $length as needed - see the PHP manual for more
  836. * information: http://www.php.net/manual/function.substr.php
  837. *
  838. */
  839. function sq_substr ($string, $start, $length=NULL, $charset='auto')
  840. {
  841. // if $length is NULL, use the full string length...
  842. // we have to do this to mimick the use of substr()
  843. // where $length is not given
  844. //
  845. if (is_null ($length))
  846. $length = sq_strlen ($length, $charset);
  847. // NULL charset? Just use substr()
  848. //
  849. if (is_null ($charset))
  850. return substr ($string, $start, $length);
  851. // use current character set?
  852. //
  853. if ($charset == 'auto')
  854. {
  855. //FIXME: this may or may not be better as a session value instead of a global one
  856. global $sq_string_func_auto_charset;
  857. if (!isset($sq_string_func_auto_charset))
  858. {
  859. global $default_charset , $squirrelmail_language;
  860. $sq_string_func_auto_charset = $default_charset;
  861. if ($squirrelmail_language == 'ja_JP') $sq_string_func_auto_charset = 'euc-jp';
  862. }
  863. $charset = $sq_string_func_auto_charset;
  864. }
  865. // standardize character set name
  866. //
  867. $charset = strtolower ($charset);
  868. /* ===== FIXME: this list is not used in 1.5.x, but if we need it, unless this differs between all our string function wrappers, we should store this info in the session
  869. // only use mbstring with the following character sets
  870. //
  871. $sq_substr_mb_charsets = array(
  872. 'utf-8',
  873. 'big5',
  874. 'gb2312',
  875. 'gb18030',
  876. 'euc-jp',
  877. 'euc-cn',
  878. 'euc-tw',
  879. 'euc-kr'
  880. );
  881. // now we can use mb_substr() if needed
  882. //
  883. if (in_array($charset, $sq_substr_mb_charsets)
  884. && in_array($charset, sq_mb_list_encodings()))
  885. ===== */
  886. //FIXME: is there any reason why this cannot be a global array used by all string wrapper functions?
  887. if (in_array ($charset, sq_mb_list_encodings ()))
  888. return mb_substr ($string, $start, $length, $charset);
  889. // else use normal substr()
  890. //
  891. return substr ($string, $start, $length);
  892. }
  893. /**
  894. * This is a replacement for PHP's substr_replace() that is
  895. * multibyte-aware.
  896. *
  897. * @param string $string The string to operate upon
  898. * @param string $replacement The string to be inserted
  899. * @param int $start The offset at which to begin substring replacement
  900. * @param int $length The number of characters after $start to remove
  901. * NOTE that if you need to specify a charset but
  902. * want to achieve normal substr_replace() behavior
  903. * where $length is not specified, use NULL (OPTIONAL;
  904. * default from $start to end of string)
  905. * @param string $charset The charset of the given string. A value of NULL
  906. * here will force the use of PHP's standard substr().
  907. * (OPTIONAL; default is "auto", which indicates that
  908. * the user's current charset should be used).
  909. *
  910. * @return string The manipulated string
  911. *
  912. * Of course, you can use more advanced (e.g., negative) values
  913. * for $start and $length as needed - see the PHP manual for more
  914. * information: http://www.php.net/manual/function.substr-replace.php
  915. *
  916. */
  917. function sq_substr_replace ($string, $replacement, $start, $length=NULL,
  918. $charset='auto')
  919. {
  920. // NULL charset? Just use substr_replace()
  921. //
  922. if (is_null ($charset))
  923. return is_null ($length) ? substr_replace ($string, $replacement, $start)
  924. : substr_replace ($string, $replacement, $start, $length);
  925. // use current character set?
  926. //
  927. if ($charset == 'auto')
  928. {
  929. //FIXME: this may or may not be better as a session value instead of a global one
  930. $charset = $auto_charset;
  931. global $sq_string_func_auto_charset;
  932. if (!isset($sq_string_func_auto_charset))
  933. {
  934. global $default_charset , $squirrelmail_language;
  935. $sq_string_func_auto_charset = $default_charset;
  936. if ($squirrelmail_language == 'ja_JP') $sq_string_func_auto_charset = 'euc-jp';
  937. }
  938. $charset = $sq_string_func_auto_charset;
  939. }
  940. // standardize character set name
  941. //
  942. $charset = strtolower ($charset);
  943. /* ===== FIXME: this list is not used in 1.5.x, but if we need it, unless this differs between all our string function wrappers, we should store this info in the session
  944. // only use mbstring with the following character sets
  945. //
  946. $sq_substr_replace_mb_charsets = array(
  947. 'utf-8',
  948. 'big5',
  949. 'gb2312',
  950. 'gb18030',
  951. 'euc-jp',
  952. 'euc-cn',
  953. 'euc-tw',
  954. 'euc-kr'
  955. );
  956. // now we can use our own implementation using
  957. // mb_substr() and mb_strlen() if needed
  958. //
  959. if (in_array($charset, $sq_substr_replace_mb_charsets)
  960. && in_array($charset, sq_mb_list_encodings()))
  961. ===== */
  962. //FIXME: is there any reason why this cannot be a global array used by all string wrapper functions?
  963. if (in_array ($charset, sq_mb_list_encodings ()))
  964. {
  965. $string_length = mb_strlen ($string, $charset);
  966. if ($start < 0)
  967. $start = max (0, $string_length + $start);
  968. else if ($start > $string_length)
  969. $start = $string_length;
  970. if ($length < 0)
  971. $length = max (0, $string_length - $start + $length);
  972. else if (is_null ($length) || $length > $string_length)
  973. $length = $string_length;
  974. if ($start + $length > $string_length)
  975. $length = $string_length - $start;
  976. return mb_substr ($string, 0, $start, $charset)
  977. . $replacement
  978. . mb_substr ($string,
  979. $start + $length,
  980. $string_length, // FIXME: I can't see why this is needed: - $start - $length,
  981. $charset);
  982. }
  983. // else use normal substr_replace()
  984. //
  985. return is_null ($length) ? substr_replace ($string, $replacement, $start)
  986. : substr_replace ($string, $replacement, $start, $length);
  987. }
  988. /**
  989. * Replacement of mb_list_encodings function
  990. *
  991. * This function provides replacement for function that is available only
  992. * in php 5.x. Function does not test all mbstring encodings. Only the ones
  993. * that might be used in SM translations.
  994. *
  995. * Supported strings are stored in session in order to reduce number of
  996. * mb_internal_encoding function calls.
  997. *
  998. * If mb_list_encodings() function is present, code uses it. Main difference
  999. * from original function behaviour - array values are lowercased in order to
  1000. * simplify use of returned array in in_array() checks.
  1001. *
  1002. * If you want to test all mbstring encodings - fill $list_of_encodings
  1003. * array.
  1004. * @return array list of encodings supported by php mbstring extension
  1005. * @since 1.5.1 and 1.4.6
  1006. */
  1007. function sq_mb_list_encodings () {
  1008. // if it's already in the session, don't need to regenerate it
  1009. if (sqgetGlobalVar ('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION )
  1010. && is_array ($mb_supported_encodings))
  1011. return $mb_supported_encodings;
  1012. // check if mbstring extension is present
  1013. if (! function_exists ('mb_internal_encoding')) {
  1014. $supported_encodings = array();
  1015. sqsession_register ($supported_encodings, 'mb_supported_encodings');
  1016. return $supported_encodings;
  1017. }
  1018. // php 5+ function
  1019. if (function_exists ('mb_list_encodings')) {
  1020. $supported_encodings = mb_list_encodings ();
  1021. array_walk ($supported_encodings, 'sq_lowercase_array_vals');
  1022. sqsession_register ($supported_encodings, 'mb_supported_encodings');
  1023. return $supported_encodings;
  1024. }
  1025. // save original encoding
  1026. $orig_encoding=mb_internal_encoding ();
  1027. $list_of_encoding=array(
  1028. 'pass',
  1029. 'auto',
  1030. 'ascii',
  1031. 'jis',
  1032. 'utf-8',
  1033. 'sjis',
  1034. 'euc-jp',
  1035. 'iso-8859-1',
  1036. 'iso-8859-2',
  1037. 'iso-8859-7',
  1038. 'iso-8859-9',
  1039. 'iso-8859-15',
  1040. 'koi8-r',
  1041. 'koi8-u',
  1042. 'big5',
  1043. 'gb2312',
  1044. 'gb18030',
  1045. 'windows-1251',
  1046. 'windows-1255',
  1047. 'windows-1256',
  1048. 'tis-620',
  1049. 'iso-2022-jp',
  1050. 'euc-cn',
  1051. 'euc-kr',
  1052. 'euc-tw',
  1053. 'uhc',
  1054. 'utf7-imap');
  1055. $supported_encodings=array();
  1056. foreach ($list_of_encoding as $encoding) {
  1057. // try setting encodings. suppress warning messages
  1058. if (@mb_internal_encoding ($encoding))
  1059. $supported_encodings[]=$encoding;
  1060. }
  1061. // restore original encoding
  1062. mb_internal_encoding ($orig_encoding);
  1063. // register list in session
  1064. sqsession_register ($supported_encodings, 'mb_supported_encodings');
  1065. return $supported_encodings;
  1066. }
  1067. /**
  1068. * Callback function used to lowercase array values.
  1069. * @param string $val array value
  1070. * @param mixed $key array key
  1071. * @since 1.5.1 and 1.4.6
  1072. */
  1073. function sq_lowercase_array_vals (&$val,$key) {
  1074. $val = strtolower ($val);
  1075. }
  1076. /**
  1077. * Callback function to trim whitespace from a value, to be used in array_walk
  1078. * @param string $value value to trim
  1079. * @since 1.5.2 and 1.4.7
  1080. */
  1081. function sq_trim_value ( &$value ) {
  1082. $value = trim ($value);
  1083. }
  1084. /**
  1085. * Gathers the list of secuirty tokens currently
  1086. * stored in the user's preferences and optionally
  1087. * purges old ones from the list.
  1088. *
  1089. * @param boolean $purge_old Indicates if old tokens
  1090. * should be purged from the
  1091. * list ("old" is 2 days or
  1092. * older unless the administrator
  1093. * overrides that value using
  1094. * $max_token_age_days in
  1095. * config/config_local.php)
  1096. * (OPTIONAL; default is to always
  1097. * purge old tokens)
  1098. *
  1099. * @return array The list of tokens
  1100. *
  1101. * @since 1.4.19 and 1.5.2
  1102. *
  1103. */
  1104. function sm_get_user_security_tokens ($purge_old=TRUE)
  1105. {
  1106. global $data_dir , $username, $max_token_age_days;
  1107. $tokens = getPref ($data_dir, $username, 'security_tokens', '');
  1108. if (($tokens = unserialize ($tokens)) === FALSE || !is_array ($tokens))
  1109. $tokens = array();
  1110. // purge old tokens if necessary
  1111. //
  1112. if ($purge_old)
  1113. {
  1114. if (empty($max_token_age_days)) $max_token_age_days = 2;
  1115. $now = time ();
  1116. $discard_token_date = $now - ($max_token_age_days * 86400);
  1117. $cleaned_tokens = array();
  1118. foreach ($tokens as $token => $timestamp)
  1119. if ($timestamp >= $discard_token_date)
  1120. $cleaned_tokens[$token] = $timestamp;
  1121. $tokens = $cleaned_tokens;
  1122. }
  1123. return $tokens;
  1124. }
  1125. /**
  1126. * Generates a security token that is then stored in
  1127. * the user's preferences with a timestamp for later
  1128. * verification/use (although session-based tokens
  1129. * are not stored in user preferences).
  1130. *
  1131. * NOTE: By default SquirrelMail will use a single session-based
  1132. * token, but if desired, user tokens can have expiration
  1133. * dates associated with them and become invalid even during
  1134. * the same login session. When in that mode, the note
  1135. * immediately below applies, otherwise it is irrelevant.
  1136. * To enable that mode, the administrator must add the
  1137. * following to config/config_local.php:
  1138. * $use_expiring_security_tokens = TRUE;
  1139. *
  1140. * NOTE: The administrator can force SquirrelMail to generate
  1141. * a new token every time one is requested (which may increase
  1142. * obscurity through token randomness at the cost of some
  1143. * performance) by adding the following to
  1144. * config/config_local.php: $do_not_use_single_token = TRUE;
  1145. * Otherwise, only one token will be generated per user which
  1146. * will change only after it expires or is used outside of the
  1147. * validity period specified when calling sm_validate_security_token()
  1148. *
  1149. * WARNING: If the administrator has turned the token system
  1150. * off by setting $disable_security_tokens to TRUE in
  1151. * config/config.php or the configuration tool, this
  1152. * function will not store tokens in the user
  1153. * preferences (but it will still generate and return
  1154. * a random string).
  1155. *
  1156. * @param boolean $force_generate_new When TRUE, a new token will
  1157. * always be created even if current
  1158. * configuration dictates otherwise
  1159. * (OPTIONAL; default FALSE)
  1160. *
  1161. * @return string A security token
  1162. *
  1163. * @since 1.4.19 and 1.5.2
  1164. *
  1165. */
  1166. function sm_generate_security_token ($force_generate_new=FALSE)
  1167. {
  1168. global $data_dir , $username, $disable_security_tokens , $do_not_use_single_token,
  1169. $use_expiring_security_tokens;
  1170. $max_generation_tries = 1000;
  1171. // if we're using session-based tokens, just return
  1172. // the same one every time (generate it if it's not there)
  1173. //
  1174. if (!$use_expiring_security_tokens)
  1175. {
  1176. if (sqgetGlobalVar ('sm_security_token', $token, SQ_SESSION ))
  1177. return $token;
  1178. // create new one since there was none in session
  1179. $token = GenerateRandomString (12, '', 7);
  1180. sqsession_register ($token, 'sm_security_token');
  1181. return $token;
  1182. }
  1183. if (!$force_generate_new && !$do_not_use_single_token && !empty($tokens))
  1184. return key ($tokens);
  1185. $new_token = GenerateRandomString (12, '', 7);
  1186. $count = 0;
  1187. while (isset($tokens[$new_token]))
  1188. {
  1189. $new_token = GenerateRandomString (12, '', 7);
  1190. if (++$count > $max_generation_tries)
  1191. {
  1192. logout_error (_ ("Fatal token generation error; please contact your system administrator or the SquirrelMail Team"));
  1193. exit;
  1194. }
  1195. }
  1196. // is the token system enabled? CAREFUL!
  1197. //
  1198. if (!$disable_security_tokens)
  1199. {
  1200. $tokens[$new_token] = time ();
  1201. setPref ($data_dir, $username, 'security_tokens', serialize ($tokens));
  1202. }
  1203. return $new_token;
  1204. }
  1205. /**
  1206. * Validates a given security token and optionally remove it
  1207. * from the user's preferences if it was valid. If the token
  1208. * is too old but otherwise valid, it will still be rejected.
  1209. *
  1210. * "Too old" is 2 days or older unless the administrator
  1211. * overrides that value using $max_token_age_days in
  1212. * config/config_local.php
  1213. *
  1214. * Session-based tokens of course are always reused and are
  1215. * valid for the lifetime of the login session.
  1216. *
  1217. * WARNING: If the administrator has turned the token system
  1218. * off by setting $disable_security_tokens to TRUE in
  1219. * config/config.php or the configuration tool, this
  1220. * function will always return TRUE.
  1221. *
  1222. * @param string $token The token to validate
  1223. * @param int $validity_period The number of seconds tokens are valid
  1224. * for (set to zero to remove valid tokens
  1225. * after only one use; set to -1 to allow
  1226. * indefinite re-use (but still subject to
  1227. * $max_token_age_days - see elsewhere);
  1228. * use 3600 to allow tokens to be reused for
  1229. * an hour) (OPTIONAL; default is to only
  1230. * allow tokens to be used once)
  1231. * NOTE this is unrelated to $max_token_age_days
  1232. * or rather is an additional time constraint on
  1233. * tokens that allows them to be re-used (or not)
  1234. * within a more narrow timeframe
  1235. * @param boolean $show_error Indicates that if the token is not
  1236. * valid, this function should display
  1237. * a generic error, log the user out
  1238. * and exit - this function will never
  1239. * return in that case.
  1240. * (OPTIONAL; default FALSE)
  1241. *
  1242. * @return boolean TRUE if the token validated; FALSE otherwise
  1243. *
  1244. * @since 1.4.19 and 1.5.2
  1245. *
  1246. */
  1247. function sm_validate_security_token ($token, $validity_period=0, $show_error=FALSE)
  1248. {
  1249. global $data_dir , $username, $max_token_age_days,
  1250. $use_expiring_security_tokens,
  1251. // bypass token validation? CAREFUL!
  1252. //
  1253. if ($disable_security_tokens) return TRUE;
  1254. // if we're using session-based tokens, just compare
  1255. // the same one every time
  1256. //
  1257. if (!$use_expiring_security_tokens)
  1258. {
  1259. if (!sqgetGlobalVar ('sm_security_token', $session_token, SQ_SESSION ))
  1260. {
  1261. if (!$show_error) return FALSE;
  1262. logout_error (_ ("Fatal security token error; please log in again"));
  1263. exit;
  1264. }
  1265. if ($token !== $session_token)
  1266. {
  1267. if (!$show_error) return FALSE;
  1268. logout_error (_ ("The current page request appears to have originated from an untrusted source."));
  1269. exit;
  1270. }
  1271. return TRUE;
  1272. }
  1273. // don't purge old tokens here because we already
  1274. // do it when generating tokens
  1275. //
  1276. $tokens = sm_get_user_security_tokens (FALSE);
  1277. // token not found?
  1278. //
  1279. if (empty($tokens[$token]))
  1280. {
  1281. if (!$show_error) return FALSE;
  1282. logout_error (_ ("This page request could not be verified and appears to have expired."));
  1283. exit;
  1284. }
  1285. $now = time ();
  1286. $timestamp = $tokens[$token];
  1287. // whether valid or not, we want to remove it from
  1288. // user prefs if it's old enough (unless requested to
  1289. // bypass this (in which case $validity_period is -1))
  1290. //
  1291. if ($validity_period >= 0
  1292. && $timestamp < $now - $validity_period)
  1293. {
  1294. unset($tokens[$token]);
  1295. setPref ($data_dir, $username, 'security_tokens', serialize ($tokens));
  1296. }
  1297. // reject tokens that are too old
  1298. //
  1299. if (empty($max_token_age_days)) $max_token_age_days = 2;
  1300. $old_token_date = $now - ($max_token_age_days * 86400);
  1301. if ($timestamp < $old_token_date)
  1302. {
  1303. if (!$show_error) return FALSE;
  1304. logout_error (_ ("The current page request appears to have originated from an untrusted source."));
  1305. exit;
  1306. }
  1307. // token OK!
  1308. //
  1309. return TRUE;
  1310. }
  1311. /**
  1312. * Wrapper for PHP's htmlspecialchars() that
  1313. * attempts to add the correct character encoding
  1314. *
  1315. * @param string $string The string to be converted
  1316. * @param int $flags A bitmask that controls the behavior of htmlspecialchars()
  1317. * (See http://php.net/manual/function.htmlspecialchars.php )
  1318. * (OPTIONAL; default ENT_COMPAT, ENT_COMPAT | ENT_SUBSTITUTE for PHP >=5.4)
  1319. * @param string $encoding The character encoding to use in the conversion
  1320. * (OPTIONAL; default automatic detection)
  1321. * @param boolean $double_encode Whether or not to convert entities that are
  1322. * already in the string (only supported in
  1323. * PHP 5.2.3+) (OPTIONAL; default TRUE)
  1324. *
  1325. * @return string The converted text
  1326. *
  1327. */
  1328. function sm_encode_html_special_chars ($string, $flags=ENT_COMPAT,
  1329. $encoding=NULL, $double_encode=TRUE)
  1330. {
  1331. if (!$encoding)
  1332. {
  1333. if ($default_charset == 'iso-2022-jp')
  1334. $default_charset = 'EUC-JP';
  1335. $encoding = $default_charset;
  1336. }
  1337. if (check_php_version (5, 2, 3)) {
  1338. // Replace invalid characters with a symbol instead of returning
  1339. // empty string for the entire to be encoded string.
  1340. if (check_php_version (5, 4, 0) && $flags == ENT_COMPAT) {
  1341. $flags = $flags | ENT_SUBSTITUTE;
  1342. }
  1343. return htmlspecialchars ($string, $flags, $encoding, $double_encode);
  1344. }
  1345. return htmlspecialchars ($string, $flags, $encoding);
  1346. }
  1347. $PHP_SELF = php_self ();

Documentation generated on 2020年1月13日 04:25:23 +0100 by phpDocumentor 1.4.3

AltStyle によって変換されたページ (->オリジナル) /