mime.php 73 KB

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