mime.php 64 KB

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