mime.php 89 KB

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