mime.php 118 KB

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