mime.php 87 KB

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