mime.php 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  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. if ($chunk{0} === '=') { /* performance, saves an unnessecarry preg call */
  513. while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  514. /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
  515. if ($iLastMatch !== $j) {
  516. if ($htmlsave) {
  517. $ret .= '&nbsp;';
  518. } else {
  519. $ret .= ' ';
  520. }
  521. }
  522. $iLastMatch = $i;
  523. $j = $i;
  524. $ret .= $res[1];
  525. $encoding = ucfirst($res[3]);
  526. switch ($encoding)
  527. {
  528. case 'B':
  529. $replace = base64_decode($res[4]);
  530. $ret .= charset_decode($res[2],$replace);
  531. break;
  532. case 'Q':
  533. $replace = str_replace('_', ' ', $res[4]);
  534. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  535. $replace);
  536. /* Only encode into entities by default. Some places
  537. * don't need the encoding, like the compose form.
  538. */
  539. if ($utfencode) {
  540. $replace = charset_decode($res[2], $replace);
  541. } else {
  542. if ($htmlsave) {
  543. $replace = htmlspecialchars($replace);
  544. }
  545. }
  546. $ret .= $replace;
  547. break;
  548. default:
  549. break;
  550. }
  551. $chunk = $res[5];
  552. $encoded = true;
  553. }
  554. }
  555. if (!$encoded) {
  556. if ($htmlsave) {
  557. $ret .= '&nbsp;';
  558. } else {
  559. $ret .= ' ';
  560. }
  561. }
  562. if (!$encoded && $htmlsave) {
  563. $ret .= htmlspecialchars($chunk);
  564. } else {
  565. $ret .= $chunk;
  566. }
  567. ++$i;
  568. }
  569. /* remove the first added space */
  570. if ($ret) {
  571. if ($htmlsave) {
  572. $ret = substr($ret,6);
  573. } else {
  574. $ret = substr($ret,1);
  575. }
  576. }
  577. return $ret;
  578. }
  579. /*
  580. * Encode a string according to RFC 1522 for use in headers if it
  581. * contains 8-bit characters or anything that looks like it should
  582. * be encoded.
  583. */
  584. function encodeHeader ($string) {
  585. global $default_charset, $languages, $squirrelmail_language;
  586. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  587. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  588. return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
  589. }
  590. if (strtolower($default_charset) == 'iso-8859-1') {
  591. $string = str_replace("\240",' ',$string);
  592. }
  593. // Encode only if the string contains 8-bit characters or =?
  594. $j = strlen($string);
  595. $max_l = 75 - strlen($default_charset) - 7;
  596. $aRet = array();
  597. $ret = '';
  598. $iEncStart = $enc_init = false;
  599. $cur_l = $iOffset = 0;
  600. for($i = 0; $i < $j; ++$i) {
  601. switch($string{$i})
  602. {
  603. case '=':
  604. case '<':
  605. case '>':
  606. case ',':
  607. case '?':
  608. case '_':
  609. if ($iEncStart === false) {
  610. $iEncStart = $i;
  611. }
  612. $cur_l+=3;
  613. if ($cur_l > ($max_l-2)) {
  614. /* if there is an stringpart that doesn't need encoding, add it */
  615. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  616. $aRet[] = "=?$default_charset?Q?$ret?=";
  617. $iOffset = $i;
  618. $cur_l = 0;
  619. $ret = '';
  620. $iEncStart = false;
  621. } else {
  622. $ret .= sprintf("=%02X",ord($string{$i}));
  623. }
  624. break;
  625. case '(':
  626. case ')':
  627. if ($iEncStart !== false) {
  628. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  629. $aRet[] = "=?$default_charset?Q?$ret?=";
  630. $iOffset = $i;
  631. $cur_l = 0;
  632. $ret = '';
  633. $iEncStart = false;
  634. }
  635. break;
  636. case ' ':
  637. if ($iEncStart !== false) {
  638. $cur_l++;
  639. if ($cur_l > $max_l) {
  640. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  641. $aRet[] = "=?$default_charset?Q?$ret?=";
  642. $iOffset = $i;
  643. $cur_l = 0;
  644. $ret = '';
  645. $iEncStart = false;
  646. } else {
  647. $ret .= '_';
  648. }
  649. }
  650. break;
  651. default:
  652. $k = ord($string{$i});
  653. if ($k > 126) {
  654. if ($iEncStart === false) {
  655. $iEncStart = $i;
  656. }
  657. $cur_l += 3;
  658. /* first we add the encoded string that reached it's max size */
  659. if ($cur_l > ($max_l-2)) {
  660. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  661. $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
  662. $cur_l = 3;
  663. $ret = '';
  664. $iOffset = $i;
  665. $iEncStart = $i;
  666. }
  667. $enc_init = true;
  668. $ret .= sprintf("=%02X", $k);
  669. } else {
  670. if ($iEncStart !== false) {
  671. $cur_l++;
  672. if ($cur_l > $max_l) {
  673. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  674. $aRet[] = "=?$default_charset?Q?$ret?=";
  675. $iEncStart = false;
  676. $iOffset = $i;
  677. $cur_l = 0;
  678. $ret = '';
  679. } else {
  680. $ret .= $string{$i};
  681. }
  682. }
  683. }
  684. break;
  685. }
  686. }
  687. if ($enc_init) {
  688. if ($iEncStart !== false) {
  689. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  690. $aRet[] = "=?$default_charset?Q?$ret?=";
  691. } else {
  692. $aRet[] = substr($string,$iOffset);
  693. }
  694. $string = implode('',$aRet);
  695. }
  696. return $string;
  697. }
  698. /* This function trys to locate the entity_id of a specific mime element */
  699. function find_ent_id($id, $message) {
  700. for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
  701. if ($message->entities[$i]->header->type0 == 'multipart') {
  702. $ret = find_ent_id($id, $message->entities[$i]);
  703. } else {
  704. if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
  705. // if (sq_check_save_extension($message->entities[$i])) {
  706. return $message->entities[$i]->entity_id;
  707. // }
  708. }
  709. }
  710. }
  711. return $ret;
  712. }
  713. function sq_check_save_extension($message) {
  714. $filename = $message->getFilename();
  715. $ext = substr($filename, strrpos($filename,'.')+1);
  716. $save_extensions = array('jpg','jpeg','gif','png','bmp');
  717. return in_array($ext, $save_extensions);
  718. }
  719. /**
  720. ** HTMLFILTER ROUTINES
  721. */
  722. /**
  723. * This function returns the final tag out of the tag name, an array
  724. * of attributes, and the type of the tag. This function is called by
  725. * sq_sanitize internally.
  726. *
  727. * @param $tagname the name of the tag.
  728. * @param $attary the array of attributes and their values
  729. * @param $tagtype The type of the tag (see in comments).
  730. * @return a string with the final tag representation.
  731. */
  732. function sq_tagprint($tagname, $attary, $tagtype){
  733. $me = 'sq_tagprint';
  734. if ($tagtype == 2){
  735. $fulltag = '</' . $tagname . '>';
  736. } else {
  737. $fulltag = '<' . $tagname;
  738. if (is_array($attary) && sizeof($attary)){
  739. $atts = Array();
  740. while (list($attname, $attvalue) = each($attary)){
  741. array_push($atts, "$attname=$attvalue");
  742. }
  743. $fulltag .= ' ' . join(" ", $atts);
  744. }
  745. if ($tagtype == 3){
  746. $fulltag .= ' /';
  747. }
  748. $fulltag .= '>';
  749. }
  750. return $fulltag;
  751. }
  752. /**
  753. * A small helper function to use with array_walk. Modifies a by-ref
  754. * value and makes it lowercase.
  755. *
  756. * @param $val a value passed by-ref.
  757. * @return void since it modifies a by-ref value.
  758. */
  759. function sq_casenormalize(&$val){
  760. $val = strtolower($val);
  761. }
  762. /**
  763. * This function skips any whitespace from the current position within
  764. * a string and to the next non-whitespace value.
  765. *
  766. * @param $body the string
  767. * @param $offset the offset within the string where we should start
  768. * looking for the next non-whitespace character.
  769. * @return the location within the $body where the next
  770. * non-whitespace char is located.
  771. */
  772. function sq_skipspace($body, $offset){
  773. $me = 'sq_skipspace';
  774. preg_match('/^(\s*)/s', substr($body, $offset), $matches);
  775. if (sizeof($matches{1})){
  776. $count = strlen($matches{1});
  777. $offset += $count;
  778. }
  779. return $offset;
  780. }
  781. /**
  782. * This function looks for the next character within a string. It's
  783. * really just a glorified "strpos", except it catches if failures
  784. * nicely.
  785. *
  786. * @param $body The string to look for needle in.
  787. * @param $offset Start looking from this position.
  788. * @param $needle The character/string to look for.
  789. * @return location of the next occurance of the needle, or
  790. * strlen($body) if needle wasn't found.
  791. */
  792. function sq_findnxstr($body, $offset, $needle){
  793. $me = 'sq_findnxstr';
  794. $pos = strpos($body, $needle, $offset);
  795. if ($pos === FALSE){
  796. $pos = strlen($body);
  797. }
  798. return $pos;
  799. }
  800. /**
  801. * This function takes a PCRE-style regexp and tries to match it
  802. * within the string.
  803. *
  804. * @param $body The string to look for needle in.
  805. * @param $offset Start looking from here.
  806. * @param $reg A PCRE-style regex to match.
  807. * @return Returns a false if no matches found, or an array
  808. * with the following members:
  809. * - integer with the location of the match within $body
  810. * - string with whatever content between offset and the match
  811. * - string with whatever it is we matched
  812. */
  813. function sq_findnxreg($body, $offset, $reg){
  814. $me = 'sq_findnxreg';
  815. $matches = Array();
  816. $retarr = Array();
  817. preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
  818. if (!$matches{0}){
  819. $retarr = false;
  820. } else {
  821. $retarr{0} = $offset + strlen($matches{1});
  822. $retarr{1} = $matches{1};
  823. $retarr{2} = $matches{2};
  824. }
  825. return $retarr;
  826. }
  827. /**
  828. * This function looks for the next tag.
  829. *
  830. * @param $body String where to look for the next tag.
  831. * @param $offset Start looking from here.
  832. * @return false if no more tags exist in the body, or
  833. * an array with the following members:
  834. * - string with the name of the tag
  835. * - array with attributes and their values
  836. * - integer with tag type (1, 2, or 3)
  837. * - integer where the tag starts (starting "<")
  838. * - integer where the tag ends (ending ">")
  839. * first three members will be false, if the tag is invalid.
  840. */
  841. function sq_getnxtag($body, $offset){
  842. $me = 'sq_getnxtag';
  843. if ($offset > strlen($body)){
  844. return false;
  845. }
  846. $lt = sq_findnxstr($body, $offset, "<");
  847. if ($lt == strlen($body)){
  848. return false;
  849. }
  850. /**
  851. * We are here:
  852. * blah blah <tag attribute="value">
  853. * \---------^
  854. */
  855. $pos = sq_skipspace($body, $lt+1);
  856. if ($pos >= strlen($body)){
  857. return Array(false, false, false, $lt, strlen($body));
  858. }
  859. /**
  860. * There are 3 kinds of tags:
  861. * 1. Opening tag, e.g.:
  862. * <a href="blah">
  863. * 2. Closing tag, e.g.:
  864. * </a>
  865. * 3. XHTML-style content-less tag, e.g.:
  866. * <img src="blah"/>
  867. */
  868. $tagtype = false;
  869. switch (substr($body, $pos, 1)){
  870. case '/':
  871. $tagtype = 2;
  872. $pos++;
  873. break;
  874. case '!':
  875. /**
  876. * A comment or an SGML declaration.
  877. */
  878. if (substr($body, $pos+1, 2) == "--"){
  879. $gt = strpos($body, "-->", $pos);
  880. if ($gt === false){
  881. $gt = strlen($body);
  882. } else {
  883. $gt += 2;
  884. }
  885. return Array(false, false, false, $lt, $gt);
  886. } else {
  887. $gt = sq_findnxstr($body, $pos, ">");
  888. return Array(false, false, false, $lt, $gt);
  889. }
  890. break;
  891. default:
  892. /**
  893. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  894. * later.
  895. */
  896. $tagtype = 1;
  897. break;
  898. }
  899. $tag_start = $pos;
  900. $tagname = '';
  901. /**
  902. * Look for next [\W-_], which will indicate the end of the tag name.
  903. */
  904. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  905. if ($regary == false){
  906. return Array(false, false, false, $lt, strlen($body));
  907. }
  908. list($pos, $tagname, $match) = $regary;
  909. $tagname = strtolower($tagname);
  910. /**
  911. * $match can be either of these:
  912. * '>' indicating the end of the tag entirely.
  913. * '\s' indicating the end of the tag name.
  914. * '/' indicating that this is type-3 xhtml tag.
  915. *
  916. * Whatever else we find there indicates an invalid tag.
  917. */
  918. switch ($match){
  919. case '/':
  920. /**
  921. * This is an xhtml-style tag with a closing / at the
  922. * end, like so: <img src="blah"/>. Check if it's followed
  923. * by the closing bracket. If not, then this tag is invalid
  924. */
  925. if (substr($body, $pos, 2) == "/>"){
  926. $pos++;
  927. $tagtype = 3;
  928. } else {
  929. $gt = sq_findnxstr($body, $pos, ">");
  930. $retary = Array(false, false, false, $lt, $gt);
  931. return $retary;
  932. }
  933. case '>':
  934. return Array($tagname, false, $tagtype, $lt, $pos);
  935. break;
  936. default:
  937. /**
  938. * Check if it's whitespace
  939. */
  940. if (!preg_match('/\s/', $match)){
  941. /**
  942. * This is an invalid tag! Look for the next closing ">".
  943. */
  944. $gt = sq_findnxstr($body, $offset, ">");
  945. return Array(false, false, false, $lt, $gt);
  946. }
  947. break;
  948. }
  949. /**
  950. * At this point we're here:
  951. * <tagname attribute='blah'>
  952. * \-------^
  953. *
  954. * At this point we loop in order to find all attributes.
  955. */
  956. $attname = '';
  957. $atttype = false;
  958. $attary = Array();
  959. while ($pos <= strlen($body)){
  960. $pos = sq_skipspace($body, $pos);
  961. if ($pos == strlen($body)){
  962. /**
  963. * Non-closed tag.
  964. */
  965. return Array(false, false, false, $lt, $pos);
  966. }
  967. /**
  968. * See if we arrived at a ">" or "/>", which means that we reached
  969. * the end of the tag.
  970. */
  971. $matches = Array();
  972. if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
  973. /**
  974. * Yep. So we did.
  975. */
  976. $pos += strlen($matches{1});
  977. if ($matches{2} == "/>"){
  978. $tagtype = 3;
  979. $pos++;
  980. }
  981. return Array($tagname, $attary, $tagtype, $lt, $pos);
  982. }
  983. /**
  984. * There are several types of attributes, with optional
  985. * [:space:] between members.
  986. * Type 1:
  987. * attrname[:space:]=[:space:]'CDATA'
  988. * Type 2:
  989. * attrname[:space:]=[:space:]"CDATA"
  990. * Type 3:
  991. * attr[:space:]=[:space:]CDATA
  992. * Type 4:
  993. * attrname
  994. *
  995. * We leave types 1 and 2 the same, type 3 we check for
  996. * '"' and convert to "&quot" if needed, then wrap in
  997. * double quotes. Type 4 we convert into:
  998. * attrname="yes".
  999. */
  1000. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  1001. if ($regary == false){
  1002. /**
  1003. * Looks like body ended before the end of tag.
  1004. */
  1005. return Array(false, false, false, $lt, strlen($body));
  1006. }
  1007. list($pos, $attname, $match) = $regary;
  1008. $attname = strtolower($attname);
  1009. /**
  1010. * We arrived at the end of attribute name. Several things possible
  1011. * here:
  1012. * '>' means the end of the tag and this is attribute type 4
  1013. * '/' if followed by '>' means the same thing as above
  1014. * '\s' means a lot of things -- look what it's followed by.
  1015. * anything else means the attribute is invalid.
  1016. */
  1017. switch($match){
  1018. case '/':
  1019. /**
  1020. * This is an xhtml-style tag with a closing / at the
  1021. * end, like so: <img src="blah"/>. Check if it's followed
  1022. * by the closing bracket. If not, then this tag is invalid
  1023. */
  1024. if (substr($body, $pos, 2) == "/>"){
  1025. $pos++;
  1026. $tagtype = 3;
  1027. } else {
  1028. $gt = sq_findnxstr($body, $pos, ">");
  1029. $retary = Array(false, false, false, $lt, $gt);
  1030. return $retary;
  1031. }
  1032. case '>':
  1033. $attary{$attname} = '"yes"';
  1034. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1035. break;
  1036. default:
  1037. /**
  1038. * Skip whitespace and see what we arrive at.
  1039. */
  1040. $pos = sq_skipspace($body, $pos);
  1041. $char = substr($body, $pos, 1);
  1042. /**
  1043. * Two things are valid here:
  1044. * '=' means this is attribute type 1 2 or 3.
  1045. * \w means this was attribute type 4.
  1046. * anything else we ignore and re-loop. End of tag and
  1047. * invalid stuff will be caught by our checks at the beginning
  1048. * of the loop.
  1049. */
  1050. if ($char == "="){
  1051. $pos++;
  1052. $pos = sq_skipspace($body, $pos);
  1053. /**
  1054. * Here are 3 possibilities:
  1055. * "'" attribute type 1
  1056. * '"' attribute type 2
  1057. * everything else is the content of tag type 3
  1058. */
  1059. $quot = substr($body, $pos, 1);
  1060. if ($quot == "'"){
  1061. $regary = sq_findnxreg($body, $pos+1, "\'");
  1062. if ($regary == false){
  1063. return Array(false, false, false, $lt, strlen($body));
  1064. }
  1065. list($pos, $attval, $match) = $regary;
  1066. $pos++;
  1067. $attary{$attname} = "'" . $attval . "'";
  1068. } else if ($quot == '"'){
  1069. $regary = sq_findnxreg($body, $pos+1, '\"');
  1070. if ($regary == false){
  1071. return Array(false, false, false, $lt, strlen($body));
  1072. }
  1073. list($pos, $attval, $match) = $regary;
  1074. $pos++;
  1075. $attary{$attname} = '"' . $attval . '"';
  1076. } else {
  1077. /**
  1078. * These are hateful. Look for \s, or >.
  1079. */
  1080. $regary = sq_findnxreg($body, $pos, "[\s>]");
  1081. if ($regary == false){
  1082. return Array(false, false, false, $lt, strlen($body));
  1083. }
  1084. list($pos, $attval, $match) = $regary;
  1085. /**
  1086. * If it's ">" it will be caught at the top.
  1087. */
  1088. $attval = preg_replace("/\"/s", "&quot;", $attval);
  1089. $attary{$attname} = '"' . $attval . '"';
  1090. }
  1091. } else if (preg_match("|[\w/>]|", $char)) {
  1092. /**
  1093. * That was attribute type 4.
  1094. */
  1095. $attary{$attname} = '"yes"';
  1096. } else {
  1097. /**
  1098. * An illegal character. Find next '>' and return.
  1099. */
  1100. $gt = sq_findnxstr($body, $pos, ">");
  1101. return Array(false, false, false, $lt, $gt);
  1102. }
  1103. break;
  1104. }
  1105. }
  1106. /**
  1107. * The fact that we got here indicates that the tag end was never
  1108. * found. Return invalid tag indication so it gets stripped.
  1109. */
  1110. return Array(false, false, false, $lt, strlen($body));
  1111. }
  1112. /**
  1113. * This function checks attribute values for entity-encoded values
  1114. * and returns them translated into 8-bit strings so we can run
  1115. * checks on them.
  1116. *
  1117. * @param $attvalue A string to run entity check against.
  1118. * @return Translated value.
  1119. */
  1120. function sq_deent($attvalue){
  1121. $me = 'sq_deent';
  1122. /**
  1123. * See if we have to run the checks first. All entities must start
  1124. * with "&".
  1125. */
  1126. if (strpos($attvalue, "&") === false){
  1127. return $attvalue;
  1128. }
  1129. /**
  1130. * Check named entities first.
  1131. */
  1132. $trans = get_html_translation_table(HTML_ENTITIES);
  1133. /**
  1134. * Leave &quot; in, as it can mess us up.
  1135. */
  1136. $trans = array_flip($trans);
  1137. unset($trans{"&quot;"});
  1138. while (list($ent, $val) = each($trans)){
  1139. $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
  1140. }
  1141. /**
  1142. * Now translate numbered entities from 1 to 255 if needed.
  1143. */
  1144. if (strpos($attvalue, "#") !== false){
  1145. $omit = Array(34, 39);
  1146. for ($asc=1; $asc<256; $asc++){
  1147. if (!in_array($asc, $omit)){
  1148. $chr = chr($asc);
  1149. $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
  1150. $attvalue);
  1151. $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
  1152. "$chr\\1", $attvalue);
  1153. }
  1154. }
  1155. }
  1156. return $attvalue;
  1157. }
  1158. /**
  1159. * This function runs various checks against the attributes.
  1160. *
  1161. * @param $tagname String with the name of the tag.
  1162. * @param $attary Array with all tag attributes.
  1163. * @param $rm_attnames See description for sq_sanitize
  1164. * @param $bad_attvals See description for sq_sanitize
  1165. * @param $add_attr_to_tag See description for sq_sanitize
  1166. * @param $message message object
  1167. * @param $id message id
  1168. * @return Array with modified attributes.
  1169. */
  1170. function sq_fixatts($tagname,
  1171. $attary,
  1172. $rm_attnames,
  1173. $bad_attvals,
  1174. $add_attr_to_tag,
  1175. $message,
  1176. $id,
  1177. $mailbox
  1178. ){
  1179. $me = 'sq_fixatts';
  1180. while (list($attname, $attvalue) = each($attary)){
  1181. /**
  1182. * See if this attribute should be removed.
  1183. */
  1184. foreach ($rm_attnames as $matchtag=>$matchattrs){
  1185. if (preg_match($matchtag, $tagname)){
  1186. foreach ($matchattrs as $matchattr){
  1187. if (preg_match($matchattr, $attname)){
  1188. unset($attary{$attname});
  1189. continue;
  1190. }
  1191. }
  1192. }
  1193. }
  1194. /**
  1195. * Remove any entities.
  1196. */
  1197. $attvalue = sq_deent($attvalue);
  1198. /**
  1199. * Now let's run checks on the attvalues.
  1200. * I don't expect anyone to comprehend this. If you do,
  1201. * get in touch with me so I can drive to where you live and
  1202. * shake your hand personally. :)
  1203. */
  1204. foreach ($bad_attvals as $matchtag=>$matchattrs){
  1205. if (preg_match($matchtag, $tagname)){
  1206. foreach ($matchattrs as $matchattr=>$valary){
  1207. if (preg_match($matchattr, $attname)){
  1208. /**
  1209. * There are two arrays in valary.
  1210. * First is matches.
  1211. * Second one is replacements
  1212. */
  1213. list($valmatch, $valrepl) = $valary;
  1214. $newvalue =
  1215. preg_replace($valmatch, $valrepl, $attvalue);
  1216. if ($newvalue != $attvalue){
  1217. $attary{$attname} = $newvalue;
  1218. }
  1219. }
  1220. }
  1221. }
  1222. }
  1223. /**
  1224. * Turn cid: urls into http-friendly ones.
  1225. */
  1226. if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
  1227. $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
  1228. }
  1229. }
  1230. /**
  1231. * See if we need to append any attributes to this tag.
  1232. */
  1233. foreach ($add_attr_to_tag as $matchtag=>$addattary){
  1234. if (preg_match($matchtag, $tagname)){
  1235. $attary = array_merge($attary, $addattary);
  1236. }
  1237. }
  1238. return $attary;
  1239. }
  1240. /**
  1241. * This function edits the style definition to make them friendly and
  1242. * usable in squirrelmail.
  1243. *
  1244. * @param $message the message object
  1245. * @param $id the message id
  1246. * @param $content a string with whatever is between <style> and </style>
  1247. * @return a string with edited content.
  1248. */
  1249. function sq_fixstyle($message, $id, $content){
  1250. global $view_unsafe_images;
  1251. $me = 'sq_fixstyle';
  1252. /**
  1253. * First look for general BODY style declaration, which would be
  1254. * like so:
  1255. * body {background: blah-blah}
  1256. * and change it to .bodyclass so we can just assign it to a <div>
  1257. */
  1258. $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
  1259. $secremoveimg = '../images/' . _("sec_remove_eng.png");
  1260. /**
  1261. * Fix url('blah') declarations.
  1262. */
  1263. $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
  1264. "url(\\1$secremoveimg\\2)", $content);
  1265. /**
  1266. * Fix url('https*://.*) declarations but only if $view_unsafe_images
  1267. * is false.
  1268. */
  1269. if (!$view_unsafe_images){
  1270. $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
  1271. "url(\\1$secremoveimg\\2)", $content);
  1272. }
  1273. /**
  1274. * Fix urls that refer to cid:
  1275. */
  1276. while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
  1277. $matches)){
  1278. $cidurl = $matches{1};
  1279. $httpurl = sq_cid2http($message, $id, $cidurl);
  1280. $content = preg_replace("|url\($cidurl\)|si",
  1281. "url($httpurl)", $content);
  1282. }
  1283. /**
  1284. * Fix stupid css declarations which lead to vulnerabilities
  1285. * in IE.
  1286. */
  1287. $match = Array('/expression/i',
  1288. '/behaviou*r/i',
  1289. '/binding/i');
  1290. $replace = Array('idiocy', 'idiocy', 'idiocy');
  1291. $content = preg_replace($match, $replace, $content);
  1292. return $content;
  1293. }
  1294. /**
  1295. * This function converts cid: url's into the ones that can be viewed in
  1296. * the browser.
  1297. *
  1298. * @param $message the message object
  1299. * @param $id the message id
  1300. * @param $cidurl the cid: url.
  1301. * @return a string with a http-friendly url
  1302. */
  1303. function sq_cid2http($message, $id, $cidurl, $mailbox){
  1304. /**
  1305. * Get rid of quotes.
  1306. */
  1307. $quotchar = substr($cidurl, 0, 1);
  1308. $cidurl = str_replace($quotchar, "", $cidurl);
  1309. $cidurl = substr(trim($cidurl), 4);
  1310. $linkurl = find_ent_id($cidurl, $message);
  1311. /* in case of non-save cid links $httpurl should be replaced by a sort of
  1312. unsave link image */
  1313. $httpurl = '';
  1314. if ($linkurl) {
  1315. $httpurl = $quotchar . SM_PATH . 'src/download.php?absolute_dl=true&amp;' .
  1316. "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
  1317. '&amp;ent_id=' . $linkurl . $quotchar;
  1318. }
  1319. return $httpurl;
  1320. }
  1321. /**
  1322. * This function changes the <body> tag into a <div> tag since we
  1323. * can't really have a body-within-body.
  1324. *
  1325. * @param $attary an array of attributes and values of <body>
  1326. * @return a modified array of attributes to be set for <div>
  1327. */
  1328. function sq_body2div($attary){
  1329. $me = 'sq_body2div';
  1330. $divattary = Array('class' => "'bodyclass'");
  1331. $bgcolor = '#ffffff';
  1332. $text = '#000000';
  1333. $styledef = '';
  1334. if (is_array($attary) && sizeof($attary) > 0){
  1335. foreach ($attary as $attname=>$attvalue){
  1336. $quotchar = substr($attvalue, 0, 1);
  1337. $attvalue = str_replace($quotchar, "", $attvalue);
  1338. switch ($attname){
  1339. case 'background':
  1340. $styledef .= "background-image: url('$attvalue'); ";
  1341. break;
  1342. case 'bgcolor':
  1343. $styledef .= "background-color: $attvalue; ";
  1344. break;
  1345. case 'text':
  1346. $styledef .= "color: $attvalue; ";
  1347. break;
  1348. }
  1349. }
  1350. if (strlen($styledef) > 0){
  1351. $divattary{"style"} = "\"$styledef\"";
  1352. }
  1353. }
  1354. return $divattary;
  1355. }
  1356. /**
  1357. * This is the main function and the one you should actually be calling.
  1358. * There are several variables you should be aware of an which need
  1359. * special description.
  1360. *
  1361. * Since the description is quite lengthy, see it here:
  1362. * http://www.mricon.com/html/phpfilter.html
  1363. *
  1364. * @param $body the string with HTML you wish to filter
  1365. * @param $tag_list see description above
  1366. * @param $rm_tags_with_content see description above
  1367. * @param $self_closing_tags see description above
  1368. * @param $force_tag_closing see description above
  1369. * @param $rm_attnames see description above
  1370. * @param $bad_attvals see description above
  1371. * @param $add_attr_to_tag see description above
  1372. * @param $message message object
  1373. * @param $id message id
  1374. * @return sanitized html safe to show on your pages.
  1375. */
  1376. function sq_sanitize($body,
  1377. $tag_list,
  1378. $rm_tags_with_content,
  1379. $self_closing_tags,
  1380. $force_tag_closing,
  1381. $rm_attnames,
  1382. $bad_attvals,
  1383. $add_attr_to_tag,
  1384. $message,
  1385. $id,
  1386. $mailbox
  1387. ){
  1388. $me = 'sq_sanitize';
  1389. /**
  1390. * Normalize rm_tags and rm_tags_with_content.
  1391. */
  1392. @array_walk($rm_tags, 'sq_casenormalize');
  1393. @array_walk($rm_tags_with_content, 'sq_casenormalize');
  1394. @array_walk($self_closing_tags, 'sq_casenormalize');
  1395. /**
  1396. * See if tag_list is of tags to remove or tags to allow.
  1397. * false means remove these tags
  1398. * true means allow these tags
  1399. */
  1400. $rm_tags = array_shift($tag_list);
  1401. $curpos = 0;
  1402. $open_tags = Array();
  1403. $trusted = "<!-- begin sanitized html -->\n";
  1404. $skip_content = false;
  1405. /**
  1406. * Take care of netscape's stupid javascript entities like
  1407. * &{alert('boo')};
  1408. */
  1409. $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
  1410. while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
  1411. list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
  1412. $free_content = substr($body, $curpos, $lt-$curpos);
  1413. /**
  1414. * Take care of <style>
  1415. */
  1416. if ($tagname == "style" && $tagtype == 2){
  1417. /**
  1418. * This is a closing </style>. Edit the
  1419. * content before we apply it.
  1420. */
  1421. $free_content = sq_fixstyle($message, $id, $free_content);
  1422. }
  1423. if ($skip_content == false){
  1424. $trusted .= $free_content;
  1425. }
  1426. if ($tagname != FALSE){
  1427. if ($tagtype == 2){
  1428. if ($skip_content == $tagname){
  1429. /**
  1430. * Got to the end of tag we needed to remove.
  1431. */
  1432. $tagname = false;
  1433. $skip_content = false;
  1434. } else {
  1435. if ($skip_content == false){
  1436. if ($tagname == "body"){
  1437. $tagname = "div";
  1438. } else {
  1439. if (isset($open_tags{$tagname}) &&
  1440. $open_tags{$tagname} > 0){
  1441. $open_tags{$tagname}--;
  1442. } else {
  1443. $tagname = false;
  1444. }
  1445. }
  1446. }
  1447. }
  1448. } else {
  1449. /**
  1450. * $rm_tags_with_content
  1451. */
  1452. if ($skip_content == false){
  1453. /**
  1454. * See if this is a self-closing type and change
  1455. * tagtype appropriately.
  1456. */
  1457. if ($tagtype == 1
  1458. && in_array($tagname, $self_closing_tags)){
  1459. $tagtype=3;
  1460. }
  1461. /**
  1462. * See if we should skip this tag and any content
  1463. * inside it.
  1464. */
  1465. if ($tagtype == 1 &&
  1466. in_array($tagname, $rm_tags_with_content)){
  1467. $skip_content = $tagname;
  1468. } else {
  1469. if (($rm_tags == false
  1470. && in_array($tagname, $tag_list)) ||
  1471. ($rm_tags == true &&
  1472. !in_array($tagname, $tag_list))){
  1473. $tagname = false;
  1474. } else {
  1475. if ($tagtype == 1){
  1476. if (isset($open_tags{$tagname})){
  1477. $open_tags{$tagname}++;
  1478. } else {
  1479. $open_tags{$tagname}=1;
  1480. }
  1481. }
  1482. /**
  1483. * This is where we run other checks.
  1484. */
  1485. if (is_array($attary) && sizeof($attary) > 0){
  1486. $attary = sq_fixatts($tagname,
  1487. $attary,
  1488. $rm_attnames,
  1489. $bad_attvals,
  1490. $add_attr_to_tag,
  1491. $message,
  1492. $id,
  1493. $mailbox
  1494. );
  1495. }
  1496. /**
  1497. * Convert body into div.
  1498. */
  1499. if ($tagname == "body"){
  1500. $tagname = "div";
  1501. $attary = sq_body2div($attary, $message, $id);
  1502. }
  1503. }
  1504. }
  1505. }
  1506. }
  1507. if ($tagname != false && $skip_content == false){
  1508. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1509. }
  1510. }
  1511. $curpos = $gt+1;
  1512. }
  1513. $trusted .= substr($body, $curpos, strlen($body)-$curpos);
  1514. if ($force_tag_closing == true){
  1515. foreach ($open_tags as $tagname=>$opentimes){
  1516. while ($opentimes > 0){
  1517. $trusted .= '</' . $tagname . '>';
  1518. $opentimes--;
  1519. }
  1520. }
  1521. $trusted .= "\n";
  1522. }
  1523. $trusted .= "<!-- end sanitized html -->\n";
  1524. return $trusted;
  1525. }
  1526. /**
  1527. * This is a wrapper function to call html sanitizing routines.
  1528. *
  1529. * @param $body the body of the message
  1530. * @param $id the id of the message
  1531. * @return a string with html safe to display in the browser.
  1532. */
  1533. function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
  1534. global $attachment_common_show_images, $view_unsafe_images,
  1535. $has_unsafe_images;
  1536. /**
  1537. * Don't display attached images in HTML mode.
  1538. */
  1539. $attachment_common_show_images = false;
  1540. $tag_list = Array(
  1541. false,
  1542. "object",
  1543. "meta",
  1544. "html",
  1545. "head",
  1546. "base",
  1547. "link",
  1548. "frame",
  1549. "iframe"
  1550. );
  1551. $rm_tags_with_content = Array(
  1552. "script",
  1553. "applet",
  1554. "embed",
  1555. "title"
  1556. );
  1557. $self_closing_tags = Array(
  1558. "img",
  1559. "br",
  1560. "hr",
  1561. "input"
  1562. );
  1563. $force_tag_closing = false;
  1564. $rm_attnames = Array(
  1565. "/.*/" =>
  1566. Array(
  1567. "/target/i",
  1568. "/^on.*/i",
  1569. "/^dynsrc/i",
  1570. "/^data.*/i",
  1571. "/^lowsrc.*/i"
  1572. )
  1573. );
  1574. $secremoveimg = "../images/" . _("sec_remove_eng.png");
  1575. $bad_attvals = Array(
  1576. "/.*/" =>
  1577. Array(
  1578. "/^src|background/i" =>
  1579. Array(
  1580. Array(
  1581. "|^([\'\"])\s*\.\./.*([\'\"])|si",
  1582. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1583. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1584. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1585. ),
  1586. Array(
  1587. "\\1$secremoveimg\\2",
  1588. "\\1$secremoveimg\\2",
  1589. "\\1$secremoveimg\\2",
  1590. "\\1$secremoveimg\\2"
  1591. )
  1592. ),
  1593. "/^href|action/i" =>
  1594. Array(
  1595. Array(
  1596. "|^([\'\"])\s*\.\./.*([\'\"])|si",
  1597. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1598. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1599. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1600. ),
  1601. Array(
  1602. "\\1#\\2",
  1603. "\\1#\\2",
  1604. "\\1#\\2",
  1605. "\\1#\\2"
  1606. )
  1607. ),
  1608. "/^style/i" =>
  1609. Array(
  1610. Array(
  1611. "/expression/i",
  1612. "/binding/i",
  1613. "/behaviou*r/i",
  1614. "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
  1615. "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
  1616. "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
  1617. "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
  1618. ),
  1619. Array(
  1620. "idiocy",
  1621. "idiocy",
  1622. "idiocy",
  1623. "url(\\1#\\2)",
  1624. "url(\\1#\\2)",
  1625. "url(\\1#\\2)",
  1626. "url(\\1#\\2)"
  1627. )
  1628. )
  1629. )
  1630. );
  1631. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  1632. $view_unsafe_images = false;
  1633. }
  1634. if (!$view_unsafe_images){
  1635. /**
  1636. * Remove any references to http/https if view_unsafe_images set
  1637. * to false.
  1638. */
  1639. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
  1640. '/^([\'\"])\s*https*:.*([\'\"])/si');
  1641. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
  1642. "\\1$secremoveimg\\2");
  1643. array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
  1644. '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
  1645. array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
  1646. "url(\\1$secremoveimg\\2)");
  1647. }
  1648. $add_attr_to_tag = Array(
  1649. "/^a$/i" => Array('target'=>'"_new"')
  1650. );
  1651. $trusted = sq_sanitize($body,
  1652. $tag_list,
  1653. $rm_tags_with_content,
  1654. $self_closing_tags,
  1655. $force_tag_closing,
  1656. $rm_attnames,
  1657. $bad_attvals,
  1658. $add_attr_to_tag,
  1659. $message,
  1660. $id,
  1661. $mailbox
  1662. );
  1663. if (preg_match("|$secremoveimg|i", $trusted)){
  1664. $has_unsafe_images = true;
  1665. }
  1666. return $trusted;
  1667. }
  1668. ?>