mime.php 71 KB

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