mime.php 110 KB

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