mime.php 97 KB

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