mime.php 120 KB

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