mime.php 101 KB

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