mime.php 121 KB

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