mime.php 112 KB

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