mime.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815
  1. <?php
  2. /**
  3. * mime.php
  4. *
  5. * Copyright (c) 1999-2003 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * This contains the functions necessary to detect and decode MIME
  9. * messages.
  10. *
  11. * $Id$
  12. */
  13. require_once(SM_PATH . 'functions/imap.php');
  14. require_once(SM_PATH . 'functions/attachment_common.php');
  15. /* -------------------------------------------------------------------------- */
  16. /* MIME DECODING */
  17. /* -------------------------------------------------------------------------- */
  18. /* This function gets the structure of a message and stores it in the "message" class.
  19. * It will return this object for use with all relevant header information and
  20. * fully parsed into the standard "message" object format.
  21. */
  22. function mime_structure ($bodystructure, $flags=array()) {
  23. /* Isolate the body structure and remove beginning and end parenthesis. */
  24. $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
  25. $read = trim(substr ($read, 0, -1));
  26. $i = 0;
  27. $msg = Message::parseStructure($read,$i);
  28. if (!is_object($msg)) {
  29. include_once(SM_PATH . 'functions/display_messages.php');
  30. global $color, $mailbox;
  31. /* removed urldecode because $_GET is auto urldecoded ??? */
  32. displayPageHeader( $color, $mailbox );
  33. $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
  34. $errormessage .= '<BR>'._("the provided bodystructure by your imap-server").':<BR><BR>';
  35. $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
  36. plain_error_message( $errormessage, $color );
  37. echo '</body></html>';
  38. exit;
  39. }
  40. if (count($flags)) {
  41. foreach ($flags as $flag) {
  42. $char = strtoupper($flag{1});
  43. switch ($char) {
  44. case 'S':
  45. if (strtolower($flag) == '\\seen') {
  46. $msg->is_seen = true;
  47. }
  48. break;
  49. case 'A':
  50. if (strtolower($flag) == '\\answered') {
  51. $msg->is_answered = true;
  52. }
  53. break;
  54. case 'D':
  55. if (strtolower($flag) == '\\deleted') {
  56. $msg->is_deleted = true;
  57. }
  58. break;
  59. case 'F':
  60. if (strtolower($flag) == '\\flagged') {
  61. $msg->is_flagged = true;
  62. }
  63. break;
  64. case 'M':
  65. if (strtolower($flag) == '$mdnsent') {
  66. $msg->is_mdnsent = true;
  67. }
  68. break;
  69. default:
  70. break;
  71. }
  72. }
  73. }
  74. // listEntities($msg);
  75. return $msg;
  76. }
  77. /* This starts the parsing of a particular structure. It is called recursively,
  78. * so it can be passed different structures. It returns an object of type
  79. * $message.
  80. * First, it checks to see if it is a multipart message. If it is, then it
  81. * handles that as it sees is necessary. If it is just a regular entity,
  82. * then it parses it and adds the necessary header information (by calling out
  83. * to mime_get_elements()
  84. */
  85. function mime_fetch_body($imap_stream, $id, $ent_id=1) {
  86. global $uid_support;
  87. /* Do a bit of error correction. If we couldn't find the entity id, just guess
  88. * that it is the first one. That is usually the case anyway.
  89. */
  90. if (!$ent_id) {
  91. $cmd = "FETCH $id BODY[]";
  92. } else {
  93. $cmd = "FETCH $id BODY[$ent_id]";
  94. }
  95. $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
  96. do {
  97. $topline = trim(array_shift($data));
  98. } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
  99. $wholemessage = implode('', $data);
  100. if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
  101. $ret = substr($wholemessage, 0, $regs[1]);
  102. /* There is some information in the content info header that could be important
  103. * in order to parse html messages. Let's get them here.
  104. */
  105. // if ($ret{0} == '<') {
  106. // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
  107. // }
  108. } else if (ereg('"([^"]*)"', $topline, $regs)) {
  109. $ret = $regs[1];
  110. } else {
  111. global $where, $what, $mailbox, $passed_id, $startMessage;
  112. $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
  113. if (isset($where) && isset($what)) {
  114. $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
  115. } else {
  116. $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  117. }
  118. $par .= '&amp;response=' . urlencode($response) .
  119. '&amp;message=' . urlencode($message) .
  120. '&amp;topline=' . urlencode($topline);
  121. echo '<tt><br>' .
  122. '<table width="80%"><tr>' .
  123. '<tr><td colspan=2>' .
  124. _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
  125. '</td></tr>' .
  126. '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
  127. '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
  128. '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
  129. '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
  130. "</table><BR></tt></font><hr>";
  131. $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
  132. array_shift($data);
  133. $wholemessage = implode('', $data);
  134. $ret = $wholemessage;
  135. }
  136. return $ret;
  137. }
  138. function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding) {
  139. global $uid_support;
  140. /* Don't kill the connection if the browser is over a dialup
  141. * and it would take over 30 seconds to download it.
  142. * Don´t call set_time_limit in safe mode.
  143. */
  144. if (!ini_get('safe_mode')) {
  145. set_time_limit(0);
  146. }
  147. /* in case of base64 encoded attachments, do not buffer them.
  148. Instead, echo the decoded attachment directly to screen */
  149. if (strtolower($encoding) == 'base64') {
  150. if (!$ent_id) {
  151. $query = "FETCH $id BODY[]";
  152. } else {
  153. $query = "FETCH $id BODY[$ent_id]";
  154. }
  155. sqimap_run_command($imap_stream,$query,true,$response,$message,$uid_support,'sqimap_base64_decode','php://stdout',true);
  156. } else {
  157. $body = mime_fetch_body ($imap_stream, $id, $ent_id);
  158. echo decodeBody($body, $encoding);
  159. }
  160. /*
  161. TODO, use the same method for quoted printable.
  162. However, I assume that quoted printable attachments aren't that large
  163. so the performancegain / memory usage drop will be minimal.
  164. If we decide to add that then we need to adapt sqimap_fread because
  165. we need to split te result on \n and fread doesn't stop at \n. That
  166. means we also should provide $results from sqimap_fread (by ref) to
  167. te function and set $no_return to false. The $filter function for
  168. quoted printable should handle unsetting of $results.
  169. */
  170. /*
  171. TODO 2: find out how we write to the output stream php://stdout. fwrite
  172. doesn't work because 'php://stdout isn't a stream.
  173. */
  174. return;
  175. /*
  176. fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
  177. $cnt = 0;
  178. $continue = true;
  179. $read = fgets ($imap_stream,8192);
  180. // This could be bad -- if the section has sqimap_session_id() . ' OK'
  181. // or similar, it will kill the download.
  182. while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
  183. if (trim($read) == ')==') {
  184. $read1 = $read;
  185. $read = fgets ($imap_stream,4096);
  186. if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
  187. return;
  188. } else {
  189. echo decodeBody($read1, $encoding) .
  190. decodeBody($read, $encoding);
  191. }
  192. } else if ($cnt) {
  193. echo decodeBody($read, $encoding);
  194. }
  195. $read = fgets ($imap_stream,4096);
  196. $cnt++;
  197. // break;
  198. }
  199. */
  200. }
  201. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  202. /* This is here for debugging purposes. It will print out a list
  203. * of all the entity IDs that are in the $message object.
  204. */
  205. function listEntities ($message) {
  206. if ($message) {
  207. echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br>';
  208. for ($i = 0; isset($message->entities[$i]); $i++) {
  209. echo "$i : ";
  210. $msg = listEntities($message->entities[$i]);
  211. if ($msg) {
  212. echo "return: ";
  213. return $msg;
  214. }
  215. }
  216. }
  217. }
  218. function getPriorityStr($priority) {
  219. $priority_level = substr($priority,0,1);
  220. switch($priority_level) {
  221. /* Check for a higher then normal priority. */
  222. case '1':
  223. case '2':
  224. $priority_string = _("High");
  225. break;
  226. /* Check for a lower then normal priority. */
  227. case '4':
  228. case '5':
  229. $priority_string = _("Low");
  230. break;
  231. /* Check for a normal priority. */
  232. case '3':
  233. default:
  234. $priority_level = '3';
  235. $priority_string = _("Normal");
  236. break;
  237. }
  238. return $priority_string;
  239. }
  240. /* returns a $message object for a particular entity id */
  241. function getEntity ($message, $ent_id) {
  242. return $message->getEntity($ent_id);
  243. }
  244. /* translateText
  245. * Extracted from strings.php 23/03/2002
  246. */
  247. function translateText(&$body, $wrap_at, $charset) {
  248. global $where, $what; /* from searching */
  249. global $color; /* color theme */
  250. require_once(SM_PATH . 'functions/url_parser.php');
  251. $body_ary = explode("\n", $body);
  252. for ($i=0; $i < count($body_ary); $i++) {
  253. $line = $body_ary[$i];
  254. if (strlen($line) - 2 >= $wrap_at) {
  255. sqWordWrap($line, $wrap_at);
  256. }
  257. $line = charset_decode($charset, $line);
  258. $line = str_replace("\t", ' ', $line);
  259. parseUrl ($line);
  260. $quotes = 0;
  261. $pos = 0;
  262. $j = strlen($line);
  263. while ($pos < $j) {
  264. if ($line[$pos] == ' ') {
  265. $pos++;
  266. } else if (strpos($line, '&gt;', $pos) === $pos) {
  267. $pos += 4;
  268. $quotes++;
  269. } else {
  270. break;
  271. }
  272. }
  273. if ($quotes % 2) {
  274. if (!isset($color[13])) {
  275. $color[13] = '#800000';
  276. }
  277. $line = '<font color="' . $color[13] . '">' . $line . '</font>';
  278. } elseif ($quotes) {
  279. if (!isset($color[14])) {
  280. $color[14] = '#FF0000';
  281. }
  282. $line = '<font color="' . $color[14] . '">' . $line . '</font>';
  283. }
  284. $body_ary[$i] = $line;
  285. }
  286. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  287. }
  288. /* This returns a parsed string called $body. That string can then
  289. * be displayed as the actual message in the HTML. It contains
  290. * everything needed, including HTML Tags, Attachments at the
  291. * bottom, etc.
  292. */
  293. function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
  294. /* This if statement checks for the entity to show as the
  295. * primary message. To add more of them, just put them in the
  296. * order that is their priority.
  297. */
  298. global $startMessage, $username, $key, $imapServerAddress, $imapPort,
  299. $show_html_default, $sort, $has_unsafe_images, $passed_ent_id;
  300. global $languages, $squirrelmail_language;
  301. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  302. $view_unsafe_images = false;
  303. }
  304. $body = '';
  305. $urlmailbox = urlencode($mailbox);
  306. $body_message = getEntity($message, $ent_num);
  307. if (($body_message->header->type0 == 'text') ||
  308. ($body_message->header->type0 == 'rfc822')) {
  309. $body = mime_fetch_body ($imap_stream, $id, $ent_num);
  310. $body = decodeBody($body, $body_message->header->encoding);
  311. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  312. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  313. if (mb_detect_encoding($body) != 'ASCII') {
  314. $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
  315. }
  316. }
  317. $hookResults = do_hook("message_body", $body);
  318. $body = $hookResults[1];
  319. /* If there are other types that shouldn't be formatted, add
  320. * them here.
  321. */
  322. if ($body_message->header->type1 == 'html') {
  323. if ($show_html_default <> 1) {
  324. $entity_conv = array('&nbsp;' => ' ',
  325. '<p>' => "\n",
  326. '<br>' => "\n",
  327. '<P>' => "\n",
  328. '<BR>' => "\n",
  329. '&gt;' => '>',
  330. '&lt;' => '<');
  331. $body = strtr($body, $entity_conv);
  332. $body = strip_tags($body);
  333. $body = trim($body);
  334. translateText($body, $wrap_at,
  335. $body_message->header->getParameter('charset'));
  336. } else {
  337. $body = magicHTML($body, $id, $message, $mailbox);
  338. }
  339. } else {
  340. translateText($body, $wrap_at,
  341. $body_message->header->getParameter('charset'));
  342. }
  343. $link = 'read_body.php?passed_id=' . $id . '&amp;ent_id='.$ent_num.
  344. '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
  345. '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  346. if (isset($passed_ent_id)) {
  347. $link .= '&amp;passed_ent_id='.$passed_ent_id;
  348. }
  349. if ($view_unsafe_images) {
  350. $text = _("Hide Unsafe Images");
  351. } else {
  352. if (isset($has_unsafe_images) && $has_unsafe_images) {
  353. $link .= '&amp;view_unsafe_images=1';
  354. $text = _("View Unsafe Images");
  355. } else {
  356. $text = '';
  357. }
  358. }
  359. $body .= '<center><small><a href="'.$link.'">'.$text.
  360. '</a></small></center><br>' . "\n";
  361. }
  362. return $body;
  363. }
  364. function formatAttachments($message, $exclude_id, $mailbox, $id) {
  365. global $where, $what, $startMessage, $color;
  366. static $ShownHTML = 0;
  367. $att_ar = $message->getAttachments($exclude_id);
  368. if (!count($att_ar)) return '';
  369. $attachments = '';
  370. $urlMailbox = urlencode($mailbox);
  371. foreach ($att_ar as $att) {
  372. $ent = $att->entity_id;
  373. $header = $att->header;
  374. $type0 = strtolower($header->type0);
  375. $type1 = strtolower($header->type1);
  376. $name = '';
  377. $links['download link']['text'] = _("download");
  378. $links['download link']['href'] = SM_PATH .
  379. "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
  380. $ImageURL = '';
  381. if ($type0 =='message' && $type1 == 'rfc822') {
  382. $default_page = SM_PATH . 'src/read_body.php';
  383. $rfc822_header = $att->rfc822_header;
  384. $filename = $rfc822_header->subject;
  385. if (trim( $filename ) == '') {
  386. $filename = 'untitled-[' . $ent . ']' ;
  387. }
  388. $from_o = $rfc822_header->from;
  389. if (is_object($from_o)) {
  390. $from_name = $from_o->getAddress(false);
  391. } else {
  392. $from_name = _("Unknown sender");
  393. }
  394. $from_name = decodeHeader(($from_name));
  395. $description = $from_name;
  396. } else {
  397. $default_page = SM_PATH . 'src/download.php';
  398. if (is_object($header->disposition)) {
  399. $filename = $header->disposition->getProperty('filename');
  400. if (trim($filename) == '') {
  401. $name = decodeHeader($header->disposition->getProperty('name'));
  402. if (trim($name) == '') {
  403. $name = $header->getParameter('name');
  404. if(trim($name) == '') {
  405. if (trim( $header->id ) == '') {
  406. $filename = 'untitled-[' . $ent . ']' ;
  407. } else {
  408. $filename = 'cid: ' . $header->id;
  409. }
  410. } else {
  411. $filename = $name;
  412. }
  413. } else {
  414. $filename = $name;
  415. }
  416. }
  417. } else {
  418. $filename = $header->getParameter('name');
  419. if (!trim($filename)) {
  420. if (trim( $header->id ) == '') {
  421. $filename = 'untitled-[' . $ent . ']' ;
  422. } else {
  423. $filename = 'cid: ' . $header->id;
  424. }
  425. }
  426. }
  427. if ($header->description) {
  428. $description = decodeHeader($header->description);
  429. } else {
  430. $description = '';
  431. }
  432. }
  433. $display_filename = $filename;
  434. if (isset($passed_ent_id)) {
  435. $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
  436. } else {
  437. $passed_ent_id_link = '';
  438. }
  439. $defaultlink = $default_page . "?startMessage=$startMessage"
  440. . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
  441. . '&amp;ent_id='.$ent.$passed_ent_id_link;
  442. if ($where && $what) {
  443. $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
  444. }
  445. /* This executes the attachment hook with a specific MIME-type.
  446. * If that doesn't have results, it tries if there's a rule
  447. * for a more generic type.
  448. */
  449. $hookresults = do_hook("attachment $type0/$type1", $links,
  450. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  451. $display_filename, $where, $what);
  452. if(count($hookresults[1]) <= 1) {
  453. $hookresults = do_hook("attachment $type0/*", $links,
  454. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  455. $display_filename, $where, $what);
  456. }
  457. $links = $hookresults[1];
  458. $defaultlink = $hookresults[6];
  459. $attachments .= '<TR><TD>' .
  460. '<A HREF="'.$defaultlink.'">'.decodeHeader($display_filename).'</A>&nbsp;</TD>' .
  461. '<TD><SMALL><b>' . show_readable_size($header->size) .
  462. '</b>&nbsp;&nbsp;</small></TD>' .
  463. "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
  464. '<TD><SMALL>';
  465. $attachments .= '<b>' . $description . '</b>';
  466. $attachments .= '</SMALL></TD><TD><SMALL>&nbsp;';
  467. $skipspaces = 1;
  468. foreach ($links as $val) {
  469. if ($skipspaces) {
  470. $skipspaces = 0;
  471. } else {
  472. $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  473. }
  474. $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
  475. }
  476. unset($links);
  477. $attachments .= "</TD></TR>\n";
  478. }
  479. $attachmentadd = do_hook_function('attachments_bottom',$attachments);
  480. if ($attachmentadd != '')
  481. $attachments = $attachmentadd;
  482. return $attachments;
  483. }
  484. function sqimap_base64_decode(&$string) {
  485. $string = str_replace("\r\n", "\n", $string);
  486. $string = base64_decode($string);
  487. }
  488. /* This function decodes the body depending on the encoding type. */
  489. function decodeBody($body, $encoding) {
  490. global $show_html_default;
  491. $body = str_replace("\r\n", "\n", $body);
  492. $encoding = strtolower($encoding);
  493. if ($encoding == 'quoted-printable' ||
  494. $encoding == 'quoted_printable') {
  495. $body = quoted_printable_decode($body);
  496. while (ereg("=\n", $body)) {
  497. $body = ereg_replace ("=\n", '', $body);
  498. }
  499. } else if ($encoding == 'base64') {
  500. $body = base64_decode($body);
  501. }
  502. // All other encodings are returned raw.
  503. return $body;
  504. }
  505. /*
  506. * This functions decode strings that is encoded according to
  507. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  508. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  509. */
  510. function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
  511. global $languages, $squirrelmail_language;
  512. if (is_array($string)) {
  513. $string = implode("\n", $string);
  514. }
  515. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  516. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  517. $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
  518. // Do we need to return at this point?
  519. // return $string;
  520. }
  521. $i = 0;
  522. $iLastMatch = -2;
  523. $encoded = false;
  524. $aString = explode(' ',$string);
  525. $ret = '';
  526. foreach ($aString as $chunk) {
  527. if ($encoded && $chunk === '') {
  528. continue;
  529. } elseif ($chunk === '') {
  530. $ret .= ' ';
  531. continue;
  532. }
  533. $encoded = false;
  534. /* if encoded words are not separated by a linear-space-white we still catch them */
  535. $j = $i-1;
  536. // if ($chunk{0} === '=') { /* performance, saves an unnessecarry preg call */
  537. while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  538. /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
  539. if ($iLastMatch !== $j) {
  540. if ($htmlsave) {
  541. $ret .= '&nbsp;';
  542. } else {
  543. $ret .= ' ';
  544. }
  545. }
  546. $iLastMatch = $i;
  547. $j = $i;
  548. $ret .= $res[1];
  549. $encoding = ucfirst($res[3]);
  550. switch ($encoding)
  551. {
  552. case 'B':
  553. $replace = base64_decode($res[4]);
  554. $ret .= charset_decode($res[2],$replace);
  555. break;
  556. case 'Q':
  557. $replace = str_replace('_', ' ', $res[4]);
  558. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  559. $replace);
  560. /* Only encode into entities by default. Some places
  561. * don't need the encoding, like the compose form.
  562. */
  563. if ($utfencode) {
  564. $replace = charset_decode($res[2], $replace);
  565. } else {
  566. if ($htmlsave) {
  567. $replace = htmlspecialchars($replace);
  568. }
  569. }
  570. $ret .= $replace;
  571. break;
  572. default:
  573. break;
  574. }
  575. $chunk = $res[5];
  576. $encoded = true;
  577. }
  578. // }
  579. if (!$encoded) {
  580. if ($htmlsave) {
  581. $ret .= '&nbsp;';
  582. } else {
  583. $ret .= ' ';
  584. }
  585. }
  586. if (!$encoded && $htmlsave) {
  587. $ret .= htmlspecialchars($chunk);
  588. } else {
  589. $ret .= $chunk;
  590. }
  591. ++$i;
  592. }
  593. /* remove the first added space */
  594. if ($ret) {
  595. if ($htmlsave) {
  596. $ret = substr($ret,6);
  597. } else {
  598. $ret = substr($ret,1);
  599. }
  600. }
  601. return $ret;
  602. }
  603. /*
  604. * Encode a string according to RFC 1522 for use in headers if it
  605. * contains 8-bit characters or anything that looks like it should
  606. * be encoded.
  607. */
  608. function encodeHeader ($string) {
  609. global $default_charset, $languages, $squirrelmail_language;
  610. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  611. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  612. return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
  613. }
  614. if (strtolower($default_charset) == 'iso-8859-1') {
  615. $string = str_replace("\240",' ',$string);
  616. }
  617. // Encode only if the string contains 8-bit characters or =?
  618. $j = strlen($string);
  619. $max_l = 75 - strlen($default_charset) - 7;
  620. $aRet = array();
  621. $ret = '';
  622. $iEncStart = $enc_init = false;
  623. $cur_l = $iOffset = 0;
  624. for($i = 0; $i < $j; ++$i) {
  625. switch($string{$i})
  626. {
  627. case '=':
  628. case '<':
  629. case '>':
  630. case ',':
  631. case '?':
  632. case '_':
  633. if ($iEncStart === false) {
  634. $iEncStart = $i;
  635. }
  636. $cur_l+=3;
  637. if ($cur_l > ($max_l-2)) {
  638. /* if there is an stringpart that doesn't need encoding, add it */
  639. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  640. $aRet[] = "=?$default_charset?Q?$ret?=";
  641. $iOffset = $i;
  642. $cur_l = 0;
  643. $ret = '';
  644. $iEncStart = false;
  645. } else {
  646. $ret .= sprintf("=%02X",ord($string{$i}));
  647. }
  648. break;
  649. case '(':
  650. case ')':
  651. if ($iEncStart !== false) {
  652. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  653. $aRet[] = "=?$default_charset?Q?$ret?=";
  654. $iOffset = $i;
  655. $cur_l = 0;
  656. $ret = '';
  657. $iEncStart = false;
  658. }
  659. break;
  660. case ' ':
  661. if ($iEncStart !== false) {
  662. $cur_l++;
  663. if ($cur_l > $max_l) {
  664. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  665. $aRet[] = "=?$default_charset?Q?$ret?=";
  666. $iOffset = $i;
  667. $cur_l = 0;
  668. $ret = '';
  669. $iEncStart = false;
  670. } else {
  671. $ret .= '_';
  672. }
  673. }
  674. break;
  675. default:
  676. $k = ord($string{$i});
  677. if ($k > 126) {
  678. if ($iEncStart === false) {
  679. // do not start encoding in the middle of a string, also take the rest of the word.
  680. $sLeadString = substr($string,0,$i);
  681. $aLeadString = explode(' ',$sLeadString);
  682. $sToBeEncoded = array_pop($aLeadString);
  683. $iEncStart = $i - strlen($sToBeEncoded);
  684. $ret .= $sToBeEncoded;
  685. $cur_l += strlen($sToBeEncoded);
  686. }
  687. $cur_l += 3;
  688. /* first we add the encoded string that reached it's max size */
  689. if ($cur_l > ($max_l-2)) {
  690. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  691. $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
  692. $cur_l = 3;
  693. $ret = '';
  694. $iOffset = $i;
  695. $iEncStart = $i;
  696. }
  697. $enc_init = true;
  698. $ret .= sprintf("=%02X", $k);
  699. } else {
  700. if ($iEncStart !== false) {
  701. $cur_l++;
  702. if ($cur_l > $max_l) {
  703. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  704. $aRet[] = "=?$default_charset?Q?$ret?=";
  705. $iEncStart = false;
  706. $iOffset = $i;
  707. $cur_l = 0;
  708. $ret = '';
  709. } else {
  710. $ret .= $string{$i};
  711. }
  712. }
  713. }
  714. break;
  715. }
  716. }
  717. if ($enc_init) {
  718. if ($iEncStart !== false) {
  719. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  720. $aRet[] = "=?$default_charset?Q?$ret?=";
  721. } else {
  722. $aRet[] = substr($string,$iOffset);
  723. }
  724. $string = implode('',$aRet);
  725. }
  726. return $string;
  727. }
  728. /* This function trys to locate the entity_id of a specific mime element */
  729. function find_ent_id($id, $message) {
  730. for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
  731. if ($message->entities[$i]->header->type0 == 'multipart') {
  732. $ret = find_ent_id($id, $message->entities[$i]);
  733. } else {
  734. if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
  735. // if (sq_check_save_extension($message->entities[$i])) {
  736. return $message->entities[$i]->entity_id;
  737. // }
  738. }
  739. }
  740. }
  741. return $ret;
  742. }
  743. function sq_check_save_extension($message) {
  744. $filename = $message->getFilename();
  745. $ext = substr($filename, strrpos($filename,'.')+1);
  746. $save_extensions = array('jpg','jpeg','gif','png','bmp');
  747. return in_array($ext, $save_extensions);
  748. }
  749. /**
  750. ** HTMLFILTER ROUTINES
  751. */
  752. /**
  753. * This function returns the final tag out of the tag name, an array
  754. * of attributes, and the type of the tag. This function is called by
  755. * sq_sanitize internally.
  756. *
  757. * @param $tagname the name of the tag.
  758. * @param $attary the array of attributes and their values
  759. * @param $tagtype The type of the tag (see in comments).
  760. * @return a string with the final tag representation.
  761. */
  762. function sq_tagprint($tagname, $attary, $tagtype){
  763. $me = 'sq_tagprint';
  764. if ($tagtype == 2){
  765. $fulltag = '</' . $tagname . '>';
  766. } else {
  767. $fulltag = '<' . $tagname;
  768. if (is_array($attary) && sizeof($attary)){
  769. $atts = Array();
  770. while (list($attname, $attvalue) = each($attary)){
  771. array_push($atts, "$attname=$attvalue");
  772. }
  773. $fulltag .= ' ' . join(" ", $atts);
  774. }
  775. if ($tagtype == 3){
  776. $fulltag .= ' /';
  777. }
  778. $fulltag .= '>';
  779. }
  780. return $fulltag;
  781. }
  782. /**
  783. * A small helper function to use with array_walk. Modifies a by-ref
  784. * value and makes it lowercase.
  785. *
  786. * @param $val a value passed by-ref.
  787. * @return void since it modifies a by-ref value.
  788. */
  789. function sq_casenormalize(&$val){
  790. $val = strtolower($val);
  791. }
  792. /**
  793. * This function skips any whitespace from the current position within
  794. * a string and to the next non-whitespace value.
  795. *
  796. * @param $body the string
  797. * @param $offset the offset within the string where we should start
  798. * looking for the next non-whitespace character.
  799. * @return the location within the $body where the next
  800. * non-whitespace char is located.
  801. */
  802. function sq_skipspace($body, $offset){
  803. $me = 'sq_skipspace';
  804. preg_match('/^(\s*)/s', substr($body, $offset), $matches);
  805. if (sizeof($matches{1})){
  806. $count = strlen($matches{1});
  807. $offset += $count;
  808. }
  809. return $offset;
  810. }
  811. /**
  812. * This function looks for the next character within a string. It's
  813. * really just a glorified "strpos", except it catches if failures
  814. * nicely.
  815. *
  816. * @param $body The string to look for needle in.
  817. * @param $offset Start looking from this position.
  818. * @param $needle The character/string to look for.
  819. * @return location of the next occurance of the needle, or
  820. * strlen($body) if needle wasn't found.
  821. */
  822. function sq_findnxstr($body, $offset, $needle){
  823. $me = 'sq_findnxstr';
  824. $pos = strpos($body, $needle, $offset);
  825. if ($pos === FALSE){
  826. $pos = strlen($body);
  827. }
  828. return $pos;
  829. }
  830. /**
  831. * This function takes a PCRE-style regexp and tries to match it
  832. * within the string.
  833. *
  834. * @param $body The string to look for needle in.
  835. * @param $offset Start looking from here.
  836. * @param $reg A PCRE-style regex to match.
  837. * @return Returns a false if no matches found, or an array
  838. * with the following members:
  839. * - integer with the location of the match within $body
  840. * - string with whatever content between offset and the match
  841. * - string with whatever it is we matched
  842. */
  843. function sq_findnxreg($body, $offset, $reg){
  844. $me = 'sq_findnxreg';
  845. $matches = Array();
  846. $retarr = Array();
  847. preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
  848. if (!isset($matches{0}) || !$matches{0}){
  849. $retarr = false;
  850. } else {
  851. $retarr{0} = $offset + strlen($matches{1});
  852. $retarr{1} = $matches{1};
  853. $retarr{2} = $matches{2};
  854. }
  855. return $retarr;
  856. }
  857. /**
  858. * This function looks for the next tag.
  859. *
  860. * @param $body String where to look for the next tag.
  861. * @param $offset Start looking from here.
  862. * @return false if no more tags exist in the body, or
  863. * an array with the following members:
  864. * - string with the name of the tag
  865. * - array with attributes and their values
  866. * - integer with tag type (1, 2, or 3)
  867. * - integer where the tag starts (starting "<")
  868. * - integer where the tag ends (ending ">")
  869. * first three members will be false, if the tag is invalid.
  870. */
  871. function sq_getnxtag($body, $offset){
  872. $me = 'sq_getnxtag';
  873. if ($offset > strlen($body)){
  874. return false;
  875. }
  876. $lt = sq_findnxstr($body, $offset, "<");
  877. if ($lt == strlen($body)){
  878. return false;
  879. }
  880. /**
  881. * We are here:
  882. * blah blah <tag attribute="value">
  883. * \---------^
  884. */
  885. $pos = sq_skipspace($body, $lt+1);
  886. if ($pos >= strlen($body)){
  887. return Array(false, false, false, $lt, strlen($body));
  888. }
  889. /**
  890. * There are 3 kinds of tags:
  891. * 1. Opening tag, e.g.:
  892. * <a href="blah">
  893. * 2. Closing tag, e.g.:
  894. * </a>
  895. * 3. XHTML-style content-less tag, e.g.:
  896. * <img src="blah"/>
  897. */
  898. $tagtype = false;
  899. switch (substr($body, $pos, 1)){
  900. case '/':
  901. $tagtype = 2;
  902. $pos++;
  903. break;
  904. case '!':
  905. /**
  906. * A comment or an SGML declaration.
  907. */
  908. if (substr($body, $pos+1, 2) == "--"){
  909. $gt = strpos($body, "-->", $pos);
  910. if ($gt === false){
  911. $gt = strlen($body);
  912. } else {
  913. $gt += 2;
  914. }
  915. return Array(false, false, false, $lt, $gt);
  916. } else {
  917. $gt = sq_findnxstr($body, $pos, ">");
  918. return Array(false, false, false, $lt, $gt);
  919. }
  920. break;
  921. default:
  922. /**
  923. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  924. * later.
  925. */
  926. $tagtype = 1;
  927. break;
  928. }
  929. $tag_start = $pos;
  930. $tagname = '';
  931. /**
  932. * Look for next [\W-_], which will indicate the end of the tag name.
  933. */
  934. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  935. if ($regary == false){
  936. return Array(false, false, false, $lt, strlen($body));
  937. }
  938. list($pos, $tagname, $match) = $regary;
  939. $tagname = strtolower($tagname);
  940. /**
  941. * $match can be either of these:
  942. * '>' indicating the end of the tag entirely.
  943. * '\s' indicating the end of the tag name.
  944. * '/' indicating that this is type-3 xhtml tag.
  945. *
  946. * Whatever else we find there indicates an invalid tag.
  947. */
  948. switch ($match){
  949. case '/':
  950. /**
  951. * This is an xhtml-style tag with a closing / at the
  952. * end, like so: <img src="blah"/>. Check if it's followed
  953. * by the closing bracket. If not, then this tag is invalid
  954. */
  955. if (substr($body, $pos, 2) == "/>"){
  956. $pos++;
  957. $tagtype = 3;
  958. } else {
  959. $gt = sq_findnxstr($body, $pos, ">");
  960. $retary = Array(false, false, false, $lt, $gt);
  961. return $retary;
  962. }
  963. case '>':
  964. return Array($tagname, false, $tagtype, $lt, $pos);
  965. break;
  966. default:
  967. /**
  968. * Check if it's whitespace
  969. */
  970. if (!preg_match('/\s/', $match)){
  971. /**
  972. * This is an invalid tag! Look for the next closing ">".
  973. */
  974. $gt = sq_findnxstr($body, $lt, ">");
  975. return Array(false, false, false, $lt, $gt);
  976. }
  977. break;
  978. }
  979. /**
  980. * At this point we're here:
  981. * <tagname attribute='blah'>
  982. * \-------^
  983. *
  984. * At this point we loop in order to find all attributes.
  985. */
  986. $attname = '';
  987. $atttype = false;
  988. $attary = Array();
  989. while ($pos <= strlen($body)){
  990. $pos = sq_skipspace($body, $pos);
  991. if ($pos == strlen($body)){
  992. /**
  993. * Non-closed tag.
  994. */
  995. return Array(false, false, false, $lt, $pos);
  996. }
  997. /**
  998. * See if we arrived at a ">" or "/>", which means that we reached
  999. * the end of the tag.
  1000. */
  1001. $matches = Array();
  1002. if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
  1003. /**
  1004. * Yep. So we did.
  1005. */
  1006. $pos += strlen($matches{1});
  1007. if ($matches{2} == "/>"){
  1008. $tagtype = 3;
  1009. $pos++;
  1010. }
  1011. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1012. }
  1013. /**
  1014. * There are several types of attributes, with optional
  1015. * [:space:] between members.
  1016. * Type 1:
  1017. * attrname[:space:]=[:space:]'CDATA'
  1018. * Type 2:
  1019. * attrname[:space:]=[:space:]"CDATA"
  1020. * Type 3:
  1021. * attr[:space:]=[:space:]CDATA
  1022. * Type 4:
  1023. * attrname
  1024. *
  1025. * We leave types 1 and 2 the same, type 3 we check for
  1026. * '"' and convert to "&quot" if needed, then wrap in
  1027. * double quotes. Type 4 we convert into:
  1028. * attrname="yes".
  1029. */
  1030. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  1031. if ($regary == false){
  1032. /**
  1033. * Looks like body ended before the end of tag.
  1034. */
  1035. return Array(false, false, false, $lt, strlen($body));
  1036. }
  1037. list($pos, $attname, $match) = $regary;
  1038. $attname = strtolower($attname);
  1039. /**
  1040. * We arrived at the end of attribute name. Several things possible
  1041. * here:
  1042. * '>' means the end of the tag and this is attribute type 4
  1043. * '/' if followed by '>' means the same thing as above
  1044. * '\s' means a lot of things -- look what it's followed by.
  1045. * anything else means the attribute is invalid.
  1046. */
  1047. switch($match){
  1048. case '/':
  1049. /**
  1050. * This is an xhtml-style tag with a closing / at the
  1051. * end, like so: <img src="blah"/>. Check if it's followed
  1052. * by the closing bracket. If not, then this tag is invalid
  1053. */
  1054. if (substr($body, $pos, 2) == "/>"){
  1055. $pos++;
  1056. $tagtype = 3;
  1057. } else {
  1058. $gt = sq_findnxstr($body, $pos, ">");
  1059. $retary = Array(false, false, false, $lt, $gt);
  1060. return $retary;
  1061. }
  1062. case '>':
  1063. $attary{$attname} = '"yes"';
  1064. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1065. break;
  1066. default:
  1067. /**
  1068. * Skip whitespace and see what we arrive at.
  1069. */
  1070. $pos = sq_skipspace($body, $pos);
  1071. $char = substr($body, $pos, 1);
  1072. /**
  1073. * Two things are valid here:
  1074. * '=' means this is attribute type 1 2 or 3.
  1075. * \w means this was attribute type 4.
  1076. * anything else we ignore and re-loop. End of tag and
  1077. * invalid stuff will be caught by our checks at the beginning
  1078. * of the loop.
  1079. */
  1080. if ($char == "="){
  1081. $pos++;
  1082. $pos = sq_skipspace($body, $pos);
  1083. /**
  1084. * Here are 3 possibilities:
  1085. * "'" attribute type 1
  1086. * '"' attribute type 2
  1087. * everything else is the content of tag type 3
  1088. */
  1089. $quot = substr($body, $pos, 1);
  1090. if ($quot == "'"){
  1091. $regary = sq_findnxreg($body, $pos+1, "\'");
  1092. if ($regary == false){
  1093. return Array(false, false, false, $lt, strlen($body));
  1094. }
  1095. list($pos, $attval, $match) = $regary;
  1096. $pos++;
  1097. $attary{$attname} = "'" . $attval . "'";
  1098. } else if ($quot == '"'){
  1099. $regary = sq_findnxreg($body, $pos+1, '\"');
  1100. if ($regary == false){
  1101. return Array(false, false, false, $lt, strlen($body));
  1102. }
  1103. list($pos, $attval, $match) = $regary;
  1104. $pos++;
  1105. $attary{$attname} = '"' . $attval . '"';
  1106. } else {
  1107. /**
  1108. * These are hateful. Look for \s, or >.
  1109. */
  1110. $regary = sq_findnxreg($body, $pos, "[\s>]");
  1111. if ($regary == false){
  1112. return Array(false, false, false, $lt, strlen($body));
  1113. }
  1114. list($pos, $attval, $match) = $regary;
  1115. /**
  1116. * If it's ">" it will be caught at the top.
  1117. */
  1118. $attval = preg_replace("/\"/s", "&quot;", $attval);
  1119. $attary{$attname} = '"' . $attval . '"';
  1120. }
  1121. } else if (preg_match("|[\w/>]|", $char)) {
  1122. /**
  1123. * That was attribute type 4.
  1124. */
  1125. $attary{$attname} = '"yes"';
  1126. } else {
  1127. /**
  1128. * An illegal character. Find next '>' and return.
  1129. */
  1130. $gt = sq_findnxstr($body, $pos, ">");
  1131. return Array(false, false, false, $lt, $gt);
  1132. }
  1133. break;
  1134. }
  1135. }
  1136. /**
  1137. * The fact that we got here indicates that the tag end was never
  1138. * found. Return invalid tag indication so it gets stripped.
  1139. */
  1140. return Array(false, false, false, $lt, strlen($body));
  1141. }
  1142. /**
  1143. * This function checks attribute values for entity-encoded values
  1144. * and returns them translated into 8-bit strings so we can run
  1145. * checks on them.
  1146. *
  1147. * @param $attvalue A string to run entity check against.
  1148. * @return Translated value.
  1149. */
  1150. function sq_deent($attvalue){
  1151. $me = 'sq_deent';
  1152. /**
  1153. * See if we have to run the checks first. All entities must start
  1154. * with "&".
  1155. */
  1156. if (strpos($attvalue, "&") === false){
  1157. return $attvalue;
  1158. }
  1159. /**
  1160. * Check named entities first.
  1161. */
  1162. $trans = get_html_translation_table(HTML_ENTITIES);
  1163. /**
  1164. * Leave &quot; in, as it can mess us up.
  1165. */
  1166. $trans = array_flip($trans);
  1167. unset($trans{"&quot;"});
  1168. while (list($ent, $val) = each($trans)){
  1169. $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
  1170. }
  1171. /**
  1172. * Now translate numbered entities from 1 to 255 if needed.
  1173. */
  1174. if (strpos($attvalue, "#") !== false){
  1175. $omit = Array(34, 39);
  1176. for ($asc=1; $asc<256; $asc++){
  1177. if (!in_array($asc, $omit)){
  1178. $chr = chr($asc);
  1179. $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
  1180. $attvalue);
  1181. $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
  1182. "$chr\\1", $attvalue);
  1183. }
  1184. }
  1185. }
  1186. return $attvalue;
  1187. }
  1188. /**
  1189. * This function runs various checks against the attributes.
  1190. *
  1191. * @param $tagname String with the name of the tag.
  1192. * @param $attary Array with all tag attributes.
  1193. * @param $rm_attnames See description for sq_sanitize
  1194. * @param $bad_attvals See description for sq_sanitize
  1195. * @param $add_attr_to_tag See description for sq_sanitize
  1196. * @param $message message object
  1197. * @param $id message id
  1198. * @return Array with modified attributes.
  1199. */
  1200. function sq_fixatts($tagname,
  1201. $attary,
  1202. $rm_attnames,
  1203. $bad_attvals,
  1204. $add_attr_to_tag,
  1205. $message,
  1206. $id,
  1207. $mailbox
  1208. ){
  1209. $me = 'sq_fixatts';
  1210. while (list($attname, $attvalue) = each($attary)){
  1211. /**
  1212. * See if this attribute should be removed.
  1213. */
  1214. foreach ($rm_attnames as $matchtag=>$matchattrs){
  1215. if (preg_match($matchtag, $tagname)){
  1216. foreach ($matchattrs as $matchattr){
  1217. if (preg_match($matchattr, $attname)){
  1218. unset($attary{$attname});
  1219. continue;
  1220. }
  1221. }
  1222. }
  1223. }
  1224. /**
  1225. * Remove any entities.
  1226. */
  1227. $attvalue = sq_deent($attvalue);
  1228. /**
  1229. * Now let's run checks on the attvalues.
  1230. * I don't expect anyone to comprehend this. If you do,
  1231. * get in touch with me so I can drive to where you live and
  1232. * shake your hand personally. :)
  1233. */
  1234. foreach ($bad_attvals as $matchtag=>$matchattrs){
  1235. if (preg_match($matchtag, $tagname)){
  1236. foreach ($matchattrs as $matchattr=>$valary){
  1237. if (preg_match($matchattr, $attname)){
  1238. /**
  1239. * There are two arrays in valary.
  1240. * First is matches.
  1241. * Second one is replacements
  1242. */
  1243. list($valmatch, $valrepl) = $valary;
  1244. $newvalue =
  1245. preg_replace($valmatch, $valrepl, $attvalue);
  1246. if ($newvalue != $attvalue){
  1247. $attary{$attname} = $newvalue;
  1248. }
  1249. }
  1250. }
  1251. }
  1252. }
  1253. /**
  1254. * Turn cid: urls into http-friendly ones.
  1255. */
  1256. if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
  1257. $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
  1258. }
  1259. }
  1260. /**
  1261. * See if we need to append any attributes to this tag.
  1262. */
  1263. foreach ($add_attr_to_tag as $matchtag=>$addattary){
  1264. if (preg_match($matchtag, $tagname)){
  1265. $attary = array_merge($attary, $addattary);
  1266. }
  1267. }
  1268. return $attary;
  1269. }
  1270. /**
  1271. * This function edits the style definition to make them friendly and
  1272. * usable in squirrelmail.
  1273. *
  1274. * @param $message the message object
  1275. * @param $id the message id
  1276. * @param $content a string with whatever is between <style> and </style>
  1277. * @return a string with edited content.
  1278. */
  1279. function sq_fixstyle($body, $pos, $message, $id){
  1280. global $view_unsafe_images;
  1281. $me = 'sq_fixstyle';
  1282. $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
  1283. if ($ret == FALSE){
  1284. return array(FALSE, strlen($body));
  1285. }
  1286. $newpos = $ret[0] + strlen($ret[2]);
  1287. $content = $ret[1];
  1288. /**
  1289. * First look for general BODY style declaration, which would be
  1290. * like so:
  1291. * body {background: blah-blah}
  1292. * and change it to .bodyclass so we can just assign it to a <div>
  1293. */
  1294. $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
  1295. $secremoveimg = '../images/' . _("sec_remove_eng.png");
  1296. /**
  1297. * Fix url('blah') declarations.
  1298. */
  1299. $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
  1300. "url(\\1$secremoveimg\\2)", $content);
  1301. /**
  1302. * Fix url('https*://.*) declarations but only if $view_unsafe_images
  1303. * is false.
  1304. */
  1305. if (!$view_unsafe_images){
  1306. $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
  1307. "url(\\1$secremoveimg\\2)", $content);
  1308. }
  1309. /**
  1310. * Fix urls that refer to cid:
  1311. */
  1312. while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
  1313. $content, $matches)){
  1314. $cidurl = $matches{1};
  1315. $httpurl = sq_cid2http($message, $id, $cidurl);
  1316. $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
  1317. "url($httpurl)", $content);
  1318. }
  1319. /**
  1320. * Fix stupid css declarations which lead to vulnerabilities
  1321. * in IE.
  1322. */
  1323. $match = Array('/expression/i',
  1324. '/behaviou*r/i',
  1325. '/binding/i');
  1326. $replace = Array('idiocy', 'idiocy', 'idiocy');
  1327. $content = preg_replace($match, $replace, $content);
  1328. return array($content, $newpos);
  1329. }
  1330. /**
  1331. * This function converts cid: url's into the ones that can be viewed in
  1332. * the browser.
  1333. *
  1334. * @param $message the message object
  1335. * @param $id the message id
  1336. * @param $cidurl the cid: url.
  1337. * @return a string with a http-friendly url
  1338. */
  1339. function sq_cid2http($message, $id, $cidurl, $mailbox){
  1340. /**
  1341. * Get rid of quotes.
  1342. */
  1343. $quotchar = substr($cidurl, 0, 1);
  1344. $cidurl = str_replace($quotchar, "", $cidurl);
  1345. $cidurl = substr(trim($cidurl), 4);
  1346. $linkurl = find_ent_id($cidurl, $message);
  1347. /* in case of non-save cid links $httpurl should be replaced by a sort of
  1348. unsave link image */
  1349. $httpurl = '';
  1350. if ($linkurl) {
  1351. $httpurl = $quotchar . SM_PATH . 'src/download.php?absolute_dl=true&amp;' .
  1352. "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
  1353. '&amp;ent_id=' . $linkurl . $quotchar;
  1354. }
  1355. return $httpurl;
  1356. }
  1357. /**
  1358. * This function changes the <body> tag into a <div> tag since we
  1359. * can't really have a body-within-body.
  1360. *
  1361. * @param $attary an array of attributes and values of <body>
  1362. * @return a modified array of attributes to be set for <div>
  1363. */
  1364. function sq_body2div($attary){
  1365. $me = 'sq_body2div';
  1366. $divattary = Array('class' => "'bodyclass'");
  1367. $bgcolor = '#ffffff';
  1368. $text = '#000000';
  1369. $styledef = '';
  1370. if (is_array($attary) && sizeof($attary) > 0){
  1371. foreach ($attary as $attname=>$attvalue){
  1372. $quotchar = substr($attvalue, 0, 1);
  1373. $attvalue = str_replace($quotchar, "", $attvalue);
  1374. switch ($attname){
  1375. case 'background':
  1376. $styledef .= "background-image: url('$attvalue'); ";
  1377. break;
  1378. case 'bgcolor':
  1379. $styledef .= "background-color: $attvalue; ";
  1380. break;
  1381. case 'text':
  1382. $styledef .= "color: $attvalue; ";
  1383. break;
  1384. }
  1385. }
  1386. if (strlen($styledef) > 0){
  1387. $divattary{"style"} = "\"$styledef\"";
  1388. }
  1389. }
  1390. return $divattary;
  1391. }
  1392. /**
  1393. * This is the main function and the one you should actually be calling.
  1394. * There are several variables you should be aware of an which need
  1395. * special description.
  1396. *
  1397. * Since the description is quite lengthy, see it here:
  1398. * http://www.mricon.com/html/phpfilter.html
  1399. *
  1400. * @param $body the string with HTML you wish to filter
  1401. * @param $tag_list see description above
  1402. * @param $rm_tags_with_content see description above
  1403. * @param $self_closing_tags see description above
  1404. * @param $force_tag_closing see description above
  1405. * @param $rm_attnames see description above
  1406. * @param $bad_attvals see description above
  1407. * @param $add_attr_to_tag see description above
  1408. * @param $message message object
  1409. * @param $id message id
  1410. * @return sanitized html safe to show on your pages.
  1411. */
  1412. function sq_sanitize($body,
  1413. $tag_list,
  1414. $rm_tags_with_content,
  1415. $self_closing_tags,
  1416. $force_tag_closing,
  1417. $rm_attnames,
  1418. $bad_attvals,
  1419. $add_attr_to_tag,
  1420. $message,
  1421. $id,
  1422. $mailbox
  1423. ){
  1424. $me = 'sq_sanitize';
  1425. $rm_tags = array_shift($tag_list);
  1426. /**
  1427. * Normalize rm_tags and rm_tags_with_content.
  1428. */
  1429. @array_walk($tag_list, 'sq_casenormalize');
  1430. @array_walk($rm_tags_with_content, 'sq_casenormalize');
  1431. @array_walk($self_closing_tags, 'sq_casenormalize');
  1432. /**
  1433. * See if tag_list is of tags to remove or tags to allow.
  1434. * false means remove these tags
  1435. * true means allow these tags
  1436. */
  1437. $curpos = 0;
  1438. $open_tags = Array();
  1439. $trusted = "<!-- begin sanitized html -->\n";
  1440. $skip_content = false;
  1441. /**
  1442. * Take care of netscape's stupid javascript entities like
  1443. * &{alert('boo')};
  1444. */
  1445. $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
  1446. while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
  1447. list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
  1448. $free_content = substr($body, $curpos, $lt-$curpos);
  1449. /**
  1450. * Take care of <style>
  1451. */
  1452. if ($tagname == "style" && $tagtype == 1){
  1453. list($free_content, $curpos) =
  1454. sq_fixstyle($body, $gt+1, $message, $id);
  1455. if ($free_content != FALSE){
  1456. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1457. $trusted .= $free_content;
  1458. $trusted .= sq_tagprint($tagname, false, 2);
  1459. }
  1460. continue;
  1461. }
  1462. if ($skip_content == false){
  1463. $trusted .= $free_content;
  1464. }
  1465. if ($tagname != FALSE){
  1466. if ($tagtype == 2){
  1467. if ($skip_content == $tagname){
  1468. /**
  1469. * Got to the end of tag we needed to remove.
  1470. */
  1471. $tagname = false;
  1472. $skip_content = false;
  1473. } else {
  1474. if ($skip_content == false){
  1475. if ($tagname == "body"){
  1476. $tagname = "div";
  1477. } else {
  1478. if (isset($open_tags{$tagname}) &&
  1479. $open_tags{$tagname} > 0){
  1480. $open_tags{$tagname}--;
  1481. } else {
  1482. $tagname = false;
  1483. }
  1484. }
  1485. }
  1486. }
  1487. } else {
  1488. /**
  1489. * $rm_tags_with_content
  1490. */
  1491. if ($skip_content == false){
  1492. /**
  1493. * See if this is a self-closing type and change
  1494. * tagtype appropriately.
  1495. */
  1496. if ($tagtype == 1
  1497. && in_array($tagname, $self_closing_tags)){
  1498. $tagtype=3;
  1499. }
  1500. /**
  1501. * See if we should skip this tag and any content
  1502. * inside it.
  1503. */
  1504. if ($tagtype == 1 &&
  1505. in_array($tagname, $rm_tags_with_content)){
  1506. $skip_content = $tagname;
  1507. } else {
  1508. if (($rm_tags == false
  1509. && in_array($tagname, $tag_list)) ||
  1510. ($rm_tags == true &&
  1511. !in_array($tagname, $tag_list))){
  1512. $tagname = false;
  1513. } else {
  1514. if ($tagtype == 1){
  1515. if (isset($open_tags{$tagname})){
  1516. $open_tags{$tagname}++;
  1517. } else {
  1518. $open_tags{$tagname}=1;
  1519. }
  1520. }
  1521. /**
  1522. * This is where we run other checks.
  1523. */
  1524. if (is_array($attary) && sizeof($attary) > 0){
  1525. $attary = sq_fixatts($tagname,
  1526. $attary,
  1527. $rm_attnames,
  1528. $bad_attvals,
  1529. $add_attr_to_tag,
  1530. $message,
  1531. $id,
  1532. $mailbox
  1533. );
  1534. }
  1535. /**
  1536. * Convert body into div.
  1537. */
  1538. if ($tagname == "body"){
  1539. $tagname = "div";
  1540. $attary = sq_body2div($attary, $message, $id);
  1541. }
  1542. }
  1543. }
  1544. }
  1545. }
  1546. if ($tagname != false && $skip_content == false){
  1547. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1548. }
  1549. }
  1550. $curpos = $gt+1;
  1551. }
  1552. $trusted .= substr($body, $curpos, strlen($body)-$curpos);
  1553. if ($force_tag_closing == true){
  1554. foreach ($open_tags as $tagname=>$opentimes){
  1555. while ($opentimes > 0){
  1556. $trusted .= '</' . $tagname . '>';
  1557. $opentimes--;
  1558. }
  1559. }
  1560. $trusted .= "\n";
  1561. }
  1562. $trusted .= "<!-- end sanitized html -->\n";
  1563. return $trusted;
  1564. }
  1565. /**
  1566. * This is a wrapper function to call html sanitizing routines.
  1567. *
  1568. * @param $body the body of the message
  1569. * @param $id the id of the message
  1570. * @return a string with html safe to display in the browser.
  1571. */
  1572. function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
  1573. global $attachment_common_show_images, $view_unsafe_images,
  1574. $has_unsafe_images;
  1575. /**
  1576. * Don't display attached images in HTML mode.
  1577. */
  1578. $attachment_common_show_images = false;
  1579. $tag_list = Array(
  1580. false,
  1581. "object",
  1582. "meta",
  1583. "html",
  1584. "head",
  1585. "base",
  1586. "link",
  1587. "frame",
  1588. "iframe"
  1589. );
  1590. $rm_tags_with_content = Array(
  1591. "script",
  1592. "applet",
  1593. "embed",
  1594. "title"
  1595. );
  1596. $self_closing_tags = Array(
  1597. "img",
  1598. "br",
  1599. "hr",
  1600. "input"
  1601. );
  1602. $force_tag_closing = false;
  1603. $rm_attnames = Array(
  1604. "/.*/" =>
  1605. Array(
  1606. "/target/i",
  1607. "/^on.*/i",
  1608. "/^dynsrc/i",
  1609. "/^data.*/i",
  1610. "/^lowsrc.*/i"
  1611. )
  1612. );
  1613. $secremoveimg = "../images/" . _("sec_remove_eng.png");
  1614. $bad_attvals = Array(
  1615. "/.*/" =>
  1616. Array(
  1617. "/^src|background/i" =>
  1618. Array(
  1619. Array(
  1620. "|^([\'\"])\s*\.\./.*([\'\"])|si",
  1621. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1622. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1623. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1624. ),
  1625. Array(
  1626. "\\1$secremoveimg\\2",
  1627. "\\1$secremoveimg\\2",
  1628. "\\1$secremoveimg\\2",
  1629. "\\1$secremoveimg\\2"
  1630. )
  1631. ),
  1632. "/^href|action/i" =>
  1633. Array(
  1634. Array(
  1635. "|^([\'\"])\s*\.\./.*([\'\"])|si",
  1636. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1637. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1638. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1639. ),
  1640. Array(
  1641. "\\1#\\2",
  1642. "\\1#\\2",
  1643. "\\1#\\2",
  1644. "\\1#\\2"
  1645. )
  1646. ),
  1647. "/^style/i" =>
  1648. Array(
  1649. Array(
  1650. "/expression/i",
  1651. "/binding/i",
  1652. "/behaviou*r/i",
  1653. "|url\s*\(\s*([\'\"])\s*\.\./.*([\'\"])\s*\)|si",
  1654. "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
  1655. "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
  1656. "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si"
  1657. ),
  1658. Array(
  1659. "idiocy",
  1660. "idiocy",
  1661. "idiocy",
  1662. "url(\\1#\\2)",
  1663. "url(\\1#\\2)",
  1664. "url(\\1#\\2)",
  1665. "url(\\1#\\2)"
  1666. )
  1667. )
  1668. )
  1669. );
  1670. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  1671. $view_unsafe_images = false;
  1672. }
  1673. if (!$view_unsafe_images){
  1674. /**
  1675. * Remove any references to http/https if view_unsafe_images set
  1676. * to false.
  1677. */
  1678. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
  1679. '/^([\'\"])\s*https*:.*([\'\"])/si');
  1680. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
  1681. "\\1$secremoveimg\\2");
  1682. array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
  1683. '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
  1684. array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
  1685. "url(\\1$secremoveimg\\2)");
  1686. }
  1687. $add_attr_to_tag = Array(
  1688. "/^a$/i" => Array('target'=>'"_new"')
  1689. );
  1690. $trusted = sq_sanitize($body,
  1691. $tag_list,
  1692. $rm_tags_with_content,
  1693. $self_closing_tags,
  1694. $force_tag_closing,
  1695. $rm_attnames,
  1696. $bad_attvals,
  1697. $add_attr_to_tag,
  1698. $message,
  1699. $id,
  1700. $mailbox
  1701. );
  1702. if (preg_match("|$secremoveimg|i", $trusted)){
  1703. $has_unsafe_images = true;
  1704. }
  1705. return $trusted;
  1706. }
  1707. ?>