mime.php 62 KB

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