mime.php 74 KB

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