mime.php 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411
  1. <?php
  2. /**
  3. * mime.php
  4. *
  5. * This contains the functions necessary to detect and decode MIME
  6. * messages.
  7. *
  8. * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  9. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  10. * @version $Id$
  11. * @package squirrelmail
  12. */
  13. /**
  14. * dependency information
  15. functions dependency
  16. mime_structure
  17. class/mime/Message.class.php
  18. Message::parseStructure
  19. functions/page_header.php
  20. displayPageHeader
  21. functions/display_messages.php
  22. plain_error_message
  23. mime_fetch_body
  24. functions/imap_general.php
  25. sqimap_run_command
  26. mime_print_body_lines
  27. functions/imap.php
  28. functions/attachment_common.php
  29. functions/display_messages.php
  30. magicHtml => url_parser
  31. translateText => url_parser
  32. */
  33. /* -------------------------------------------------------------------------- */
  34. /* MIME DECODING */
  35. /* -------------------------------------------------------------------------- */
  36. /**
  37. * Get the MIME structure
  38. *
  39. * This function gets the structure of a message and stores it in the "message" class.
  40. * It will return this object for use with all relevant header information and
  41. * fully parsed into the standard "message" object format.
  42. */
  43. function mime_structure ($bodystructure, $flags=array()) {
  44. /* Isolate the body structure and remove beginning and end parenthesis. */
  45. $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
  46. $read = trim(substr ($read, 0, -1));
  47. $i = 0;
  48. $msg = Message::parseStructure($read,$i);
  49. if (!is_object($msg)) {
  50. global $color, $mailbox;
  51. /* removed urldecode because $_GET is auto urldecoded ??? */
  52. displayPageHeader( $color, $mailbox );
  53. $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
  54. $errormessage .= '<br />'._("The bodystructure provided by your IMAP server:").'<br /><br />';
  55. $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
  56. plain_error_message( $errormessage, $color );
  57. echo '</body></html>';
  58. exit;
  59. }
  60. if (count($flags)) {
  61. foreach ($flags as $flag) {
  62. $char = strtoupper($flag{1});
  63. switch ($char) {
  64. case 'S':
  65. if (strtolower($flag) == '\\seen') {
  66. $msg->is_seen = true;
  67. }
  68. break;
  69. case 'A':
  70. if (strtolower($flag) == '\\answered') {
  71. $msg->is_answered = true;
  72. }
  73. break;
  74. case 'D':
  75. if (strtolower($flag) == '\\deleted') {
  76. $msg->is_deleted = true;
  77. }
  78. break;
  79. case 'F':
  80. if (strtolower($flag) == '\\flagged') {
  81. $msg->is_flagged = true;
  82. }
  83. break;
  84. case 'M':
  85. if (strtolower($flag) == '$mdnsent') {
  86. $msg->is_mdnsent = true;
  87. }
  88. break;
  89. default:
  90. break;
  91. }
  92. }
  93. }
  94. // listEntities($msg);
  95. return $msg;
  96. }
  97. /* This starts the parsing of a particular structure. It is called recursively,
  98. * so it can be passed different structures. It returns an object of type
  99. * $message.
  100. * First, it checks to see if it is a multipart message. If it is, then it
  101. * handles that as it sees is necessary. If it is just a regular entity,
  102. * then it parses it and adds the necessary header information (by calling out
  103. * to mime_get_elements()
  104. */
  105. function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
  106. /* Do a bit of error correction. If we couldn't find the entity id, just guess
  107. * that it is the first one. That is usually the case anyway.
  108. */
  109. if (!$ent_id) {
  110. $cmd = "FETCH $id BODY[]";
  111. } else {
  112. $cmd = "FETCH $id BODY[$ent_id]";
  113. }
  114. if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
  115. $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
  116. do {
  117. $topline = trim(array_shift($data));
  118. } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
  119. $wholemessage = implode('', $data);
  120. if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
  121. $ret = substr($wholemessage, 0, $regs[1]);
  122. /* There is some information in the content info header that could be important
  123. * in order to parse html messages. Let's get them here.
  124. */
  125. // if ($ret{0} == '<') {
  126. // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
  127. // }
  128. } else if (ereg('"([^"]*)"', $topline, $regs)) {
  129. $ret = $regs[1];
  130. } else {
  131. global $where, $what, $mailbox, $passed_id, $startMessage;
  132. $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
  133. if (isset($where) && isset($what)) {
  134. $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
  135. } else {
  136. $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  137. }
  138. $par .= '&amp;response=' . urlencode($response) .
  139. '&amp;message=' . urlencode($message) .
  140. '&amp;topline=' . urlencode($topline);
  141. echo '<tt><br />' .
  142. '<table width="80%"><tr>' .
  143. '<tr><td colspan="2">' .
  144. _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
  145. '</td></tr>' .
  146. '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
  147. '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
  148. '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
  149. '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
  150. "</table><br /></tt></font><hr />";
  151. $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
  152. array_shift($data);
  153. $wholemessage = implode('', $data);
  154. $ret = $wholemessage;
  155. }
  156. return $ret;
  157. }
  158. function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout') {
  159. /* Don't kill the connection if the browser is over a dialup
  160. * and it would take over 30 seconds to download it.
  161. * Don't call set_time_limit in safe mode.
  162. */
  163. if (!ini_get('safe_mode')) {
  164. set_time_limit(0);
  165. }
  166. /* in case of base64 encoded attachments, do not buffer them.
  167. Instead, echo the decoded attachment directly to screen */
  168. if (strtolower($encoding) == 'base64') {
  169. if (!$ent_id) {
  170. $query = "FETCH $id BODY[]";
  171. } else {
  172. $query = "FETCH $id BODY[$ent_id]";
  173. }
  174. sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode',$rStream,true);
  175. } else {
  176. $body = mime_fetch_body ($imap_stream, $id, $ent_id);
  177. if (is_resource($rStream)) {
  178. fputs($rStream,decodeBody($body,$encoding));
  179. } else {
  180. echo decodeBody($body, $encoding);
  181. }
  182. }
  183. /*
  184. TODO, use the same method for quoted printable.
  185. However, I assume that quoted printable attachments aren't that large
  186. so the performancegain / memory usage drop will be minimal.
  187. If we decide to add that then we need to adapt sqimap_fread because
  188. we need to split te result on \n and fread doesn't stop at \n. That
  189. means we also should provide $results from sqimap_fread (by ref) to
  190. te function and set $no_return to false. The $filter function for
  191. quoted printable should handle unsetting of $results.
  192. */
  193. /*
  194. TODO 2: find out how we write to the output stream php://stdout. fwrite
  195. doesn't work because 'php://stdout isn't a stream.
  196. */
  197. return;
  198. }
  199. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  200. /* This is here for debugging purposes. It will print out a list
  201. * of all the entity IDs that are in the $message object.
  202. */
  203. function listEntities ($message) {
  204. if ($message) {
  205. echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br />';
  206. for ($i = 0; isset($message->entities[$i]); $i++) {
  207. echo "$i : ";
  208. $msg = listEntities($message->entities[$i]);
  209. if ($msg) {
  210. echo "return: ";
  211. return $msg;
  212. }
  213. }
  214. }
  215. }
  216. function getPriorityStr($priority) {
  217. $priority_level = substr($priority,0,1);
  218. switch($priority_level) {
  219. /* Check for a higher then normal priority. */
  220. case '1':
  221. case '2':
  222. $priority_string = _("High");
  223. break;
  224. /* Check for a lower then normal priority. */
  225. case '4':
  226. case '5':
  227. $priority_string = _("Low");
  228. break;
  229. /* Check for a normal priority. */
  230. case '3':
  231. default:
  232. $priority_level = '3';
  233. $priority_string = _("Normal");
  234. break;
  235. }
  236. return $priority_string;
  237. }
  238. /* returns a $message object for a particular entity id */
  239. function getEntity ($message, $ent_id) {
  240. return $message->getEntity($ent_id);
  241. }
  242. /* translateText
  243. * Extracted from strings.php 23/03/2002
  244. */
  245. function translateText(&$body, $wrap_at, $charset) {
  246. global $where, $what; /* from searching */
  247. global $color; /* color theme */
  248. // require_once(SM_PATH . 'functions/url_parser.php');
  249. $body_ary = explode("\n", $body);
  250. for ($i=0; $i < count($body_ary); $i++) {
  251. $line = $body_ary[$i];
  252. if (strlen($line) - 2 >= $wrap_at) {
  253. sqWordWrap($line, $wrap_at, $charset);
  254. }
  255. $line = charset_decode($charset, $line);
  256. $line = str_replace("\t", ' ', $line);
  257. parseUrl ($line);
  258. $quotes = 0;
  259. $pos = 0;
  260. $j = strlen($line);
  261. while ($pos < $j) {
  262. if ($line[$pos] == ' ') {
  263. $pos++;
  264. } else if (strpos($line, '&gt;', $pos) === $pos) {
  265. $pos += 4;
  266. $quotes++;
  267. } else {
  268. break;
  269. }
  270. }
  271. if ($quotes % 2) {
  272. if (!isset($color[13])) {
  273. $color[13] = '#800000';
  274. }
  275. $line = '<font color="' . $color[13] . '">' . $line . '</font>';
  276. } elseif ($quotes) {
  277. if (!isset($color[14])) {
  278. $color[14] = '#FF0000';
  279. }
  280. $line = '<font color="' . $color[14] . '">' . $line . '</font>';
  281. }
  282. $body_ary[$i] = $line;
  283. }
  284. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  285. }
  286. /**
  287. * This returns a parsed string called $body. That string can then
  288. * be displayed as the actual message in the HTML. It contains
  289. * everything needed, including HTML Tags, Attachments at the
  290. * bottom, etc.
  291. *
  292. * Since 1.2.0 function uses message_body hook.
  293. * Till 1.3.0 function included output of formatAttachments().
  294. *
  295. * @param resource $imap_stream imap connection resource
  296. * @param object $message squirrelmail message object
  297. * @param array $color squirrelmail color theme array
  298. * @param integer $wrap_at number of characters per line
  299. * @param string $ent_num (since 1.3.0) message part id
  300. * @param integer $id (since 1.3.0) message id
  301. * @param string $mailbox (since 1.3.0) imap folder name
  302. * @param boolean $clean (since 1.5.1) Do not output stuff that's irrelevant for the printable version.
  303. * @return string html formated message text
  304. */
  305. function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=FALSE) {
  306. /* This if statement checks for the entity to show as the
  307. * primary message. To add more of them, just put them in the
  308. * order that is their priority.
  309. */
  310. global $startMessage, $languages, $squirrelmail_language,
  311. $show_html_default, $sort, $has_unsafe_images, $passed_ent_id,
  312. $use_iframe, $iframe_height, $download_and_unsafe_link;
  313. // workaround for not updated config.php
  314. if (! isset($use_iframe)) $use_iframe = false;
  315. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  316. $view_unsafe_images = false;
  317. }
  318. $body = '';
  319. $urlmailbox = urlencode($mailbox);
  320. $body_message = getEntity($message, $ent_num);
  321. if (($body_message->header->type0 == 'text') ||
  322. ($body_message->header->type0 == 'rfc822')) {
  323. $body = mime_fetch_body ($imap_stream, $id, $ent_num);
  324. $body = decodeBody($body, $body_message->header->encoding);
  325. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  326. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
  327. if (mb_detect_encoding($body) != 'ASCII') {
  328. $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
  329. }
  330. }
  331. $hookResults = do_hook("message_body", $body);
  332. $body = $hookResults[1];
  333. /* If there are other types that shouldn't be formatted, add
  334. * them here.
  335. */
  336. if ($body_message->header->type1 == 'html') {
  337. if ($show_html_default <> 1) {
  338. $entity_conv = array('&nbsp;' => ' ',
  339. '<p>' => "\n",
  340. '<P>' => "\n",
  341. '<br>' => "\n",
  342. '<BR>' => "\n",
  343. '<br />' => "\n",
  344. '<BR />' => "\n",
  345. '&gt;' => '>',
  346. '&lt;' => '<');
  347. $body = strtr($body, $entity_conv);
  348. $body = strip_tags($body);
  349. $body = trim($body);
  350. translateText($body, $wrap_at,
  351. $body_message->header->getParameter('charset'));
  352. } elseif ($use_iframe && ! $clean) {
  353. // $clean is used to remove iframe in printable view.
  354. /**
  355. * If we don't add html message between iframe tags,
  356. * we must detect unsafe images and modify $has_unsafe_images.
  357. */
  358. $html_body = magicHTML($body, $id, $message, $mailbox);
  359. // Convert character set in order to display html mails in different character set
  360. $html_body = charset_decode($body_message->header->getParameter('charset'),$html_body,false,true);
  361. // creating iframe url
  362. $iframeurl=sqm_baseuri().'src/view_html.php?'
  363. . 'mailbox=' . $urlmailbox
  364. . '&amp;passed_id=' . $id
  365. . '&amp;ent_id=' . $ent_num
  366. . '&amp;view_unsafe_images=' . (int) $view_unsafe_images;
  367. // adding warning message
  368. $body = html_tag('div',_("Viewing HTML formatted email"),'center');
  369. /**
  370. * height can't be set to 100%, because it does not work as expected when
  371. * iframe is inside the table. Browsers do not create full height objects
  372. * even when iframe is not nested. Maybe there is some way to get full size
  373. * with CSS. Tested in firefox 1.02 and opera 7.53
  374. *
  375. * width="100%" does not work as expected, when table width is not set (automatic)
  376. *
  377. * tokul: I think <iframe> are safer sandbox than <object>. Objects might
  378. * need special handling for IE and IE6SP2.
  379. */
  380. $body.= "<div><iframe name=\"message_frame\" width=\"100%\" height=\"$iframe_height\" src=\"$iframeurl\""
  381. .' frameborder="1" marginwidth="0" marginheight="0" scrolling="auto">' . "\n";
  382. // Message for browsers without iframe support
  383. //$body.= _("Your browser does not support inline frames.
  384. // You can view HTML formated message by following below link.");
  385. //$body.= "<br /><a href=\"$iframeurl\">"._("View HTML Message")."</a>";
  386. // if browser can't render iframe, it renders html message.
  387. $body.= $html_body;
  388. // close iframe
  389. $body.="</iframe></div>\n";
  390. } else {
  391. // old way of html rendering
  392. $body = magicHTML($body, $id, $message, $mailbox);
  393. /**
  394. * convert character set. charset_decode does not remove html special chars
  395. * applied by magicHTML functions and does not sanitize them second time if
  396. * fourth argument is true.
  397. */
  398. $body = charset_decode($body_message->header->getParameter('charset'),$body,false,true);
  399. }
  400. } else {
  401. translateText($body, $wrap_at,
  402. $body_message->header->getParameter('charset'));
  403. }
  404. // if this is the clean display (i.e. printer friendly), stop here.
  405. if ( $clean ) {
  406. return $body;
  407. }
  408. $download_and_unsafe_link = '';
  409. $link = 'passed_id=' . $id . '&amp;ent_id='.$ent_num.
  410. '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
  411. '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  412. if (isset($passed_ent_id)) {
  413. $link .= '&amp;passed_ent_id='.$passed_ent_id;
  414. }
  415. $download_and_unsafe_link .= '&nbsp;|&nbsp;<a href="download.php?absolute_dl=true&amp;' .
  416. $link . '">' . _("Download this as a file") . '</a>';
  417. if ($view_unsafe_images) {
  418. $text = _("Hide Unsafe Images");
  419. } else {
  420. if (isset($has_unsafe_images) && $has_unsafe_images) {
  421. $link .= '&amp;view_unsafe_images=1';
  422. $text = _("View Unsafe Images");
  423. } else {
  424. $text = '';
  425. }
  426. }
  427. if($text != '') {
  428. $download_and_unsafe_link .= '&nbsp;|&nbsp;<a href="read_body.php?' . $link . '">' . $text . '</a>';
  429. }
  430. }
  431. return $body;
  432. }
  433. /**
  434. * Displays attachment links and information
  435. *
  436. * Since 1.3.0 function is not included in formatBody() call.
  437. *
  438. * Since 1.0.2 uses attachment $type0/$type1 hook.
  439. * Since 1.2.5 uses attachment $type0/* hook.
  440. * Since 1.5.0 uses attachments_bottom hook.
  441. *
  442. * @param object $message SquirrelMail message object
  443. * @param array $exclude_id message parts that are not attachments.
  444. * @param string $mailbox mailbox name
  445. * @param integer $id message id
  446. * @return string html formated attachment information.
  447. */
  448. function formatAttachments($message, $exclude_id, $mailbox, $id) {
  449. global $where, $what, $startMessage, $color, $passed_ent_id, $base_uri;
  450. $att_ar = $message->getAttachments($exclude_id);
  451. if (!count($att_ar)) return '';
  452. $attachments = '';
  453. $urlMailbox = urlencode($mailbox);
  454. foreach ($att_ar as $att) {
  455. $ent = $att->entity_id;
  456. $header = $att->header;
  457. $type0 = strtolower($header->type0);
  458. $type1 = strtolower($header->type1);
  459. $name = '';
  460. $links['download link']['text'] = _("Download");
  461. $links['download link']['href'] = $base_uri .
  462. "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
  463. if ($type0 =='message' && $type1 == 'rfc822') {
  464. $default_page = $base_uri . 'src/read_body.php';
  465. $rfc822_header = $att->rfc822_header;
  466. $filename = $rfc822_header->subject;
  467. if (trim( $filename ) == '') {
  468. $filename = 'untitled-[' . $ent . ']' ;
  469. }
  470. $from_o = $rfc822_header->from;
  471. if (is_object($from_o)) {
  472. $from_name = decodeHeader($from_o->getAddress(false));
  473. } elseif (is_array($from_o) && count($from_o) && is_object($from_o[0])) {
  474. // something weird happens when a digest message is opened and you return to the digest
  475. // now the from object is part of an array. Probably the parseHeader call overwrites the info
  476. // retrieved from the bodystructure in a different way. We need to fix this later.
  477. // possible starting point, do not fetch header we already have and inspect how
  478. // the rfc822_header object behaves.
  479. $from_name = decodeHeader($from_o[0]->getAddress(false));
  480. } else {
  481. $from_name = _("Unknown sender");
  482. }
  483. $description = $from_name;
  484. } else {
  485. $default_page = $base_uri . 'src/download.php';
  486. $filename = $att->getFilename();
  487. if ($header->description) {
  488. $description = decodeHeader($header->description);
  489. } else {
  490. $description = '';
  491. }
  492. }
  493. $display_filename = $filename;
  494. if (isset($passed_ent_id)) {
  495. $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
  496. } else {
  497. $passed_ent_id_link = '';
  498. }
  499. $defaultlink = $default_page . "?startMessage=$startMessage"
  500. . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
  501. . '&amp;ent_id='.$ent.$passed_ent_id_link;
  502. if ($where && $what) {
  503. $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
  504. }
  505. /* This executes the attachment hook with a specific MIME-type.
  506. * If that doesn't have results, it tries if there's a rule
  507. * for a more generic type.
  508. */
  509. $hookresults = do_hook("attachment $type0/$type1", $links,
  510. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  511. $display_filename, $where, $what);
  512. if(count($hookresults[1]) <= 1) {
  513. $hookresults = do_hook("attachment $type0/*", $links,
  514. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  515. $display_filename, $where, $what);
  516. }
  517. $links = $hookresults[1];
  518. $defaultlink = $hookresults[6];
  519. $attachments .= '<tr><td>' .
  520. '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a>&nbsp;</td>' .
  521. '<td><small><b>' . show_readable_size($header->size) .
  522. '</b>&nbsp;&nbsp;</small></td>' .
  523. '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ]&nbsp;</small></td>' .
  524. '<td><small>';
  525. $attachments .= '<b>' . $description . '</b>';
  526. $attachments .= '</small></td><td><small>&nbsp;';
  527. $skipspaces = 1;
  528. foreach ($links as $val) {
  529. if ($skipspaces) {
  530. $skipspaces = 0;
  531. } else {
  532. $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  533. }
  534. $attachments .= '<a href="' . $val['href'] . '">'
  535. . (isset($val['text']) && !empty($val['text']) ? $val['text'] : '')
  536. . (isset($val['extra']) && !empty($val['extra']) ? $val['extra'] : '')
  537. . '</a>';
  538. }
  539. unset($links);
  540. $attachments .= "</td></tr>\n";
  541. }
  542. $attachmentadd = do_hook_function('attachments_bottom',$attachments);
  543. if ($attachmentadd != '')
  544. $attachments = $attachmentadd;
  545. return $attachments;
  546. }
  547. function sqimap_base64_decode(&$string) {
  548. // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
  549. // fly decoding (to reduce memory usage) you have to check if the
  550. // data has incomplete pairs
  551. // Remove the noise in order to check if the 4 bytes pairs are complete
  552. $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
  553. $sStringRem = '';
  554. $iMod = strlen($string) % 4;
  555. if ($iMod) {
  556. $sStringRem = substr($string,-$iMod);
  557. // Check if $sStringRem contains padding characters
  558. if (substr($sStringRem,-1) != '=') {
  559. $string = substr($string,0,-$iMod);
  560. } else {
  561. $sStringRem = '';
  562. }
  563. }
  564. $string = base64_decode($string);
  565. return $sStringRem;
  566. }
  567. /**
  568. * Decodes encoded message body
  569. *
  570. * This function decodes the body depending on the encoding type.
  571. * Currently quoted-printable and base64 encodings are supported.
  572. * decode_body hook was added to this function in 1.4.2/1.5.0
  573. * @param string $body encoded message body
  574. * @param string $encoding used encoding
  575. * @return string decoded string
  576. * @since 1.0
  577. */
  578. function decodeBody($body, $encoding) {
  579. $body = str_replace("\r\n", "\n", $body);
  580. $encoding = strtolower($encoding);
  581. $encoding_handler = do_hook_function('decode_body', $encoding);
  582. // plugins get first shot at decoding the body
  583. //
  584. if (!empty($encoding_handler) && function_exists($encoding_handler)) {
  585. $body = $encoding_handler('decode', $body);
  586. } elseif ($encoding == 'quoted-printable' ||
  587. $encoding == 'quoted_printable') {
  588. /**
  589. * quoted_printable_decode() function is broken in older
  590. * php versions. Text with \r\n decoding was fixed only
  591. * in php 4.3.0. Minimal code requirement 4.0.4 +
  592. * str_replace("\r\n", "\n", $body); call.
  593. */
  594. $body = quoted_printable_decode($body);
  595. } elseif ($encoding == 'base64') {
  596. $body = base64_decode($body);
  597. }
  598. // All other encodings are returned raw.
  599. return $body;
  600. }
  601. /**
  602. * Decodes headers
  603. *
  604. * This functions decode strings that is encoded according to
  605. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  606. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  607. *
  608. * @param string $string header string that has to be made readable
  609. * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
  610. * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
  611. * @param boolean $decide decide if string can be utfencoded. defaults to false
  612. * @return string decoded header string
  613. */
  614. function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
  615. global $languages, $squirrelmail_language,$default_charset;
  616. if (is_array($string)) {
  617. $string = implode("\n", $string);
  618. }
  619. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  620. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
  621. $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
  622. // Do we need to return at this point?
  623. // return $string;
  624. }
  625. $i = 0;
  626. $iLastMatch = -2;
  627. $encoded = true;
  628. $aString = explode(' ',$string);
  629. $ret = '';
  630. foreach ($aString as $chunk) {
  631. if ($encoded && $chunk === '') {
  632. continue;
  633. } elseif ($chunk === '') {
  634. $ret .= ' ';
  635. continue;
  636. }
  637. $encoded = false;
  638. /* if encoded words are not separated by a linear-space-white we still catch them */
  639. $j = $i-1;
  640. while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  641. /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
  642. if ($iLastMatch !== $j) {
  643. if ($htmlsave) {
  644. $ret .= '&#32;';
  645. } else {
  646. $ret .= ' ';
  647. }
  648. }
  649. $iLastMatch = $i;
  650. $j = $i;
  651. if ($htmlsave) {
  652. $ret .= htmlspecialchars($res[1]);
  653. } else {
  654. $ret .= $res[1];
  655. }
  656. $encoding = ucfirst($res[3]);
  657. /* decide about valid decoding */
  658. if ($decide && is_conversion_safe($res[2])) {
  659. $utfencode=true;
  660. $can_be_encoded=true;
  661. } else {
  662. $can_be_encoded=false;
  663. }
  664. switch ($encoding)
  665. {
  666. case 'B':
  667. $replace = base64_decode($res[4]);
  668. if ($utfencode) {
  669. if ($can_be_encoded) {
  670. /* convert string to different charset,
  671. * if functions asks for it (usually in compose)
  672. */
  673. $ret .= charset_convert($res[2],$replace,$default_charset,$htmlsave);
  674. } else {
  675. // convert string to html codes in order to display it
  676. $ret .= charset_decode($res[2],$replace);
  677. }
  678. } else {
  679. if ($htmlsave) {
  680. $replace = htmlspecialchars($replace);
  681. }
  682. $ret.= $replace;
  683. }
  684. break;
  685. case 'Q':
  686. $replace = str_replace('_', ' ', $res[4]);
  687. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  688. $replace);
  689. if ($utfencode) {
  690. if ($can_be_encoded) {
  691. /* convert string to different charset,
  692. * if functions asks for it (usually in compose)
  693. */
  694. $replace = charset_convert($res[2], $replace,$default_charset,$htmlsave);
  695. } else {
  696. // convert string to html codes in order to display it
  697. $replace = charset_decode($res[2], $replace);
  698. }
  699. } else {
  700. if ($htmlsave) {
  701. $replace = htmlspecialchars($replace);
  702. }
  703. }
  704. $ret .= $replace;
  705. break;
  706. default:
  707. break;
  708. }
  709. $chunk = $res[5];
  710. $encoded = true;
  711. }
  712. if (!$encoded) {
  713. if ($htmlsave) {
  714. $ret .= '&#32;';
  715. } else {
  716. $ret .= ' ';
  717. }
  718. }
  719. if (!$encoded && $htmlsave) {
  720. $ret .= htmlspecialchars($chunk);
  721. } else {
  722. $ret .= $chunk;
  723. }
  724. ++$i;
  725. }
  726. /* remove the first added space */
  727. if ($ret) {
  728. if ($htmlsave) {
  729. $ret = substr($ret,5);
  730. } else {
  731. $ret = substr($ret,1);
  732. }
  733. }
  734. return $ret;
  735. }
  736. /**
  737. * Encodes header
  738. *
  739. * Function uses XTRA_CODE _encodeheader function, if such function exists.
  740. *
  741. * Function uses Q encoding by default and encodes a string according to RFC
  742. * 1522 for use in headers if it contains 8-bit characters or anything that
  743. * looks like it should be encoded.
  744. *
  745. * Function switches to B encoding and encodeHeaderBase64() function, if
  746. * string is 8bit and multibyte character set supported by mbstring extension
  747. * is used. It can cause E_USER_NOTICE errors, if interface is used with
  748. * multibyte character set unsupported by mbstring extension.
  749. *
  750. * @param string $string header string, that has to be encoded
  751. * @return string quoted-printable encoded string
  752. * @todo make $mb_charsets system wide constant
  753. */
  754. function encodeHeader ($string) {
  755. global $default_charset, $languages, $squirrelmail_language;
  756. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  757. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
  758. return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
  759. }
  760. // Use B encoding for multibyte charsets
  761. $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
  762. if (in_array($default_charset,$mb_charsets) &&
  763. in_array($default_charset,sq_mb_list_encodings()) &&
  764. sq_is8bit($string)) {
  765. return encodeHeaderBase64($string,$default_charset);
  766. } elseif (in_array($default_charset,$mb_charsets) &&
  767. sq_is8bit($string) &&
  768. ! in_array($default_charset,sq_mb_list_encodings())) {
  769. // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
  770. // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
  771. }
  772. // Encode only if the string contains 8-bit characters or =?
  773. $j = strlen($string);
  774. $max_l = 75 - strlen($default_charset) - 7;
  775. $aRet = array();
  776. $ret = '';
  777. $iEncStart = $enc_init = false;
  778. $cur_l = $iOffset = 0;
  779. for($i = 0; $i < $j; ++$i) {
  780. switch($string{$i})
  781. {
  782. case '=':
  783. case '<':
  784. case '>':
  785. case ',':
  786. case '?':
  787. case '_':
  788. if ($iEncStart === false) {
  789. $iEncStart = $i;
  790. }
  791. $cur_l+=3;
  792. if ($cur_l > ($max_l-2)) {
  793. /* if there is an stringpart that doesn't need encoding, add it */
  794. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  795. $aRet[] = "=?$default_charset?Q?$ret?=";
  796. $iOffset = $i;
  797. $cur_l = 0;
  798. $ret = '';
  799. $iEncStart = false;
  800. } else {
  801. $ret .= sprintf("=%02X",ord($string{$i}));
  802. }
  803. break;
  804. case '(':
  805. case ')':
  806. if ($iEncStart !== false) {
  807. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  808. $aRet[] = "=?$default_charset?Q?$ret?=";
  809. $iOffset = $i;
  810. $cur_l = 0;
  811. $ret = '';
  812. $iEncStart = false;
  813. }
  814. break;
  815. case ' ':
  816. if ($iEncStart !== false) {
  817. $cur_l++;
  818. if ($cur_l > $max_l) {
  819. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  820. $aRet[] = "=?$default_charset?Q?$ret?=";
  821. $iOffset = $i;
  822. $cur_l = 0;
  823. $ret = '';
  824. $iEncStart = false;
  825. } else {
  826. $ret .= '_';
  827. }
  828. }
  829. break;
  830. default:
  831. $k = ord($string{$i});
  832. if ($k > 126) {
  833. if ($iEncStart === false) {
  834. // do not start encoding in the middle of a string, also take the rest of the word.
  835. $sLeadString = substr($string,0,$i);
  836. $aLeadString = explode(' ',$sLeadString);
  837. $sToBeEncoded = array_pop($aLeadString);
  838. $iEncStart = $i - strlen($sToBeEncoded);
  839. $ret .= $sToBeEncoded;
  840. $cur_l += strlen($sToBeEncoded);
  841. }
  842. $cur_l += 3;
  843. /* first we add the encoded string that reached it's max size */
  844. if ($cur_l > ($max_l-2)) {
  845. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  846. $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
  847. $cur_l = 3;
  848. $ret = '';
  849. $iOffset = $i;
  850. $iEncStart = $i;
  851. }
  852. $enc_init = true;
  853. $ret .= sprintf("=%02X", $k);
  854. } else {
  855. if ($iEncStart !== false) {
  856. $cur_l++;
  857. if ($cur_l > $max_l) {
  858. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  859. $aRet[] = "=?$default_charset?Q?$ret?=";
  860. $iEncStart = false;
  861. $iOffset = $i;
  862. $cur_l = 0;
  863. $ret = '';
  864. } else {
  865. $ret .= $string{$i};
  866. }
  867. }
  868. }
  869. break;
  870. }
  871. }
  872. if ($enc_init) {
  873. if ($iEncStart !== false) {
  874. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  875. $aRet[] = "=?$default_charset?Q?$ret?=";
  876. } else {
  877. $aRet[] = substr($string,$iOffset);
  878. }
  879. $string = implode('',$aRet);
  880. }
  881. return $string;
  882. }
  883. /**
  884. * Encodes string according to rfc2047 B encoding header formating rules
  885. *
  886. * It is recommended way to encode headers with character sets that store
  887. * symbols in more than one byte.
  888. *
  889. * Function requires mbstring support. If required mbstring functions are missing,
  890. * function returns false and sets E_USER_WARNING level error message.
  891. *
  892. * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
  893. * that mbstring functions will generate E_WARNING errors, if unsupported
  894. * character set is used. mb_encode_mimeheader function provided by php
  895. * mbstring extension is not used in order to get better control of header
  896. * encoding.
  897. *
  898. * Used php code functions - function_exists(), trigger_error(), strlen()
  899. * (is used with charset names and base64 strings). Used php mbstring
  900. * functions - mb_strlen and mb_substr.
  901. *
  902. * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
  903. * encoding), rfc 2822 (header folding)
  904. *
  905. * @param string $string header string that must be encoded
  906. * @param string $charset character set. Must be supported by mbstring extension.
  907. * Use sq_mb_list_encodings() to detect supported charsets.
  908. * @return string string encoded according to rfc2047 B encoding formating rules
  909. * @since 1.5.1
  910. * @todo First header line can be wrapped to $iMaxLength - $HeaderFieldLength - 1
  911. * @todo Do we want to control max length of header?
  912. * @todo Do we want to control EOL (end-of-line) marker?
  913. * @todo Do we want to translate error message?
  914. */
  915. function encodeHeaderBase64($string,$charset) {
  916. /**
  917. * Check mbstring function requirements.
  918. */
  919. if (! function_exists('mb_strlen') ||
  920. ! function_exists('mb_substr')) {
  921. // set E_USER_WARNING
  922. trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING);
  923. // return false
  924. return false;
  925. }
  926. // initial return array
  927. $aRet = array();
  928. /**
  929. * header length = 75 symbols max (same as in encodeHeader)
  930. * remove $charset length
  931. * remove =? ? ?= (5 chars)
  932. * remove 2 more chars (\r\n ?)
  933. */
  934. $iMaxLength = 75 - strlen($charset) - 7;
  935. // set first character position
  936. $iStartCharNum = 0;
  937. // loop through all characters. count characters and not bytes.
  938. for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++) {
  939. // encode string from starting character to current character.
  940. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  941. // Check encoded string length
  942. if(strlen($encoded_string)>$iMaxLength) {
  943. // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
  944. $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
  945. // set new starting character
  946. $iStartCharNum = $iCharNum-1;
  947. // encode last char (in case it is last character in string)
  948. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  949. } // if string is shorter than max length - add next character
  950. }
  951. // add last encoded string to array
  952. $aRet[] = $encoded_string;
  953. // set initial return string
  954. $sRet = '';
  955. // loop through encoded strings
  956. foreach($aRet as $string) {
  957. // TODO: Do we want to control EOL (end-of-line) marker
  958. if ($sRet!='') $sRet.= " ";
  959. // add header tags and encoded string to return string
  960. $sRet.= '=?'.$charset.'?B?'.$string.'?=';
  961. }
  962. return $sRet;
  963. }
  964. /* This function trys to locate the entity_id of a specific mime element */
  965. function find_ent_id($id, $message) {
  966. for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
  967. if ($message->entities[$i]->header->type0 == 'multipart') {
  968. $ret = find_ent_id($id, $message->entities[$i]);
  969. } else {
  970. if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
  971. // if (sq_check_save_extension($message->entities[$i])) {
  972. return $message->entities[$i]->entity_id;
  973. // }
  974. } elseif (!empty($message->entities[$i]->header->parameters['name'])) {
  975. /**
  976. * This is part of a fix for Outlook Express 6.x generating
  977. * cid URLs without creating content-id headers
  978. * @@JA - 20050207
  979. */
  980. if (strcasecmp($message->entities[$i]->header->parameters['name'], $id) == 0) {
  981. return $message->entities[$i]->entity_id;
  982. }
  983. }
  984. }
  985. }
  986. return $ret;
  987. }
  988. function sq_check_save_extension($message) {
  989. $filename = $message->getFilename();
  990. $ext = substr($filename, strrpos($filename,'.')+1);
  991. $save_extensions = array('jpg','jpeg','gif','png','bmp');
  992. return in_array($ext, $save_extensions);
  993. }
  994. /**
  995. ** HTMLFILTER ROUTINES
  996. */
  997. /**
  998. * This function checks attribute values for entity-encoded values
  999. * and returns them translated into 8-bit strings so we can run
  1000. * checks on them.
  1001. *
  1002. * @param $attvalue A string to run entity check against.
  1003. * @return Nothing, modifies a reference value.
  1004. */
  1005. function sq_defang(&$attvalue){
  1006. $me = 'sq_defang';
  1007. /**
  1008. * Skip this if there aren't ampersands or backslashes.
  1009. */
  1010. if (strpos($attvalue, '&') === false
  1011. && strpos($attvalue, '\\') === false){
  1012. return;
  1013. }
  1014. $m = false;
  1015. do {
  1016. $m = false;
  1017. $m = $m || sq_deent($attvalue, '/\&#0*(\d+);*/s');
  1018. $m = $m || sq_deent($attvalue, '/\&#x0*((\d|[a-f])+);*/si', true);
  1019. $m = $m || sq_deent($attvalue, '/\\\\(\d+)/s', true);
  1020. } while ($m == true);
  1021. $attvalue = stripslashes($attvalue);
  1022. }
  1023. /**
  1024. * Kill any tabs, newlines, or carriage returns. Our friends the
  1025. * makers of the browser with 95% market value decided that it'd
  1026. * be funny to make "java[tab]script" be just as good as "javascript".
  1027. *
  1028. * @param attvalue The attribute value before extraneous spaces removed.
  1029. * @return attvalue Nothing, modifies a reference value.
  1030. */
  1031. function sq_unspace(&$attvalue){
  1032. $me = 'sq_unspace';
  1033. if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
  1034. $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
  1035. Array('', '', '', '', ''), $attvalue);
  1036. }
  1037. }
  1038. /**
  1039. * This function returns the final tag out of the tag name, an array
  1040. * of attributes, and the type of the tag. This function is called by
  1041. * sq_sanitize internally.
  1042. *
  1043. * @param $tagname the name of the tag.
  1044. * @param $attary the array of attributes and their values
  1045. * @param $tagtype The type of the tag (see in comments).
  1046. * @return a string with the final tag representation.
  1047. */
  1048. function sq_tagprint($tagname, $attary, $tagtype){
  1049. $me = 'sq_tagprint';
  1050. if ($tagtype == 2){
  1051. $fulltag = '</' . $tagname . '>';
  1052. } else {
  1053. $fulltag = '<' . $tagname;
  1054. if (is_array($attary) && sizeof($attary)){
  1055. $atts = Array();
  1056. while (list($attname, $attvalue) = each($attary)){
  1057. array_push($atts, "$attname=$attvalue");
  1058. }
  1059. $fulltag .= ' ' . join(" ", $atts);
  1060. }
  1061. if ($tagtype == 3){
  1062. $fulltag .= ' /';
  1063. }
  1064. $fulltag .= '>';
  1065. }
  1066. return $fulltag;
  1067. }
  1068. /**
  1069. * A small helper function to use with array_walk. Modifies a by-ref
  1070. * value and makes it lowercase.
  1071. *
  1072. * @param $val a value passed by-ref.
  1073. * @return void since it modifies a by-ref value.
  1074. */
  1075. function sq_casenormalize(&$val){
  1076. $val = strtolower($val);
  1077. }
  1078. /**
  1079. * This function skips any whitespace from the current position within
  1080. * a string and to the next non-whitespace value.
  1081. *
  1082. * @param $body the string
  1083. * @param $offset the offset within the string where we should start
  1084. * looking for the next non-whitespace character.
  1085. * @return the location within the $body where the next
  1086. * non-whitespace char is located.
  1087. */
  1088. function sq_skipspace($body, $offset){
  1089. $me = 'sq_skipspace';
  1090. preg_match('/^(\s*)/s', substr($body, $offset), $matches);
  1091. if (sizeof($matches{1})){
  1092. $count = strlen($matches{1});
  1093. $offset += $count;
  1094. }
  1095. return $offset;
  1096. }
  1097. /**
  1098. * This function looks for the next character within a string. It's
  1099. * really just a glorified "strpos", except it catches if failures
  1100. * nicely.
  1101. *
  1102. * @param $body The string to look for needle in.
  1103. * @param $offset Start looking from this position.
  1104. * @param $needle The character/string to look for.
  1105. * @return location of the next occurance of the needle, or
  1106. * strlen($body) if needle wasn't found.
  1107. */
  1108. function sq_findnxstr($body, $offset, $needle){
  1109. $me = 'sq_findnxstr';
  1110. $pos = strpos($body, $needle, $offset);
  1111. if ($pos === FALSE){
  1112. $pos = strlen($body);
  1113. }
  1114. return $pos;
  1115. }
  1116. /**
  1117. * This function takes a PCRE-style regexp and tries to match it
  1118. * within the string.
  1119. *
  1120. * @param $body The string to look for needle in.
  1121. * @param $offset Start looking from here.
  1122. * @param $reg A PCRE-style regex to match.
  1123. * @return Returns a false if no matches found, or an array
  1124. * with the following members:
  1125. * - integer with the location of the match within $body
  1126. * - string with whatever content between offset and the match
  1127. * - string with whatever it is we matched
  1128. */
  1129. function sq_findnxreg($body, $offset, $reg){
  1130. $me = 'sq_findnxreg';
  1131. $matches = Array();
  1132. $retarr = Array();
  1133. preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
  1134. if (!isset($matches{0}) || !$matches{0}){
  1135. $retarr = false;
  1136. } else {
  1137. $retarr{0} = $offset + strlen($matches{1});
  1138. $retarr{1} = $matches{1};
  1139. $retarr{2} = $matches{2};
  1140. }
  1141. return $retarr;
  1142. }
  1143. /**
  1144. * This function looks for the next tag.
  1145. *
  1146. * @param $body String where to look for the next tag.
  1147. * @param $offset Start looking from here.
  1148. * @return false if no more tags exist in the body, or
  1149. * an array with the following members:
  1150. * - string with the name of the tag
  1151. * - array with attributes and their values
  1152. * - integer with tag type (1, 2, or 3)
  1153. * - integer where the tag starts (starting "<")
  1154. * - integer where the tag ends (ending ">")
  1155. * first three members will be false, if the tag is invalid.
  1156. */
  1157. function sq_getnxtag($body, $offset){
  1158. $me = 'sq_getnxtag';
  1159. if ($offset > strlen($body)){
  1160. return false;
  1161. }
  1162. $lt = sq_findnxstr($body, $offset, "<");
  1163. if ($lt == strlen($body)){
  1164. return false;
  1165. }
  1166. /**
  1167. * We are here:
  1168. * blah blah <tag attribute="value">
  1169. * \---------^
  1170. */
  1171. $pos = sq_skipspace($body, $lt+1);
  1172. if ($pos >= strlen($body)){
  1173. return Array(false, false, false, $lt, strlen($body));
  1174. }
  1175. /**
  1176. * There are 3 kinds of tags:
  1177. * 1. Opening tag, e.g.:
  1178. * <a href="blah">
  1179. * 2. Closing tag, e.g.:
  1180. * </a>
  1181. * 3. XHTML-style content-less tag, e.g.:
  1182. * <img src="blah" />
  1183. */
  1184. $tagtype = false;
  1185. switch (substr($body, $pos, 1)){
  1186. case '/':
  1187. $tagtype = 2;
  1188. $pos++;
  1189. break;
  1190. case '!':
  1191. /**
  1192. * A comment or an SGML declaration.
  1193. */
  1194. if (substr($body, $pos+1, 2) == "--"){
  1195. $gt = strpos($body, "-->", $pos);
  1196. if ($gt === false){
  1197. $gt = strlen($body);
  1198. } else {
  1199. $gt += 2;
  1200. }
  1201. return Array(false, false, false, $lt, $gt);
  1202. } else {
  1203. $gt = sq_findnxstr($body, $pos, ">");
  1204. return Array(false, false, false, $lt, $gt);
  1205. }
  1206. break;
  1207. default:
  1208. /**
  1209. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  1210. * later.
  1211. */
  1212. $tagtype = 1;
  1213. break;
  1214. }
  1215. $tag_start = $pos;
  1216. $tagname = '';
  1217. /**
  1218. * Look for next [\W-_], which will indicate the end of the tag name.
  1219. */
  1220. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  1221. if ($regary == false){
  1222. return Array(false, false, false, $lt, strlen($body));
  1223. }
  1224. list($pos, $tagname, $match) = $regary;
  1225. $tagname = strtolower($tagname);
  1226. /**
  1227. * $match can be either of these:
  1228. * '>' indicating the end of the tag entirely.
  1229. * '\s' indicating the end of the tag name.
  1230. * '/' indicating that this is type-3 xhtml tag.
  1231. *
  1232. * Whatever else we find there indicates an invalid tag.
  1233. */
  1234. switch ($match){
  1235. case '/':
  1236. /**
  1237. * This is an xhtml-style tag with a closing / at the
  1238. * end, like so: <img src="blah" />. Check if it's followed
  1239. * by the closing bracket. If not, then this tag is invalid
  1240. */
  1241. if (substr($body, $pos, 2) == "/>"){
  1242. $pos++;
  1243. $tagtype = 3;
  1244. } else {
  1245. $gt = sq_findnxstr($body, $pos, ">");
  1246. $retary = Array(false, false, false, $lt, $gt);
  1247. return $retary;
  1248. }
  1249. case '>':
  1250. return Array($tagname, false, $tagtype, $lt, $pos);
  1251. break;
  1252. default:
  1253. /**
  1254. * Check if it's whitespace
  1255. */
  1256. if (!preg_match('/\s/', $match)){
  1257. /**
  1258. * This is an invalid tag! Look for the next closing ">".
  1259. */
  1260. $gt = sq_findnxstr($body, $lt, ">");
  1261. return Array(false, false, false, $lt, $gt);
  1262. }
  1263. break;
  1264. }
  1265. /**
  1266. * At this point we're here:
  1267. * <tagname attribute='blah'>
  1268. * \-------^
  1269. *
  1270. * At this point we loop in order to find all attributes.
  1271. */
  1272. $attname = '';
  1273. $atttype = false;
  1274. $attary = Array();
  1275. while ($pos <= strlen($body)){
  1276. $pos = sq_skipspace($body, $pos);
  1277. if ($pos == strlen($body)){
  1278. /**
  1279. * Non-closed tag.
  1280. */
  1281. return Array(false, false, false, $lt, $pos);
  1282. }
  1283. /**
  1284. * See if we arrived at a ">" or "/>", which means that we reached
  1285. * the end of the tag.
  1286. */
  1287. $matches = Array();
  1288. if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
  1289. /**
  1290. * Yep. So we did.
  1291. */
  1292. $pos += strlen($matches{1});
  1293. if ($matches{2} == "/>"){
  1294. $tagtype = 3;
  1295. $pos++;
  1296. }
  1297. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1298. }
  1299. /**
  1300. * There are several types of attributes, with optional
  1301. * [:space:] between members.
  1302. * Type 1:
  1303. * attrname[:space:]=[:space:]'CDATA'
  1304. * Type 2:
  1305. * attrname[:space:]=[:space:]"CDATA"
  1306. * Type 3:
  1307. * attr[:space:]=[:space:]CDATA
  1308. * Type 4:
  1309. * attrname
  1310. *
  1311. * We leave types 1 and 2 the same, type 3 we check for
  1312. * '"' and convert to "&quot" if needed, then wrap in
  1313. * double quotes. Type 4 we convert into:
  1314. * attrname="yes".
  1315. */
  1316. $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
  1317. if ($regary == false){
  1318. /**
  1319. * Looks like body ended before the end of tag.
  1320. */
  1321. return Array(false, false, false, $lt, strlen($body));
  1322. }
  1323. list($pos, $attname, $match) = $regary;
  1324. $attname = strtolower($attname);
  1325. /**
  1326. * We arrived at the end of attribute name. Several things possible
  1327. * here:
  1328. * '>' means the end of the tag and this is attribute type 4
  1329. * '/' if followed by '>' means the same thing as above
  1330. * '\s' means a lot of things -- look what it's followed by.
  1331. * anything else means the attribute is invalid.
  1332. */
  1333. switch($match){
  1334. case '/':
  1335. /**
  1336. * This is an xhtml-style tag with a closing / at the
  1337. * end, like so: <img src="blah" />. Check if it's followed
  1338. * by the closing bracket. If not, then this tag is invalid
  1339. */
  1340. if (substr($body, $pos, 2) == "/>"){
  1341. $pos++;
  1342. $tagtype = 3;
  1343. } else {
  1344. $gt = sq_findnxstr($body, $pos, ">");
  1345. $retary = Array(false, false, false, $lt, $gt);
  1346. return $retary;
  1347. }
  1348. case '>':
  1349. $attary{$attname} = '"yes"';
  1350. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1351. break;
  1352. default:
  1353. /**
  1354. * Skip whitespace and see what we arrive at.
  1355. */
  1356. $pos = sq_skipspace($body, $pos);
  1357. $char = substr($body, $pos, 1);
  1358. /**
  1359. * Two things are valid here:
  1360. * '=' means this is attribute type 1 2 or 3.
  1361. * \w means this was attribute type 4.
  1362. * anything else we ignore and re-loop. End of tag and
  1363. * invalid stuff will be caught by our checks at the beginning
  1364. * of the loop.
  1365. */
  1366. if ($char == "="){
  1367. $pos++;
  1368. $pos = sq_skipspace($body, $pos);
  1369. /**
  1370. * Here are 3 possibilities:
  1371. * "'" attribute type 1
  1372. * '"' attribute type 2
  1373. * everything else is the content of tag type 3
  1374. */
  1375. $quot = substr($body, $pos, 1);
  1376. if ($quot == "'"){
  1377. $regary = sq_findnxreg($body, $pos+1, "\'");
  1378. if ($regary == false){
  1379. return Array(false, false, false, $lt, strlen($body));
  1380. }
  1381. list($pos, $attval, $match) = $regary;
  1382. $pos++;
  1383. $attary{$attname} = "'" . $attval . "'";
  1384. } else if ($quot == '"'){
  1385. $regary = sq_findnxreg($body, $pos+1, '\"');
  1386. if ($regary == false){
  1387. return Array(false, false, false, $lt, strlen($body));
  1388. }
  1389. list($pos, $attval, $match) = $regary;
  1390. $pos++;
  1391. $attary{$attname} = '"' . $attval . '"';
  1392. } else {
  1393. /**
  1394. * These are hateful. Look for \s, or >.
  1395. */
  1396. $regary = sq_findnxreg($body, $pos, "[\s>]");
  1397. if ($regary == false){
  1398. return Array(false, false, false, $lt, strlen($body));
  1399. }
  1400. list($pos, $attval, $match) = $regary;
  1401. /**
  1402. * If it's ">" it will be caught at the top.
  1403. */
  1404. $attval = preg_replace("/\"/s", "&quot;", $attval);
  1405. $attary{$attname} = '"' . $attval . '"';
  1406. }
  1407. } else if (preg_match("|[\w/>]|", $char)) {
  1408. /**
  1409. * That was attribute type 4.
  1410. */
  1411. $attary{$attname} = '"yes"';
  1412. } else {
  1413. /**
  1414. * An illegal character. Find next '>' and return.
  1415. */
  1416. $gt = sq_findnxstr($body, $pos, ">");
  1417. return Array(false, false, false, $lt, $gt);
  1418. }
  1419. break;
  1420. }
  1421. }
  1422. /**
  1423. * The fact that we got here indicates that the tag end was never
  1424. * found. Return invalid tag indication so it gets stripped.
  1425. */
  1426. return Array(false, false, false, $lt, strlen($body));
  1427. }
  1428. /**
  1429. * Translates entities into literal values so they can be checked.
  1430. *
  1431. * @param $attvalue the by-ref value to check.
  1432. * @param $regex the regular expression to check against.
  1433. * @param $hex whether the entites are hexadecimal.
  1434. * @return True or False depending on whether there were matches.
  1435. */
  1436. function sq_deent(&$attvalue, $regex, $hex=false){
  1437. $me = 'sq_deent';
  1438. $ret_match = false;
  1439. preg_match_all($regex, $attvalue, $matches);
  1440. if (is_array($matches) && sizeof($matches[0]) > 0){
  1441. $repl = Array();
  1442. for ($i = 0; $i < sizeof($matches[0]); $i++){
  1443. $numval = $matches[1][$i];
  1444. if ($hex){
  1445. $numval = hexdec($numval);
  1446. }
  1447. $repl{$matches[0][$i]} = chr($numval);
  1448. }
  1449. $attvalue = strtr($attvalue, $repl);
  1450. return true;
  1451. } else {
  1452. return false;
  1453. }
  1454. }
  1455. /**
  1456. * This function runs various checks against the attributes.
  1457. *
  1458. * @param $tagname String with the name of the tag.
  1459. * @param $attary Array with all tag attributes.
  1460. * @param $rm_attnames See description for sq_sanitize
  1461. * @param $bad_attvals See description for sq_sanitize
  1462. * @param $add_attr_to_tag See description for sq_sanitize
  1463. * @param $message message object
  1464. * @param $id message id
  1465. * @return Array with modified attributes.
  1466. */
  1467. function sq_fixatts($tagname,
  1468. $attary,
  1469. $rm_attnames,
  1470. $bad_attvals,
  1471. $add_attr_to_tag,
  1472. $message,
  1473. $id,
  1474. $mailbox
  1475. ){
  1476. $me = 'sq_fixatts';
  1477. while (list($attname, $attvalue) = each($attary)){
  1478. /**
  1479. * See if this attribute should be removed.
  1480. */
  1481. foreach ($rm_attnames as $matchtag=>$matchattrs){
  1482. if (preg_match($matchtag, $tagname)){
  1483. foreach ($matchattrs as $matchattr){
  1484. if (preg_match($matchattr, $attname)){
  1485. unset($attary{$attname});
  1486. continue;
  1487. }
  1488. }
  1489. }
  1490. }
  1491. /**
  1492. * Remove any backslashes, entities, and extraneous whitespace.
  1493. */
  1494. sq_defang($attvalue);
  1495. sq_unspace($attvalue);
  1496. /**
  1497. * Now let's run checks on the attvalues.
  1498. * I don't expect anyone to comprehend this. If you do,
  1499. * get in touch with me so I can drive to where you live and
  1500. * shake your hand personally. :)
  1501. */
  1502. foreach ($bad_attvals as $matchtag=>$matchattrs){
  1503. if (preg_match($matchtag, $tagname)){
  1504. foreach ($matchattrs as $matchattr=>$valary){
  1505. if (preg_match($matchattr, $attname)){
  1506. /**
  1507. * There are two arrays in valary.
  1508. * First is matches.
  1509. * Second one is replacements
  1510. */
  1511. list($valmatch, $valrepl) = $valary;
  1512. $newvalue =
  1513. preg_replace($valmatch, $valrepl, $attvalue);
  1514. if ($newvalue != $attvalue){
  1515. $attary{$attname} = $newvalue;
  1516. }
  1517. }
  1518. }
  1519. }
  1520. }
  1521. /**
  1522. * Replace empty src tags with the blank image. src is only used
  1523. * for frames, images, and image inputs. Doing a replace should
  1524. * not affect them working as should be, however it will stop
  1525. * IE from being kicked off when src for img tags are not set
  1526. */
  1527. if (($attname == 'src') && ($attvalue == '""')) {
  1528. $attary{$attname} = '"' . SM_PATH . 'images/blank.png"';
  1529. }
  1530. /**
  1531. * Turn cid: urls into http-friendly ones.
  1532. */
  1533. if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
  1534. $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
  1535. }
  1536. /**
  1537. * "Hack" fix for Outlook using propriatary outbind:// protocol in img tags.
  1538. * One day MS might actually make it match something useful, for now, falling
  1539. * back to using cid2http, so we can grab the blank.png.
  1540. */
  1541. if (preg_match("/^[\'\"]\s*outbind:\/\//si", $attvalue)) {
  1542. $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
  1543. }
  1544. }
  1545. /**
  1546. * See if we need to append any attributes to this tag.
  1547. */
  1548. foreach ($add_attr_to_tag as $matchtag=>$addattary){
  1549. if (preg_match($matchtag, $tagname)){
  1550. $attary = array_merge($attary, $addattary);
  1551. }
  1552. }
  1553. return $attary;
  1554. }
  1555. /**
  1556. * This function edits the style definition to make them friendly and
  1557. * usable in SquirrelMail.
  1558. *
  1559. * @param $message the message object
  1560. * @param $id the message id
  1561. * @param $content a string with whatever is between <style> and </style>
  1562. * @param $mailbox the message mailbox
  1563. * @return a string with edited content.
  1564. */
  1565. function sq_fixstyle($body, $pos, $message, $id, $mailbox){
  1566. global $view_unsafe_images;
  1567. $me = 'sq_fixstyle';
  1568. $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
  1569. if ($ret == FALSE){
  1570. return array(FALSE, strlen($body));
  1571. }
  1572. $newpos = $ret[0] + strlen($ret[2]);
  1573. $content = $ret[1];
  1574. /**
  1575. * First look for general BODY style declaration, which would be
  1576. * like so:
  1577. * body {background: blah-blah}
  1578. * and change it to .bodyclass so we can just assign it to a <div>
  1579. */
  1580. $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
  1581. $secremoveimg = '../images/' . _("sec_remove_eng.png");
  1582. /**
  1583. * Fix url('blah') declarations.
  1584. */
  1585. // $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
  1586. // "url(\\1$secremoveimg\\2)", $content);
  1587. // remove NUL
  1588. $content = str_replace("\0", "", $content);
  1589. // translate ur\l and variations (IE parses that)
  1590. $content = preg_replace("/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i", 'url', $content);
  1591. // NB I insert NUL characters to keep to avoid an infinite loop. They are removed after the loop.
  1592. while (preg_match("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si", $content, $matches)) {
  1593. $sProto = strtolower($matches[1]);
  1594. switch ($sProto) {
  1595. /**
  1596. * Fix url('https*://.*) declarations but only if $view_unsafe_images
  1597. * is false.
  1598. */
  1599. case 'https':
  1600. case 'http':
  1601. if (!$view_unsafe_images){
  1602. $sExpr = "/url\s*\(\s*[\'\"]?\s*$sProto*:.*[\'\"]?\s*\)/si";
  1603. $content = preg_replace($sExpr, "u\0r\0l(\\1$secremoveimg\\2)", $content);
  1604. } else {
  1605. $content = preg_replace('/url/i',"u\0r\0l",$content);
  1606. }
  1607. break;
  1608. /**
  1609. * Fix urls that refer to cid:
  1610. */
  1611. case 'cid':
  1612. $cidurl = 'cid:'. $matches[2];
  1613. $httpurl = sq_cid2http($message, $id, $cidurl, $mailbox);
  1614. // escape parentheses that can modify the regular expression
  1615. $cidurl = str_replace(array('(',')'),array('\\(','\\)'),$cidurl);
  1616. $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
  1617. "u\0r\0l($httpurl)", $content);
  1618. break;
  1619. default:
  1620. /**
  1621. * replace url with protocol other then the white list
  1622. * http,https and cid by an empty string.
  1623. */
  1624. $content = preg_replace("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si",
  1625. "", $content);
  1626. break;
  1627. }
  1628. }
  1629. // remove NUL
  1630. $content = str_replace("\0", "", $content);
  1631. /**
  1632. * Remove any backslashes, entities, and extraneous whitespace.
  1633. */
  1634. $contentTemp = $content;
  1635. sq_defang($contentTemp);
  1636. sq_unspace($contentTemp);
  1637. /**
  1638. * Fix stupid css declarations which lead to vulnerabilities
  1639. * in IE.
  1640. */
  1641. $match = Array('/\/\*.*\*\//',
  1642. '/expression/i',
  1643. '/behaviou*r/i',
  1644. '/binding/i',
  1645. '/include-source/i');
  1646. $replace = Array('','idiocy', 'idiocy', 'idiocy', 'idiocy');
  1647. $contentNew = preg_replace($match, $replace, $contentTemp);
  1648. if ($contentNew !== $contentTemp) {
  1649. // insecure css declarations are used. From now on we don't care
  1650. // anymore if the css is destroyed by sq_deent, sq_unspace or sq_unbackslash
  1651. $content = $contentNew;
  1652. }
  1653. return array($content, $newpos);
  1654. }
  1655. /**
  1656. * This function converts cid: url's into the ones that can be viewed in
  1657. * the browser.
  1658. *
  1659. * @param $message the message object
  1660. * @param $id the message id
  1661. * @param $cidurl the cid: url.
  1662. * @param $mailbox the message mailbox
  1663. * @return a string with a http-friendly url
  1664. */
  1665. function sq_cid2http($message, $id, $cidurl, $mailbox){
  1666. /**
  1667. * Get rid of quotes.
  1668. */
  1669. $quotchar = substr($cidurl, 0, 1);
  1670. if ($quotchar == '"' || $quotchar == "'"){
  1671. $cidurl = str_replace($quotchar, "", $cidurl);
  1672. } else {
  1673. $quotchar = '';
  1674. }
  1675. $cidurl = substr(trim($cidurl), 4);
  1676. $match_str = '/\{.*?\}\//';
  1677. $str_rep = '';
  1678. $cidurl = preg_replace($match_str, $str_rep, $cidurl);
  1679. $linkurl = find_ent_id($cidurl, $message);
  1680. /* in case of non-save cid links $httpurl should be replaced by a sort of
  1681. unsave link image */
  1682. $httpurl = '';
  1683. /**
  1684. * This is part of a fix for Outlook Express 6.x generating
  1685. * cid URLs without creating content-id headers. These images are
  1686. * not part of the multipart/related html mail. The html contains
  1687. * <img src="cid:{some_id}/image_filename.ext"> references to
  1688. * attached images with as goal to render them inline although
  1689. * the attachment disposition property is not inline.
  1690. */
  1691. if (empty($linkurl)) {
  1692. if (preg_match('/{.*}\//', $cidurl)) {
  1693. $cidurl = preg_replace('/{.*}\//','', $cidurl);
  1694. if (!empty($cidurl)) {
  1695. $linkurl = find_ent_id($cidurl, $message);
  1696. }
  1697. }
  1698. }
  1699. if (!empty($linkurl)) {
  1700. $httpurl = $quotchar . SM_PATH . 'src/download.php?absolute_dl=true&amp;' .
  1701. "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
  1702. '&amp;ent_id=' . $linkurl . $quotchar;
  1703. } else {
  1704. /**
  1705. * If we couldn't generate a proper img url, drop in a blank image
  1706. * instead of sending back empty, otherwise it causes unusual behaviour
  1707. */
  1708. $httpurl = $quotchar . SM_PATH . 'images/blank.png' . $quotchar;
  1709. }
  1710. return $httpurl;
  1711. }
  1712. /**
  1713. * This function changes the <body> tag into a <div> tag since we
  1714. * can't really have a body-within-body.
  1715. *
  1716. * @param $attary an array of attributes and values of <body>
  1717. * @param $mailbox mailbox we're currently reading (for cid2http)
  1718. * @param $message current message (for cid2http)
  1719. * @param $id current message id (for cid2http)
  1720. * @return a modified array of attributes to be set for <div>
  1721. */
  1722. function sq_body2div($attary, $mailbox, $message, $id){
  1723. $me = 'sq_body2div';
  1724. $divattary = Array('class' => "'bodyclass'");
  1725. $text = '#000000';
  1726. $has_bgc_stl = $has_txt_stl = false;
  1727. $styledef = '';
  1728. if (is_array($attary) && sizeof($attary) > 0){
  1729. foreach ($attary as $attname=>$attvalue){
  1730. $quotchar = substr($attvalue, 0, 1);
  1731. $attvalue = str_replace($quotchar, "", $attvalue);
  1732. switch ($attname){
  1733. case 'background':
  1734. $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
  1735. $styledef .= "background-image: url('$attvalue'); ";
  1736. break;
  1737. case 'bgcolor':
  1738. $has_bgc_stl = true;
  1739. $styledef .= "background-color: $attvalue; ";
  1740. break;
  1741. case 'text':
  1742. $has_txt_stl = true;
  1743. $styledef .= "color: $attvalue; ";
  1744. break;
  1745. }
  1746. }
  1747. // Outlook defines a white bgcolor and no text color. This can lead to
  1748. // white text on a white bg with certain themes.
  1749. if ($has_bgc_stl && !$has_txt_stl) {
  1750. $styledef .= "color: $text; ";
  1751. }
  1752. if (strlen($styledef) > 0){
  1753. $divattary{"style"} = "\"$styledef\"";
  1754. }
  1755. }
  1756. return $divattary;
  1757. }
  1758. /**
  1759. * This is the main function and the one you should actually be calling.
  1760. * There are several variables you should be aware of an which need
  1761. * special description.
  1762. *
  1763. * Since the description is quite lengthy, see it here:
  1764. * http://linux.duke.edu/projects/mini/htmlfilter/
  1765. *
  1766. * @param $body the string with HTML you wish to filter
  1767. * @param $tag_list see description above
  1768. * @param $rm_tags_with_content see description above
  1769. * @param $self_closing_tags see description above
  1770. * @param $force_tag_closing see description above
  1771. * @param $rm_attnames see description above
  1772. * @param $bad_attvals see description above
  1773. * @param $add_attr_to_tag see description above
  1774. * @param $message message object
  1775. * @param $id message id
  1776. * @return sanitized html safe to show on your pages.
  1777. */
  1778. function sq_sanitize($body,
  1779. $tag_list,
  1780. $rm_tags_with_content,
  1781. $self_closing_tags,
  1782. $force_tag_closing,
  1783. $rm_attnames,
  1784. $bad_attvals,
  1785. $add_attr_to_tag,
  1786. $message,
  1787. $id,
  1788. $mailbox
  1789. ){
  1790. $me = 'sq_sanitize';
  1791. $rm_tags = array_shift($tag_list);
  1792. /**
  1793. * Normalize rm_tags and rm_tags_with_content.
  1794. */
  1795. @array_walk($tag_list, 'sq_casenormalize');
  1796. @array_walk($rm_tags_with_content, 'sq_casenormalize');
  1797. @array_walk($self_closing_tags, 'sq_casenormalize');
  1798. /**
  1799. * See if tag_list is of tags to remove or tags to allow.
  1800. * false means remove these tags
  1801. * true means allow these tags
  1802. */
  1803. $curpos = 0;
  1804. $open_tags = Array();
  1805. $trusted = "\n<!-- begin sanitized html -->\n";
  1806. $skip_content = false;
  1807. /**
  1808. * Take care of netscape's stupid javascript entities like
  1809. * &{alert('boo')};
  1810. */
  1811. $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
  1812. while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
  1813. list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
  1814. $free_content = substr($body, $curpos, $lt-$curpos);
  1815. /**
  1816. * Take care of <style>
  1817. */
  1818. if ($tagname == "style" && $tagtype == 1){
  1819. list($free_content, $curpos) =
  1820. sq_fixstyle($body, $gt+1, $message, $id, $mailbox);
  1821. if ($free_content != FALSE){
  1822. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1823. $trusted .= $free_content;
  1824. $trusted .= sq_tagprint($tagname, false, 2);
  1825. }
  1826. continue;
  1827. }
  1828. if ($skip_content == false){
  1829. $trusted .= $free_content;
  1830. }
  1831. if ($tagname != FALSE){
  1832. if ($tagtype == 2){
  1833. if ($skip_content == $tagname){
  1834. /**
  1835. * Got to the end of tag we needed to remove.
  1836. */
  1837. $tagname = false;
  1838. $skip_content = false;
  1839. } else {
  1840. if ($skip_content == false){
  1841. if ($tagname == "body"){
  1842. $tagname = "div";
  1843. }
  1844. if (isset($open_tags{$tagname}) &&
  1845. $open_tags{$tagname} > 0){
  1846. $open_tags{$tagname}--;
  1847. } else {
  1848. $tagname = false;
  1849. }
  1850. }
  1851. }
  1852. } else {
  1853. /**
  1854. * $rm_tags_with_content
  1855. */
  1856. if ($skip_content == false){
  1857. /**
  1858. * See if this is a self-closing type and change
  1859. * tagtype appropriately.
  1860. */
  1861. if ($tagtype == 1
  1862. && in_array($tagname, $self_closing_tags)){
  1863. $tagtype = 3;
  1864. }
  1865. /**
  1866. * See if we should skip this tag and any content
  1867. * inside it.
  1868. */
  1869. if ($tagtype == 1 &&
  1870. in_array($tagname, $rm_tags_with_content)){
  1871. $skip_content = $tagname;
  1872. } else {
  1873. if (($rm_tags == false
  1874. && in_array($tagname, $tag_list)) ||
  1875. ($rm_tags == true &&
  1876. !in_array($tagname, $tag_list))){
  1877. $tagname = false;
  1878. } else {
  1879. /**
  1880. * Convert body into div.
  1881. */
  1882. if ($tagname == "body"){
  1883. $tagname = "div";
  1884. $attary = sq_body2div($attary, $mailbox,
  1885. $message, $id);
  1886. }
  1887. if ($tagtype == 1){
  1888. if (isset($open_tags{$tagname})){
  1889. $open_tags{$tagname}++;
  1890. } else {
  1891. $open_tags{$tagname}=1;
  1892. }
  1893. }
  1894. /**
  1895. * This is where we run other checks.
  1896. */
  1897. if (is_array($attary) && sizeof($attary) > 0){
  1898. $attary = sq_fixatts($tagname,
  1899. $attary,
  1900. $rm_attnames,
  1901. $bad_attvals,
  1902. $add_attr_to_tag,
  1903. $message,
  1904. $id,
  1905. $mailbox
  1906. );
  1907. }
  1908. }
  1909. }
  1910. }
  1911. }
  1912. if ($tagname != false && $skip_content == false){
  1913. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1914. }
  1915. }
  1916. $curpos = $gt+1;
  1917. }
  1918. $trusted .= substr($body, $curpos, strlen($body)-$curpos);
  1919. if ($force_tag_closing == true){
  1920. foreach ($open_tags as $tagname=>$opentimes){
  1921. while ($opentimes > 0){
  1922. $trusted .= '</' . $tagname . '>';
  1923. $opentimes--;
  1924. }
  1925. }
  1926. $trusted .= "\n";
  1927. }
  1928. $trusted .= "<!-- end sanitized html -->\n";
  1929. return $trusted;
  1930. }
  1931. /**
  1932. * This is a wrapper function to call html sanitizing routines.
  1933. *
  1934. * @param $body the body of the message
  1935. * @param $id the id of the message
  1936. * @param $message
  1937. * @param $mailbox
  1938. * @param boolean $take_mailto_links When TRUE, converts mailto: links
  1939. * into internal SM compose links
  1940. * (optional; default = TRUE)
  1941. * @return a string with html safe to display in the browser.
  1942. */
  1943. function magicHTML($body, $id, $message, $mailbox = 'INBOX', $take_mailto_links =true) {
  1944. // require_once(SM_PATH . 'functions/url_parser.php'); // for $MailTo_PReg_Match
  1945. global $attachment_common_show_images, $view_unsafe_images,
  1946. $has_unsafe_images;
  1947. /**
  1948. * Don't display attached images in HTML mode.
  1949. */
  1950. $attachment_common_show_images = false;
  1951. $tag_list = Array(
  1952. false,
  1953. "object",
  1954. "meta",
  1955. "html",
  1956. "head",
  1957. "base",
  1958. "link",
  1959. "frame",
  1960. "iframe",
  1961. "plaintext",
  1962. "marquee"
  1963. );
  1964. $rm_tags_with_content = Array(
  1965. "script",
  1966. "applet",
  1967. "embed",
  1968. "title",
  1969. "frameset",
  1970. "xmp",
  1971. "xml"
  1972. );
  1973. $self_closing_tags = Array(
  1974. "img",
  1975. "br",
  1976. "hr",
  1977. "input",
  1978. "outbind"
  1979. );
  1980. $force_tag_closing = true;
  1981. $rm_attnames = Array(
  1982. "/.*/" =>
  1983. Array(
  1984. "/target/i",
  1985. "/^on.*/i",
  1986. "/^dynsrc/i",
  1987. "/^data.*/i",
  1988. "/^lowsrc.*/i"
  1989. )
  1990. );
  1991. $secremoveimg = "../images/" . _("sec_remove_eng.png");
  1992. $bad_attvals = Array(
  1993. "/.*/" =>
  1994. Array(
  1995. "/^src|background/i" =>
  1996. Array(
  1997. Array(
  1998. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1999. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  2000. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  2001. ),
  2002. Array(
  2003. "\\1$secremoveimg\\2",
  2004. "\\1$secremoveimg\\2",
  2005. "\\1$secremoveimg\\2",
  2006. )
  2007. ),
  2008. "/^href|action/i" =>
  2009. Array(
  2010. Array(
  2011. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  2012. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  2013. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  2014. ),
  2015. Array(
  2016. "\\1#\\1",
  2017. "\\1#\\1",
  2018. "\\1#\\1"
  2019. )
  2020. ),
  2021. "/^style/i" =>
  2022. Array(
  2023. Array(
  2024. "/\/\*.*\*\//",
  2025. "/expression/i",
  2026. "/binding/i",
  2027. "/behaviou*r/i",
  2028. "/include-source/i",
  2029. "/position\s*:\s*absolute/i",
  2030. "/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i",
  2031. "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
  2032. "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
  2033. "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
  2034. "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
  2035. ),
  2036. Array(
  2037. "",
  2038. "idiocy",
  2039. "idiocy",
  2040. "idiocy",
  2041. "idiocy",
  2042. "",
  2043. "url",
  2044. "url(\\1#\\1)",
  2045. "url(\\1#\\1)",
  2046. "url(\\1#\\1)",
  2047. "\\1:url(\\2#\\3)"
  2048. )
  2049. )
  2050. )
  2051. );
  2052. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  2053. $view_unsafe_images = false;
  2054. }
  2055. if (!$view_unsafe_images){
  2056. /**
  2057. * Remove any references to http/https if view_unsafe_images set
  2058. * to false.
  2059. */
  2060. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
  2061. '/^([\'\"])\s*https*:.*([\'\"])/si');
  2062. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
  2063. "\\1$secremoveimg\\1");
  2064. array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
  2065. '/url\([\'\"]?https?:[^\)]*[\'\"]?\)/si');
  2066. array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
  2067. "url(\\1$secremoveimg\\1)");
  2068. }
  2069. $add_attr_to_tag = Array(
  2070. "/^a$/i" =>
  2071. Array('target'=>'"_blank"',
  2072. 'title'=>'"'._("This external link will open in a new window").'"'
  2073. )
  2074. );
  2075. $trusted = sq_sanitize($body,
  2076. $tag_list,
  2077. $rm_tags_with_content,
  2078. $self_closing_tags,
  2079. $force_tag_closing,
  2080. $rm_attnames,
  2081. $bad_attvals,
  2082. $add_attr_to_tag,
  2083. $message,
  2084. $id,
  2085. $mailbox
  2086. );
  2087. if (preg_match("|$secremoveimg|i", $trusted)){
  2088. $has_unsafe_images = true;
  2089. }
  2090. // we want to parse mailto's in HTML output, change to SM compose links
  2091. // this is a modified version of code from url_parser.php... but Marc is
  2092. // right: we need a better filtering implementation; adding this randomly
  2093. // here is not a great solution
  2094. //
  2095. if ($take_mailto_links) {
  2096. // parseUrl($trusted); // this even parses URLs inside of tags... too aggressive
  2097. global $MailTo_PReg_Match;
  2098. $MailTo_PReg_Match = '/mailto:' . substr($MailTo_PReg_Match, 1) ;
  2099. if ((preg_match_all($MailTo_PReg_Match, $trusted, $regs)) && ($regs[0][0] != '')) {
  2100. foreach ($regs[0] as $i => $mailto_before) {
  2101. $mailto_params = $regs[10][$i];
  2102. // get rid of any tailing quote since we have to add send_to to the end
  2103. //
  2104. if (substr($mailto_before, strlen($mailto_before) - 1) == '"')
  2105. $mailto_before = substr($mailto_before, 0, strlen($mailto_before) - 1);
  2106. if (substr($mailto_params, strlen($mailto_params) - 1) == '"')
  2107. $mailto_params = substr($mailto_params, 0, strlen($mailto_params) - 1);
  2108. if ($regs[1][$i]) { //if there is an email addr before '?', we need to merge it with the params
  2109. $to = 'to=' . $regs[1][$i];
  2110. if (strpos($mailto_params, 'to=') > -1) //already a 'to='
  2111. $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
  2112. else {
  2113. if ($mailto_params) //already some params, append to them
  2114. $mailto_params .= '&amp;' . $to;
  2115. else
  2116. $mailto_params .= '?' . $to;
  2117. }
  2118. }
  2119. $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
  2120. // we'll already have target=_blank, no need to allow comp_in_new
  2121. // here (which would be a lot more work anyway)
  2122. //
  2123. global $compose_new_win;
  2124. $temp_comp_in_new = $compose_new_win;
  2125. $compose_new_win = 0;
  2126. $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
  2127. $compose_new_win = $temp_comp_in_new;
  2128. // remove <a href=" and anything after the next quote (we only
  2129. // need the uri, not the link HTML) in compose uri
  2130. //
  2131. $comp_uri = substr($comp_uri, 9);
  2132. $comp_uri = substr($comp_uri, 0, strpos($comp_uri, '"', 1));
  2133. $trusted = str_replace($mailto_before, $comp_uri, $trusted);
  2134. }
  2135. }
  2136. }
  2137. return $trusted;
  2138. }
  2139. /**
  2140. * function SendDownloadHeaders - send file to the browser
  2141. *
  2142. * Original Source: SM core src/download.php
  2143. * moved here to make it available to other code, and separate
  2144. * front end from back end functionality.
  2145. *
  2146. * @param string $type0 first half of mime type
  2147. * @param string $type1 second half of mime type
  2148. * @param string $filename filename to tell the browser for downloaded file
  2149. * @param boolean $force whether to force the download dialog to pop
  2150. * @param optional integer $filesize send the Content-Header and length to the browser
  2151. * @return void
  2152. */
  2153. function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
  2154. global $languages, $squirrelmail_language;
  2155. $isIE = $isIE6plus = false;
  2156. sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER);
  2157. if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
  2158. strstr($HTTP_USER_AGENT, 'Opera') === false) {
  2159. $isIE = true;
  2160. }
  2161. if (preg_match('/compatible; MSIE ([0-9]+)/', $HTTP_USER_AGENT, $match) &&
  2162. ((int)$match[1]) >= 6 && strstr($HTTP_USER_AGENT, 'Opera') === false) {
  2163. $isIE6plus = true;
  2164. }
  2165. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  2166. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
  2167. $filename =
  2168. call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
  2169. } else {
  2170. $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace('&nbsp;', ' ', $filename));
  2171. }
  2172. // A Pox on Microsoft and it's Internet Explorer!
  2173. //
  2174. // IE has lots of bugs with file downloads.
  2175. // It also has problems with SSL. Both of these cause problems
  2176. // for us in this function.
  2177. //
  2178. // See this article on Cache Control headers and SSL
  2179. // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
  2180. //
  2181. // The best thing you can do for IE is to upgrade to the latest
  2182. // version
  2183. //set all the Cache Control Headers for IE
  2184. if ($isIE) {
  2185. $filename=rawurlencode($filename);
  2186. header ("Pragma: public");
  2187. header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
  2188. header ("Cache-Control: post-check=0, pre-check=0", false);
  2189. header ("Cache-Control: private");
  2190. //set the inline header for IE, we'll add the attachment header later if we need it
  2191. header ("Content-Disposition: inline; filename=$filename");
  2192. }
  2193. if (!$force) {
  2194. // Try to show in browser window
  2195. header ("Content-Disposition: inline; filename=\"$filename\"");
  2196. header ("Content-Type: $type0/$type1; name=\"$filename\"");
  2197. } else {
  2198. // Try to pop up the "save as" box
  2199. // IE makes this hard. It pops up 2 save boxes, or none.
  2200. // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
  2201. // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
  2202. // But, according to Microsoft, it is "RFC compliant but doesn't
  2203. // take into account some deviations that allowed within the
  2204. // specification." Doesn't that mean RFC non-compliant?
  2205. // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
  2206. // all browsers need the application/octet-stream header for this
  2207. header ("Content-Type: application/octet-stream; name=\"$filename\"");
  2208. // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
  2209. // Do not have quotes around filename, but that applied to
  2210. // "attachment"... does it apply to inline too?
  2211. header ("Content-Disposition: attachment; filename=\"$filename\"");
  2212. if ($isIE && !$isIE6plus) {
  2213. // This combination seems to work mostly. IE 5.5 SP 1 has
  2214. // known issues (see the Microsoft Knowledge Base)
  2215. // This works for most types, but doesn't work with Word files
  2216. header ("Content-Type: application/download; name=\"$filename\"");
  2217. // These are spares, just in case. :-)
  2218. //header("Content-Type: $type0/$type1; name=\"$filename\"");
  2219. //header("Content-Type: application/x-msdownload; name=\"$filename\"");
  2220. //header("Content-Type: application/octet-stream; name=\"$filename\"");
  2221. } else {
  2222. // another application/octet-stream forces download for Netscape
  2223. header ("Content-Type: application/octet-stream; name=\"$filename\"");
  2224. }
  2225. }
  2226. //send the content-length header if the calling function provides it
  2227. if ($filesize > 0) {
  2228. header("Content-Length: $filesize");
  2229. }
  2230. } // end fn SendDownloadHeaders