mime.php 63 KB

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