mime.php 107 KB

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