mime.php 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946
  1. <?php
  2. /**
  3. * mime.php
  4. *
  5. * This contains the functions necessary to detect and decode MIME
  6. * messages.
  7. *
  8. * @copyright 1999-2019 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. displayPageHeader( $color, $mailbox );
  52. $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
  53. $errormessage .= '<br />'._("The bodystructure provided by your IMAP server:").'<br /><br />';
  54. $errormessage .= '<pre>' . sm_encode_html_special_chars($read) . '</pre>';
  55. plain_error_message( $errormessage );
  56. echo '</body></html>';
  57. exit;
  58. }
  59. if (count($flags)) {
  60. foreach ($flags as $flag) {
  61. //FIXME: please document why it is we have to check the first char of the flag but we then go ahead and do a full string comparison anyway. Is this a speed enhancement? If not, let's keep it simple and just compare the full string and forget the switch block.
  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. else if (strtolower($flag) == '$forwarded') {
  84. $msg->is_forwarded = true;
  85. }
  86. break;
  87. case 'M':
  88. if (strtolower($flag) == '$mdnsent') {
  89. $msg->is_mdnsent = true;
  90. }
  91. break;
  92. default:
  93. break;
  94. }
  95. }
  96. }
  97. // listEntities($msg);
  98. return $msg;
  99. }
  100. /* This starts the parsing of a particular structure. It is called recursively,
  101. * so it can be passed different structures. It returns an object of type
  102. * $message.
  103. * First, it checks to see if it is a multipart message. If it is, then it
  104. * handles that as it sees is necessary. If it is just a regular entity,
  105. * then it parses it and adds the necessary header information (by calling out
  106. * to mime_get_elements()
  107. */
  108. function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
  109. /* Do a bit of error correction. If we couldn't find the entity id, just guess
  110. * that it is the first one. That is usually the case anyway.
  111. */
  112. if (!$ent_id) {
  113. $cmd = "FETCH $id BODY[]";
  114. } else {
  115. $cmd = "FETCH $id BODY[$ent_id]";
  116. }
  117. if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
  118. $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
  119. do {
  120. $topline = trim(array_shift($data));
  121. } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH .*BODY.*/i', $topline)) ;
  122. // Matching with "BODY" above is difficult: in most cases "FETCH \(BODY" would work
  123. // but some servers may put other things in the same result, perhaps something such
  124. // as "* 23 FETCH (FLAGS (\Seen) BODY[1] {174}". There is some small chance that
  125. // if the character sequence "BODY" appears in a response where it isn't actually
  126. // a FETCH response data item name, the current regex will break things. The better
  127. // way to do this would be to parse the response correctly and not use a regex.
  128. $wholemessage = implode('', $data);
  129. if (preg_match('/\{([^\}]*)\}/', $topline, $regs)) {
  130. $ret = substr($wholemessage, 0, $regs[1]);
  131. /* There is some information in the content info header that could be important
  132. * in order to parse html messages. Let's get them here.
  133. */
  134. // if ($ret{0} == '<') {
  135. // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
  136. // }
  137. } else if (preg_match('/"([^"]*)"/', $topline, $regs)) {
  138. $ret = $regs[1];
  139. } else if ((stristr($topline, 'nil') !== false) && (empty($wholemessage))) {
  140. $ret = $wholemessage;
  141. } else {
  142. global $where, $what, $mailbox, $passed_id, $startMessage;
  143. $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
  144. if (isset($where) && isset($what)) {
  145. $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
  146. } else {
  147. $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  148. }
  149. $par .= '&amp;response=' . urlencode($response) .
  150. '&amp;message=' . urlencode($message) .
  151. '&amp;topline=' . urlencode($topline);
  152. echo '<tt><br />' .
  153. '<table width="80%"><tr>' .
  154. '<tr><td colspan="2">' .
  155. _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
  156. '</td></tr>' .
  157. '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
  158. '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
  159. '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
  160. '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
  161. "</table><br /></tt></font><hr />";
  162. $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
  163. array_shift($data);
  164. $wholemessage = implode('', $data);
  165. $ret = $wholemessage;
  166. }
  167. return $ret;
  168. }
  169. function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout', $force_crlf='') {
  170. /* Don't kill the connection if the browser is over a dialup
  171. * and it would take over 30 seconds to download it.
  172. * Don't call set_time_limit in safe mode.
  173. */
  174. if (!ini_get('safe_mode')) {
  175. set_time_limit(0);
  176. }
  177. /* in case of base64 encoded attachments, do not buffer them.
  178. Instead, echo the decoded attachment directly to screen */
  179. if (strtolower($encoding) == 'base64') {
  180. if (!$ent_id) {
  181. $query = "FETCH $id BODY[]";
  182. } else {
  183. $query = "FETCH $id BODY[$ent_id]";
  184. }
  185. sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode',$rStream,true);
  186. } else {
  187. $body = mime_fetch_body ($imap_stream, $id, $ent_id);
  188. if (is_resource($rStream)) {
  189. fputs($rStream,decodeBody($body, $encoding, $force_crlf));
  190. } else {
  191. echo decodeBody($body, $encoding, $force_crlf);
  192. }
  193. }
  194. /*
  195. TODO, use the same method for quoted printable.
  196. However, I assume that quoted printable attachments aren't that large
  197. so the performancegain / memory usage drop will be minimal.
  198. If we decide to add that then we need to adapt sqimap_fread because
  199. we need to split te result on \n and fread doesn't stop at \n. That
  200. means we also should provide $results from sqimap_fread (by ref) to
  201. te function and set $no_return to false. The $filter function for
  202. quoted printable should handle unsetting of $results.
  203. */
  204. /*
  205. TODO 2: find out how we write to the output stream php://stdout. fwrite
  206. doesn't work because 'php://stdout isn't a stream.
  207. */
  208. return;
  209. }
  210. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  211. /* This is here for debugging purposes. It will print out a list
  212. * of all the entity IDs that are in the $message object.
  213. */
  214. function listEntities ($message) {
  215. if ($message) {
  216. echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br />';
  217. for ($i = 0; isset($message->entities[$i]); $i++) {
  218. echo "$i : ";
  219. $msg = listEntities($message->entities[$i]);
  220. if ($msg) {
  221. echo "return: ";
  222. return $msg;
  223. }
  224. }
  225. }
  226. }
  227. function getPriorityStr($priority) {
  228. $priority_level = substr($priority,0,1);
  229. switch($priority_level) {
  230. /* Check for a higher then normal priority. */
  231. case '1':
  232. case '2':
  233. $priority_string = _("High");
  234. break;
  235. /* Check for a lower then normal priority. */
  236. case '4':
  237. case '5':
  238. $priority_string = _("Low");
  239. break;
  240. /* Check for a normal priority. */
  241. case '3':
  242. default:
  243. $priority_level = '3';
  244. $priority_string = _("Normal");
  245. break;
  246. }
  247. return $priority_string;
  248. }
  249. /* returns a $message object for a particular entity id */
  250. function getEntity ($message, $ent_id) {
  251. return $message->getEntity($ent_id);
  252. }
  253. /* translateText
  254. * Extracted from strings.php 23/03/2002
  255. */
  256. function translateText(&$body, $wrap_at, $charset) {
  257. global $where, $what; /* from searching */
  258. global $color; /* color theme */
  259. // require_once(SM_PATH . 'functions/url_parser.php');
  260. $body_ary = explode("\n", $body);
  261. for ($i=0; $i < count($body_ary); $i++) {
  262. $line = rtrim($body_ary[$i],"\r");
  263. if (strlen($line) - 2 >= $wrap_at) {
  264. sqWordWrap($line, $wrap_at, $charset);
  265. }
  266. $line = charset_decode($charset, $line);
  267. $line = str_replace("\t", ' ', $line);
  268. parseUrl ($line);
  269. $quotes = 0;
  270. $pos = 0;
  271. $j = strlen($line);
  272. while ($pos < $j) {
  273. if ($line[$pos] == ' ') {
  274. $pos++;
  275. } else if (strpos($line, '&gt;', $pos) === $pos) {
  276. $pos += 4;
  277. $quotes++;
  278. } else {
  279. break;
  280. }
  281. }
  282. if ($quotes % 2) {
  283. $line = '<span class="quote1">' . $line . '</span>';
  284. } elseif ($quotes) {
  285. $line = '<span class="quote2">' . $line . '</span>';
  286. }
  287. $body_ary[$i] = $line;
  288. }
  289. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  290. }
  291. /**
  292. * This returns a parsed string called $body. That string can then
  293. * be displayed as the actual message in the HTML. It contains
  294. * everything needed, including HTML Tags, Attachments at the
  295. * bottom, etc.
  296. *
  297. * Since 1.2.0 function uses message_body hook.
  298. * Till 1.3.0 function included output of formatAttachments().
  299. *
  300. * @param resource $imap_stream imap connection resource
  301. * @param object $message squirrelmail message object
  302. * @param array $color squirrelmail color theme array
  303. * @param integer $wrap_at number of characters per line
  304. * @param string $ent_num (since 1.3.0) message part id
  305. * @param integer $id (since 1.3.0) message id
  306. * @param string $mailbox (since 1.3.0) imap folder name
  307. * @return string html formated message text
  308. */
  309. function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
  310. /* This if statement checks for the entity to show as the
  311. * primary message. To add more of them, just put them in the
  312. * order that is their priority.
  313. */
  314. global $startMessage, $languages, $squirrelmail_language,
  315. $show_html_default, $sort, $has_unsafe_images, $passed_ent_id,
  316. $use_iframe, $iframe_height, $download_and_unsafe_link,
  317. $download_href, $unsafe_image_toggle_href, $unsafe_image_toggle_text,
  318. $oTemplate, $nbsp;
  319. // workaround for not updated config.php
  320. if (! isset($use_iframe)) $use_iframe = false;
  321. // If there's no "view_unsafe_images" variable in the URL, turn unsafe
  322. // images off by default.
  323. sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET, FALSE);
  324. $body = '';
  325. $urlmailbox = urlencode($mailbox);
  326. $body_message = getEntity($message, $ent_num);
  327. if (($body_message->header->type0 == 'text') ||
  328. ($body_message->header->type0 == 'rfc822')) {
  329. $body = mime_fetch_body ($imap_stream, $id, $ent_num);
  330. $body = decodeBody($body, $body_message->header->encoding);
  331. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  332. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
  333. if (mb_detect_encoding($body) != 'ASCII') {
  334. $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
  335. }
  336. }
  337. /* As of 1.5.2, $body is passed (and modified) by reference */
  338. do_hook('message_body', $body);
  339. /* If there are other types that shouldn't be formatted, add
  340. * them here.
  341. */
  342. if ($body_message->header->type1 == 'html') {
  343. if ($show_html_default <> 1) {
  344. $entity_conv = array('&nbsp;' => ' ',
  345. '<p>' => "\n",
  346. '<P>' => "\n",
  347. '<br>' => "\n",
  348. '<BR>' => "\n",
  349. '<br />' => "\n",
  350. '<BR />' => "\n",
  351. '&gt;' => '>',
  352. '&lt;' => '<');
  353. $body = strtr($body, $entity_conv);
  354. $body = strip_tags($body);
  355. $body = trim($body);
  356. translateText($body, $wrap_at,
  357. $body_message->header->getParameter('charset'));
  358. } elseif ($use_iframe) {
  359. /**
  360. * If we don't add html message between iframe tags,
  361. * we must detect unsafe images and modify $has_unsafe_images.
  362. */
  363. $html_body = magicHTML($body, $id, $message, $mailbox);
  364. // Convert character set in order to display html mails in different character set
  365. $html_body = charset_decode($body_message->header->getParameter('charset'),$html_body,false,true);
  366. // creating iframe url
  367. $iframeurl=sqm_baseuri().'src/view_html.php?'
  368. . 'mailbox=' . $urlmailbox
  369. . '&amp;passed_id=' . $id
  370. . '&amp;ent_id=' . $ent_num
  371. . '&amp;view_unsafe_images=' . (int) $view_unsafe_images;
  372. global $oTemplate;
  373. $oTemplate->assign('iframe_url', $iframeurl);
  374. $oTemplate->assign('iframe_height', $iframe_height);
  375. $oTemplate->assign('html_body', $html_body);
  376. $body = $oTemplate->fetch('read_html_iframe.tpl');
  377. } else {
  378. // old way of html rendering
  379. /**
  380. * convert character set. charset_decode does not remove html special chars
  381. * applied by magicHTML functions and does not sanitize them second time if
  382. * fourth argument is true.
  383. */
  384. $charset = $body_message->header->getParameter('charset');
  385. if (!empty($charset)) {
  386. $body = charset_decode($charset,$body,false,true);
  387. }
  388. $body = magicHTML($body, $id, $message, $mailbox);
  389. }
  390. } else {
  391. translateText($body, $wrap_at,
  392. $body_message->header->getParameter('charset'));
  393. }
  394. /*
  395. * Previously the links for downloading and unsafe images were printed
  396. * under the mail. By putting the links in a global variable we can
  397. * print it in the toolbar where it belongs. Since the original code was
  398. * in this place it's left here. It might be possible to move it to some
  399. * other place if that makes sense. The possibility to do so has not
  400. * been evaluated yet.
  401. */
  402. // Initialize the global variable to an empty string.
  403. // FIXME: To have $download_and_unsafe_link as a global variable might not be needed since the use of separate variables ($download_href, $unsafe_image_toggle_href, and $unsafe_image_toggle_text) for the templates was introduced.
  404. $download_and_unsafe_link = '';
  405. // Prepare and build a link for downloading the mail.
  406. $link = 'passed_id=' . $id . '&amp;ent_id='.$ent_num.
  407. '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
  408. '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  409. if (isset($passed_ent_id)) {
  410. $link .= '&amp;passed_ent_id='.$passed_ent_id;
  411. }
  412. $download_href = SM_PATH . 'src/download.php?absolute_dl=true&amp;' . $link;
  413. // Always add the link for downloading the mail as a file to the global
  414. // variable.
  415. $download_and_unsafe_link .= "$nbsp|$nbsp"
  416. . create_hyperlink($download_href, _("Download this as a file"));
  417. // Find out the right text to use in the link depending on the
  418. // circumstances. If the unsafe images are displayed the link should
  419. // hide them, if they aren't displayed the link should only appear if
  420. // the mail really contains unsafe images.
  421. if ($view_unsafe_images) {
  422. $text = _("Hide Unsafe Images");
  423. } else {
  424. if (isset($has_unsafe_images) && $has_unsafe_images) {
  425. $link .= '&amp;view_unsafe_images=1';
  426. $text = _("View Unsafe Images");
  427. } else {
  428. $text = '';
  429. }
  430. }
  431. // Only create a link for unsafe images if there's need for one. If so:
  432. // add it to the global variable.
  433. if($text != '') {
  434. $unsafe_image_toggle_href = SM_PATH . 'src/read_body.php?'.$link;
  435. $unsafe_image_toggle_text = $text;
  436. $download_and_unsafe_link .= "$nbsp|$nbsp"
  437. . create_hyperlink($unsafe_image_toggle_href, $text);
  438. }
  439. }
  440. return $body;
  441. }
  442. /**
  443. * Generate attachments array for passing to templates.
  444. *
  445. * @since 1.5.2
  446. * @param object $message SquirrelMail message object
  447. * @param array $exclude_id message parts that are not attachments.
  448. * @param string $mailbox mailbox name
  449. * @param integer $id message id
  450. */
  451. function buildAttachmentArray($message, $exclude_id, $mailbox, $id) {
  452. global $where, $what, $startMessage, $color, $passed_ent_id,
  453. $base_uri, $block_svg_download;
  454. $att_ar = $message->getAttachments($exclude_id);
  455. $urlMailbox = urlencode($mailbox);
  456. $attachments = array();
  457. foreach ($att_ar as $att) {
  458. $ent = $att->entity_id;
  459. $header = $att->header;
  460. $type0 = strtolower($header->type0);
  461. $type1 = strtolower($header->type1);
  462. if ($block_svg_download && strpos($type1, 'svg') === 0)
  463. continue;
  464. $name = '';
  465. $links = array();
  466. $links['download link']['text'] = _("Download");
  467. $links['download link']['href'] = $base_uri .
  468. "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
  469. if ($type0 =='message' && $type1 == 'rfc822') {
  470. $default_page = $base_uri . 'src/read_body.php';
  471. $rfc822_header = $att->rfc822_header;
  472. $filename = $rfc822_header->subject;
  473. if (trim( $filename ) == '') {
  474. $filename = 'untitled-[' . $ent . ']' ;
  475. }
  476. $from_o = $rfc822_header->from;
  477. if (is_object($from_o)) {
  478. $from_name = decodeHeader($from_o->getAddress(false));
  479. } elseif (is_array($from_o) && count($from_o) && is_object($from_o[0])) {
  480. // something weird happens when a digest message is opened and you return to the digest
  481. // now the from object is part of an array. Probably the parseHeader call overwrites the info
  482. // retrieved from the bodystructure in a different way. We need to fix this later.
  483. // possible starting point, do not fetch header we already have and inspect how
  484. // the rfc822_header object behaves.
  485. $from_name = decodeHeader($from_o[0]->getAddress(false));
  486. } else {
  487. $from_name = _("Unknown sender");
  488. }
  489. $description = _("From").': '.$from_name;
  490. } else {
  491. $default_page = $base_uri . 'src/download.php';
  492. $filename = $att->getFilename();
  493. if ($header->description) {
  494. $description = decodeHeader($header->description);
  495. } else {
  496. $description = '';
  497. }
  498. }
  499. $display_filename = $filename;
  500. if (isset($passed_ent_id)) {
  501. $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
  502. } else {
  503. $passed_ent_id_link = '';
  504. }
  505. $defaultlink = $default_page . "?startMessage=$startMessage"
  506. . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
  507. . '&amp;ent_id='.$ent.$passed_ent_id_link;
  508. if ($where && $what) {
  509. $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
  510. }
  511. // IE does make use of mime content sniffing. Forcing a download
  512. // prohibit execution of XSS inside an application/octet-stream attachment
  513. if ($type0 == 'application' && $type1 == 'octet-stream') {
  514. $defaultlink .= '&amp;absolute_dl=true';
  515. }
  516. /* This executes the attachment hook with a specific MIME-type.
  517. * It also allows plugins to run if there's a rule for a more
  518. * generic type. Finally, a hook for ALL attachment types is
  519. * run as well.
  520. */
  521. // First remember the default link.
  522. $defaultlink_orig = $defaultlink;
  523. /* The API for this hook has changed as of 1.5.2 so that all plugin
  524. arguments are passed in an array instead of each their own plugin
  525. argument, and arguments are passed by reference, so instead of
  526. returning any changes, changes should simply be made to the original
  527. arguments themselves. */
  528. $temp = array(&$links, &$startMessage, &$id, &$urlMailbox, &$ent,
  529. &$defaultlink, &$display_filename, &$where, &$what);
  530. do_hook("attachment $type0/$type1", $temp);
  531. /* The API for this hook has changed as of 1.5.2 so that all plugin
  532. arguments are passed in an array instead of each their own plugin
  533. argument, and arguments are passed by reference, so instead of
  534. returning any changes, changes should simply be made to the original
  535. arguments themselves. */
  536. $temp = array(&$links, &$startMessage, &$id, &$urlMailbox, &$ent,
  537. &$defaultlink, &$display_filename, &$where, &$what);
  538. // Do not let a generic plugin change the default link if a more
  539. // specialized one already did it...
  540. if ($defaultlink != $defaultlink_orig) {
  541. $dummy = '';
  542. $temp[5] = &$dummy;
  543. }
  544. do_hook("attachment $type0/*", $temp);
  545. /* The API for this hook has changed as of 1.5.2 so that all plugin
  546. arguments are passed in an array instead of each their own plugin
  547. argument, and arguments are passed by reference, so instead of
  548. returning any changes, changes should simply be made to the original
  549. arguments themselves. */
  550. $temp = array(&$links, &$startMessage, &$id, &$urlMailbox, &$ent,
  551. &$defaultlink, &$display_filename, &$where, &$what);
  552. // Do not let a generic plugin change the default link if a more
  553. // specialized one already did it...
  554. if ($defaultlink != $defaultlink_orig) {
  555. $dummy = '';
  556. $temp[5] = &$dummy;
  557. }
  558. do_hook("attachment */*", $temp);
  559. $this_attachment = array();
  560. $this_attachment['Name'] = decodeHeader($display_filename);
  561. $this_attachment['Description'] = $description;
  562. $this_attachment['DefaultHREF'] = $defaultlink;
  563. $this_attachment['DownloadHREF'] = $links['download link']['href'];
  564. $this_attachment['ViewHREF'] = isset($links['attachment_common']) ? $links['attachment_common']['href'] : '';
  565. $this_attachment['Size'] = $header->size;
  566. $this_attachment['ContentType'] = sm_encode_html_special_chars($type0 .'/'. $type1);
  567. $this_attachment['OtherLinks'] = array();
  568. foreach ($links as $val) {
  569. if ($val['text']==_("Download") || $val['text'] == _("View"))
  570. continue;
  571. if (empty($val['text']) && empty($val['extra']))
  572. continue;
  573. $temp = array();
  574. $temp['HREF'] = $val['href'];
  575. $temp['Text'] = (empty($val['text']) ? '' : $val['text']) . (empty($val['extra']) ? '' : $val['extra']);
  576. $this_attachment['OtherLinks'][] = $temp;
  577. }
  578. $attachments[] = $this_attachment;
  579. unset($links);
  580. }
  581. return $attachments;
  582. }
  583. /**
  584. * Displays attachment links and information
  585. *
  586. * Since 1.3.0 function is not included in formatBody() call.
  587. *
  588. * Since 1.0.2 uses attachment $type0/$type1 hook.
  589. * Since 1.2.5 uses attachment $type0/* hook.
  590. * Since 1.5.0 uses attachments_bottom hook.
  591. * Since 1.5.2 uses templates and does *not* return a value.
  592. *
  593. * @param object $message SquirrelMail message object
  594. * @param array $exclude_id message parts that are not attachments.
  595. * @param string $mailbox mailbox name
  596. * @param integer $id message id
  597. */
  598. function formatAttachments($message, $exclude_id, $mailbox, $id) {
  599. global $oTemplate;
  600. $attach = buildAttachmentArray($message, $exclude_id, $mailbox, $id);
  601. $oTemplate->assign('attachments', $attach);
  602. $oTemplate->display('read_attachments.tpl');
  603. }
  604. function sqimap_base64_decode(&$string) {
  605. // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
  606. // fly decoding (to reduce memory usage) you have to check if the
  607. // data has incomplete pairs
  608. // Remove the noise in order to check if the 4 bytes pairs are complete
  609. $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
  610. $sStringRem = '';
  611. $iMod = strlen($string) % 4;
  612. if ($iMod) {
  613. $sStringRem = substr($string,-$iMod);
  614. // Check if $sStringRem contains padding characters
  615. if (substr($sStringRem,-1) != '=') {
  616. $string = substr($string,0,-$iMod);
  617. } else {
  618. $sStringRem = '';
  619. }
  620. }
  621. $string = base64_decode($string);
  622. return $sStringRem;
  623. }
  624. /**
  625. * Decodes encoded string (usually message body)
  626. *
  627. * This function decodes a string (usually the message body)
  628. * depending on the encoding type. Currently quoted-printable
  629. * and base64 encodings are supported.
  630. *
  631. * The decode_body hook was added to this function in 1.4.2/1.5.0.
  632. * The $force_crlf parameter was added in 1.5.2.
  633. *
  634. * @param string $string The encoded string
  635. * @param string $encoding used encoding
  636. * @param string $force_crlf Whether or not to force CRLF or LF
  637. * line endings (or to leave as is).
  638. * If given as "LF", line endings will
  639. * all be converted to LF; if "CRLF",
  640. * line endings will all be converted
  641. * to CRLF. If given as an empty value,
  642. * the global $force_crlf_default will
  643. * be consulted (it can be specified in
  644. * config/config_local.php). Otherwise,
  645. * any other value will cause the string
  646. * to be left alone. Note that this will
  647. * be overridden to "LF" if not using at
  648. * least PHP version 4.3.0. (OPTIONAL;
  649. * default is empty - consult global
  650. * default value)
  651. *
  652. * @return string The decoded string
  653. *
  654. * @since 1.0
  655. *
  656. */
  657. function decodeBody($string, $encoding, $force_crlf='') {
  658. global $force_crlf_default;
  659. if (empty($force_crlf)) $force_crlf = $force_crlf_default;
  660. $force_crlf = strtoupper($force_crlf);
  661. // must force line endings to LF due to broken
  662. // quoted_printable_decode() in PHP versions
  663. // before 4.3.0 (see below)
  664. //
  665. if (!check_php_version(4, 3, 0) || $force_crlf == 'LF')
  666. $string = str_replace("\r\n", "\n", $string);
  667. else if ($force_crlf == 'CRLF')
  668. $string = str_replace("\n", "\r\n", $string);
  669. $encoding = strtolower($encoding);
  670. $encoding_handler = do_hook('decode_body', $encoding);
  671. // plugins get first shot at decoding the string
  672. //
  673. if (!empty($encoding_handler) && function_exists($encoding_handler)) {
  674. $string = $encoding_handler('decode', $string);
  675. } elseif ($encoding == 'quoted-printable' ||
  676. $encoding == 'quoted_printable') {
  677. // quoted_printable_decode() function is broken in older
  678. // php versions. Text with \r\n decoding was fixed only
  679. // in php 4.3.0. Minimal code requirement is PHP 4.0.4+
  680. // and the above call to: str_replace("\r\n", "\n", $string);
  681. //
  682. $string = quoted_printable_decode($string);
  683. } elseif ($encoding == 'base64') {
  684. $string = base64_decode($string);
  685. }
  686. // All other encodings are returned raw.
  687. return $string;
  688. }
  689. /**
  690. * Decodes headers
  691. *
  692. * This function decodes strings that are encoded according to
  693. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  694. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  695. *
  696. * @param string $string header string that has to be made readable
  697. * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
  698. * @param boolean $htmlsafe preserve spaces and sanitize html special characters. defaults to true
  699. * @param boolean $decide decide if string can be utfencoded. defaults to false
  700. * @return string decoded header string
  701. */
  702. function decodeHeader ($string, $utfencode=true,$htmlsafe=true,$decide=false) {
  703. global $languages, $squirrelmail_language,$default_charset, $fix_broken_base64_encoded_messages;
  704. if (is_array($string)) {
  705. $string = implode("\n", $string);
  706. }
  707. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  708. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
  709. $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
  710. // Do we need to return at this point?
  711. // return $string;
  712. }
  713. $i = 0;
  714. $iLastMatch = -2;
  715. $encoded = true;
  716. // FIXME: spaces are allowed inside quoted-printable encoding, but the following line will bust up any such encoded strings
  717. $aString = explode(' ',$string);
  718. $ret = '';
  719. foreach ($aString as $chunk) {
  720. if ($encoded && $chunk === '') {
  721. continue;
  722. } elseif ($chunk === '') {
  723. $ret .= ' ';
  724. continue;
  725. }
  726. $encoded = false;
  727. /* if encoded words are not separated by a linear-space-white we still catch them */
  728. $j = $i-1;
  729. while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  730. /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
  731. if ($iLastMatch !== $j) {
  732. if ($htmlsafe) {
  733. $ret .= '&#32;';
  734. } else {
  735. $ret .= ' ';
  736. }
  737. }
  738. $iLastMatch = $i;
  739. $j = $i;
  740. if ($htmlsafe) {
  741. $ret .= sm_encode_html_special_chars($res[1]);
  742. } else {
  743. $ret .= $res[1];
  744. }
  745. $encoding = ucfirst($res[3]);
  746. /* decide about valid decoding */
  747. if ($decide && is_conversion_safe($res[2])) {
  748. $utfencode=true;
  749. $can_be_encoded=true;
  750. } else {
  751. $can_be_encoded=false;
  752. }
  753. switch ($encoding)
  754. {
  755. case 'B':
  756. // fix broken base64-encoded strings (remove end = padding,
  757. // change any = to + in middle of string, add padding back
  758. // to the end)
  759. if ($fix_broken_base64_encoded_messages) {
  760. $encoded_string_minus_padding = strtr(rtrim($res[4], '='), '=', '+');
  761. $res[4] = str_pad($encoded_string_minus_padding, strlen($res[4]), '=');
  762. }
  763. $replace = base64_decode($res[4]);
  764. if ($utfencode) {
  765. if ($can_be_encoded) {
  766. /* convert string to different charset,
  767. * if functions asks for it (usually in compose)
  768. */
  769. $ret .= charset_convert($res[2],$replace,$default_charset,$htmlsafe);
  770. } else {
  771. // convert string to html codes in order to display it
  772. $ret .= charset_decode($res[2],$replace);
  773. }
  774. } else {
  775. if ($htmlsafe) {
  776. $replace = sm_encode_html_special_chars($replace);
  777. }
  778. $ret.= $replace;
  779. }
  780. break;
  781. case 'Q':
  782. $replace = str_replace('_', ' ', $res[4]);
  783. $replace = preg_replace_callback('/=([0-9a-f]{2})/i',
  784. create_function ('$matches', 'return chr(hexdec($matches[1]));'),
  785. $replace);
  786. if ($utfencode) {
  787. if ($can_be_encoded) {
  788. /* convert string to different charset,
  789. * if functions asks for it (usually in compose)
  790. */
  791. $replace = charset_convert($res[2], $replace,$default_charset,$htmlsafe);
  792. } else {
  793. // convert string to html codes in order to display it
  794. $replace = charset_decode($res[2], $replace);
  795. }
  796. } else {
  797. if ($htmlsafe) {
  798. $replace = sm_encode_html_special_chars($replace);
  799. }
  800. }
  801. $ret .= $replace;
  802. break;
  803. default:
  804. break;
  805. }
  806. $chunk = $res[5];
  807. $encoded = true;
  808. }
  809. if (!$encoded) {
  810. if ($htmlsafe) {
  811. $ret .= '&#32;';
  812. } else {
  813. $ret .= ' ';
  814. }
  815. }
  816. if (!$encoded && $htmlsafe) {
  817. $ret .= sm_encode_html_special_chars($chunk);
  818. } else {
  819. $ret .= $chunk;
  820. }
  821. ++$i;
  822. }
  823. /* remove the first added space */
  824. if ($ret) {
  825. if ($htmlsafe) {
  826. $ret = substr($ret,5);
  827. } else {
  828. $ret = substr($ret,1);
  829. }
  830. }
  831. return $ret;
  832. }
  833. /**
  834. * Encodes header
  835. *
  836. * Function uses XTRA_CODE _encodeheader function, if such function exists.
  837. *
  838. * Function uses Q encoding by default and encodes a string according to RFC
  839. * 1522 for use in headers if it contains 8-bit characters or anything that
  840. * looks like it should be encoded.
  841. *
  842. * Function switches to B encoding and encodeHeaderBase64() function, if
  843. * string is 8bit and multibyte character set supported by mbstring extension
  844. * is used. It can cause E_USER_NOTICE errors, if interface is used with
  845. * multibyte character set unsupported by mbstring extension.
  846. *
  847. * @param string $string header string, that has to be encoded
  848. * @return string quoted-printable encoded string
  849. * @todo make $mb_charsets system wide constant
  850. */
  851. function encodeHeader ($string) {
  852. global $default_charset, $languages, $squirrelmail_language;
  853. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  854. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
  855. return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
  856. }
  857. // Use B encoding for multibyte charsets
  858. $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
  859. if (in_array($default_charset,$mb_charsets) &&
  860. in_array($default_charset,sq_mb_list_encodings()) &&
  861. sq_is8bit($string)) {
  862. return encodeHeaderBase64($string,$default_charset);
  863. } elseif (in_array($default_charset,$mb_charsets) &&
  864. sq_is8bit($string) &&
  865. ! in_array($default_charset,sq_mb_list_encodings())) {
  866. // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
  867. // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
  868. }
  869. // Encode only if the string contains 8-bit characters or =?
  870. $j = strlen($string);
  871. $max_l = 75 - strlen($default_charset) - 7;
  872. $aRet = array();
  873. $ret = '';
  874. $iEncStart = $enc_init = false;
  875. $cur_l = $iOffset = 0;
  876. for($i = 0; $i < $j; ++$i) {
  877. switch($string{$i})
  878. {
  879. case '"':
  880. case '=':
  881. case '<':
  882. case '>':
  883. case ',':
  884. case '?':
  885. case '_':
  886. if ($iEncStart === false) {
  887. $iEncStart = $i;
  888. }
  889. $cur_l+=3;
  890. if ($cur_l > ($max_l-2)) {
  891. /* if there is an stringpart that doesn't need encoding, add it */
  892. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  893. $aRet[] = "=?$default_charset?Q?$ret?=";
  894. $iOffset = $i;
  895. $cur_l = 0;
  896. $ret = '';
  897. $iEncStart = false;
  898. } else {
  899. $ret .= sprintf("=%02X",ord($string{$i}));
  900. }
  901. break;
  902. case '(':
  903. case ')':
  904. if ($iEncStart !== false) {
  905. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  906. $aRet[] = "=?$default_charset?Q?$ret?=";
  907. $iOffset = $i;
  908. $cur_l = 0;
  909. $ret = '';
  910. $iEncStart = false;
  911. }
  912. break;
  913. case ' ':
  914. if ($iEncStart !== false) {
  915. $cur_l++;
  916. if ($cur_l > $max_l) {
  917. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  918. $aRet[] = "=?$default_charset?Q?$ret?=";
  919. $iOffset = $i;
  920. $cur_l = 0;
  921. $ret = '';
  922. $iEncStart = false;
  923. } else {
  924. $ret .= '_';
  925. }
  926. }
  927. break;
  928. default:
  929. $k = ord($string{$i});
  930. if ($k > 126) {
  931. if ($iEncStart === false) {
  932. // do not start encoding in the middle of a string, also take the rest of the word.
  933. $sLeadString = substr($string,0,$i);
  934. $aLeadString = explode(' ',$sLeadString);
  935. $sToBeEncoded = array_pop($aLeadString);
  936. $iEncStart = $i - strlen($sToBeEncoded);
  937. $ret .= $sToBeEncoded;
  938. $cur_l += strlen($sToBeEncoded);
  939. }
  940. $cur_l += 3;
  941. /* first we add the encoded string that reached it's max size */
  942. if ($cur_l > ($max_l-2)) {
  943. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  944. $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
  945. $cur_l = 3;
  946. $ret = '';
  947. $iOffset = $i;
  948. $iEncStart = $i;
  949. }
  950. $enc_init = true;
  951. $ret .= sprintf("=%02X", $k);
  952. } else {
  953. if ($iEncStart !== false) {
  954. $cur_l++;
  955. if ($cur_l > $max_l) {
  956. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  957. $aRet[] = "=?$default_charset?Q?$ret?=";
  958. $iEncStart = false;
  959. $iOffset = $i;
  960. $cur_l = 0;
  961. $ret = '';
  962. } else {
  963. $ret .= $string{$i};
  964. }
  965. }
  966. }
  967. break;
  968. }
  969. }
  970. if ($enc_init) {
  971. if ($iEncStart !== false) {
  972. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  973. $aRet[] = "=?$default_charset?Q?$ret?=";
  974. } else {
  975. $aRet[] = substr($string,$iOffset);
  976. }
  977. $string = implode('',$aRet);
  978. }
  979. return $string;
  980. }
  981. /**
  982. * Encodes string according to rfc2047 B encoding header formating rules
  983. *
  984. * It is recommended way to encode headers with character sets that store
  985. * symbols in more than one byte.
  986. *
  987. * Function requires mbstring support. If required mbstring functions are missing,
  988. * function returns false and sets E_USER_WARNING level error message.
  989. *
  990. * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
  991. * that mbstring functions will generate E_WARNING errors, if unsupported
  992. * character set is used. mb_encode_mimeheader function provided by php
  993. * mbstring extension is not used in order to get better control of header
  994. * encoding.
  995. *
  996. * Used php code functions - function_exists(), trigger_error(), strlen()
  997. * (is used with charset names and base64 strings). Used php mbstring
  998. * functions - mb_strlen and mb_substr.
  999. *
  1000. * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
  1001. * encoding), rfc 2822 (header folding)
  1002. *
  1003. * @param string $string header string that must be encoded
  1004. * @param string $charset character set. Must be supported by mbstring extension.
  1005. * Use sq_mb_list_encodings() to detect supported charsets.
  1006. * @return string string encoded according to rfc2047 B encoding formating rules
  1007. * @since 1.5.1
  1008. * @todo First header line can be wrapped to $iMaxLength - $HeaderFieldLength - 1
  1009. * @todo Do we want to control max length of header?
  1010. * @todo Do we want to control EOL (end-of-line) marker?
  1011. * @todo Do we want to translate error message?
  1012. */
  1013. function encodeHeaderBase64($string,$charset) {
  1014. /**
  1015. * Check mbstring function requirements.
  1016. */
  1017. if (! function_exists('mb_strlen') ||
  1018. ! function_exists('mb_substr')) {
  1019. // set E_USER_WARNING
  1020. trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING);
  1021. // return false
  1022. return false;
  1023. }
  1024. // initial return array
  1025. $aRet = array();
  1026. /**
  1027. * header length = 75 symbols max (same as in encodeHeader)
  1028. * remove $charset length
  1029. * remove =? ? ?= (5 chars)
  1030. * remove 2 more chars (\r\n ?)
  1031. */
  1032. $iMaxLength = 75 - strlen($charset) - 7;
  1033. // set first character position
  1034. $iStartCharNum = 0;
  1035. // loop through all characters. count characters and not bytes.
  1036. for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++) {
  1037. // encode string from starting character to current character.
  1038. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  1039. // Check encoded string length
  1040. if(strlen($encoded_string)>$iMaxLength) {
  1041. // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
  1042. $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
  1043. // set new starting character
  1044. $iStartCharNum = $iCharNum-1;
  1045. // encode last char (in case it is last character in string)
  1046. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  1047. } // if string is shorter than max length - add next character
  1048. }
  1049. // add last encoded string to array
  1050. $aRet[] = $encoded_string;
  1051. // set initial return string
  1052. $sRet = '';
  1053. // loop through encoded strings
  1054. foreach($aRet as $string) {
  1055. // TODO: Do we want to control EOL (end-of-line) marker
  1056. if ($sRet!='') $sRet.= " ";
  1057. // add header tags and encoded string to return string
  1058. $sRet.= '=?'.$charset.'?B?'.$string.'?=';
  1059. }
  1060. return $sRet;
  1061. }
  1062. /* This function trys to locate the entity_id of a specific mime element */
  1063. function find_ent_id($id, $message) {
  1064. for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
  1065. if ($message->entities[$i]->header->type0 == 'multipart') {
  1066. $ret = find_ent_id($id, $message->entities[$i]);
  1067. } else {
  1068. if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
  1069. // if (sq_check_save_extension($message->entities[$i])) {
  1070. return $message->entities[$i]->entity_id;
  1071. // }
  1072. } elseif (!empty($message->entities[$i]->header->parameters['name'])) {
  1073. /**
  1074. * This is part of a fix for Outlook Express 6.x generating
  1075. * cid URLs without creating content-id headers
  1076. * @@JA - 20050207
  1077. */
  1078. if (strcasecmp($message->entities[$i]->header->parameters['name'], $id) == 0) {
  1079. return $message->entities[$i]->entity_id;
  1080. }
  1081. }
  1082. }
  1083. }
  1084. return $ret;
  1085. }
  1086. function sq_check_save_extension($message) {
  1087. $filename = $message->getFilename();
  1088. $ext = substr($filename, strrpos($filename,'.')+1);
  1089. $save_extensions = array('jpg','jpeg','gif','png','bmp');
  1090. return in_array($ext, $save_extensions);
  1091. }
  1092. /**
  1093. ** HTMLFILTER ROUTINES
  1094. */
  1095. /**
  1096. * This function checks attribute values for entity-encoded values
  1097. * and returns them translated into 8-bit strings so we can run
  1098. * checks on them.
  1099. *
  1100. * @param $attvalue A string to run entity check against.
  1101. * @return Nothing, modifies a reference value.
  1102. */
  1103. function sq_defang(&$attvalue){
  1104. $me = 'sq_defang';
  1105. /**
  1106. * Skip this if there aren't ampersands or backslashes.
  1107. */
  1108. if (strpos($attvalue, '&') === false
  1109. && strpos($attvalue, '\\') === false){
  1110. return;
  1111. }
  1112. $m = false;
  1113. // before deent, translate the dangerous unicode characters and ... to safe values
  1114. // otherwise the regular expressions do not match.
  1115. do {
  1116. $m = false;
  1117. $m = $m || sq_deent($attvalue, '/\&#0*(\d+);*/s');
  1118. $m = $m || sq_deent($attvalue, '/\&#x0*((\d|[a-f])+);*/si', true);
  1119. $m = $m || sq_deent($attvalue, '/\\\\(\d+)/s', true);
  1120. } while ($m == true);
  1121. $attvalue = stripslashes($attvalue);
  1122. }
  1123. /**
  1124. * Kill any tabs, newlines, or carriage returns. Our friends the
  1125. * makers of the browser with 95% market value decided that it'd
  1126. * be funny to make "java[tab]script" be just as good as "javascript".
  1127. *
  1128. * @param attvalue The attribute value before extraneous spaces removed.
  1129. * @return attvalue Nothing, modifies a reference value.
  1130. */
  1131. function sq_unspace(&$attvalue){
  1132. $me = 'sq_unspace';
  1133. if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
  1134. $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
  1135. Array('', '', '', '', ''), $attvalue);
  1136. }
  1137. }
  1138. /**
  1139. * Translate all dangerous Unicode or Shift_JIS characters which are accepted by
  1140. * IE as regular characters.
  1141. *
  1142. * @param attvalue The attribute value before dangerous characters are translated.
  1143. * @return attvalue Nothing, modifies a reference value.
  1144. * @author Marc Groot Koerkamp.
  1145. */
  1146. function sq_fixIE_idiocy(&$attvalue) {
  1147. // remove NUL
  1148. $attvalue = str_replace("\0", "", $attvalue);
  1149. // remove comments
  1150. $attvalue = preg_replace("/(\/\*.*?\*\/)/","",$attvalue);
  1151. // IE has the evil habit of accepting every possible value for the attribute expression.
  1152. // The table below contains characters which are parsed by IE if they are used in the "expression"
  1153. // attribute value.
  1154. $aDangerousCharsReplacementTable = array(
  1155. array('&#x029F;', '&#0671;' ,/* L UNICODE IPA Extension */
  1156. '&#x0280;', '&#0640;' ,/* R UNICODE IPA Extension */
  1157. '&#x0274;', '&#0628;' ,/* N UNICODE IPA Extension */
  1158. '&#xFF25;', '&#65317;' ,/* Unicode FULLWIDTH LATIN CAPITAL LETTER E */
  1159. '&#xFF45;', '&#65349;' ,/* Unicode FULLWIDTH LATIN SMALL LETTER E */
  1160. '&#xFF38;', '&#65336;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER X */
  1161. '&#xFF58;', '&#65368;',/* Unicode FULLWIDTH LATIN SMALL LETTER X */
  1162. '&#xFF30;', '&#65328;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER P */
  1163. '&#xFF50;', '&#65360;',/* Unicode FULLWIDTH LATIN SMALL LETTER P */
  1164. '&#xFF32;', '&#65330;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER R */
  1165. '&#xFF52;', '&#65362;',/* Unicode FULLWIDTH LATIN SMALL LETTER R */
  1166. '&#xFF33;', '&#65331;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER S */
  1167. '&#xFF53;', '&#65363;',/* Unicode FULLWIDTH LATIN SMALL LETTER S */
  1168. '&#xFF29;', '&#65321;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER I */
  1169. '&#xFF49;', '&#65353;',/* Unicode FULLWIDTH LATIN SMALL LETTER I */
  1170. '&#xFF2F;', '&#65327;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER O */
  1171. '&#xFF4F;', '&#65359;',/* Unicode FULLWIDTH LATIN SMALL LETTER O */
  1172. '&#xFF2E;', '&#65326;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER N */
  1173. '&#xFF4E;', '&#65358;',/* Unicode FULLWIDTH LATIN SMALL LETTER N */
  1174. '&#xFF2C;', '&#65324;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER L */
  1175. '&#xFF4C;', '&#65356;',/* Unicode FULLWIDTH LATIN SMALL LETTER L */
  1176. '&#xFF35;', '&#65333;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER U */
  1177. '&#xFF55;', '&#65365;',/* Unicode FULLWIDTH LATIN SMALL LETTER U */
  1178. '&#x207F;', '&#8319;' ,/* Unicode SUPERSCRIPT LATIN SMALL LETTER N */
  1179. "\xEF\xBC\xA5", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER E */ // in unicode this is some Chinese char range
  1180. "\xEF\xBD\x85", /* Shift JIS FULLWIDTH LATIN SMALL LETTER E */
  1181. "\xEF\xBC\xB8", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER X */
  1182. "\xEF\xBD\x98", /* Shift JIS FULLWIDTH LATIN SMALL LETTER X */
  1183. "\xEF\xBC\xB0", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER P */
  1184. "\xEF\xBD\x90", /* Shift JIS FULLWIDTH LATIN SMALL LETTER P */
  1185. "\xEF\xBC\xB2", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER R */
  1186. "\xEF\xBD\x92", /* Shift JIS FULLWIDTH LATIN SMALL LETTER R */
  1187. "\xEF\xBC\xB3", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER S */
  1188. "\xEF\xBD\x93", /* Shift JIS FULLWIDTH LATIN SMALL LETTER S */
  1189. "\xEF\xBC\xA9", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER I */
  1190. "\xEF\xBD\x89", /* Shift JIS FULLWIDTH LATIN SMALL LETTER I */
  1191. "\xEF\xBC\xAF", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER O */
  1192. "\xEF\xBD\x8F", /* Shift JIS FULLWIDTH LATIN SMALL LETTER O */
  1193. "\xEF\xBC\xAE", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER N */
  1194. "\xEF\xBD\x8E", /* Shift JIS FULLWIDTH LATIN SMALL LETTER N */
  1195. "\xEF\xBC\xAC", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER L */
  1196. "\xEF\xBD\x8C", /* Shift JIS FULLWIDTH LATIN SMALL LETTER L */
  1197. "\xEF\xBC\xB5", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER U */
  1198. "\xEF\xBD\x95", /* Shift JIS FULLWIDTH LATIN SMALL LETTER U */
  1199. "\xE2\x81\xBF", /* Shift JIS FULLWIDTH SUPERSCRIPT N */
  1200. "\xCA\x9F", /* L UNICODE IPA Extension */
  1201. "\xCA\x80", /* R UNICODE IPA Extension */
  1202. "\xC9\xB4"), /* N UNICODE IPA Extension */
  1203. array('l', 'l', 'r','r','n','n',
  1204. 'E','E','e','e','X','X','x','x','P','P','p','p','R','R','r','r','S','S','s','s','I','I',
  1205. 'i','i','O','O','o','o','N','N','n','n','L','L','l','l','U','U','u','u','n','n',
  1206. 'E','e','X','x','P','p','R','r','S','s','I','i','O','o','N','n','L','l','U','u','n','l','r','n'));
  1207. $attvalue = str_replace($aDangerousCharsReplacementTable[0],$aDangerousCharsReplacementTable[1],$attvalue);
  1208. // Escapes are useful for special characters like "{}[]()'&. In other cases they are
  1209. // used for XSS.
  1210. $attvalue = preg_replace("/(\\\\)([a-zA-Z]{1})/",'$2',$attvalue);
  1211. }
  1212. /**
  1213. * This function returns the final tag out of the tag name, an array
  1214. * of attributes, and the type of the tag. This function is called by
  1215. * sq_sanitize internally.
  1216. *
  1217. * @param $tagname the name of the tag.
  1218. * @param $attary the array of attributes and their values
  1219. * @param $tagtype The type of the tag (see in comments).
  1220. * @return a string with the final tag representation.
  1221. */
  1222. function sq_tagprint($tagname, $attary, $tagtype){
  1223. $me = 'sq_tagprint';
  1224. if ($tagtype == 2){
  1225. $fulltag = '</' . $tagname . '>';
  1226. } else {
  1227. $fulltag = '<' . $tagname;
  1228. if (is_array($attary) && sizeof($attary)){
  1229. $atts = Array();
  1230. while (list($attname, $attvalue) = each($attary)){
  1231. array_push($atts, "$attname=$attvalue");
  1232. }
  1233. $fulltag .= ' ' . join(" ", $atts);
  1234. }
  1235. if ($tagtype == 3){
  1236. $fulltag .= ' /';
  1237. }
  1238. $fulltag .= '>';
  1239. }
  1240. return $fulltag;
  1241. }
  1242. /**
  1243. * A small helper function to use with array_walk. Modifies a by-ref
  1244. * value and makes it lowercase.
  1245. *
  1246. * @param $val a value passed by-ref.
  1247. * @return void since it modifies a by-ref value.
  1248. */
  1249. function sq_casenormalize(&$val){
  1250. $val = strtolower($val);
  1251. }
  1252. /**
  1253. * This function skips any whitespace from the current position within
  1254. * a string and to the next non-whitespace value.
  1255. *
  1256. * @param $body the string
  1257. * @param $offset the offset within the string where we should start
  1258. * looking for the next non-whitespace character.
  1259. * @return the location within the $body where the next
  1260. * non-whitespace char is located.
  1261. */
  1262. function sq_skipspace($body, $offset){
  1263. $me = 'sq_skipspace';
  1264. preg_match('/^(\s*)/s', substr($body, $offset), $matches);
  1265. if (!empty($matches[1])){
  1266. $count = strlen($matches[1]);
  1267. $offset += $count;
  1268. }
  1269. return $offset;
  1270. }
  1271. /**
  1272. * This function looks for the next character within a string. It's
  1273. * really just a glorified "strpos", except it catches if failures
  1274. * nicely.
  1275. *
  1276. * @param $body The string to look for needle in.
  1277. * @param $offset Start looking from this position.
  1278. * @param $needle The character/string to look for.
  1279. * @return location of the next occurance of the needle, or
  1280. * strlen($body) if needle wasn't found.
  1281. */
  1282. function sq_findnxstr($body, $offset, $needle){
  1283. $me = 'sq_findnxstr';
  1284. $pos = strpos($body, $needle, $offset);
  1285. if ($pos === FALSE){
  1286. $pos = strlen($body);
  1287. }
  1288. return $pos;
  1289. }
  1290. /**
  1291. * This function takes a PCRE-style regexp and tries to match it
  1292. * within the string.
  1293. *
  1294. * @param $body The string to look for needle in.
  1295. * @param $offset Start looking from here.
  1296. * @param $reg A PCRE-style regex to match.
  1297. * @return Returns a false if no matches found, or an array
  1298. * with the following members:
  1299. * - integer with the location of the match within $body
  1300. * - string with whatever content between offset and the match
  1301. * - string with whatever it is we matched
  1302. */
  1303. function sq_findnxreg($body, $offset, $reg){
  1304. $me = 'sq_findnxreg';
  1305. $matches = Array();
  1306. $retarr = Array();
  1307. preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
  1308. if (!isset($matches{0}) || !$matches{0}){
  1309. $retarr = false;
  1310. } else {
  1311. $retarr{0} = $offset + strlen($matches{1});
  1312. $retarr{1} = $matches{1};
  1313. $retarr{2} = $matches{2};
  1314. }
  1315. return $retarr;
  1316. }
  1317. /**
  1318. * This function looks for the next tag.
  1319. *
  1320. * @param $body String where to look for the next tag.
  1321. * @param $offset Start looking from here.
  1322. * @return false if no more tags exist in the body, or
  1323. * an array with the following members:
  1324. * - string with the name of the tag
  1325. * - array with attributes and their values
  1326. * - integer with tag type (1, 2, or 3)
  1327. * - integer where the tag starts (starting "<")
  1328. * - integer where the tag ends (ending ">")
  1329. * first three members will be false, if the tag is invalid.
  1330. */
  1331. function sq_getnxtag($body, $offset){
  1332. $me = 'sq_getnxtag';
  1333. if ($offset > strlen($body)){
  1334. return false;
  1335. }
  1336. $lt = sq_findnxstr($body, $offset, "<");
  1337. if ($lt == strlen($body)){
  1338. return false;
  1339. }
  1340. /**
  1341. * We are here:
  1342. * blah blah <tag attribute="value">
  1343. * \---------^
  1344. */
  1345. $pos = sq_skipspace($body, $lt+1);
  1346. if ($pos >= strlen($body)){
  1347. return Array(false, false, false, $lt, strlen($body));
  1348. }
  1349. /**
  1350. * There are 3 kinds of tags:
  1351. * 1. Opening tag, e.g.:
  1352. * <a href="blah">
  1353. * 2. Closing tag, e.g.:
  1354. * </a>
  1355. * 3. XHTML-style content-less tag, e.g.:
  1356. * <img src="blah" />
  1357. */
  1358. $tagtype = false;
  1359. switch (substr($body, $pos, 1)){
  1360. case '/':
  1361. $tagtype = 2;
  1362. $pos++;
  1363. break;
  1364. case '!':
  1365. /**
  1366. * A comment or an SGML declaration.
  1367. */
  1368. if (substr($body, $pos+1, 2) == "--"){
  1369. $gt = strpos($body, "-->", $pos);
  1370. if ($gt === false){
  1371. $gt = strlen($body);
  1372. } else {
  1373. $gt += 2;
  1374. }
  1375. return Array(false, false, false, $lt, $gt);
  1376. } else {
  1377. $gt = sq_findnxstr($body, $pos, ">");
  1378. return Array(false, false, false, $lt, $gt);
  1379. }
  1380. break;
  1381. default:
  1382. /**
  1383. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  1384. * later.
  1385. */
  1386. $tagtype = 1;
  1387. break;
  1388. }
  1389. $tag_start = $pos;
  1390. $tagname = '';
  1391. /**
  1392. * Look for next [\W-_], which will indicate the end of the tag name.
  1393. */
  1394. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  1395. if ($regary == false){
  1396. return Array(false, false, false, $lt, strlen($body));
  1397. }
  1398. list($pos, $tagname, $match) = $regary;
  1399. $tagname = strtolower($tagname);
  1400. /**
  1401. * $match can be either of these:
  1402. * '>' indicating the end of the tag entirely.
  1403. * '\s' indicating the end of the tag name.
  1404. * '/' indicating that this is type-3 xhtml tag.
  1405. *
  1406. * Whatever else we find there indicates an invalid tag.
  1407. */
  1408. switch ($match){
  1409. case '/':
  1410. /**
  1411. * This is an xhtml-style tag with a closing / at the
  1412. * end, like so: <img src="blah" />. Check if it's followed
  1413. * by the closing bracket. If not, then this tag is invalid
  1414. */
  1415. if (substr($body, $pos, 2) == "/>"){
  1416. $pos++;
  1417. $tagtype = 3;
  1418. } else {
  1419. $gt = sq_findnxstr($body, $pos, ">");
  1420. $retary = Array(false, false, false, $lt, $gt);
  1421. return $retary;
  1422. }
  1423. case '>':
  1424. return Array($tagname, false, $tagtype, $lt, $pos);
  1425. break;
  1426. default:
  1427. /**
  1428. * Check if it's whitespace
  1429. */
  1430. if (!preg_match('/\s/', $match)){
  1431. /**
  1432. * This is an invalid tag! Look for the next closing ">".
  1433. */
  1434. $gt = sq_findnxstr($body, $lt, ">");
  1435. return Array(false, false, false, $lt, $gt);
  1436. }
  1437. break;
  1438. }
  1439. /**
  1440. * At this point we're here:
  1441. * <tagname attribute='blah'>
  1442. * \-------^
  1443. *
  1444. * At this point we loop in order to find all attributes.
  1445. */
  1446. $attname = '';
  1447. $atttype = false;
  1448. $attary = Array();
  1449. while ($pos <= strlen($body)){
  1450. $pos = sq_skipspace($body, $pos);
  1451. if ($pos == strlen($body)){
  1452. /**
  1453. * Non-closed tag.
  1454. */
  1455. return Array(false, false, false, $lt, $pos);
  1456. }
  1457. /**
  1458. * See if we arrived at a ">" or "/>", which means that we reached
  1459. * the end of the tag.
  1460. */
  1461. $matches = Array();
  1462. if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
  1463. /**
  1464. * Yep. So we did.
  1465. */
  1466. $pos += strlen($matches{1});
  1467. if ($matches{2} == "/>"){
  1468. $tagtype = 3;
  1469. $pos++;
  1470. }
  1471. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1472. }
  1473. /**
  1474. * There are several types of attributes, with optional
  1475. * [:space:] between members.
  1476. * Type 1:
  1477. * attrname[:space:]=[:space:]'CDATA'
  1478. * Type 2:
  1479. * attrname[:space:]=[:space:]"CDATA"
  1480. * Type 3:
  1481. * attr[:space:]=[:space:]CDATA
  1482. * Type 4:
  1483. * attrname
  1484. *
  1485. * We leave types 1 and 2 the same, type 3 we check for
  1486. * '"' and convert to "&quot" if needed, then wrap in
  1487. * double quotes. Type 4 we convert into:
  1488. * attrname="yes".
  1489. */
  1490. $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
  1491. if ($regary == false){
  1492. /**
  1493. * Looks like body ended before the end of tag.
  1494. */
  1495. return Array(false, false, false, $lt, strlen($body));
  1496. }
  1497. list($pos, $attname, $match) = $regary;
  1498. $attname = strtolower($attname);
  1499. /**
  1500. * We arrived at the end of attribute name. Several things possible
  1501. * here:
  1502. * '>' means the end of the tag and this is attribute type 4
  1503. * '/' if followed by '>' means the same thing as above
  1504. * '\s' means a lot of things -- look what it's followed by.
  1505. * anything else means the attribute is invalid.
  1506. */
  1507. switch($match){
  1508. case '/':
  1509. /**
  1510. * This is an xhtml-style tag with a closing / at the
  1511. * end, like so: <img src="blah" />. Check if it's followed
  1512. * by the closing bracket. If not, then this tag is invalid
  1513. */
  1514. if (substr($body, $pos, 2) == "/>"){
  1515. $pos++;
  1516. $tagtype = 3;
  1517. } else {
  1518. $gt = sq_findnxstr($body, $pos, ">");
  1519. $retary = Array(false, false, false, $lt, $gt);
  1520. return $retary;
  1521. }
  1522. case '>':
  1523. $attary{$attname} = '"yes"';
  1524. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1525. break;
  1526. default:
  1527. /**
  1528. * Skip whitespace and see what we arrive at.
  1529. */
  1530. $pos = sq_skipspace($body, $pos);
  1531. $char = substr($body, $pos, 1);
  1532. /**
  1533. * Two things are valid here:
  1534. * '=' means this is attribute type 1 2 or 3.
  1535. * \w means this was attribute type 4.
  1536. * anything else we ignore and re-loop. End of tag and
  1537. * invalid stuff will be caught by our checks at the beginning
  1538. * of the loop.
  1539. */
  1540. if ($char == "="){
  1541. $pos++;
  1542. $pos = sq_skipspace($body, $pos);
  1543. /**
  1544. * Here are 3 possibilities:
  1545. * "'" attribute type 1
  1546. * '"' attribute type 2
  1547. * everything else is the content of tag type 3
  1548. */
  1549. $quot = substr($body, $pos, 1);
  1550. if ($quot == "'"){
  1551. $regary = sq_findnxreg($body, $pos+1, "\'");
  1552. if ($regary == false){
  1553. return Array(false, false, false, $lt, strlen($body));
  1554. }
  1555. list($pos, $attval, $match) = $regary;
  1556. $pos++;
  1557. $attary{$attname} = "'" . $attval . "'";
  1558. } else if ($quot == '"'){
  1559. $regary = sq_findnxreg($body, $pos+1, '\"');
  1560. if ($regary == false){
  1561. return Array(false, false, false, $lt, strlen($body));
  1562. }
  1563. list($pos, $attval, $match) = $regary;
  1564. $pos++;
  1565. $attary{$attname} = '"' . $attval . '"';
  1566. } else {
  1567. /**
  1568. * These are hateful. Look for \s, or >.
  1569. */
  1570. $regary = sq_findnxreg($body, $pos, "[\s>]");
  1571. if ($regary == false){
  1572. return Array(false, false, false, $lt, strlen($body));
  1573. }
  1574. list($pos, $attval, $match) = $regary;
  1575. /**
  1576. * If it's ">" it will be caught at the top.
  1577. */
  1578. $attval = preg_replace("/\"/s", "&quot;", $attval);
  1579. $attary{$attname} = '"' . $attval . '"';
  1580. }
  1581. } else if (preg_match("|[\w/>]|", $char)) {
  1582. /**
  1583. * That was attribute type 4.
  1584. */
  1585. $attary{$attname} = '"yes"';
  1586. } else {
  1587. /**
  1588. * An illegal character. Find next '>' and return.
  1589. */
  1590. $gt = sq_findnxstr($body, $pos, ">");
  1591. return Array(false, false, false, $lt, $gt);
  1592. }
  1593. break;
  1594. }
  1595. }
  1596. /**
  1597. * The fact that we got here indicates that the tag end was never
  1598. * found. Return invalid tag indication so it gets stripped.
  1599. */
  1600. return Array(false, false, false, $lt, strlen($body));
  1601. }
  1602. /**
  1603. * Translates entities into literal values so they can be checked.
  1604. *
  1605. * @param $attvalue the by-ref value to check.
  1606. * @param $regex the regular expression to check against.
  1607. * @param $hex whether the entites are hexadecimal.
  1608. * @return True or False depending on whether there were matches.
  1609. */
  1610. function sq_deent(&$attvalue, $regex, $hex=false){
  1611. $me = 'sq_deent';
  1612. $ret_match = false;
  1613. // remove comments
  1614. //$attvalue = preg_replace("/(\/\*.*\*\/)/","",$attvalue);
  1615. preg_match_all($regex, $attvalue, $matches);
  1616. if (is_array($matches) && sizeof($matches[0]) > 0){
  1617. $repl = Array();
  1618. for ($i = 0; $i < sizeof($matches[0]); $i++){
  1619. $numval = $matches[1][$i];
  1620. if ($hex){
  1621. $numval = hexdec($numval);
  1622. }
  1623. $repl{$matches[0][$i]} = chr($numval);
  1624. }
  1625. $attvalue = strtr($attvalue, $repl);
  1626. return true;
  1627. } else {
  1628. return false;
  1629. }
  1630. }
  1631. /**
  1632. * This function runs various checks against the attributes.
  1633. *
  1634. * @param $tagname String with the name of the tag.
  1635. * @param $attary Array with all tag attributes.
  1636. * @param $rm_attnames See description for sq_sanitize
  1637. * @param $bad_attvals See description for sq_sanitize
  1638. * @param $add_attr_to_tag See description for sq_sanitize
  1639. * @param $message message object
  1640. * @param $id message id
  1641. * @return Array with modified attributes.
  1642. */
  1643. function sq_fixatts($tagname,
  1644. $attary,
  1645. $rm_attnames,
  1646. $bad_attvals,
  1647. $add_attr_to_tag,
  1648. $message,
  1649. $id,
  1650. $mailbox
  1651. ){
  1652. $me = 'sq_fixatts';
  1653. while (list($attname, $attvalue) = each($attary)){
  1654. /**
  1655. * See if this attribute should be removed.
  1656. */
  1657. foreach ($rm_attnames as $matchtag=>$matchattrs){
  1658. if (preg_match($matchtag, $tagname)){
  1659. foreach ($matchattrs as $matchattr){
  1660. if (preg_match($matchattr, $attname)){
  1661. unset($attary{$attname});
  1662. continue;
  1663. }
  1664. }
  1665. }
  1666. }
  1667. /**
  1668. * Workaround for IE quirks
  1669. */
  1670. sq_fixIE_idiocy($attvalue);
  1671. /**
  1672. * Remove any backslashes, entities, and extraneous whitespace.
  1673. */
  1674. $oldattvalue = $attvalue;
  1675. sq_defang($attvalue);
  1676. if ($attname == 'style' && $attvalue !== $oldattvalue) {
  1677. // entities are used in the attribute value. In 99% of the cases it's there as XSS
  1678. // i.e.<div style="{ left:exp&#x0280;essio&#x0274;( alert('XSS') ) }">
  1679. $attvalue = "idiocy";
  1680. $attary{$attname} = $attvalue;
  1681. }
  1682. sq_unspace($attvalue);
  1683. /**
  1684. * Now let's run checks on the attvalues.
  1685. * I don't expect anyone to comprehend this. If you do,
  1686. * get in touch with me so I can drive to where you live and
  1687. * shake your hand personally. :)
  1688. */
  1689. foreach ($bad_attvals as $matchtag=>$matchattrs){
  1690. if (preg_match($matchtag, $tagname)){
  1691. foreach ($matchattrs as $matchattr=>$valary){
  1692. if (preg_match($matchattr, $attname)){
  1693. /**
  1694. * There are two arrays in valary.
  1695. * First is matches.
  1696. * Second one is replacements
  1697. */
  1698. list($valmatch, $valrepl) = $valary;
  1699. $newvalue =
  1700. preg_replace($valmatch, $valrepl, $attvalue);
  1701. if ($newvalue != $attvalue){
  1702. $attary{$attname} = $newvalue;
  1703. $attvalue = $newvalue;
  1704. }
  1705. }
  1706. }
  1707. }
  1708. }
  1709. if ($attname == 'style') {
  1710. if (preg_match('/[\0-\37\200-\377]+/',$attvalue)) {
  1711. // 8bit and control characters in style attribute values can be used for XSS, remove them
  1712. $attary{$attname} = '"disallowed character"';
  1713. }
  1714. preg_match_all("/url\s*\((.+)\)/si",$attvalue,$aMatch);
  1715. if (count($aMatch)) {
  1716. foreach($aMatch[1] as $sMatch) {
  1717. // url value
  1718. $urlvalue = $sMatch;
  1719. sq_fix_url($attname, $urlvalue, $message, $id, $mailbox,"'");
  1720. $attary{$attname} = str_replace($sMatch,$urlvalue,$attvalue);
  1721. }
  1722. }
  1723. }
  1724. /**
  1725. * Use white list based filtering on attributes which can contain url's
  1726. */
  1727. else if ($attname == 'href' || $attname == 'xlink:href' || $attname == 'src'
  1728. || $attname == 'poster' || $attname == 'formaction'
  1729. || $attname == 'background' || $attname == 'action') {
  1730. sq_fix_url($attname, $attvalue, $message, $id, $mailbox);
  1731. $attary{$attname} = $attvalue;
  1732. }
  1733. }
  1734. /**
  1735. * See if we need to append any attributes to this tag.
  1736. */
  1737. foreach ($add_attr_to_tag as $matchtag=>$addattary){
  1738. if (preg_match($matchtag, $tagname)){
  1739. $attary = array_merge($attary, $addattary);
  1740. }
  1741. }
  1742. return $attary;
  1743. }
  1744. /**
  1745. * This function filters url's
  1746. *
  1747. * @param $attvalue String with attribute value to filter
  1748. * @param $message message object
  1749. * @param $id message id
  1750. * @param $mailbox mailbox
  1751. * @param $sQuote quoting characters around url's
  1752. */
  1753. function sq_fix_url($attname, &$attvalue, $message, $id, $mailbox,$sQuote = '"') {
  1754. $attvalue = trim($attvalue);
  1755. if ($attvalue && ($attvalue[0] =='"'|| $attvalue[0] == "'")) {
  1756. // remove the double quotes
  1757. $sQuote = $attvalue[0];
  1758. $attvalue = trim(substr($attvalue,1,-1));
  1759. }
  1760. // If there's no "view_unsafe_images" variable in the URL, turn unsafe
  1761. // images off by default.
  1762. sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET, FALSE);
  1763. global $use_transparent_security_image;
  1764. if ($use_transparent_security_image) $secremoveimg = '../images/spacer.png';
  1765. else $secremoveimg = '../images/' . _("sec_remove_eng.png");
  1766. /**
  1767. * Replace empty src tags with the blank image. src is only used
  1768. * for frames, images, and image inputs. Doing a replace should
  1769. * not affect them working as should be, however it will stop
  1770. * IE from being kicked off when src for img tags are not set
  1771. */
  1772. if ($attvalue == '') {
  1773. $attvalue = '"' . SM_PATH . 'images/blank.png"';
  1774. } else {
  1775. // first, disallow 8 bit characters and control characters
  1776. if (preg_match('/[\0-\37\200-\377]+/',$attvalue)) {
  1777. switch ($attname) {
  1778. case 'href':
  1779. $attvalue = $sQuote . 'http://invalid-stuff-detected.example.com' . $sQuote;
  1780. break;
  1781. default:
  1782. $attvalue = $sQuote . SM_PATH . 'images/blank.png'. $sQuote;
  1783. break;
  1784. }
  1785. } else {
  1786. $aUrl = parse_url($attvalue);
  1787. if (isset($aUrl['scheme'])) {
  1788. switch(strtolower($aUrl['scheme'])) {
  1789. case 'mailto':
  1790. case 'http':
  1791. case 'https':
  1792. case 'ftp':
  1793. if ($attname != 'href') {
  1794. if ($view_unsafe_images == false) {
  1795. $attvalue = $sQuote . $secremoveimg . $sQuote;
  1796. } else {
  1797. if (isset($aUrl['path'])) {
  1798. // No one has been able to show that image URIs
  1799. // can be exploited, so for now, no restrictions
  1800. // are made at all. If this proves to be a problem,
  1801. // the commented-out code below can be of help.
  1802. // (One consideration is that I see nothing in this
  1803. // function that specifically says that we will
  1804. // only ever arrive here when inspecting an image
  1805. // tag, although that does seem to be the end
  1806. // result - e.g., <script src="..."> where malicious
  1807. // image URIs are in fact a problem are already
  1808. // filtered out elsewhere.
  1809. /* ---------------------------------
  1810. // validate image extension.
  1811. $ext = strtolower(substr($aUrl['path'],strrpos($aUrl['path'],'.')));
  1812. if (!in_array($ext,array('.jpeg','.jpg','xjpeg','.gif','.bmp','.jpe','.png','.xbm'))) {
  1813. // If URI is to something other than
  1814. // a regular image file, get the contents
  1815. // and try to see if it is an image.
  1816. // Don't use Fileinfo (finfo_file()) because
  1817. // we'd need to make the admin configure the
  1818. // location of the magic.mime file (FIXME: add finfo_file() support later?)
  1819. //
  1820. $mime_type = '';
  1821. if (function_exists('mime_content_type')
  1822. && ($FILE = @fopen($attvalue, 'rb', FALSE))) {
  1823. // fetch file
  1824. //
  1825. $file_contents = '';
  1826. while (!feof($FILE)) {
  1827. $file_contents .= fread($FILE, 8192);
  1828. }
  1829. fclose($FILE);
  1830. // store file locally
  1831. //
  1832. global $attachment_dir, $username;
  1833. $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
  1834. $localfilename = GenerateRandomString(32, '', 7);
  1835. $full_localfilename = "$hashed_attachment_dir/$localfilename";
  1836. while (file_exists($full_localfilename)) {
  1837. $localfilename = GenerateRandomString(32, '', 7);
  1838. $full_localfilename = "$hashed_attachment_dir/$localfilename";
  1839. }
  1840. $FILE = fopen("$hashed_attachment_dir/$localfilename", 'wb');
  1841. fwrite($FILE, $file_contents);
  1842. fclose($FILE);
  1843. // get mime type and remove file
  1844. //
  1845. $mime_type = mime_content_type("$hashed_attachment_dir/$localfilename");
  1846. unlink("$hashed_attachment_dir/$localfilename");
  1847. }
  1848. // debug: echo "$attvalue FILE TYPE IS $mime_type<HR>";
  1849. if (substr(strtolower($mime_type), 0, 5) != 'image') {
  1850. $attvalue = $sQuote . SM_PATH . 'images/blank.png'. $sQuote;
  1851. }
  1852. }
  1853. --------------------------------- */
  1854. } else {
  1855. $attvalue = $sQuote . SM_PATH . 'images/blank.png'. $sQuote;
  1856. }
  1857. }
  1858. } else {
  1859. $attvalue = $sQuote . $attvalue . $sQuote;
  1860. }
  1861. break;
  1862. case 'outbind':
  1863. /**
  1864. * "Hack" fix for Outlook using propriatary outbind:// protocol in img tags.
  1865. * One day MS might actually make it match something useful, for now, falling
  1866. * back to using cid2http, so we can grab the blank.png.
  1867. */
  1868. $attvalue = $sQuote . sq_cid2http($message, $id, $attvalue, $mailbox) . $sQuote;
  1869. break;
  1870. case 'cid':
  1871. /**
  1872. * Turn cid: urls into http-friendly ones.
  1873. */
  1874. $attvalue = $sQuote . sq_cid2http($message, $id, $attvalue, $mailbox) . $sQuote;
  1875. break;
  1876. default:
  1877. $attvalue = $sQuote . SM_PATH . 'images/blank.png' . $sQuote;
  1878. break;
  1879. }
  1880. } else {
  1881. if (!isset($aUrl['path']) || $aUrl['path'] != $secremoveimg) {
  1882. // parse_url did not lead to satisfying result
  1883. $attvalue = $sQuote . SM_PATH . 'images/blank.png' . $sQuote;
  1884. }
  1885. }
  1886. }
  1887. }
  1888. }
  1889. /**
  1890. * This function edits the style definition to make them friendly and
  1891. * usable in SquirrelMail.
  1892. *
  1893. * @param $message the message object
  1894. * @param $id the message id
  1895. * @param $content a string with whatever is between <style> and </style>
  1896. * @param $mailbox the message mailbox
  1897. * @return a string with edited content.
  1898. */
  1899. function sq_fixstyle($body, $pos, $message, $id, $mailbox){
  1900. $me = 'sq_fixstyle';
  1901. // workaround for </style> in between comments
  1902. $iCurrentPos = $pos;
  1903. $content = '';
  1904. $sToken = '';
  1905. $bSucces = false;
  1906. $bEndTag = false;
  1907. for ($i=$pos,$iCount=strlen($body);$i<$iCount;++$i) {
  1908. $char = $body{$i};
  1909. switch ($char) {
  1910. case '<':
  1911. $sToken = $char;
  1912. break;
  1913. case '/':
  1914. if ($sToken == '<') {
  1915. $sToken .= $char;
  1916. $bEndTag = true;
  1917. } else {
  1918. $content .= $char;
  1919. }
  1920. break;
  1921. case '>':
  1922. if ($bEndTag) {
  1923. $sToken .= $char;
  1924. if (preg_match('/\<\/\s*style\s*\>/i',$sToken,$aMatch)) {
  1925. $newpos = $i + 1;
  1926. $bSucces = true;
  1927. break 2;
  1928. } else {
  1929. $content .= $sToken;
  1930. }
  1931. $bEndTag = false;
  1932. } else {
  1933. $content .= $char;
  1934. }
  1935. break;
  1936. case '!':
  1937. if ($sToken == '<') {
  1938. // possible comment
  1939. if (isset($body{$i+2}) && substr($body,$i,3) == '!--') {
  1940. $i = strpos($body,'-->',$i+3);
  1941. if ($i === false) { // no end comment
  1942. $i = strlen($body);
  1943. }
  1944. $sToken = '';
  1945. }
  1946. } else {
  1947. $content .= $char;
  1948. }
  1949. break;
  1950. default:
  1951. if ($bEndTag) {
  1952. $sToken .= $char;
  1953. } else {
  1954. $content .= $char;
  1955. }
  1956. break;
  1957. }
  1958. }
  1959. if ($bSucces == FALSE){
  1960. return array(FALSE, strlen($body));
  1961. }
  1962. /**
  1963. * First look for general BODY style declaration, which would be
  1964. * like so:
  1965. * body {background: blah-blah}
  1966. * and change it to .bodyclass so we can just assign it to a <div>
  1967. */
  1968. // $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
  1969. // Nah, this is even better - try to preface all CSS selectors with
  1970. // our <div> class ID "bodyclass" then correct generic "body" selectors
  1971. // TODO: this works pretty good but breaks stuff like this:
  1972. // @media print { body { font-size: 10pt; } }
  1973. // but there isn't an easy way to make this regex skip @media
  1974. // definitions... though lots of the ones in the wild will be
  1975. // correctly handled because they tend to end with a parenthesis, like:
  1976. // @media screen and (max-width:480px) { ...
  1977. $content = preg_replace('/([a-z0-9._-][a-z0-9 >+~|:._-]*\s*(?:,|{.*?}))/si', '.bodyclass $1', $content);
  1978. $content = str_replace('.bodyclass body', '.bodyclass', $content);
  1979. global $use_transparent_security_image;
  1980. if ($use_transparent_security_image) $secremoveimg = '../images/spacer.png';
  1981. else $secremoveimg = '../images/' . _("sec_remove_eng.png");
  1982. /**
  1983. * Fix url('blah') declarations.
  1984. */
  1985. // $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
  1986. // "url(\\1$secremoveimg\\2)", $content);
  1987. // first check for 8bit sequences and disallowed control characters
  1988. if (preg_match('/[\16-\37\200-\377]+/',$content)) {
  1989. $content = '<!-- style block removed by html filter due to presence of 8bit characters -->';
  1990. return array($content, $newpos);
  1991. }
  1992. // IE Sucks hard. We have a special function for it.
  1993. sq_fixIE_idiocy($content);
  1994. // remove @import line
  1995. $content = preg_replace("/^\s*(@import.*)$/mi","\n<!-- @import rules forbidden -->\n",$content);
  1996. // translate ur\l and variations (IE parses that)
  1997. // TODO check if the sq_fixIE_idiocy function already handles this.
  1998. $content = preg_replace("/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i", 'url', $content);
  1999. preg_match_all("/url\s*\((.+)\)/si",$content,$aMatch);
  2000. if (count($aMatch)) {
  2001. $aValue = $aReplace = array();
  2002. foreach($aMatch[1] as $sMatch) {
  2003. // url value
  2004. $urlvalue = $sMatch;
  2005. sq_fix_url('style',$urlvalue, $message, $id, $mailbox,"'");
  2006. $aValue[] = $sMatch;
  2007. $aReplace[] = $urlvalue;
  2008. }
  2009. $content = str_replace($aValue,$aReplace,$content);
  2010. }
  2011. /**
  2012. * Remove any backslashes, entities, and extraneous whitespace.
  2013. */
  2014. $contentTemp = $content;
  2015. sq_defang($contentTemp);
  2016. sq_unspace($contentTemp);
  2017. /**
  2018. * Fix stupid css declarations which lead to vulnerabilities
  2019. * in IE.
  2020. *
  2021. * Also remove "position" attribute, as it can easily be set
  2022. * to "fixed" or "absolute" with "left" and "top" attributes
  2023. * of zero, taking over the whole content frame. It can also
  2024. * be set to relative and move itself anywhere it wants to,
  2025. * displaying content in areas it shouldn't be allowed to touch.
  2026. */
  2027. $match = Array('/\/\*.*\*\//', // removes /* blah blah */
  2028. '/expression/i',
  2029. '/behaviou*r/i',
  2030. '/binding/i',
  2031. '/include-source/i',
  2032. '/javascript/i',
  2033. '/script/i',
  2034. '/position/i');
  2035. $replace = Array('','idiocy', 'idiocy', 'idiocy', 'idiocy', 'idiocy', 'idiocy', '');
  2036. $contentNew = preg_replace($match, $replace, $contentTemp);
  2037. if ($contentNew !== $contentTemp) {
  2038. // insecure css declarations are used. From now on we don't care
  2039. // anymore if the css is destroyed by sq_deent, sq_unspace or sq_unbackslash
  2040. $content = $contentNew;
  2041. }
  2042. return array($content, $newpos);
  2043. }
  2044. /**
  2045. * This function converts cid: url's into the ones that can be viewed in
  2046. * the browser.
  2047. *
  2048. * @param $message the message object
  2049. * @param $id the message id
  2050. * @param $cidurl the cid: url.
  2051. * @param $mailbox the message mailbox
  2052. * @return a string with a http-friendly url
  2053. */
  2054. function sq_cid2http($message, $id, $cidurl, $mailbox){
  2055. /**
  2056. * Get rid of quotes.
  2057. */
  2058. $quotchar = substr($cidurl, 0, 1);
  2059. if ($quotchar == '"' || $quotchar == "'"){
  2060. $cidurl = str_replace($quotchar, "", $cidurl);
  2061. } else {
  2062. $quotchar = '';
  2063. }
  2064. $cidurl = substr(trim($cidurl), 4);
  2065. $match_str = '/\{.*?\}\//';
  2066. $str_rep = '';
  2067. $cidurl = preg_replace($match_str, $str_rep, $cidurl);
  2068. $linkurl = find_ent_id($cidurl, $message);
  2069. /* in case of non-safe cid links $httpurl should be replaced by a sort of
  2070. unsafe link image */
  2071. $httpurl = '';
  2072. /**
  2073. * This is part of a fix for Outlook Express 6.x generating
  2074. * cid URLs without creating content-id headers. These images are
  2075. * not part of the multipart/related html mail. The html contains
  2076. * <img src="cid:{some_id}/image_filename.ext"> references to
  2077. * attached images with as goal to render them inline although
  2078. * the attachment disposition property is not inline.
  2079. */
  2080. if (empty($linkurl)) {
  2081. if (preg_match('/{.*}\//', $cidurl)) {
  2082. $cidurl = preg_replace('/{.*}\//','', $cidurl);
  2083. if (!empty($cidurl)) {
  2084. $linkurl = find_ent_id($cidurl, $message);
  2085. }
  2086. }
  2087. }
  2088. if (!empty($linkurl)) {
  2089. $httpurl = $quotchar . sqm_baseuri() . 'src/download.php?absolute_dl=true&amp;' .
  2090. "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
  2091. '&amp;ent_id=' . $linkurl . $quotchar;
  2092. } else {
  2093. /**
  2094. * If we couldn't generate a proper img url, drop in a blank image
  2095. * instead of sending back empty, otherwise it causes unusual behaviour
  2096. */
  2097. $httpurl = $quotchar . SM_PATH . 'images/blank.png' . $quotchar;
  2098. }
  2099. return $httpurl;
  2100. }
  2101. /**
  2102. * This function changes the <body> tag into a <div> tag since we
  2103. * can't really have a body-within-body.
  2104. *
  2105. * @param $attary an array of attributes and values of <body>
  2106. * @param $mailbox mailbox we're currently reading (for cid2http)
  2107. * @param $message current message (for cid2http)
  2108. * @param $id current message id (for cid2http)
  2109. * @return a modified array of attributes to be set for <div>
  2110. */
  2111. function sq_body2div($attary, $mailbox, $message, $id){
  2112. $me = 'sq_body2div';
  2113. $divattary = Array('class' => "'bodyclass'");
  2114. $text = '#000000';
  2115. $has_bgc_stl = $has_txt_stl = false;
  2116. $styledef = '';
  2117. if (is_array($attary) && sizeof($attary) > 0){
  2118. foreach ($attary as $attname=>$attvalue){
  2119. $quotchar = substr($attvalue, 0, 1);
  2120. $attvalue = str_replace($quotchar, "", $attvalue);
  2121. switch ($attname){
  2122. case 'background':
  2123. $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
  2124. $styledef .= "background-image: url('$attvalue'); ";
  2125. break;
  2126. case 'bgcolor':
  2127. $has_bgc_stl = true;
  2128. $styledef .= "background-color: $attvalue; ";
  2129. break;
  2130. case 'text':
  2131. $has_txt_stl = true;
  2132. $styledef .= "color: $attvalue; ";
  2133. break;
  2134. }
  2135. }
  2136. // Outlook defines a white bgcolor and no text color. This can lead to
  2137. // white text on a white bg with certain themes.
  2138. if ($has_bgc_stl && !$has_txt_stl) {
  2139. $styledef .= "color: $text; ";
  2140. }
  2141. if (strlen($styledef) > 0){
  2142. $divattary{"style"} = "\"$styledef\"";
  2143. }
  2144. }
  2145. return $divattary;
  2146. }
  2147. /**
  2148. * This is the main function and the one you should actually be calling.
  2149. * There are several variables you should be aware of an which need
  2150. * special description.
  2151. *
  2152. * Since the description is quite lengthy, see it here:
  2153. * http://linux.duke.edu/projects/mini/htmlfilter/
  2154. *
  2155. * @param $body the string with HTML you wish to filter
  2156. * @param $tag_list see description above
  2157. * @param $rm_tags_with_content see description above
  2158. * @param $self_closing_tags see description above
  2159. * @param $force_tag_closing see description above
  2160. * @param $rm_attnames see description above
  2161. * @param $bad_attvals see description above
  2162. * @param $add_attr_to_tag see description above
  2163. * @param $message message object
  2164. * @param $id message id
  2165. * @param $recursively_called boolean flag for recursive calls into this function (optional; default FALSE)
  2166. * @return sanitized html safe to show on your pages.
  2167. */
  2168. function sq_sanitize($body,
  2169. $tag_list,
  2170. $rm_tags_with_content,
  2171. $self_closing_tags,
  2172. $force_tag_closing,
  2173. $rm_attnames,
  2174. $bad_attvals,
  2175. $add_attr_to_tag,
  2176. $message,
  2177. $id,
  2178. $mailbox,
  2179. $recursively_called=FALSE
  2180. ){
  2181. $me = 'sq_sanitize';
  2182. /**
  2183. * See if tag_list is of tags to remove or tags to allow.
  2184. * false means remove these tags
  2185. * true means allow these tags
  2186. */
  2187. $orig_tag_list = $tag_list;
  2188. $rm_tags = array_shift($tag_list);
  2189. /**
  2190. * Normalize rm_tags and rm_tags_with_content.
  2191. */
  2192. @array_walk($tag_list, 'sq_casenormalize');
  2193. @array_walk($rm_tags_with_content, 'sq_casenormalize');
  2194. @array_walk($self_closing_tags, 'sq_casenormalize');
  2195. $curpos = 0;
  2196. $open_tags = Array();
  2197. $trusted = "\n<!-- begin sanitized html -->\n";
  2198. $skip_content = false;
  2199. /**
  2200. * Take care of netscape's stupid javascript entities like
  2201. * &{alert('boo')};
  2202. */
  2203. $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
  2204. while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
  2205. list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
  2206. /**
  2207. * RCDATA and RAWTEXT tags are handled differently:
  2208. * next instance of closing tag is used, whether or not
  2209. * the HTML is well formed before that
  2210. */
  2211. global $rcdata_rawtext_tags;
  2212. if (!$recursively_called
  2213. && in_array($tagname, $rcdata_rawtext_tags)
  2214. && $tagtype === 1){
  2215. $closing_tag = false;
  2216. $closing_tag_offset = $curpos;
  2217. // seek out the closing tag for the current RCDATA/RAWTEXT tag
  2218. while (1) {
  2219. // first we need to move forward to next available closing tag
  2220. // (intentionally leave off the closing > and let sq_getnxtag() validate a proper tag syntax)
  2221. $next_tag = sq_findnxreg($body, $closing_tag_offset, "</\s*$tagname");
  2222. if ($next_tag === false) {
  2223. $closing_tag = false;
  2224. break;
  2225. }
  2226. // but then we have to make sure it's a well-formed tag
  2227. $closing_tag = sq_getnxtag($body, $next_tag[0]);
  2228. if ($closing_tag === false)
  2229. break;
  2230. else if ($closing_tag[0] !== false
  2231. // these should be redundant
  2232. && $closing_tag[0] === $tagname && $closing_tag[2] === 2) {
  2233. $trusted .= sq_sanitize(substr($body, $curpos, $closing_tag[4] - $curpos + 1),
  2234. $orig_tag_list, $rm_tags_with_content, $self_closing_tags,
  2235. $force_tag_closing, $rm_attnames, $bad_attvals, $add_attr_to_tag,
  2236. $message, $id, $mailbox, true);
  2237. $curpos = $closing_tag[4] + 1;
  2238. continue 2;
  2239. }
  2240. $closing_tag_offset = $next_tag[0] + 1;
  2241. }
  2242. if ($closing_tag === false)
  2243. { /* no-op... there was no closing tag for this RCDATA/RAWTEXT tag - we could probably set $curpos to the end of $body, but this HTML is malformed anyway and should just fall apart on its own */ }
  2244. }
  2245. $free_content = substr($body, $curpos, $lt-$curpos);
  2246. /**
  2247. * Take care of <style>
  2248. */
  2249. if ($tagname == "style" && $tagtype == 1){
  2250. list($free_content, $curpos) =
  2251. sq_fixstyle($body, $gt+1, $message, $id, $mailbox);
  2252. if ($free_content != FALSE){
  2253. if ( !empty($attary) ) {
  2254. $attary = sq_fixatts($tagname,
  2255. $attary,
  2256. $rm_attnames,
  2257. $bad_attvals,
  2258. $add_attr_to_tag,
  2259. $message,
  2260. $id,
  2261. $mailbox
  2262. );
  2263. }
  2264. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  2265. $trusted .= $free_content;
  2266. $trusted .= sq_tagprint($tagname, false, 2);
  2267. }
  2268. continue;
  2269. }
  2270. if ($skip_content == false){
  2271. $trusted .= $free_content;
  2272. }
  2273. if ($tagname != FALSE){
  2274. if ($tagtype == 2){
  2275. if ($skip_content == $tagname){
  2276. /**
  2277. * Got to the end of tag we needed to remove.
  2278. */
  2279. $tagname = false;
  2280. $skip_content = false;
  2281. } else {
  2282. if ($skip_content == false){
  2283. if ($tagname == "body"){
  2284. $tagname = "div";
  2285. }
  2286. if (isset($open_tags{$tagname}) &&
  2287. $open_tags{$tagname} > 0){
  2288. $open_tags{$tagname}--;
  2289. } else {
  2290. $tagname = false;
  2291. }
  2292. }
  2293. }
  2294. } else {
  2295. /**
  2296. * $rm_tags_with_content
  2297. */
  2298. if ($skip_content == false){
  2299. /**
  2300. * See if this is a self-closing type and change
  2301. * tagtype appropriately.
  2302. */
  2303. if ($tagtype == 1
  2304. && in_array($tagname, $self_closing_tags)){
  2305. $tagtype = 3;
  2306. }
  2307. /**
  2308. * See if we should skip this tag and any content
  2309. * inside it.
  2310. */
  2311. if ($tagtype == 1 &&
  2312. in_array($tagname, $rm_tags_with_content)){
  2313. $skip_content = $tagname;
  2314. } else {
  2315. if (($rm_tags == false
  2316. && in_array($tagname, $tag_list)) ||
  2317. ($rm_tags == true &&
  2318. !in_array($tagname, $tag_list))){
  2319. $tagname = false;
  2320. } else {
  2321. /**
  2322. * Convert body into div.
  2323. */
  2324. if ($tagname == "body"){
  2325. $tagname = "div";
  2326. $attary = sq_body2div($attary, $mailbox,
  2327. $message, $id);
  2328. }
  2329. if ($tagtype == 1){
  2330. if (isset($open_tags{$tagname})){
  2331. $open_tags{$tagname}++;
  2332. } else {
  2333. $open_tags{$tagname}=1;
  2334. }
  2335. }
  2336. /**
  2337. * This is where we run other checks.
  2338. */
  2339. if (is_array($attary) && sizeof($attary) > 0){
  2340. $attary = sq_fixatts($tagname,
  2341. $attary,
  2342. $rm_attnames,
  2343. $bad_attvals,
  2344. $add_attr_to_tag,
  2345. $message,
  2346. $id,
  2347. $mailbox
  2348. );
  2349. }
  2350. }
  2351. }
  2352. }
  2353. }
  2354. if ($tagname != false && $skip_content == false){
  2355. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  2356. }
  2357. }
  2358. $curpos = $gt+1;
  2359. }
  2360. $trusted .= substr($body, $curpos, strlen($body)-$curpos);
  2361. if ($force_tag_closing == true){
  2362. foreach ($open_tags as $tagname=>$opentimes){
  2363. while ($opentimes > 0){
  2364. $trusted .= '</' . $tagname . '>';
  2365. $opentimes--;
  2366. }
  2367. }
  2368. $trusted .= "\n";
  2369. }
  2370. $trusted .= "<!-- end sanitized html -->\n";
  2371. return $trusted;
  2372. }
  2373. /**
  2374. * This is a wrapper function to call html sanitizing routines.
  2375. *
  2376. * @param $body the body of the message
  2377. * @param $id the id of the message
  2378. * @param $message
  2379. * @param $mailbox
  2380. * @param boolean $take_mailto_links When TRUE, converts mailto: links
  2381. * into internal SM compose links
  2382. * (optional; default = TRUE)
  2383. * @return a string with html safe to display in the browser.
  2384. */
  2385. function magicHTML($body, $id, $message, $mailbox = 'INBOX', $take_mailto_links =true) {
  2386. // require_once(SM_PATH . 'functions/url_parser.php'); // for $MailTo_PReg_Match
  2387. global $attachment_common_show_images, $view_unsafe_images,
  2388. $has_unsafe_images, $allow_svg_display, $rcdata_rawtext_tags,
  2389. $remove_rcdata_rawtext_tags_and_content;
  2390. $rcdata_rawtext_tags = array(
  2391. "noscript",
  2392. "noframes",
  2393. "noembed",
  2394. "textarea",
  2395. // also "title", "xmp", "script", "iframe", "plaintext" which we already remove below
  2396. );
  2397. /**
  2398. * Don't display attached images in HTML mode.
  2399. *
  2400. * SB: why?
  2401. */
  2402. $attachment_common_show_images = false;
  2403. $tag_list = Array(
  2404. false, // remove these tags
  2405. "meta",
  2406. "html",
  2407. "head",
  2408. "base",
  2409. "link",
  2410. "frame",
  2411. "iframe",
  2412. "plaintext",
  2413. "marquee",
  2414. );
  2415. $rm_tags_with_content = Array(
  2416. "script",
  2417. "object",
  2418. "applet",
  2419. "embed",
  2420. "title",
  2421. "frameset",
  2422. "xmp",
  2423. "xml",
  2424. );
  2425. if (!$allow_svg_display)
  2426. $rm_tags_with_content[] = 'svg';
  2427. /**
  2428. * SquirrelMail will parse RCDATA and RAWTEXT tags and handle them as the special
  2429. * case that they are, but if you prefer to remove them and their contents entirely
  2430. * (in most cases, should be a safe thing with minimal impact), you can add the
  2431. * following to config/config_local.php
  2432. * $remove_rcdata_rawtext_tags_and_content = TRUE;
  2433. */
  2434. if ($remove_rcdata_rawtext_tags_and_content)
  2435. $rm_tags_with_content = array_merge($rm_tags_with_content, $rcdata_rawtext_tags);
  2436. $self_closing_tags = Array(
  2437. "img",
  2438. "br",
  2439. "hr",
  2440. "input",
  2441. "outbind",
  2442. );
  2443. $force_tag_closing = true;
  2444. $rm_attnames = Array(
  2445. "/.*/" =>
  2446. Array(
  2447. "/target/i",
  2448. "/^on.*/i",
  2449. "/^dynsrc/i",
  2450. "/^data.*/i",
  2451. "/^lowsrc.*/i",
  2452. )
  2453. );
  2454. global $use_transparent_security_image;
  2455. if ($use_transparent_security_image) $secremoveimg = '../images/spacer.png';
  2456. else $secremoveimg = '../images/' . _("sec_remove_eng.png");
  2457. $bad_attvals = Array(
  2458. "/.*/" =>
  2459. Array(
  2460. "/^src|background/i" =>
  2461. Array(
  2462. Array(
  2463. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  2464. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  2465. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  2466. ),
  2467. Array(
  2468. "\\1$secremoveimg\\2",
  2469. "\\1$secremoveimg\\2",
  2470. "\\1$secremoveimg\\2",
  2471. )
  2472. ),
  2473. "/^href|action/i" =>
  2474. Array(
  2475. Array(
  2476. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  2477. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  2478. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  2479. ),
  2480. Array(
  2481. "\\1#\\1",
  2482. "\\1#\\1",
  2483. "\\1#\\1"
  2484. )
  2485. ),
  2486. "/^style/i" =>
  2487. Array(
  2488. Array(
  2489. "/\/\*.*\*\//",
  2490. "/expression/i",
  2491. "/binding/i",
  2492. "/behaviou*r/i",
  2493. "/include-source/i",
  2494. // position:relative can also be exploited
  2495. // to put content outside of email body area
  2496. // and position:fixed is similarly exploitable
  2497. // as position:absolute, so we'll remove it
  2498. // altogether....
  2499. //
  2500. // Does this screw up legitimate HTML messages?
  2501. // If so, the only fix I see is to allow position
  2502. // attributes (any values? I think we still have
  2503. // to block static and fixed) only if $use_iframe
  2504. // is enabled (1.5.0+)
  2505. //
  2506. // was: "/position\s*:\s*absolute/i",
  2507. //
  2508. "/position\s*:/i",
  2509. "/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i",
  2510. "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
  2511. "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
  2512. "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
  2513. "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si",
  2514. ),
  2515. Array(
  2516. "",
  2517. "idiocy",
  2518. "idiocy",
  2519. "idiocy",
  2520. "idiocy",
  2521. "idiocy",
  2522. "url",
  2523. "url(\\1#\\1)",
  2524. "url(\\1#\\1)",
  2525. "url(\\1#\\1)",
  2526. "\\1:url(\\2#\\3)"
  2527. )
  2528. )
  2529. )
  2530. );
  2531. // If there's no "view_unsafe_images" variable in the URL, turn unsafe
  2532. // images off by default.
  2533. sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET, FALSE);
  2534. if (!$view_unsafe_images){
  2535. /**
  2536. * Remove any references to http/https if view_unsafe_images set
  2537. * to false.
  2538. */
  2539. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
  2540. '/^([\'\"])\s*https*:.*([\'\"])/si');
  2541. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
  2542. "\\1$secremoveimg\\1");
  2543. array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
  2544. '/url\([\'\"]?https?:[^\)]*[\'\"]?\)/si');
  2545. array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
  2546. "url(\\1$secremoveimg\\1)");
  2547. }
  2548. $add_attr_to_tag = Array(
  2549. "/^a$/i" =>
  2550. Array('target'=>'"_blank"',
  2551. 'title'=>'"'._("This external link will open in a new window").'"'
  2552. )
  2553. );
  2554. $trusted = sq_sanitize($body,
  2555. $tag_list,
  2556. $rm_tags_with_content,
  2557. $self_closing_tags,
  2558. $force_tag_closing,
  2559. $rm_attnames,
  2560. $bad_attvals,
  2561. $add_attr_to_tag,
  2562. $message,
  2563. $id,
  2564. $mailbox
  2565. );
  2566. if (strpos($trusted,$secremoveimg)){
  2567. $has_unsafe_images = true;
  2568. }
  2569. // we want to parse mailto's in HTML output, change to SM compose links
  2570. // this is a modified version of code from url_parser.php... but Marc is
  2571. // right: we need a better filtering implementation; adding this randomly
  2572. // here is not a great solution
  2573. //
  2574. if ($take_mailto_links) {
  2575. // parseUrl($trusted); // this even parses URLs inside of tags... too aggressive
  2576. global $MailTo_PReg_Match;
  2577. // some mailers (Microsoft, surprise surprise) produce mailto strings without being
  2578. // inside an anchor (link) tag, so we have to make sure the regex looks for the
  2579. // quote before mailto, and we'll also try to convert the non-links back into links
  2580. $MailTo_PReg_Match = '/([\'"])?mailto:' . substr($MailTo_PReg_Match, 1) ;
  2581. if ((preg_match_all($MailTo_PReg_Match, $trusted, $regs)) && ($regs[0][0] != '')) {
  2582. foreach ($regs[0] as $i => $mailto_before) {
  2583. $mailto_params = $regs[11][$i];
  2584. // get rid of any leading quote we may have captured but don't care about
  2585. //
  2586. $mailto_before = ltrim($mailto_before, '"\'');
  2587. // get rid of any tailing quote since we have to add send_to to the end
  2588. //
  2589. $mailto_before = rtrim($mailto_before, '"\'');
  2590. $mailto_params = rtrim($mailto_params, '"\'');
  2591. if ($regs[2][$i]) { //if there is an email addr before '?', we need to merge it with the params
  2592. $to = 'to=' . $regs[2][$i];
  2593. if (strpos($mailto_params, 'to=') > -1) //already a 'to='
  2594. $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
  2595. else {
  2596. if ($mailto_params) //already some params, append to them
  2597. $mailto_params .= '&amp;' . $to;
  2598. else
  2599. $mailto_params .= '?' . $to;
  2600. }
  2601. }
  2602. $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
  2603. // we'll already have target=_blank, no need to allow comp_in_new
  2604. // here (which would be a lot more work anyway)
  2605. //
  2606. global $compose_new_win;
  2607. $temp_comp_in_new = $compose_new_win;
  2608. $compose_new_win = 0;
  2609. $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
  2610. $compose_new_win = $temp_comp_in_new;
  2611. // remove <a href=" and anything after the next quote (we only
  2612. // need the uri, not the link HTML) in compose uri
  2613. //
  2614. // but only do this if the original mailto was in a real anchor tag
  2615. //
  2616. if (!empty($regs[1][$i])) {
  2617. $comp_uri = substr($comp_uri, 9);
  2618. $comp_uri = substr($comp_uri, 0, strpos($comp_uri, '"', 1));
  2619. }
  2620. $trusted = str_replace($mailto_before, $comp_uri, $trusted);
  2621. }
  2622. }
  2623. }
  2624. return $trusted;
  2625. }
  2626. /**
  2627. * function SendDownloadHeaders - send file to the browser
  2628. *
  2629. * Original Source: SM core src/download.php
  2630. * moved here to make it available to other code, and separate
  2631. * front end from back end functionality.
  2632. *
  2633. * @param string $type0 first half of mime type
  2634. * @param string $type1 second half of mime type
  2635. * @param string $filename filename to tell the browser for downloaded file
  2636. * @param boolean $force whether to force the download dialog to pop
  2637. * @param optional integer $filesize send the Content-Header and length to the browser
  2638. * @return void
  2639. */
  2640. function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
  2641. global $languages, $squirrelmail_language;
  2642. $isIE = $isIE6plus = false;
  2643. sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER);
  2644. if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
  2645. strstr($HTTP_USER_AGENT, 'Opera') === false) {
  2646. $isIE = true;
  2647. }
  2648. if (preg_match('/compatible; MSIE ([0-9]+)/', $HTTP_USER_AGENT, $match) &&
  2649. ((int)$match[1]) >= 6 && strstr($HTTP_USER_AGENT, 'Opera') === false) {
  2650. $isIE6plus = true;
  2651. }
  2652. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  2653. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
  2654. $filename =
  2655. call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
  2656. } else {
  2657. $filename = preg_replace('/[\\\\\/:*?"<>|;]/', '_', str_replace('&nbsp;', ' ', $filename));
  2658. }
  2659. // A Pox on Microsoft and it's Internet Explorer!
  2660. //
  2661. // IE has lots of bugs with file downloads.
  2662. // It also has problems with SSL. Both of these cause problems
  2663. // for us in this function.
  2664. //
  2665. // See this article on Cache Control headers and SSL
  2666. // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
  2667. //
  2668. // The best thing you can do for IE is to upgrade to the latest
  2669. // version
  2670. //set all the Cache Control Headers for IE
  2671. if ($isIE) {
  2672. $filename=rawurlencode($filename);
  2673. header ("Pragma: public");
  2674. header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
  2675. // does nothing - see: https://blogs.msdn.microsoft.com/ieinternals/2009/07/20/internet-explorers-cache-control-extensions/
  2676. // header ("Cache-Control: post-check=0, pre-check=0", false);
  2677. header ("Cache-Control: private");
  2678. //set the inline header for IE, we'll add the attachment header later if we need it
  2679. header ("Content-Disposition: inline; filename=$filename");
  2680. }
  2681. if (!$force) {
  2682. // Try to show in browser window
  2683. header ("Content-Disposition: inline; filename=\"$filename\"");
  2684. header ("Content-Type: $type0/$type1; name=\"$filename\"");
  2685. } else {
  2686. // Try to pop up the "save as" box
  2687. // IE makes this hard. It pops up 2 save boxes, or none.
  2688. // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
  2689. // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
  2690. // But, according to Microsoft, it is "RFC compliant but doesn't
  2691. // take into account some deviations that allowed within the
  2692. // specification." Doesn't that mean RFC non-compliant?
  2693. // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
  2694. // all browsers need the application/octet-stream header for this
  2695. header ("Content-Type: application/octet-stream; name=\"$filename\"");
  2696. // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
  2697. // Do not have quotes around filename, but that applied to
  2698. // "attachment"... does it apply to inline too?
  2699. header ("Content-Disposition: attachment; filename=\"$filename\"");
  2700. if ($isIE && !$isIE6plus) {
  2701. // This combination seems to work mostly. IE 5.5 SP 1 has
  2702. // known issues (see the Microsoft Knowledge Base)
  2703. // This works for most types, but doesn't work with Word files
  2704. header ("Content-Type: application/download; name=\"$filename\"");
  2705. header ("Content-Type: application/force-download; name=\"$filename\"");
  2706. // These are spares, just in case. :-)
  2707. //header("Content-Type: $type0/$type1; name=\"$filename\"");
  2708. //header("Content-Type: application/x-msdownload; name=\"$filename\"");
  2709. //header("Content-Type: application/octet-stream; name=\"$filename\"");
  2710. } else if ($isIE) {
  2711. // This is to prevent IE for MIME sniffing and auto open a file in IE
  2712. header ("Content-Type: application/force-download; name=\"$filename\"");
  2713. } else {
  2714. // another application/octet-stream forces download for Netscape
  2715. header ("Content-Type: application/octet-stream; name=\"$filename\"");
  2716. }
  2717. }
  2718. //send the content-length header if the calling function provides it
  2719. if ($filesize > 0) {
  2720. header("Content-Length: $filesize");
  2721. }
  2722. } // end fn SendDownloadHeaders