mime.php 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049
  1. <?php
  2. /**
  3. * mime.php
  4. *
  5. * Copyright (c) 1999-2002 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * This contains the functions necessary to detect and decode MIME
  9. * messages.
  10. *
  11. * $Id$
  12. */
  13. require_once('../functions/imap.php');
  14. require_once('../functions/attachment_common.php');
  15. /** Setting up the objects that have the structure for the message **/
  16. class msg_header {
  17. /** msg_header contains generic variables for values that **/
  18. /** could be in a header. **/
  19. var $type0 = '', $type1 = '', $boundary = '', $charset = '',
  20. $encoding = '', $size = 0, $to = array(), $from = '', $date = '',
  21. $cc = array(), $bcc = array(), $reply_to = '', $subject = '',
  22. $id = 0, $mailbox = '', $description = '', $filename = '',
  23. $entity_id = 0, $message_id = 0, $name = '', $priority = 3, $type = '';
  24. }
  25. class message {
  26. /** message is the object that contains messages. It is a recursive
  27. object in that through the $entities variable, it can contain
  28. more objects of type message. See documentation in mime.txt for
  29. a better description of how this works.
  30. **/
  31. var $header = '', $entities = array();
  32. function addEntity ($msg) {
  33. $this->entities[] = $msg;
  34. }
  35. }
  36. /* --------------------------------------------------------------------------------- */
  37. /* MIME DECODING */
  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 ($imap_stream, $header) {
  44. $ssid = sqimap_session_id();
  45. $lsid = strlen( $ssid );
  46. $id = $header->id;
  47. fputs ($imap_stream, "$ssid FETCH $id BODYSTRUCTURE\r\n");
  48. //
  49. // This should use sqimap_read_data instead of reading it itself
  50. //
  51. $read = fgets ($imap_stream, 9216);
  52. $bodystructure = '';
  53. while ( substr($read, 0, $lsid) <> $ssid &&
  54. !feof( $imap_stream ) ) {
  55. $bodystructure .= $read;
  56. $read = fgets ($imap_stream, 9216);
  57. }
  58. $read = $bodystructure;
  59. // isolate the body structure and remove beginning and end parenthesis
  60. $read = trim(substr ($read, strpos(strtolower($read), 'bodystructure') + 13));
  61. $read = trim(substr ($read, 0, -1));
  62. $end = mime_match_parenthesis(0, $read);
  63. while ($end == strlen($read)-1) {
  64. $read = trim(substr ($read, 0, -1));
  65. $read = trim(substr ($read, 1));
  66. $end = mime_match_parenthesis(0, $read);
  67. }
  68. $msg = mime_parse_structure ($read, 0);
  69. $msg->header = $header;
  70. return( $msg );
  71. }
  72. /* this starts the parsing of a particular structure. It is called recursively,
  73. * so it can be passed different structures. It returns an object of type
  74. * $message.
  75. * First, it checks to see if it is a multipart message. If it is, then it
  76. * handles that as it sees is necessary. If it is just a regular entity,
  77. * then it parses it and adds the necessary header information (by calling out
  78. * to mime_get_elements()
  79. */
  80. function mime_parse_structure ($structure, $ent_id) {
  81. global $mailbox;
  82. $properties = array();
  83. $msg = new message();
  84. if ($structure{0} == '(') {
  85. $old_ent_id = $ent_id;
  86. $ent_id = mime_new_element_level($ent_id);
  87. $start = $end = -1;
  88. do {
  89. $start = $end+1;
  90. $end = mime_match_parenthesis ($start, $structure);
  91. /* check if we are dealing with a new entity-level */
  92. $i = strrpos($ent_id,'.');
  93. if ($i>0) {
  94. $ent = substr($ent_id, $i+1);
  95. } else {
  96. $ent = '';
  97. }
  98. /* add "forgotten" parent entities (alternative and relative) */
  99. if ($ent == '0') {
  100. /* new entity levels have information about the type (type1) and
  101. * the properties. This information is situated at the end of the
  102. * structure string like for example (example between the brackets)
  103. * [ "RELATED" ("BOUNDARY" "myboundary" "TYPE" "plain/html") ]
  104. */
  105. /* get the involved properties for parsing to mime_get_properties */
  106. $startprop = strrpos($structure,'(');
  107. $properties_str = substr($structure,$startprop);
  108. $endprop = mime_match_parenthesis ($startprop, $structure);
  109. $propstr = substr($structure, $startprop + 1, ($endprop - $startprop)-1);
  110. /* cut off the used properties */
  111. if ($startprop) {
  112. $structure_end = substr($structure, $endprop+2);
  113. $structure = trim(substr($structure,0,$startprop));
  114. }
  115. /* get type1 */
  116. $pos = strrpos($structure,' ');
  117. $type1 = strtolower(substr($structure, $pos+2, (count($structure)-2)));
  118. /* cut off type1 */
  119. if ($pos && $startprop) {
  120. $structure = trim(substr($structure, 0, $pos));
  121. }
  122. /* process the found information */
  123. $properties = mime_get_props($properties, $properties_str);
  124. if (count($properties)>0) {
  125. $msg->header->entity_id = $old_ent_id;
  126. $msg->header->type0 = 'multipart';
  127. $msg->header->type1 = $type1;
  128. for ($i=0; $i < count($properties); $i++) {
  129. $msg->header->{$properties[$i]['name']} = $properties[$i]['value'];
  130. }
  131. }
  132. $structure = $structure . ' ' . $structure_end;
  133. }
  134. $element = substr($structure, $start+1, ($end - $start)-1);
  135. $ent_id = mime_increment_id ($ent_id);
  136. $newmsg = mime_parse_structure ($element, $ent_id);
  137. /* set mailbox in case of message/rfc822 entities */
  138. if (isset($newmsg->header->type0) && isset($newmsg->header->type1)) {
  139. if ($newmsg->header->type0 == 'message' && $newmsg->header->type1 == 'rfc822') {
  140. $newmsg->header->mailbox=$mailbox;
  141. }
  142. }
  143. $msg->addEntity ($newmsg);
  144. } while ($structure{$end+1} == '(');
  145. } else {
  146. // parse the elements
  147. $msg = mime_get_element ($structure, $msg, $ent_id);
  148. }
  149. return $msg;
  150. }
  151. /* Increments the element ID. An element id can look like any of
  152. * the following: 1, 1.2, 4.3.2.4.1, etc. This function increments
  153. * the last number of the element id, changing 1.2 to 1.3.
  154. */
  155. function mime_increment_id ($id) {
  156. if (strpos($id, '.')) {
  157. $first = substr($id, 0, strrpos($id, '.'));
  158. $last = substr($id, strrpos($id, '.')+1);
  159. $last++;
  160. $new = $first . '.' .$last;
  161. } else {
  162. $new = $id + 1;
  163. }
  164. return $new;
  165. }
  166. /*
  167. * See comment for mime_increment_id().
  168. * This adds another level on to the entity_id changing 1.3 to 1.3.0
  169. * NOTE: 1.3.0 is not a valid element ID. It MUST be incremented
  170. * before it can be used. I left it this way so as not to have
  171. * to make a special case if it is the first entity_id. It
  172. * always increments it, and that works fine.
  173. */
  174. function mime_new_element_level ($id) {
  175. if (!$id) {
  176. $id = 0;
  177. } else {
  178. $id = $id . '.0';
  179. }
  180. return( $id );
  181. }
  182. function mime_get_element (&$structure, $msg, $ent_id) {
  183. $elem_num = 1;
  184. $msg->header = new msg_header();
  185. $msg->header->entity_id = $ent_id;
  186. $properties = array();
  187. while (strlen($structure) > 0) {
  188. $structure = trim($structure);
  189. $char = $structure{0};
  190. if (strtolower(substr($structure, 0, 3)) == 'nil') {
  191. $text = '';
  192. $structure = substr($structure, 3);
  193. } else if ($char == '"') {
  194. // loop through until we find the matching quote, and return that as a string
  195. $pos = 1;
  196. $text = '';
  197. while ( ($char = $structure{$pos} ) <> '"' && $pos < strlen($structure)) {
  198. $text .= $char;
  199. $pos++;
  200. }
  201. $structure = substr($structure, strlen($text) + 2);
  202. } else if ($char == '(') {
  203. // comment me
  204. $end = mime_match_parenthesis (0, $structure);
  205. $sub = substr($structure, 1, $end-1);
  206. $properties = mime_get_props($properties, $sub);
  207. $structure = substr($structure, strlen($sub) + 2);
  208. } else {
  209. // loop through until we find a space or an end parenthesis
  210. $pos = 0;
  211. $char = $structure{$pos};
  212. $text = '';
  213. while ($char != ' ' && $char != ')' && $pos < strlen($structure)) {
  214. $text .= $char;
  215. $pos++;
  216. $char = $structure{$pos};
  217. }
  218. $structure = substr($structure, strlen($text));
  219. }
  220. // This is where all the text parts get put into the header
  221. switch ($elem_num) {
  222. case 1:
  223. $msg->header->type0 = strtolower($text);
  224. break;
  225. case 2:
  226. $msg->header->type1 = strtolower($text);
  227. break;
  228. case 4: // Id
  229. // Invisimail enclose images with <>
  230. $msg->header->id = str_replace( '<', '', str_replace( '>', '', $text ) );
  231. break;
  232. case 5:
  233. $msg->header->description = $text;
  234. break;
  235. case 6:
  236. $msg->header->encoding = strtolower($text);
  237. break;
  238. case 7:
  239. $msg->header->size = $text;
  240. break;
  241. default:
  242. if ($msg->header->type0 == 'text' && $elem_num == 8) {
  243. // This is a plain text message, so lets get the number of lines
  244. // that it contains.
  245. $msg->header->num_lines = $text;
  246. } else if ($msg->header->type0 == 'message' && $msg->header->type1 == 'rfc822' && $elem_num == 8) {
  247. // This is an encapsulated message, so lets start all over again and
  248. // parse this message adding it on to the existing one.
  249. $structure = trim($structure);
  250. if ( $structure{0} == '(' ) {
  251. $e = mime_match_parenthesis (0, $structure);
  252. $structure = substr($structure, 0, $e);
  253. $structure = substr($structure, 1);
  254. $m = mime_parse_structure($structure, $msg->header->entity_id);
  255. // the following conditional is there to correct a bug that wasn't
  256. // incrementing the entity IDs correctly because of the special case
  257. // that message/rfc822 is. This fixes it fine.
  258. if (substr($structure, 1, 1) != '(')
  259. $m->header->entity_id = mime_increment_id(mime_new_element_level($ent_id));
  260. // Now we'll go through and reformat the results.
  261. if ($m->entities) {
  262. for ($i=0; $i < count($m->entities); $i++) {
  263. $msg->addEntity($m->entities[$i]);
  264. }
  265. } else {
  266. $msg->addEntity($m);
  267. }
  268. $structure = "";
  269. }
  270. }
  271. break;
  272. }
  273. $elem_num++;
  274. $text = "";
  275. }
  276. // loop through the additional properties and put those in the various headers
  277. for ($i=0; $i < count($properties); $i++) {
  278. $msg->header->{$properties[$i]['name']} = $properties[$i]['value'];
  279. }
  280. return $msg;
  281. }
  282. /*
  283. * I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
  284. * figure out how to do this part, so I decided to go to bed. I woke up
  285. * in the morning and had a flash of insight. I went to the white-board
  286. * and scribbled it out, then spent a bit programming it, and this is the
  287. * result. Nothing complicated, but I think my brain was fried yesterday.
  288. * Funny how that happens some times.
  289. *
  290. * This gets properties in a nested parenthesisized list. For example,
  291. * this would get passed something like: ("attachment" ("filename" "luke.tar.gz"))
  292. * This returns an array called $props with all paired up properties.
  293. * It ignores the "attachment" for now, maybe that should change later
  294. * down the road. In this case, what is returned is:
  295. * $props[0]["name"] = "filename";
  296. * $props[0]["value"] = "luke.tar.gz";
  297. */
  298. function mime_get_props ($props, $structure) {
  299. while (strlen($structure) > 0) {
  300. $structure = trim($structure);
  301. $char = $structure{0};
  302. if ($char == '"') {
  303. $pos = 1;
  304. $tmp = '';
  305. while ( ( $char = $structure{$pos} ) != '"' &&
  306. $pos < strlen($structure)) {
  307. $tmp .= $char;
  308. $pos++;
  309. }
  310. $structure = trim(substr($structure, strlen($tmp) + 2));
  311. $char = $structure{0};
  312. if ($char == '"') {
  313. $pos = 1;
  314. $value = '';
  315. while ( ( $char = $structure{$pos} ) != '"' &&
  316. $pos < strlen($structure) ) {
  317. $value .= $char;
  318. $pos++;
  319. }
  320. $structure = trim(substr($structure, strlen($value) + 2));
  321. $k = count($props);
  322. $props[$k]['name'] = strtolower($tmp);
  323. $props[$k]['value'] = $value;
  324. if ($structure != '') {
  325. mime_get_props($props, $structure);
  326. } else {
  327. return $props;
  328. }
  329. } else if ($char == '(') {
  330. $end = mime_match_parenthesis (0, $structure);
  331. $sub = substr($structure, 1, $end-1);
  332. if (! isset($props))
  333. $props = array();
  334. $props = mime_get_props($props, $sub);
  335. $structure = substr($structure, strlen($sub) + 2);
  336. return $props;
  337. }
  338. } else if ($char == '(') {
  339. $end = mime_match_parenthesis (0, $structure);
  340. $sub = substr($structure, 1, $end-1);
  341. $props = mime_get_props($props, $sub);
  342. $structure = substr($structure, strlen($sub) + 2);
  343. return $props;
  344. } else {
  345. return $props;
  346. }
  347. }
  348. }
  349. /*
  350. * Matches parenthesis. It will return the position of the matching
  351. * parenthesis in $structure. For instance, if $structure was:
  352. * ("text" "plain" ("val1name", "1") nil ... )
  353. * x x
  354. * then this would return 42 to match up those two.
  355. */
  356. function mime_match_parenthesis ($pos, $structure) {
  357. $j = strlen( $structure );
  358. // ignore all extra characters
  359. // If inside of a string, skip string -- Boundary IDs and other
  360. // things can have ) in them.
  361. if ( $structure{$pos} != '(' ) {
  362. return( $j );
  363. }
  364. while ( $pos < $j ) {
  365. $pos++;
  366. if ($structure{$pos} == ')') {
  367. return $pos;
  368. } elseif ($structure{$pos} == '"') {
  369. $pos++;
  370. while ( $structure{$pos} != '"' &&
  371. $pos < $j ) {
  372. if (substr($structure, $pos, 2) == '\\"') {
  373. $pos++;
  374. } elseif (substr($structure, $pos, 2) == '\\\\') {
  375. $pos++;
  376. }
  377. $pos++;
  378. }
  379. } elseif ( $structure{$pos} == '(' ) {
  380. $pos = mime_match_parenthesis ($pos, $structure);
  381. }
  382. }
  383. echo _("Error decoding mime structure. Report this as a bug!") . '<br>';
  384. return( $pos );
  385. }
  386. function mime_fetch_body($imap_stream, $id, $ent_id ) {
  387. /*
  388. * do a bit of error correction. If we couldn't find the entity id, just guess
  389. * that it is the first one. That is usually the case anyway.
  390. */
  391. if (!$ent_id) {
  392. $ent_id = 1;
  393. }
  394. $cmd = "FETCH $id BODY[$ent_id]";
  395. $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message);
  396. do {
  397. $topline = trim(array_shift( $data ));
  398. } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
  399. $wholemessage = implode('', $data);
  400. if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
  401. $ret = substr( $wholemessage, 0, $regs[1] );
  402. /*
  403. There is some information in the content info header that could be important
  404. in order to parse html messages. Let's get them here.
  405. */
  406. if ( $ret{0} == '<' ) {
  407. $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message);
  408. /* BASE within HTML documents is illegal (see w3 spec)
  409. * $base = '';
  410. * $k = 10;
  411. * foreach( $data as $d ) {
  412. * if ( substr( $d, 0, 13 ) == 'Content-Base:' ) {
  413. * $j = strlen( $d );
  414. * $i = 13;
  415. * $base = '';
  416. * while ( $i < $j &&
  417. * ( !isNoSep( $d{$i} ) || $d{$i} == '"' ) )
  418. * $i++;
  419. * while ( $i < $j ) {
  420. * if ( isNoSep( $d{$i} ) )
  421. * $base .= $d{$i};
  422. * $i++;
  423. * }
  424. * $k = 0;
  425. * } elseif ( $k == 1 && !isnosep( $d{0} ) ) {
  426. * $base .= substr( $d, 1 );
  427. * }
  428. * $k++;
  429. * }
  430. * if ( $base <> '' ) {
  431. * $ret = "<base href=\"$base\">" . $ret;
  432. * }
  433. * */
  434. }
  435. } else if (ereg('"([^"]*)"', $topline, $regs)) {
  436. $ret = $regs[1];
  437. } else {
  438. global $where, $what, $mailbox, $passed_id, $startMessage;
  439. $par = 'mailbox=' . urlencode($mailbox) . "&amp;passed_id=$passed_id";
  440. if (isset($where) && isset($what)) {
  441. $par .= '&amp;where='. urlencode($where) . "&amp;what=" . urlencode($what);
  442. } else {
  443. $par .= "&amp;startMessage=$startMessage&amp;show_more=0";
  444. }
  445. $par .= '&amp;response=' . urlencode($response) .
  446. '&amp;message=' . urlencode($message).
  447. '&amp;topline=' . urlencode($topline);
  448. echo '<tt><br>' .
  449. '<table width="80%"><tr>' .
  450. '<tr><td colspan=2>' .
  451. _("Body retrieval error. The reason for this is most probably that the message is malformed. Please help us making future versions better by submitting this message to the developers knowledgebase!") .
  452. " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
  453. _("Submit message") . '</A><BR>&nbsp;' .
  454. '</td></tr>' .
  455. '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
  456. '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
  457. '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
  458. '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
  459. "</table><BR></tt></font><hr>";
  460. $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message);
  461. array_shift($data);
  462. $wholemessage = implode('', $data);
  463. $ret = $wholemessage;
  464. }
  465. return( $ret );
  466. }
  467. function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
  468. // do a bit of error correction. If we couldn't find the entity id, just guess
  469. // that it is the first one. That is usually the case anyway.
  470. if (!$ent_id) {
  471. $ent_id = 1;
  472. }
  473. $sid = sqimap_session_id();
  474. // Don't kill the connection if the browser is over a dialup
  475. // and it would take over 30 seconds to download it.
  476. // don´t call set_time_limit in safe mode.
  477. if (!ini_get("safe_mode")) {
  478. set_time_limit(0);
  479. }
  480. fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
  481. $cnt = 0;
  482. $continue = true;
  483. $read = fgets ($imap_stream,4096);
  484. // This could be bad -- if the section has sqimap_session_id() . ' OK'
  485. // or similar, it will kill the download.
  486. while (!ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
  487. if (trim($read) == ')==') {
  488. $read1 = $read;
  489. $read = fgets ($imap_stream,4096);
  490. if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
  491. return;
  492. } else {
  493. echo decodeBody($read1, $encoding) .
  494. decodeBody($read, $encoding);
  495. }
  496. } else if ($cnt) {
  497. echo decodeBody($read, $encoding);
  498. }
  499. $read = fgets ($imap_stream,4096);
  500. $cnt++;
  501. }
  502. }
  503. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  504. /* This is the first function called. It decides if this is a multipart
  505. message or if it should be handled as a single entity
  506. */
  507. function decodeMime ($imap_stream, &$header) {
  508. global $username, $key, $imapServerAddress, $imapPort;
  509. return mime_structure ($imap_stream, $header);
  510. }
  511. // This is here for debugging purposese. It will print out a list
  512. // of all the entity IDs that are in the $message object.
  513. function listEntities ($message) {
  514. if ($message) {
  515. if ($message->header->entity_id)
  516. echo "<tt>" . $message->header->entity_id . ' : ' . $message->header->type0 . '/' . $message->header->type1 . '<br>';
  517. for ($i = 0; $message->entities[$i]; $i++) {
  518. $msg = listEntities($message->entities[$i], $ent_id);
  519. if ($msg)
  520. return $msg;
  521. }
  522. }
  523. }
  524. /* returns a $message object for a particular entity id */
  525. function getEntity ($message, $ent_id) {
  526. if ($message) {
  527. if ($message->header->entity_id == $ent_id && strlen($ent_id) == strlen($message->header->entity_id))
  528. {
  529. return $message;
  530. } else {
  531. for ($i = 0; isset($message->entities[$i]); $i++) {
  532. $msg = getEntity ($message->entities[$i], $ent_id);
  533. if ($msg) {
  534. return $msg;
  535. }
  536. }
  537. }
  538. }
  539. }
  540. /*
  541. * figures out what entity to display and returns the $message object
  542. * for that entity.
  543. */
  544. function findDisplayEntity ($msg, $textOnly = 1) {
  545. global $show_html_default;
  546. $entity = 0;
  547. if ($msg) {
  548. if ( $msg->header->type0 == 'multipart' &&
  549. ( $msg->header->type1 == 'alternative' ||
  550. $msg->header->type1 == 'mixed' ||
  551. $msg->header->type1 == 'related' ) &&
  552. $show_html_default && ! $textOnly ) {
  553. $entity = findDisplayEntityHTML($msg);
  554. }
  555. // Show text/plain or text/html -- the first one we find.
  556. if ( $entity == 0 &&
  557. $msg->header->type0 == 'text' &&
  558. ( $msg->header->type1 == 'plain' ||
  559. $msg->header->type1 == 'html' ) &&
  560. isset($msg->header->entity_id) ) {
  561. $entity = $msg->header->entity_id;
  562. }
  563. $i = 0;
  564. while ($entity == 0 && isset($msg->entities[$i]) ) {
  565. $entity = findDisplayEntity($msg->entities[$i], $textOnly);
  566. $i++;
  567. }
  568. }
  569. return( $entity );
  570. }
  571. /* Shows the HTML version */
  572. function findDisplayEntityHTML ($message) {
  573. if ( $message->header->type0 == 'text' &&
  574. $message->header->type1 == 'html' &&
  575. isset($message->header->entity_id)) {
  576. return $message->header->entity_id;
  577. }
  578. for ($i = 0; isset($message->entities[$i]); $i ++) {
  579. if ( $message->header->type0 == 'message' &&
  580. $message->header->type1 == 'rfc822' &&
  581. isset($message->header->entity_id)) {
  582. return 0;
  583. }
  584. $entity = findDisplayEntityHTML($message->entities[$i]);
  585. if ($entity != 0) {
  586. return $entity;
  587. }
  588. }
  589. return 0;
  590. }
  591. /*
  592. * translateText
  593. * Extracted from strings.php 23/03/2002
  594. */
  595. function translateText(&$body, $wrap_at, $charset) {
  596. global $where, $what; /* from searching */
  597. global $color; /* color theme */
  598. require_once('../functions/url_parser.php');
  599. $body_ary = explode("\n", $body);
  600. $PriorQuotes = 0;
  601. for ($i=0; $i < count($body_ary); $i++) {
  602. $line = $body_ary[$i];
  603. if (strlen($line) - 2 >= $wrap_at) {
  604. sqWordWrap($line, $wrap_at);
  605. }
  606. $line = charset_decode($charset, $line);
  607. $line = str_replace("\t", ' ', $line);
  608. parseUrl ($line);
  609. $Quotes = 0;
  610. $pos = 0;
  611. $j = strlen( $line );
  612. while ( $pos < $j ) {
  613. if ($line[$pos] == ' ') {
  614. $pos ++;
  615. } else if (strpos($line, '&gt;', $pos) === $pos) {
  616. $pos += 4;
  617. $Quotes ++;
  618. } else {
  619. break;
  620. }
  621. }
  622. if ($Quotes > 1) {
  623. if (! isset($color[14])) {
  624. $color[14] = '#FF0000';
  625. }
  626. $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
  627. } elseif ($Quotes) {
  628. if (! isset($color[13])) {
  629. $color[13] = '#800000';
  630. }
  631. $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
  632. }
  633. $body_ary[$i] = $line;
  634. }
  635. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  636. }
  637. /* debugfunction for looping through entities and displaying correct entities */
  638. function listMyEntities ($message) {
  639. if ($message) {
  640. if ($message->header->entity_id) {
  641. echo "<tt>" . $message->header->entity_id . ' : ' . $message->header->type0 . '/' . $message->header->type1 . '<br>';
  642. }
  643. if (!($message->header->type0 == 'message' && $message->header->type1 == 'rfc822')) {
  644. if (isset($message->header->boundary) ) {
  645. $ent_id = $message->header->entity_id;
  646. $var = $message->header->boundary;
  647. if ($var !='')
  648. echo "<b>$ent_id boundary = $var</b><br>";
  649. }
  650. if (isset($message->header->type) ) {
  651. $var = $message->header->type;
  652. if ($var !='')
  653. echo "<b>$ent_id type = $var</b><br>";
  654. }
  655. for ($i = 0; $message->entities[$i]; $i++) {
  656. $msg = listMyEntities($message->entities[$i]);
  657. }
  658. if ($msg ) return $msg;
  659. }
  660. }
  661. }
  662. /* This returns a parsed string called $body. That string can then
  663. be displayed as the actual message in the HTML. It contains
  664. everything needed, including HTML Tags, Attachments at the
  665. bottom, etc.
  666. */
  667. function formatBody($imap_stream, $message, $color, $wrap_at) {
  668. // this if statement checks for the entity to show as the
  669. // primary message. To add more of them, just put them in the
  670. // order that is their priority.
  671. global $startMessage, $username, $key, $imapServerAddress, $imapPort, $body,
  672. $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
  673. $has_unsafe_images = 0;
  674. $id = $message->header->id;
  675. $urlmailbox = urlencode($message->header->mailbox);
  676. // Get the right entity and redefine message to be this entity
  677. // Pass the 0 to mean that we want the 'best' viewable one
  678. $ent_num = findDisplayEntity ($message, 0);
  679. $body_message = getEntity($message, $ent_num);
  680. if (($body_message->header->type0 == 'text') ||
  681. ($body_message->header->type0 == 'rfc822')) {
  682. $body = mime_fetch_body ($imap_stream, $id, $ent_num);
  683. $body = decodeBody($body, $body_message->header->encoding);
  684. $hookResults = do_hook("message_body", $body);
  685. $body = $hookResults[1];
  686. // If there are other types that shouldn't be formatted, add
  687. // them here
  688. if ($body_message->header->type1 == 'html') {
  689. if ( $show_html_default <> 1 ) {
  690. $body = strip_tags( $body );
  691. translateText($body, $wrap_at, $body_message->header->charset);
  692. } else {
  693. $body = MagicHTML( $body, $id );
  694. }
  695. } else {
  696. translateText($body, $wrap_at, $body_message->header->charset);
  697. }
  698. $body .= "<CENTER><SMALL><A HREF=\"../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;passed_ent_id=$ent_num&amp;mailbox=$urlmailbox&amp;showHeaders=1\">". _("Download this as a file") ."</A></SMALL></CENTER><BR>";
  699. if ($has_unsafe_images) {
  700. if ($view_unsafe_images) {
  701. $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0\">". _("Hide Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
  702. } else {
  703. $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0&amp;view_unsafe_images=1\">". _("View Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
  704. }
  705. }
  706. /** Display the ATTACHMENTS: message if there's more than one part **/
  707. if (isset($message->entities[1])) {
  708. $body .= formatAttachments ($message, $ent_num, $message->header->mailbox, $id);
  709. }
  710. } else {
  711. $body = formatAttachments ($message, -1, $message->header->mailbox, $id);
  712. }
  713. return ($body);
  714. }
  715. /*
  716. * A recursive function that returns a list of attachments with links
  717. * to where to download these attachments
  718. */
  719. function formatAttachments($message, $ent_id, $mailbox, $id) {
  720. global $where, $what;
  721. global $startMessage, $color;
  722. static $ShownHTML = 0;
  723. $body = '';
  724. if ($ShownHTML == 0) {
  725. $ShownHTML = 1;
  726. $body .= "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
  727. "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
  728. _("Attachments") . ':' .
  729. "</B></TH></TR><TR><TD>\n" .
  730. "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n" .
  731. formatAttachments($message, $ent_id, $mailbox, $id) .
  732. "</TABLE></TD></TR></TABLE>";
  733. } else if ($message) {
  734. $header = $message->header;
  735. $type0 = strtolower($header->type0);
  736. $type1 = strtolower($header->type1);
  737. $name = '';
  738. if (isset($header->name)) {
  739. $name = decodeHeader($header->name);
  740. }
  741. if ($type0 =='message' && $type1 == 'rfc822') {
  742. $filename = decodeHeader($message->header->filename);
  743. if (trim($filename) == '') {
  744. if (trim($name) == '') {
  745. $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
  746. } else {
  747. $display_filename = $name;
  748. $filename = $name;
  749. }
  750. } else {
  751. $display_filename = $filename;
  752. }
  753. $urlMailbox = urlencode($mailbox);
  754. $ent = urlencode($message->header->entity_id);
  755. $DefaultLink =
  756. "../src/download.php?startMessage=$startMessage&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
  757. if ($where && $what) {
  758. $DefaultLink .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
  759. }
  760. $Links['download link']['text'] = _("download");
  761. $Links['download link']['href'] =
  762. "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
  763. $ImageURL = '';
  764. /* this executes the attachment hook with a specific MIME-type.
  765. * if that doens't have results, it tries if there's a rule
  766. * for a more generic type. */
  767. $HookResults = do_hook("attachment $type0/$type1", $Links,
  768. $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
  769. if(count($HookResults[1]) <= 1) {
  770. $HookResults = do_hook("attachment $type0/*", $Links,
  771. $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
  772. $display_filename, $where, $what);
  773. }
  774. $Links = $HookResults[1];
  775. $DefaultLink = $HookResults[6];
  776. $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
  777. "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
  778. '<TD><SMALL><b>' . show_readable_size($message->header->size) .
  779. '</b>&nbsp;&nbsp;</small></TD>' .
  780. "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
  781. '<TD><SMALL>';
  782. if ($message->header->description) {
  783. $body .= '<b>' . htmlspecialchars(_($message->header->description)) . '</b>';
  784. }
  785. $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
  786. $SkipSpaces = 1;
  787. foreach ($Links as $Val) {
  788. if ($SkipSpaces) {
  789. $SkipSpaces = 0;
  790. } else {
  791. $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  792. }
  793. $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
  794. }
  795. unset($Links);
  796. $body .= "</SMALL></TD></TR>\n";
  797. return( $body );
  798. } elseif (!$message->entities) {
  799. $type0 = strtolower($message->header->type0);
  800. $type1 = strtolower($message->header->type1);
  801. $name = decodeHeader($message->header->name);
  802. if ($message->header->entity_id != $ent_id) {
  803. $filename = decodeHeader($message->header->filename);
  804. if (trim($filename) == '') {
  805. if (trim($name) == '') {
  806. if ( trim( $message->header->id ) == '' )
  807. $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
  808. else
  809. $display_filename = 'cid: ' . $message->header->id;
  810. // $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
  811. } else {
  812. $display_filename = $name;
  813. $filename = $name;
  814. }
  815. } else {
  816. $display_filename = $filename;
  817. }
  818. $urlMailbox = urlencode($mailbox);
  819. $ent = urlencode($message->header->entity_id);
  820. $DefaultLink =
  821. "../src/download.php?startMessage=$startMessage&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
  822. if ($where && $what) {
  823. $DefaultLink = '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
  824. }
  825. $Links['download link']['text'] = _("download");
  826. $Links['download link']['href'] =
  827. "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
  828. $ImageURL = '';
  829. /* this executes the attachment hook with a specific MIME-type.
  830. * if that doens't have results, it tries if there's a rule
  831. * for a more generic type. */
  832. $HookResults = do_hook("attachment $type0/$type1", $Links,
  833. $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
  834. $display_filename, $where, $what);
  835. if(count($HookResults[1]) <= 1) {
  836. $HookResults = do_hook("attachment $type0/*", $Links,
  837. $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
  838. $display_filename, $where, $what);
  839. }
  840. $Links = $HookResults[1];
  841. $DefaultLink = $HookResults[6];
  842. $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
  843. "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
  844. '<TD><SMALL><b>' . show_readable_size($message->header->size) .
  845. '</b>&nbsp;&nbsp;</small></TD>' .
  846. "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
  847. '<TD><SMALL>';
  848. if ($message->header->description) {
  849. $body .= '<b>' . htmlspecialchars(_($message->header->description)) . '</b>';
  850. }
  851. $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
  852. $SkipSpaces = 1;
  853. foreach ($Links as $Val) {
  854. if ($SkipSpaces) {
  855. $SkipSpaces = 0;
  856. } else {
  857. $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  858. }
  859. $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
  860. }
  861. unset($Links);
  862. $body .= "</SMALL></TD></TR>\n";
  863. }
  864. } else {
  865. for ($i = 0; $i < count($message->entities); $i++) {
  866. $body .= formatAttachments($message->entities[$i], $ent_id, $mailbox, $id);
  867. }
  868. }
  869. }
  870. return( $body );
  871. }
  872. /** this function decodes the body depending on the encoding type. **/
  873. function decodeBody($body, $encoding) {
  874. $body = str_replace("\r\n", "\n", $body);
  875. $encoding = strtolower($encoding);
  876. global $show_html_default;
  877. if ($encoding == 'quoted-printable') {
  878. $body = quoted_printable_decode($body);
  879. while (ereg("=\n", $body))
  880. $body = ereg_replace ("=\n", "", $body);
  881. } else if ($encoding == 'base64') {
  882. $body = base64_decode($body);
  883. }
  884. // All other encodings are returned raw.
  885. return $body;
  886. }
  887. /*
  888. * This functions decode strings that is encoded according to
  889. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  890. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  891. */
  892. function decodeHeader ($string, $utfencode=true) {
  893. if (is_array($string)) {
  894. $string = implode("\n", $string);
  895. }
  896. $i = 0;
  897. while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
  898. $string, $res)) {
  899. $prefix = $res[1];
  900. // Ignore white-space between consecutive encoded-words
  901. if (strspn($res[2], " \t") != strlen($res[2])) {
  902. $prefix .= $res[2];
  903. }
  904. if (ucfirst($res[4]) == 'B') {
  905. $replace = base64_decode($res[5]);
  906. } else {
  907. $replace = str_replace('_', ' ', $res[5]);
  908. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  909. $replace);
  910. /* Only encode into entities by default. Some places
  911. don't need the encoding, like the compose form. */
  912. if ($utfencode) {
  913. $replace = charset_decode($res[3], $replace);
  914. }
  915. }
  916. $string = $prefix . $replace . substr($string, strlen($res[0]));
  917. $i = strlen($prefix) + strlen($replace);
  918. }
  919. return( $string );
  920. }
  921. /*
  922. * Encode a string according to RFC 1522 for use in headers if it
  923. * contains 8-bit characters or anything that looks like it should
  924. * be encoded.
  925. */
  926. function encodeHeader ($string) {
  927. global $default_charset;
  928. // Encode only if the string contains 8-bit characters or =?
  929. $j = strlen( $string );
  930. $l = strstr($string, '=?'); // Must be encoded ?
  931. $ret = '';
  932. for( $i=0; $i < $j; ++$i) {
  933. switch( $string{$i} ) {
  934. case '=':
  935. $ret .= '=3D';
  936. break;
  937. case '?':
  938. $ret .= '=3F';
  939. break;
  940. case '_':
  941. $ret .= '=5F';
  942. break;
  943. case ' ':
  944. $ret .= '_';
  945. break;
  946. default:
  947. $k = ord( $string{$i} );
  948. if ( $k > 126 ) {
  949. $ret .= sprintf("=%02X", $k);
  950. $l = TRUE;
  951. } else
  952. $ret .= $string{$i};
  953. }
  954. }
  955. if ( $l ) {
  956. $string = "=?$default_charset?Q?$ret?=";
  957. }
  958. return( $string );
  959. }
  960. /* This function trys to locate the entity_id of a specific mime element */
  961. function find_ent_id( $id, $message ) {
  962. $ret = '';
  963. for ($i=0; $ret == '' && $i < count($message->entities); $i++) {
  964. if (( $message->entities[$i]->header->type1 == 'alternative') ||
  965. ( $message->entities[$i]->header->type1 == 'related') ||
  966. ( $message->entities[$i]->header->type1 == 'mixed')) {
  967. $ret = find_ent_id( $id, $message->entities[$i] );
  968. } else {
  969. if ( strcasecmp( $message->entities[$i]->header->id, $id ) == 0 )
  970. $ret = $message->entities[$i]->header->entity_id;
  971. }
  972. }
  973. return( $ret );
  974. }
  975. /**
  976. ** HTMLFILTER ROUTINES
  977. */
  978. /**
  979. * This function returns the final tag out of the tag name, an array
  980. * of attributes, and the type of the tag. This function is called by
  981. * sq_sanitize internally.
  982. *
  983. * @param $tagname the name of the tag.
  984. * @param $attary the array of attributes and their values
  985. * @param $tagtype The type of the tag (see in comments).
  986. * @return a string with the final tag representation.
  987. */
  988. function sq_tagprint($tagname, $attary, $tagtype){
  989. $me = "sq_tagprint";
  990. if ($tagtype == 2){
  991. $fulltag = '</' . $tagname . '>';
  992. } else {
  993. $fulltag = '<' . $tagname;
  994. if (is_array($attary) && sizeof($attary)){
  995. $atts = Array();
  996. while (list($attname, $attvalue) = each($attary)){
  997. array_push($atts, "$attname=$attvalue");
  998. }
  999. $fulltag .= ' ' . join(" ", $atts);
  1000. }
  1001. if ($tagtype == 3){
  1002. $fulltag .= " /";
  1003. }
  1004. $fulltag .= ">";
  1005. }
  1006. return $fulltag;
  1007. }
  1008. /**
  1009. * A small helper function to use with array_walk. Modifies a by-ref
  1010. * value and makes it lowercase.
  1011. *
  1012. * @param $val a value passed by-ref.
  1013. * @return void since it modifies a by-ref value.
  1014. */
  1015. function sq_casenormalize(&$val){
  1016. $val = strtolower($val);
  1017. }
  1018. /**
  1019. * This function skips any whitespace from the current position within
  1020. * a string and to the next non-whitespace value.
  1021. *
  1022. * @param $body the string
  1023. * @param $offset the offset within the string where we should start
  1024. * looking for the next non-whitespace character.
  1025. * @return the location within the $body where the next
  1026. * non-whitespace char is located.
  1027. */
  1028. function sq_skipspace($body, $offset){
  1029. $me = "sq_skipspace";
  1030. preg_match("/^(\s*)/s", substr($body, $offset), $matches);
  1031. if (sizeof($matches{1})){
  1032. $count = strlen($matches{1});
  1033. $offset += $count;
  1034. }
  1035. return $offset;
  1036. }
  1037. /**
  1038. * This function looks for the next character within a string. It's
  1039. * really just a glorified "strpos", except it catches if failures
  1040. * nicely.
  1041. *
  1042. * @param $body The string to look for needle in.
  1043. * @param $offset Start looking from this position.
  1044. * @param $needle The character/string to look for.
  1045. * @return location of the next occurance of the needle, or
  1046. * strlen($body) if needle wasn't found.
  1047. */
  1048. function sq_findnxstr($body, $offset, $needle){
  1049. $me = "sq_findnxstr";
  1050. $pos = strpos($body, $needle, $offset);
  1051. if ($pos === FALSE){
  1052. $pos = strlen($body);
  1053. }
  1054. return $pos;
  1055. }
  1056. /**
  1057. * This function takes a PCRE-style regexp and tries to match it
  1058. * within the string.
  1059. *
  1060. * @param $body The string to look for needle in.
  1061. * @param $offset Start looking from here.
  1062. * @param $reg A PCRE-style regex to match.
  1063. * @return Returns a false if no matches found, or an array
  1064. * with the following members:
  1065. * - integer with the location of the match within $body
  1066. * - string with whatever content between offset and the match
  1067. * - string with whatever it is we matched
  1068. */
  1069. function sq_findnxreg($body, $offset, $reg){
  1070. $me = "sq_findnxreg";
  1071. $matches = Array();
  1072. $retarr = Array();
  1073. preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
  1074. if (!$matches{0}){
  1075. $retarr = false;
  1076. } else {
  1077. $retarr{0} = $offset + strlen($matches{1});
  1078. $retarr{1} = $matches{1};
  1079. $retarr{2} = $matches{2};
  1080. }
  1081. return $retarr;
  1082. }
  1083. /**
  1084. * This function looks for the next tag.
  1085. *
  1086. * @param $body String where to look for the next tag.
  1087. * @param $offset Start looking from here.
  1088. * @return false if no more tags exist in the body, or
  1089. * an array with the following members:
  1090. * - string with the name of the tag
  1091. * - array with attributes and their values
  1092. * - integer with tag type (1, 2, or 3)
  1093. * - integer where the tag starts (starting "<")
  1094. * - integer where the tag ends (ending ">")
  1095. * first three members will be false, if the tag is invalid.
  1096. */
  1097. function sq_getnxtag($body, $offset){
  1098. $me = "sq_getnxtag";
  1099. if ($offset > strlen($body)){
  1100. return false;
  1101. }
  1102. $lt = sq_findnxstr($body, $offset, "<");
  1103. if ($lt == strlen($body)){
  1104. return false;
  1105. }
  1106. /**
  1107. * We are here:
  1108. * blah blah <tag attribute="value">
  1109. * \---------^
  1110. */
  1111. $pos = sq_skipspace($body, $lt+1);
  1112. if ($pos >= strlen($body)){
  1113. return Array(false, false, false, $lt, strlen($body));
  1114. }
  1115. /**
  1116. * There are 3 kinds of tags:
  1117. * 1. Opening tag, e.g.:
  1118. * <a href="blah">
  1119. * 2. Closing tag, e.g.:
  1120. * </a>
  1121. * 3. XHTML-style content-less tag, e.g.:
  1122. * <img src="blah"/>
  1123. */
  1124. $tagtype = false;
  1125. switch (substr($body, $pos, 1)){
  1126. case "/":
  1127. $tagtype = 2;
  1128. $pos++;
  1129. break;
  1130. case "!":
  1131. /**
  1132. * A comment or an SGML declaration.
  1133. */
  1134. if (substr($body, $pos+1, 2) == "--"){
  1135. $gt = strpos($body, "-->", $pos)+2;
  1136. if ($gt === false){
  1137. $gt = strlen($body);
  1138. }
  1139. return Array(false, false, false, $lt, $gt);
  1140. } else {
  1141. $gt = sq_findnxstr($body, $pos, ">");
  1142. return Array(false, false, false, $lt, $gt);
  1143. }
  1144. break;
  1145. default:
  1146. /**
  1147. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  1148. * later.
  1149. */
  1150. $tagtype = 1;
  1151. break;
  1152. }
  1153. $tag_start = $pos;
  1154. $tagname = '';
  1155. /**
  1156. * Look for next [\W-_], which will indicate the end of the tag name.
  1157. */
  1158. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  1159. if ($regary == false){
  1160. return Array(false, false, false, $lt, strlen($body));
  1161. }
  1162. list($pos, $tagname, $match) = $regary;
  1163. $tagname = strtolower($tagname);
  1164. /**
  1165. * $match can be either of these:
  1166. * '>' indicating the end of the tag entirely.
  1167. * '\s' indicating the end of the tag name.
  1168. * '/' indicating that this is type-3 xhtml tag.
  1169. *
  1170. * Whatever else we find there indicates an invalid tag.
  1171. */
  1172. switch ($match){
  1173. case "/":
  1174. /**
  1175. * This is an xhtml-style tag with a closing / at the
  1176. * end, like so: <img src="blah"/>. Check if it's followed
  1177. * by the closing bracket. If not, then this tag is invalid
  1178. */
  1179. if (substr($body, $pos, 2) == "/>"){
  1180. $pos++;
  1181. $tagtype = 3;
  1182. } else {
  1183. $gt = sq_findnxstr($body, $pos, ">");
  1184. $retary = Array(false, false, false, $lt, $gt);
  1185. return $retary;
  1186. }
  1187. case ">":
  1188. return Array($tagname, false, $tagtype, $lt, $pos);
  1189. break;
  1190. default:
  1191. /**
  1192. * Check if it's whitespace
  1193. */
  1194. if (preg_match("/\s/", $match)){
  1195. } else {
  1196. /**
  1197. * This is an invalid tag! Look for the next closing ">".
  1198. */
  1199. $gt = sq_findnxstr($body, $offset, ">");
  1200. return Array(false, false, false, $lt, $gt);
  1201. }
  1202. }
  1203. /**
  1204. * At this point we're here:
  1205. * <tagname attribute='blah'>
  1206. * \-------^
  1207. *
  1208. * At this point we loop in order to find all attributes.
  1209. */
  1210. $attname = '';
  1211. $atttype = false;
  1212. $attary = Array();
  1213. while ($pos <= strlen($body)){
  1214. $pos = sq_skipspace($body, $pos);
  1215. if ($pos == strlen($body)){
  1216. /**
  1217. * Non-closed tag.
  1218. */
  1219. return Array(false, false, false, $lt, $pos);
  1220. }
  1221. /**
  1222. * See if we arrived at a ">" or "/>", which means that we reached
  1223. * the end of the tag.
  1224. */
  1225. $matches = Array();
  1226. if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
  1227. /**
  1228. * Yep. So we did.
  1229. */
  1230. $pos += strlen($matches{1});
  1231. if ($matches{2} == "/>"){
  1232. $tagtype = 3;
  1233. $pos++;
  1234. }
  1235. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1236. }
  1237. /**
  1238. * There are several types of attributes, with optional
  1239. * [:space:] between members.
  1240. * Type 1:
  1241. * attrname[:space:]=[:space:]'CDATA'
  1242. * Type 2:
  1243. * attrname[:space:]=[:space:]"CDATA"
  1244. * Type 3:
  1245. * attr[:space:]=[:space:]CDATA
  1246. * Type 4:
  1247. * attrname
  1248. *
  1249. * We leave types 1 and 2 the same, type 3 we check for
  1250. * '"' and convert to "&quot" if needed, then wrap in
  1251. * double quotes. Type 4 we convert into:
  1252. * attrname="yes".
  1253. */
  1254. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  1255. if ($regary == false){
  1256. /**
  1257. * Looks like body ended before the end of tag.
  1258. */
  1259. return Array(false, false, false, $lt, strlen($body));
  1260. }
  1261. list($pos, $attname, $match) = $regary;
  1262. $attname = strtolower($attname);
  1263. /**
  1264. * We arrived at the end of attribute name. Several things possible
  1265. * here:
  1266. * '>' means the end of the tag and this is attribute type 4
  1267. * '/' if followed by '>' means the same thing as above
  1268. * '\s' means a lot of things -- look what it's followed by.
  1269. * anything else means the attribute is invalid.
  1270. */
  1271. switch($match){
  1272. case "/":
  1273. /**
  1274. * This is an xhtml-style tag with a closing / at the
  1275. * end, like so: <img src="blah"/>. Check if it's followed
  1276. * by the closing bracket. If not, then this tag is invalid
  1277. */
  1278. if (substr($body, $pos, 2) == "/>"){
  1279. $pos++;
  1280. $tagtype = 3;
  1281. } else {
  1282. $gt = sq_findnxstr($body, $pos, ">");
  1283. $retary = Array(false, false, false, $lt, $gt);
  1284. return $retary;
  1285. }
  1286. case ">":
  1287. $attary{$attname} = '"yes"';
  1288. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1289. break;
  1290. default:
  1291. /**
  1292. * Skip whitespace and see what we arrive at.
  1293. */
  1294. $pos = sq_skipspace($body, $pos);
  1295. $char = substr($body, $pos, 1);
  1296. /**
  1297. * Two things are valid here:
  1298. * '=' means this is attribute type 1 2 or 3.
  1299. * \w means this was attribute type 4.
  1300. * anything else we ignore and re-loop. End of tag and
  1301. * invalid stuff will be caught by our checks at the beginning
  1302. * of the loop.
  1303. */
  1304. if ($char == "="){
  1305. $pos++;
  1306. $pos = sq_skipspace($body, $pos);
  1307. /**
  1308. * Here are 3 possibilities:
  1309. * "'" attribute type 1
  1310. * '"' attribute type 2
  1311. * everything else is the content of tag type 3
  1312. */
  1313. $quot = substr($body, $pos, 1);
  1314. if ($quot == "'"){
  1315. $regary = sq_findnxreg($body, $pos+1, "\'");
  1316. if ($regary == false){
  1317. return Array(false, false, false, $lt, strlen($body));
  1318. }
  1319. list($pos, $attval, $match) = $regary;
  1320. $pos++;
  1321. $attary{$attname} = "'" . $attval . "'";
  1322. } else if ($quot == '"'){
  1323. $regary = sq_findnxreg($body, $pos+1, '\"');
  1324. if ($regary == false){
  1325. return Array(false, false, false, $lt, strlen($body));
  1326. }
  1327. list($pos, $attval, $match) = $regary;
  1328. $pos++;
  1329. $attary{$attname} = '"' . $attval . '"';
  1330. } else {
  1331. /**
  1332. * These are hateful. Look for \s, or >.
  1333. */
  1334. $regary = sq_findnxreg($body, $pos, "[\s>]");
  1335. if ($regary == false){
  1336. return Array(false, false, false, $lt, strlen($body));
  1337. }
  1338. list($pos, $attval, $match) = $regary;
  1339. /**
  1340. * If it's ">" it will be caught at the top.
  1341. */
  1342. $attval = preg_replace("/\"/s", "&quot;", $attval);
  1343. $attary{$attname} = '"' . $attval . '"';
  1344. }
  1345. } else if (preg_match("|[\w/>]|", $char)) {
  1346. /**
  1347. * That was attribute type 4.
  1348. */
  1349. $attary{$attname} = '"yes"';
  1350. } else {
  1351. /**
  1352. * An illegal character. Find next '>' and return.
  1353. */
  1354. $gt = sq_findnxstr($body, $pos, ">");
  1355. return Array(false, false, false, $lt, $gt);
  1356. }
  1357. }
  1358. }
  1359. /**
  1360. * The fact that we got here indicates that the tag end was never
  1361. * found. Return invalid tag indication so it gets stripped.
  1362. */
  1363. return Array(false, false, false, $lt, strlen($body));
  1364. }
  1365. /**
  1366. * This function checks attribute values for entity-encoded values
  1367. * and returns them translated into 8-bit strings so we can run
  1368. * checks on them.
  1369. *
  1370. * @param $attvalue A string to run entity check against.
  1371. * @return Translated value.
  1372. */
  1373. function sq_deent($attvalue){
  1374. $me="sq_deent";
  1375. /**
  1376. * See if we have to run the checks first. All entities must start
  1377. * with "&".
  1378. */
  1379. if (strpos($attvalue, "&") === false){
  1380. return $attvalue;
  1381. }
  1382. /**
  1383. * Check named entities first.
  1384. */
  1385. $trans = get_html_translation_table(HTML_ENTITIES);
  1386. /**
  1387. * Leave &quot; in, as it can mess us up.
  1388. */
  1389. $trans = array_flip($trans);
  1390. unset($trans{"&quot;"});
  1391. while (list($ent, $val) = each($trans)){
  1392. $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
  1393. }
  1394. /**
  1395. * Now translate numbered entities from 1 to 255 if needed.
  1396. */
  1397. if (strpos($attvalue, "#") !== false){
  1398. $omit = Array(34, 39);
  1399. for ($asc=1; $asc<256; $asc++){
  1400. if (!in_array($asc, $omit)){
  1401. $chr = chr($asc);
  1402. $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
  1403. $attvalue);
  1404. $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
  1405. "$chr\\1", $attvalue);
  1406. }
  1407. }
  1408. }
  1409. return $attvalue;
  1410. }
  1411. /**
  1412. * This function runs various checks against the attributes.
  1413. *
  1414. * @param $tagname String with the name of the tag.
  1415. * @param $attary Array with all tag attributes.
  1416. * @param $rm_attnames See description for sq_sanitize
  1417. * @param $bad_attvals See description for sq_sanitize
  1418. * @param $add_attr_to_tag See description for sq_sanitize
  1419. * @param $message message object
  1420. * @param $id message id
  1421. * @return Array with modified attributes.
  1422. */
  1423. function sq_fixatts($tagname,
  1424. $attary,
  1425. $rm_attnames,
  1426. $bad_attvals,
  1427. $add_attr_to_tag,
  1428. $message,
  1429. $id
  1430. ){
  1431. $me = "sq_fixatts";
  1432. while (list($attname, $attvalue) = each($attary)){
  1433. /**
  1434. * See if this attribute should be removed.
  1435. */
  1436. foreach ($rm_attnames as $matchtag=>$matchattrs){
  1437. if (preg_match($matchtag, $tagname)){
  1438. foreach ($matchattrs as $matchattr){
  1439. if (preg_match($matchattr, $attname)){
  1440. unset($attary{$attname});
  1441. continue;
  1442. }
  1443. }
  1444. }
  1445. }
  1446. /**
  1447. * Remove any entities.
  1448. */
  1449. $attvalue = sq_deent($attvalue);
  1450. /**
  1451. * Now let's run checks on the attvalues.
  1452. * I don't expect anyone to comprehend this. If you do,
  1453. * get in touch with me so I can drive to where you live and
  1454. * shake your hand personally. :)
  1455. */
  1456. foreach ($bad_attvals as $matchtag=>$matchattrs){
  1457. if (preg_match($matchtag, $tagname)){
  1458. foreach ($matchattrs as $matchattr=>$valary){
  1459. if (preg_match($matchattr, $attname)){
  1460. /**
  1461. * There are two arrays in valary.
  1462. * First is matches.
  1463. * Second one is replacements
  1464. */
  1465. list($valmatch, $valrepl) = $valary;
  1466. $newvalue =
  1467. preg_replace($valmatch, $valrepl, $attvalue);
  1468. if ($newvalue != $attvalue){
  1469. $attary{$attname} = $newvalue;
  1470. }
  1471. }
  1472. }
  1473. }
  1474. }
  1475. /**
  1476. * Turn cid: urls into http-friendly ones.
  1477. */
  1478. if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
  1479. $attary{$attname} = sq_cid2http($message, $id, $attvalue);
  1480. }
  1481. }
  1482. /**
  1483. * See if we need to append any attributes to this tag.
  1484. */
  1485. foreach ($add_attr_to_tag as $matchtag=>$addattary){
  1486. if (preg_match($matchtag, $tagname)){
  1487. $attary = array_merge($attary, $addattary);
  1488. }
  1489. }
  1490. return $attary;
  1491. }
  1492. /**
  1493. * This function edits the style definition to make them friendly and
  1494. * usable in squirrelmail.
  1495. *
  1496. * @param $message the message object
  1497. * @param $id the message id
  1498. * @param $content a string with whatever is between <style> and </style>
  1499. * @return a string with edited content.
  1500. */
  1501. function sq_fixstyle($message, $id, $content){
  1502. global $view_unsafe_images;
  1503. $me = "sq_fixstyle";
  1504. /**
  1505. * First look for general BODY style declaration, which would be
  1506. * like so:
  1507. * body {background: blah-blah}
  1508. * and change it to .bodyclass so we can just assign it to a <div>
  1509. */
  1510. $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
  1511. $secremoveimg = "../images/" . _("sec_remove_eng.png");
  1512. /**
  1513. * Fix url('blah') declarations.
  1514. */
  1515. $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
  1516. "url(\\1$secremoveimg\\2)", $content);
  1517. /**
  1518. * Fix url('https*://.*) declarations but only if $view_unsafe_images
  1519. * is false.
  1520. */
  1521. if (!$view_unsafe_images){
  1522. $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
  1523. "url(\\1$secremoveimg\\2)", $content);
  1524. }
  1525. /**
  1526. * Fix urls that refer to cid:
  1527. */
  1528. while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
  1529. $matches)){
  1530. $cidurl = $matches{1};
  1531. $httpurl = sq_cid2http($message, $id, $cidurl);
  1532. $content = preg_replace("|url\($cidurl\)|si",
  1533. "url($httpurl)", $content);
  1534. }
  1535. /**
  1536. * Fix stupid expression: declarations which lead to vulnerabilities
  1537. * in IE.
  1538. */
  1539. $content = preg_replace("/expression\s*:/si", "idiocy:", $content);
  1540. return $content;
  1541. }
  1542. /**
  1543. * This function converts cid: url's into the ones that can be viewed in
  1544. * the browser.
  1545. *
  1546. * @param $message the message object
  1547. * @param $id the message id
  1548. * @param $cidurl the cid: url.
  1549. * @return a string with a http-friendly url
  1550. */
  1551. function sq_cid2http($message, $id, $cidurl){
  1552. /**
  1553. * Get rid of quotes.
  1554. */
  1555. $quotchar = substr($cidurl, 0, 1);
  1556. $cidurl = str_replace($quotchar, "", $cidurl);
  1557. $cidurl = substr(trim($cidurl), 4);
  1558. $httpurl = $quotchar . "../src/download.php?absolute_dl=true&amp;" .
  1559. "passed_id=$id&amp;mailbox=" . urlencode($message->header->mailbox) .
  1560. "&amp;passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
  1561. return $httpurl;
  1562. }
  1563. /**
  1564. * This function changes the <body> tag into a <div> tag since we
  1565. * can't really have a body-within-body.
  1566. *
  1567. * @param $attary an array of attributes and values of <body>
  1568. * @return a modified array of attributes to be set for <div>
  1569. */
  1570. function sq_body2div($attary){
  1571. $me = "sq_body2div";
  1572. $divattary = Array("class"=>"'bodyclass'");
  1573. $bgcolor="#ffffff";
  1574. $text="#000000";
  1575. $styledef="";
  1576. if (is_array($attary) && sizeof($attary) > 0){
  1577. foreach ($attary as $attname=>$attvalue){
  1578. $quotchar = substr($attvalue, 0, 1);
  1579. $attvalue = str_replace($quotchar, "", $attvalue);
  1580. switch ($attname){
  1581. case "background":
  1582. $styledef .= "background-image: url('$attvalue'); ";
  1583. break;
  1584. case "bgcolor":
  1585. $styledef .= "background-color: $attvalue; ";
  1586. break;
  1587. case "text":
  1588. $styledef .= "color: $attvalue; ";
  1589. }
  1590. }
  1591. if (strlen($styledef) > 0){
  1592. $divattary{"style"} = "\"$styledef\"";
  1593. }
  1594. }
  1595. return $divattary;
  1596. }
  1597. /**
  1598. * This is the main function and the one you should actually be calling.
  1599. * There are several variables you should be aware of an which need
  1600. * special description.
  1601. *
  1602. * Since the description is quite lengthy, see it here:
  1603. * http://www.mricon.com/html/phpfilter.html
  1604. *
  1605. * @param $body the string with HTML you wish to filter
  1606. * @param $tag_list see description above
  1607. * @param $rm_tags_with_content see description above
  1608. * @param $self_closing_tags see description above
  1609. * @param $force_tag_closing see description above
  1610. * @param $rm_attnames see description above
  1611. * @param $bad_attvals see description above
  1612. * @param $add_attr_to_tag see description above
  1613. * @param $message message object
  1614. * @param $id message id
  1615. * @return sanitized html safe to show on your pages.
  1616. */
  1617. function sq_sanitize($body,
  1618. $tag_list,
  1619. $rm_tags_with_content,
  1620. $self_closing_tags,
  1621. $force_tag_closing,
  1622. $rm_attnames,
  1623. $bad_attvals,
  1624. $add_attr_to_tag,
  1625. $message,
  1626. $id
  1627. ){
  1628. $me = "sq_sanitize";
  1629. /**
  1630. * Normalize rm_tags and rm_tags_with_content.
  1631. */
  1632. @array_walk($rm_tags, 'sq_casenormalize');
  1633. @array_walk($rm_tags_with_content, 'sq_casenormalize');
  1634. @array_walk($self_closing_tags, 'sq_casenormalize');
  1635. /**
  1636. * See if tag_list is of tags to remove or tags to allow.
  1637. * false means remove these tags
  1638. * true means allow these tags
  1639. */
  1640. $rm_tags = array_shift($tag_list);
  1641. $curpos = 0;
  1642. $open_tags = Array();
  1643. $trusted = "<!-- begin sanitized html -->\n";
  1644. $skip_content = false;
  1645. while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
  1646. list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
  1647. $free_content = substr($body, $curpos, $lt-$curpos);
  1648. /**
  1649. * Take care of <style>
  1650. */
  1651. if ($tagname == "style" && $tagtype == 2){
  1652. /**
  1653. * This is a closing </style>. Edit the
  1654. * content before we apply it.
  1655. */
  1656. $free_content = sq_fixstyle($message, $id, $free_content);
  1657. }
  1658. if ($skip_content == false){
  1659. $trusted .= $free_content;
  1660. } else {
  1661. }
  1662. if ($tagname != FALSE){
  1663. if ($tagtype == 2){
  1664. if ($skip_content == $tagname){
  1665. /**
  1666. * Got to the end of tag we needed to remove.
  1667. */
  1668. $tagname = false;
  1669. $skip_content = false;
  1670. } else {
  1671. if ($skip_content == false){
  1672. if ($tagname == "body"){
  1673. $tagname = "div";
  1674. } else {
  1675. if (isset($open_tags{$tagname}) &&
  1676. $open_tags{$tagname} > 0){
  1677. $open_tags{$tagname}--;
  1678. } else {
  1679. $tagname = false;
  1680. }
  1681. }
  1682. } else {
  1683. }
  1684. }
  1685. } else {
  1686. /**
  1687. * $rm_tags_with_content
  1688. */
  1689. if ($skip_content == false){
  1690. /**
  1691. * See if this is a self-closing type and change
  1692. * tagtype appropriately.
  1693. */
  1694. if ($tagtype == 1
  1695. && in_array($tagname, $self_closing_tags)){
  1696. $tagtype=3;
  1697. }
  1698. /**
  1699. * See if we should skip this tag and any content
  1700. * inside it.
  1701. */
  1702. if ($tagtype == 1 &&
  1703. in_array($tagname, $rm_tags_with_content)){
  1704. $skip_content = $tagname;
  1705. } else {
  1706. if (($rm_tags == false
  1707. && in_array($tagname, $tag_list)) ||
  1708. ($rm_tags == true &&
  1709. !in_array($tagname, $tag_list))){
  1710. $tagname = false;
  1711. } else {
  1712. if ($tagtype == 1){
  1713. if (isset($open_tags{$tagname})){
  1714. $open_tags{$tagname}++;
  1715. } else {
  1716. $open_tags{$tagname}=1;
  1717. }
  1718. }
  1719. /**
  1720. * This is where we run other checks.
  1721. */
  1722. if (is_array($attary) && sizeof($attary) > 0){
  1723. $attary = sq_fixatts($tagname,
  1724. $attary,
  1725. $rm_attnames,
  1726. $bad_attvals,
  1727. $add_attr_to_tag,
  1728. $message,
  1729. $id
  1730. );
  1731. }
  1732. /**
  1733. * Convert body into div.
  1734. */
  1735. if ($tagname == "body"){
  1736. $tagname = "div";
  1737. $attary = sq_body2div($attary, $message, $id);
  1738. }
  1739. }
  1740. }
  1741. } else {
  1742. }
  1743. }
  1744. if ($tagname != false && $skip_content == false){
  1745. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1746. }
  1747. } else {
  1748. }
  1749. $curpos = $gt+1;
  1750. }
  1751. $trusted .= substr($body, $curpos, strlen($body)-$curpos);
  1752. if ($force_tag_closing == true){
  1753. foreach ($open_tags as $tagname=>$opentimes){
  1754. while ($opentimes > 0){
  1755. $trusted .= '</' . $tagname . '>';
  1756. $opentimes--;
  1757. }
  1758. }
  1759. $trusted .= "\n";
  1760. }
  1761. $trusted .= "<!-- end sanitized html -->\n";
  1762. return $trusted;
  1763. }
  1764. /**
  1765. * This is a wrapper function to call html sanitizing routines.
  1766. *
  1767. * @param $body the body of the message
  1768. * @param $id the id of the message
  1769. * @return a string with html safe to display in the browser.
  1770. */
  1771. function magicHTML($body, $id){
  1772. global $attachment_common_show_images, $view_unsafe_images,
  1773. $has_unsafe_images, $message;
  1774. /**
  1775. * Don't display attached images in HTML mode.
  1776. */
  1777. $attachment_common_show_images = false;
  1778. $tag_list = Array(
  1779. false,
  1780. "object",
  1781. "meta",
  1782. "html",
  1783. "head",
  1784. "base"
  1785. );
  1786. $rm_tags_with_content = Array(
  1787. "script",
  1788. "applet",
  1789. "embed",
  1790. "title"
  1791. );
  1792. $self_closing_tags = Array(
  1793. "img",
  1794. "br",
  1795. "hr",
  1796. "input"
  1797. );
  1798. $force_tag_closing = false;
  1799. $rm_attnames = Array(
  1800. "/.*/" =>
  1801. Array(
  1802. "/target/si",
  1803. "/^on.*/si"
  1804. )
  1805. );
  1806. $secremoveimg = "../images/" . _("sec_remove_eng.png");
  1807. $bad_attvals = Array(
  1808. "/.*/" =>
  1809. Array(
  1810. "/^src|background|href|action/i" =>
  1811. Array(
  1812. Array(
  1813. "|^([\'\"])\s*\.\./.*([\'\"])|si",
  1814. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si"
  1815. ),
  1816. Array(
  1817. "\\1$secremoveimg\\2",
  1818. "\\1$secremoveimg\\2"
  1819. )
  1820. ),
  1821. "/^style/si" =>
  1822. Array(
  1823. Array(
  1824. "/expression\s*:/si",
  1825. "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
  1826. "/url\(([\'\"])\s*\S+script:.*([\'\"])\)/si"
  1827. ),
  1828. Array(
  1829. "idiocy:",
  1830. "url(\\1$secremoveimg\\2)",
  1831. "url(\\1$secremoveimg\\2)"
  1832. )
  1833. )
  1834. )
  1835. );
  1836. if (!$view_unsafe_images){
  1837. /**
  1838. * Remove any references to http/https if view_unsafe_images set
  1839. * to false.
  1840. */
  1841. $addendum = Array(
  1842. "/.*/" =>
  1843. Array(
  1844. "/^src|background/i" =>
  1845. Array(
  1846. Array(
  1847. "/^([\'\"])\s*https*:.*([\'\"])/si"
  1848. ),
  1849. Array(
  1850. "\\1$secremoveimg\\2"
  1851. )
  1852. ),
  1853. "/^style/si" =>
  1854. Array(
  1855. Array(
  1856. "/url\(([\'\"])\s*https*:.*([\'\"])\)/si"
  1857. ),
  1858. Array(
  1859. "url(\\1$secremoveimg\\2)"
  1860. )
  1861. )
  1862. )
  1863. );
  1864. $bad_attvals = array_merge($bad_attvals, $addendum);
  1865. }
  1866. $add_attr_to_tag = Array(
  1867. "/^a$/si" => Array('target'=>'"_new"')
  1868. );
  1869. $trusted = sq_sanitize($body,
  1870. $tag_list,
  1871. $rm_tags_with_content,
  1872. $self_closing_tags,
  1873. $force_tag_closing,
  1874. $rm_attnames,
  1875. $bad_attvals,
  1876. $add_attr_to_tag,
  1877. $message,
  1878. $id
  1879. );
  1880. if (preg_match("|$secremoveimg|si", $trusted)){
  1881. $has_unsafe_images = true;
  1882. }
  1883. return $trusted;
  1884. }
  1885. ?>