PageRenderTime 52ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/mailz/lists/admin/lib.php

https://bitbucket.org/antonyravel/cape-resorts
PHP | 887 lines | 745 code | 74 blank | 68 comment | 208 complexity | e1c5a3751c75554898aef653c14bfca1 MD5 | raw file
  1. <?php
  2. require_once dirname(__FILE__)."/accesscheck.php";
  3. # library used for plugging into the webbler, instead of "connect"
  4. # depricated and should be removed
  5. #error_reporting(63);
  6. # set some defaults if they are not specified
  7. if (!defined("REGISTER")) define("REGISTER",1);
  8. if (!defined("USE_PDF")) define("USE_PDF",0);
  9. if (!defined("VERBOSE")) define("VERBOSE",0);
  10. if (!defined("ENABLE_RSS")) define("ENABLE_RSS",0);
  11. if (!defined("ALLOW_ATTACHMENTS")) define("ALLOW_ATTACHMENTS",0);
  12. if (!defined("EMAILTEXTCREDITS")) define("EMAILTEXTCREDITS",0);
  13. if (!defined("PAGETEXTCREDITS")) define("PAGETEXTCREDITS",0);
  14. //zingiri: fck editor
  15. if (!defined('USEFCK')) define('USEFCK',getConfig('fckeditor_active'));
  16. //zingiri: smtp settings
  17. global $phpmailer_smtpuser,$phpmailer_smtppassword;
  18. if (!defined("PHPMAILERHOST")) define("PHPMAILERHOST",getConfig('phpmailerhost'));
  19. $phpmailer_smtpuser=getConfig('phpmailer_smtpuser');
  20. $phpmailer_smtppassword=getConfig('phpmailer_smtppassword');
  21. if (!defined("ASKFORPASSWORD")) define("ASKFORPASSWORD",0);
  22. if (!defined("UNSUBSCRIBE_REQUIRES_PASSWORD")) define("UNSUBSCRIBE_REQUIRES_PASSWORD",0);
  23. if (!defined("UNSUBSCRIBE_JUMPOFF")) define("UNSUBSCRIBE_JUMPOFF",0);
  24. if (!defined("ENCRYPTPASSWORD")) define("ENCRYPTPASSWORD",0);
  25. if (!defined("PHPMAILER")) define("PHPMAILER",0);
  26. if (!defined("MANUALLY_PROCESS_QUEUE")) define("MANUALLY_PROCESS_QUEUE",1);
  27. if (!defined("CHECK_SESSIONIP")) define("CHECK_SESSIONIP",1);
  28. if (!defined("FILESYSTEM_ATTACHMENTS")) define("FILESYSTEM_ATTACHMENTS",0);
  29. if (!defined("MIMETYPES_FILE")) define("MIMETYPES_FILE","/etc/mime.types");
  30. if (!defined("DEFAULT_MIMETYPE")) define("DEFAULT_MIMETYPE","application/octet-stream");
  31. if (!defined("USE_REPETITION")) define("USE_REPETITION",0);
  32. if (!defined("USE_EDITMESSAGE")) define("USE_EDITMESSAGE",0);
  33. if (!defined("FCKIMAGES_DIR")) define("FCKIMAGES_DIR","uploadimages");
  34. if (!defined("USE_MANUAL_TEXT_PART")) define("USE_MANUAL_TEXT_PART",0);
  35. if (!defined("ALLOW_NON_LIST_SUBSCRIBE")) define("ALLOW_NON_LIST_SUBSCRIBE",0);
  36. if (!defined("MAILQUEUE_BATCH_SIZE")) define("MAILQUEUE_BATCH_SIZE",0);
  37. if (!defined("MAILQUEUE_BATCH_PERIOD")) define("MAILQUEUE_BATCH_PERIOD",3600);
  38. if (!defined('MAILQUEUE_THROTTLE')) define('MAILQUEUE_THROTTLE',0);
  39. if (!defined('MAILQUEUE_AUTOTHROTTLE')) define('MAILQUEUE_AUTOTHROTTLE',0);
  40. if (!defined("NAME")) define("NAME",'phplist');
  41. if (!defined("USE_OUTLOOK_OPTIMIZED_HTML")) define("USE_OUTLOOK_OPTIMIZED_HTML",0);
  42. if (!defined("EXPORT_EXCEL")) define("EXPORT_EXCEL",0);
  43. if (!defined("USE_PREPARE")) define("USE_PREPARE",0);
  44. if (!defined("HTMLEMAIL_ENCODING")) define("HTMLEMAIL_ENCODING","quoted-printable");
  45. if (!defined('TEXTEMAIL_ENCODING')) define('TEXTEMAIL_ENCODING','7bit');
  46. if (!defined("USE_LIST_EXCLUDE")) define("USE_LIST_EXCLUDE",0);
  47. if (!defined("WARN_SAVECHANGES")) define("WARN_SAVECHANGES",1);
  48. if (!defined("STACKED_ATTRIBUTE_SELECTION")) define("STACKED_ATTRIBUTE_SELECTION",0);
  49. if (!defined("REMOTE_URL_REFETCH_TIMEOUT")) define('REMOTE_URL_REFETCH_TIMEOUT',3600);
  50. if (!defined('CLICKTRACK')) define('CLICKTRACK',0);
  51. if (!defined('CLICKTRACK_SHOWDETAIL')) define('CLICKTRACK_SHOWDETAIL',0);
  52. if (!defined('USETINYMCEMESG')) define('USETINYMCEMESG',0);
  53. if (!defined('USETINYMCETEMPL')) define('USETINYMCETEMPL',0);
  54. if (!defined('TINYMCEPATH')) define('TINYMCEPATH','');
  55. if (!defined('STATS_INTERVAL')) define('STATS_INTERVAL','monthly');
  56. if (!defined('USE_DOMAIN_THROTTLE')) define('USE_DOMAIN_THROTTLE',0);
  57. if (!defined('DOMAIN_BATCH_SIZE')) define('DOMAIN_BATCH_SIZE',1);
  58. if (!defined('DOMAIN_BATCH_PERIOD')) define('DOMAIN_BATCH_PERIOD',120);
  59. if (!defined('DOMAIN_AUTO_THROTTLE')) define('DOMAIN_AUTO_THROTTLE',0);
  60. if (!defined('LANGUAGE_SWITCH')) define('LANGUAGE_SWITCH',1);
  61. if (!defined('USE_ADVANCED_BOUNCEHANDLING')) define('USE_ADVANCED_BOUNCEHANDLING',0);
  62. if (!defined('DATE_START_YEAR')) define('DATE_START_YEAR',1900);
  63. if (!defined('DATE_END_YEAR')) define('DATE_END_YEAR',0);
  64. if (!defined('ALLOW_IMPORT')) define('ALLOW_IMPORT',1);
  65. if (!defined('EMPTY_VALUE_PREFIX')) define('EMPTY_VALUE_PREFIX','--');
  66. if (!defined('USE_ADMIN_DETAILS_FOR_MESSAGES')) define('USE_ADMIN_DETAILS_FOR_MESSAGES',1);
  67. if (!defined('SEND_ONE_TESTMAIL')) define('SEND_ONE_TESTMAIL',0);
  68. if (!defined('USE_SPAM_BLOCK')) define('USE_SPAM_BLOCK',1);
  69. if (!defined('NOTIFY_SPAM')) define('NOTIFY_SPAM',1);
  70. if (!defined('FORWARD_ALTERNATIVE_CONTENT')) define('FORWARD_ALTERNATIVE_CONTENT',0);
  71. if (!defined('KEEPFORWARDERATTRIBUTES')) define('KEEPFORWARDERATTRIBUTES',0);
  72. if (!defined('FORWARD_EMAIL_COUNT') ) define('FORWARD_EMAIL_COUNT',1);
  73. if (FORWARD_EMAIL_COUNT < 1) {Error('FORWARD_EMAIL_COUNT must be > (int) 0');}
  74. # allows FORWARD_EMAIL_COUNT forwards per user per period in mysql interval terms default one day
  75. if (!defined('FORWARD_EMAIL_PERIOD') ) define('FORWARD_EMAIL_PERIOD', '1 day');
  76. if (!defined('SEND_QUEUE_PROCESSING_REPORT')) define('SEND_QUEUE_PROCESSING_REPORT',true);
  77. if (!defined('FORWARD_PERSONAL_NOTE_SIZE')) define('FORWARD_PERSONAL_NOTE_SIZE',0);
  78. if (!defined('FORWARD_FRIEND_COUNT_ATTRIBUTE')) define('FORWARD_FRIEND_COUNT_ATTRIBUTE','');
  79. if (!defined('EMBEDUPLOADIMAGES')) define('EMBEDUPLOADIMAGES',0);
  80. if (!defined('IMPORT_FILESIZE')) define('IMPORT_FILESIZE',1);
  81. if (!defined('CHECK_REFERRER')) define('CHECK_REFERRER',false);
  82. if (!defined("EMAIL_ADDRESS_VALIDATION_LEVEL")) define("EMAIL_ADDRESS_VALIDATION_LEVEL",1);
  83. if (!isset($GLOBALS["export_mimetype"])) $GLOBALS["export_mimetype"] = 'application/csv';
  84. if (!isset($GLOBALS["admin_auth_module"])) $GLOBALS["admin_auth_module"] = 'phplist_auth.inc';
  85. if (!isset($GLOBALS["require_login"])) $GLOBALS["require_login"] = 0;
  86. if (!isset($allowed_referrers)) $allowed_referrers = array();
  87. if (!defined("WORKAROUND_OUTLOOK_BUG") && defined("USE_CARRIAGE_RETURNS")) {
  88. define("WORKAROUND_OUTLOOK_BUG",USE_CARRIAGE_RETURNS);
  89. }
  90. if (!isset($GLOBALS["blacklist_gracetime"])) $GLOBALS["blacklist_gracetime"] = 5;
  91. if (!isset($GLOBALS["message_envelope"])) $GLOBALS["message_envelope"] = '';
  92. $domain = getConfig("domain");
  93. $website = getConfig("website");
  94. if (defined("IN_WEBBLER") && is_object($GLOBALS["config"]["plugins"]["phplist"])) {
  95. $GLOBALS["tables"] = $GLOBALS["config"]["plugins"]["phplist"]->tables;
  96. $GLOBALS["table_prefix"] = $GLOBALS["config"]["plugins"]["phplist"]->table_prefix;
  97. }
  98. $usephpmailer = 0;
  99. if (PHPMAILER && is_file(dirname(__FILE__).'/phpmailer/class.phpmailer.php')) {
  100. include_once dirname(__FILE__) . '/class.phplistmailer.php';
  101. $usephpmailer = 1;
  102. }
  103. $GLOBALS['bounceruleactions'] = array(
  104. 'deleteuser' => $GLOBALS['I18N']->get('delete user'),
  105. 'unconfirmuser' => $GLOBALS['I18N']->get('unconfirm user'),
  106. 'blacklistuser' => $GLOBALS['I18N']->get('blacklist user'),
  107. 'deleteuserandbounce' => $GLOBALS['I18N']->get('delete user and bounce'),
  108. 'unconfirmuseranddeletebounce' => $GLOBALS['I18N']->get('unconfirm user and delete bounce'),
  109. 'blacklistuseranddeletebounce' => $GLOBALS['I18N']->get('blacklist user and delete bounce'),
  110. 'deletebounce' => $GLOBALS['I18N']->get('delete bounce'),
  111. );
  112. # check whether Pear HTTP/Request is available
  113. @include_once "HTTP/Request.php";
  114. $GLOBALS['has_pear_http_request'] = class_exists('HTTP_Request');
  115. ini_set('error_append_string','<font style=\"{font-variant: small-caps;font-size: 12px}\">phplist</font> version '.VERSION);
  116. ini_set('error_prepend_string','<P><font color=red style=\"{font-size: 12px}\">Sorry a software error occurred:</font><br/>
  117. Please <a href="http://mantis.phplist.com">report a bug</a> when reporting the bug, please include URL and the entire content of this page.<br/>');
  118. function listName($id) {
  119. global $tables;
  120. $req = Sql_Fetch_Row_Query(sprintf('select name from %s where id = %d',$tables["list"],$id));
  121. return $req[0] ? stripslashes($req[0]) : $GLOBALS['I18N']->get('Unnamed List');
  122. }
  123. function setMessageData($msgid,$name,$value) {
  124. Sql_Query(sprintf('replace into %s set id = %d,name = "%s", data = "%s"',
  125. $GLOBALS['tables']['messagedata'],$msgid,addslashes($name),$value));
  126. # print "setting $name for $msgid to $value";
  127. # exit;
  128. }
  129. function loadMessageData($msgid) {
  130. $messagedata = array();
  131. $msgdata_req = Sql_Query(sprintf('select * from %s where id = %d',
  132. $GLOBALS['tables']['messagedata'],$msgid));
  133. while ($row = Sql_Fetch_Array($msgdata_req)) {
  134. $messagedata[$row['name']] = $row['data'];
  135. }
  136. return $messagedata;
  137. }
  138. function HTMLselect ($name, $table, $column, $value) {
  139. $res = "<!--$value--><select name=$name>\n";
  140. $result = Sql_Query("SELECT id,$column FROM $table");
  141. while($row = Sql_Fetch_Array($result)) {
  142. $res .= "<option value=".$row["id"] ;
  143. if ($row["$column"] == $value)
  144. $res .= " selected";
  145. if ($row["id"] == $value)
  146. $res .= " selected";
  147. $res .= ">" . $row[$column] . "\n";
  148. }
  149. $res .= "</select>\n";
  150. return $res;
  151. }
  152. function sendMail ($to,$subject,$message,$header = "",$parameters = "",$skipblacklistcheck = 0) {
  153. if (TEST)
  154. return 1;
  155. # do a quick check on mail injection attempt, @@@ needs more work
  156. if (preg_match("/\n/",$to)) {
  157. logEvent("Error: invalid recipient, containing newlines, email blocked");
  158. return 0;
  159. }
  160. if (preg_match("/\n/",$subject)) {
  161. logEvent("Error: invalid subject, containing newlines, email blocked");
  162. return 0;
  163. }
  164. if (!$to) {
  165. logEvent("Error: empty To: in message with subject $subject to send");
  166. return 0;
  167. } elseif (!$subject) {
  168. logEvent("Error: empty Subject: in message to send to $to");
  169. return 0;
  170. }
  171. if (!$skipblacklistcheck && isBlackListed($to)) {
  172. logEvent("Error, $to is blacklisted, not sending");
  173. Sql_Query(sprintf('update %s set blacklisted = 1 where email = "%s"',$GLOBALS["tables"]["user"],$to));
  174. addUserHistory($to,"Marked Blacklisted","Found user in blacklist while trying to send an email, marked black listed");
  175. return 0;
  176. }
  177. if ($GLOBALS['usephpmailer']) {
  178. return sendMailPhpMailer($to,$subject,$message);
  179. } else {
  180. return sendMailOriginal($to,$subject,$message,$header,$parameters);
  181. }
  182. return 0;
  183. }
  184. function sendMailOriginal ($to,$subject,$message,$header = "",$parameters = "") {
  185. # global function to capture sending emails, to avoid trouble with
  186. # older (and newer!) php versions
  187. $v = phpversion();
  188. $v = preg_replace("/\-.*$/","",$v);
  189. if ($GLOBALS["message_envelope"]) {
  190. $header = rtrim($header);
  191. if ($header)
  192. $header .= "\n";
  193. $header .= "Errors-To: ".$GLOBALS["message_envelope"];
  194. if (!$parameters || !ereg("-f".$GLOBALS["message_envelope"],$parameters)) {
  195. $parameters = '-f'.$GLOBALS["message_envelope"];
  196. }
  197. }
  198. // Use the system email encoding method
  199. if (TEXTEMAIL_ENCODING) {
  200. // only add if the required header is not already present
  201. if (!strpos(strtolower($header), 'content-transfer-encoding')) {
  202. $header = rtrim($header);
  203. if ($header)
  204. $header .= "\n";
  205. $header .= "Content-Transfer-Encoding: " . TEXTEMAIL_ENCODING;
  206. }
  207. }
  208. if (WORKAROUND_OUTLOOK_BUG) {
  209. $header = rtrim($header);
  210. if ($header)
  211. $header .= "\n";
  212. $header .= "X-Outlookbug-fixed: Yes";
  213. $message = preg_replace("/\r?\n/", "\r\n", $message);
  214. }
  215. # version 4.2.3 (and presumably up) does not allow the fifth parameter in safe mode
  216. # make sure not to send out loads of test emails to ppl when developing
  217. if (!ereg("dev",VERSION)) {
  218. if ($v > "4.0.5" && !ini_get("safe_mode")) {
  219. if (mail($to,$subject,$message,$header,$parameters))
  220. return 1;
  221. else
  222. return mail($to,$subject,$message,$header);
  223. }
  224. else
  225. return mail($to,$subject,$message,$header);
  226. } else {
  227. # send mails to one place when running a test version
  228. $message = "To: $to\n".$message;
  229. if ($GLOBALS["developer_email"]) {
  230. # fake occasional failure
  231. if (mt_rand(0,50) == 1) {
  232. return 0;
  233. } else {
  234. if(@mail($GLOBALS["developer_email"],$subject,$message,$header,$parameters)) {
  235. return 1;
  236. } else {
  237. # Changed by Bas: Always ok, since the mac/xampp return false while sending and no error in /var/log/mail.log
  238. # We are in developermode anyway, and errors are faked by code just above this.
  239. mail($GLOBALS["developer_email"],$subject,$message,$header);
  240. return 1;
  241. }
  242. }
  243. } else {
  244. print "Error: Running CVS version, but developer_email not set";
  245. }
  246. }
  247. }
  248. function sendMailPhpMailer ($to,$subject,$message) {
  249. # global function to capture sending emails, to avoid trouble with
  250. # older (and newer!) php versions
  251. $fromemail = getConfig("message_from_address");
  252. $fromname = getConfig("message_from_name");
  253. $message_replyto_address = getConfig("message_replyto_address");
  254. if ($message_replyto_address)
  255. $reply_to = $message_replyto_address;
  256. else
  257. $reply_to = $from_address;
  258. $destinationemail = '';
  259. if (!ereg("dev",VERSION)) {
  260. $mail = new PHPlistMailer('systemmessage',$to);
  261. $destinationemail = $to;
  262. $mail->add_text($message);
  263. } else {
  264. # send mails to one place when running a test version
  265. $message = "To: $to\n".$message;
  266. if ($GLOBALS["developer_email"]) {
  267. # fake occasional failure
  268. if (mt_rand(0,50) == 1) {
  269. return 0;
  270. } else {
  271. $mail = new PHPlistMailer('systemmessage',$GLOBALS["developer_email"]);
  272. $mail->add_text($message);
  273. $destinationemail = $GLOBALS["developer_email"];
  274. }
  275. } else {
  276. print "Error: Running CVS version, but developer_email not set";
  277. }
  278. }
  279. # 0008549: message envelope not passed to php mailer,
  280. $mail->Sender = $GLOBALS["message_envelope"];
  281. $mail->build_message(
  282. array(
  283. "html_charset" => getConfig("html_charset"),
  284. "html_encoding" => HTMLEMAIL_ENCODING,
  285. "text_charset" => getConfig("text_charset"),
  286. "text_encoding" => TEXTEMAIL_ENCODING)
  287. );
  288. return $mail->send("", $destinationemail, $fromname, $fromemail, $subject);
  289. }
  290. function sendAdminCopy($subject,$message) {
  291. $sendcopy = getConfig("send_admin_copies");
  292. if ($sendcopy == "true") {
  293. $admin_mail = getConfig("admin_address");
  294. $mails = explode(",",getConfig("admin_addresses"));
  295. array_push($mails,$admin_mail);
  296. $sent = array();
  297. foreach ($mails as $admin_mail) {
  298. $admin_mail = trim($admin_mail);
  299. if (!$sent[$admin_mail] && $admin_mail) {
  300. sendMail($admin_mail,$subject,$message,system_messageheaders($admin_mail));
  301. $sent[$admin_mail] = 1;
  302. }
  303. }
  304. }
  305. }
  306. function safeImageName($name) {
  307. $name = "image".ereg_replace("\.","DOT",$name);
  308. $name = ereg_replace("-","DASH",$name);
  309. $name = ereg_replace("_","US",$name);
  310. $name = ereg_replace("/","SLASH",$name);
  311. $name = ereg_replace(':','COLON',$name);
  312. return $name;
  313. }
  314. function clean2 ($value) {
  315. $value = trim($value);
  316. $value = ereg_replace("\r","",$value);
  317. $value = ereg_replace("\n","",$value);
  318. $value = ereg_replace('"',"&quot;",$value);
  319. $value = ereg_replace("'","&rsquo;",$value);
  320. $value = ereg_replace("`","&lsquo;",$value);
  321. $value = stripslashes($value);
  322. return $value;
  323. }
  324. function cleanEmail ($value) {
  325. $value = trim($value);
  326. $value = preg_replace("/\r/","",$value);
  327. $value = preg_replace("/\n/","",$value);
  328. $value = preg_replace('/"/',"&quot;",$value);
  329. ## these are allowed in emails
  330. // $value = preg_replace("/'/","&rsquo;",$value);
  331. $value = preg_replace("/`/","&lsquo;",$value);
  332. $value = stripslashes($value);
  333. return $value;
  334. }
  335. if (TEST && REGISTER)
  336. $pixel = '<img src="http://phplist.tincan.co.uk/images/pixel.gif" width=1 height=1>';
  337. function timeDiff($time1,$time2) {
  338. if (!$time1 || !$time2) {
  339. return $GLOBALS['I18N']->get('Unknown');
  340. }
  341. $t1 = strtotime($time1);
  342. $t2 = strtotime($time2);
  343. if ($t1 < $t2) {
  344. $diff = $t2 - $t1;
  345. } else {
  346. $diff = $t1 - $t2;
  347. }
  348. if ($diff == 0)
  349. return $GLOBALS['I18N']->get('very little time');
  350. $hours = (int)($diff / 3600);
  351. $mins = (int)(($diff - ($hours * 3600)) / 60);
  352. $secs = (int)($diff - $hours * 3600 - $mins * 60);
  353. $res = '';
  354. if ($hours)
  355. $res = $hours . " hours";
  356. if ($mins)
  357. $res .= " ".$mins . " mins";
  358. if ($secs)
  359. $res .= " ".$secs . " secs";
  360. return $res;
  361. }
  362. function previewTemplate($id,$adminid = 0,$text = "", $footer = "") {
  363. global $tables;
  364. if (defined("IN_WEBBLER")) {
  365. $more = '&pi='.$_GET["pi"];
  366. } else {
  367. $more = '';
  368. }
  369. $tmpl = Sql_Fetch_Row_Query(sprintf('select template from %s where id = %d',$tables["template"],$id));
  370. $template = stripslashes($tmpl[0]);
  371. $img_req = Sql_Query(sprintf('select id,filename from %s where template = %d order by filename desc',$tables["templateimage"],$id));
  372. while ($img = Sql_Fetch_Array($img_req)) {
  373. $template = preg_replace("#".preg_quote($img["filename"])."#","?page=image&id=".$img["id"].$more,$template);
  374. }
  375. if ($adminid) {
  376. $att_req = Sql_Query("select name,value from {$tables["adminattribute"]},{$tables["admin_attribute"]} where {$tables["adminattribute"]}.id = {$tables["admin_attribute"]}.adminattributeid and {$tables["admin_attribute"]}.adminid = $adminid");
  377. while ($att = Sql_Fetch_Array($att_req)) {
  378. $template = preg_replace("#\[LISTOWNER.".strtoupper(preg_quote($att["name"]))."\]#",$att["value"],$template);
  379. }
  380. }
  381. if ($footer)
  382. $template = eregi_replace("\[FOOTER\]",$footer,$template);
  383. $template = preg_replace("#\[CONTENT\]#",$text,$template);
  384. $template = eregi_replace("\[UNSUBSCRIBE\]",sprintf('<a href="%s">%s</a>',getConfig("unsubscribeurl"),$GLOBALS["strThisLink"]),$template);
  385. #0013076: Blacklisting posibility for unknown users
  386. $template = eregi_replace("\[BLACKLIST\]",sprintf('<a href="%s">%s</a>',getConfig("blacklisturl"),$GLOBALS["strThisLink"]),$template);
  387. $template = eregi_replace("\[PREFERENCES\]",sprintf('<a href="%s">%s</a>',getConfig("preferencesurl"),$GLOBALS["strThisLink"]),$template);
  388. if (!EMAILTEXTCREDITS) {
  389. $template = eregi_replace("\[SIGNATURE\]",$GLOBALS["PoweredByImage"],$template);
  390. } else {
  391. $template = eregi_replace("\[SIGNATURE\]",$GLOBALS["PoweredByText"],$template);
  392. }
  393. $template = ereg_replace("\[[A-Z\. ]+\]","",$template);
  394. $template = ereg_replace('<form','< form',$template);
  395. $template = ereg_replace('</form','< /form',$template);
  396. return $template;
  397. }
  398. function parseMessage($content,$template,$adminid = 0) {
  399. global $tables;
  400. $tmpl = Sql_Fetch_Row_Query("select template from {$tables["template"]} where id = $template");
  401. $template = $tmpl[0];
  402. $template = preg_replace("#\[CONTENT\]#",$content,$template);
  403. $att_req = Sql_Query("select name,value from {$tables["adminattribute"]},{$tables["admin_attribute"]} where {$tables["adminattribute"]}.id = {$tables["admin_attribute"]}.adminattributeid and {$tables["admin_attribute"]}.adminid = $adminid");
  404. while ($att = Sql_Fetch_Array($att_req)) {
  405. $template = preg_replace("#\[LISTOWNER.".strtoupper(preg_quote($att["name"]))."\]#",$att["value"],$template);
  406. }
  407. return $template;
  408. }
  409. function listOwner($listid = 0) {
  410. global $tables;
  411. $req = Sql_Fetch_Row_Query("select owner from {$tables["list"]} where id = $listid");
  412. return $req[0];
  413. }
  414. function system_messageHeaders($useremail = "") {
  415. $from_address = getConfig("message_from_address");
  416. $from_name = getConfig("message_from_name");
  417. if ($from_name)
  418. $additional_headers = "From: \"$from_name\" <$from_address>\n";
  419. else
  420. $additional_headers = "From: $from_address\n";
  421. $message_replyto_address = getConfig("message_replyto_address");
  422. if ($message_replyto_address)
  423. $additional_headers .= "Reply-To: $message_replyto_address\n";
  424. else
  425. $additional_headers .= "Reply-To: $from_address\n";
  426. $v = VERSION;
  427. $v = ereg_replace("-dev","",$v);
  428. $additional_headers .= "X-Mailer: phplist version $v (www.phplist.com)\n";
  429. $additional_headers .= "X-MessageID: systemmessage\n";
  430. if ($useremail)
  431. $additional_headers .= "X-User: ".$useremail."\n";
  432. return $additional_headers;
  433. }
  434. function logEvent($msg) {
  435. global $tables;
  436. if (isset($GLOBALS['page'])) {
  437. $p = $GLOBALS['page'];
  438. } elseif (isset($_GET['page'])) {
  439. $p = $_GET['page'];
  440. } elseif (isset($_GET['p'])) {
  441. $p = $_GET['p'];
  442. } else {
  443. $p = 'unknown page';
  444. }
  445. if (Sql_Table_Exists($tables["eventlog"]))
  446. Sql_Query(sprintf('insert into %s (entered,page,entry) values(now(),"%s","%s")',$tables["eventlog"],
  447. $p,addslashes($msg)));
  448. }
  449. ### process locking stuff
  450. function getPageLock() {
  451. global $tables;
  452. $thispage = $GLOBALS["page"];
  453. $running_req = Sql_query("select now() - modified,id from ".$tables["sendprocess"]." where page = \"$thispage\" and alive order by started desc");
  454. $running_res = Sql_Fetch_row($running_req);
  455. $waited = 0;
  456. while ($running_res[1]) { # a process is already running
  457. if ($running_res[0] > 600) {# some sql queries can take quite a while
  458. # process has been inactive for too long, kill it
  459. Sql_query("update {$tables["sendprocess"]} set alive = 0 where id = $running_res[1]");
  460. } else {
  461. output ($GLOBALS['I18N']->get('A process for this page is already running and it was still alive').' '.$running_res[0].' '.$GLOBALS['I18N']->get('seconds ago'));
  462. sleep(1); # to log the messages in the correct order
  463. if ($GLOBALS["commandline"]) {
  464. output("Running commandline, quitting. We'll find out what to do in the next run.");
  465. exit;
  466. }
  467. output ($GLOBALS['I18N']->get('Sleeping for 20 seconds, aborting will quit'));
  468. flush();
  469. $abort = ignore_user_abort(0);
  470. sleep(20);
  471. }
  472. $waited++;
  473. if ($waited > 10) {
  474. # we have waited 10 cycles, abort and quit script
  475. output($GLOBALS['I18N']->get('We have been waiting too long, I guess the other process is still going ok'));
  476. exit;
  477. }
  478. $running_req = Sql_query("select now() - modified,id from ".$tables["sendprocess"]." where page = \"$thispage\" and alive order by started desc");
  479. $running_res = Sql_Fetch_row($running_req);
  480. }
  481. $res = Sql_query('insert into '.$tables["sendprocess"].' (started,page,alive,ipaddress) values(now(),"'.$thispage.'",1,"'.getenv("REMOTE_ADDR").'")');
  482. $send_process_id = Sql_Insert_Id();
  483. $abort = ignore_user_abort(1);
  484. return $send_process_id;
  485. }
  486. function keepLock($processid) {
  487. global $tables;
  488. $thispage = $GLOBALS["page"];
  489. Sql_query("Update ".$tables["sendprocess"]." set alive = alive + 1 where id = $processid");
  490. }
  491. function checkLock($processid) {
  492. global $tables;
  493. $thispage = $GLOBALS["page"];
  494. $res = Sql_query("select alive from {$tables['sendprocess']} where id = $processid");
  495. $row = Sql_Fetch_Row($res);
  496. return $row[0];
  497. }
  498. function addAbsoluteResources($text,$url) {
  499. $parts = parse_url($url);
  500. $tags = array('src\s*=\s*','href\s*=\s*','action\s*=\s*',
  501. 'background\s*=\s*','@import\s+','@import\s+url\(');
  502. foreach ($tags as $tag) {
  503. # preg_match_all('/'.preg_quote($tag).'"([^"|\#]*)"/Uim', $text, $foundtags);
  504. # we're only handling nicely formatted src="something" and not src=something, ie quotes are required
  505. # bit of a nightmare to not handle it with quotes.
  506. preg_match_all('/('.$tag.')"([^"|\#]*)"/Uim', $text, $foundtags);
  507. for ($i=0; $i< count($foundtags[0]); $i++) {
  508. $match = $foundtags[2][$i];
  509. $tagmatch = $foundtags[1][$i];
  510. # print "$match<br/>";
  511. if (preg_match("#^(http|javascript|https|ftp|mailto):#i",$match)) {
  512. # scheme exists, leave it alone
  513. } elseif (preg_match("#\[.*\]#U",$match)) {
  514. # placeholders used, leave alone as well
  515. } elseif (ereg("^/",$match)) {
  516. # starts with /
  517. $text = preg_replace('#'.preg_quote($foundtags[0][$i]).'#im',$tagmatch.'"'.$parts["scheme"].'://'.$parts["host"].$match.'"',$text,1);
  518. } else {
  519. $path = '';
  520. if (isset($parts['path'])) {
  521. $path = $parts["path"];
  522. }
  523. if (!preg_match('#/$#',$path)) {
  524. $pathparts = explode('/',$path);
  525. array_pop($pathparts);
  526. $path = join('/',$pathparts);
  527. $path .= '/';
  528. }
  529. $text = preg_replace('#'.preg_quote($foundtags[0][$i]).'#im',
  530. $tagmatch.'"'.$parts["scheme"].'://'.$parts["host"].$path.$match.'"',$text,1);
  531. }
  532. }
  533. }
  534. # $text = preg_replace('#PHPSESSID=[^\s]+
  535. return $text;
  536. }
  537. function getPageCache($url,$lastmodified = 0) {
  538. $req = Sql_Fetch_Row_Query(sprintf('select content from %s where url = "%s" and lastmodified >= %d',$GLOBALS["tables"]["urlcache"],$url,$lastmodified));
  539. return $req[0];
  540. }
  541. function getPageCacheLastModified($url) {
  542. $req = Sql_Fetch_Row_Query(sprintf('select lastmodified from %s where url = "%s"',$GLOBALS["tables"]["urlcache"],$url));
  543. return $req[0];
  544. }
  545. function setPageCache($url,$lastmodified = 0,$content) {
  546. if (isset($GLOBALS['developer_email'])) return;
  547. Sql_Query(sprintf('delete from %s where url = "%s"',$GLOBALS["tables"]["urlcache"],$url));
  548. Sql_Query(sprintf('insert into %s (url,lastmodified,added,content)
  549. values("%s",%d,now(),"%s")',$GLOBALS["tables"]["urlcache"],$url,$lastmodified,addslashes($content)));
  550. }
  551. function fetchUrl($url,$userdata = array()) {
  552. require_once "HTTP/Request.php";
  553. # logEvent("Fetching $url");
  554. if (sizeof($userdata)) {
  555. foreach ($userdata as $key => $val) {
  556. $url = eregi_replace("\[$key\]",urlencode($val),$url);
  557. }
  558. }
  559. if (!isset($GLOBALS['urlcache'])) {
  560. $GLOBALS['urlcache'] = array();
  561. }
  562. # keep in memory cache in case we send a page to many emails
  563. if (isset($GLOBALS['urlcache'][$url]) && is_array($GLOBALS['urlcache'][$url])
  564. && (time() - $GLOBALS['urlcache'][$url]['fetched'] < REMOTE_URL_REFETCH_TIMEOUT)) {
  565. # logEvent($url . " is cached in memory");
  566. return $GLOBALS['urlcache'][$url]['content'];
  567. }
  568. $dbcache_lastmodified = getPageCacheLastModified($url);
  569. $timeout = time() - $dbcache_lastmodified;
  570. if ($timeout < REMOTE_URL_REFETCH_TIMEOUT) {
  571. # logEvent($url.' was cached in database');
  572. return getPageCache($url);
  573. } else {
  574. # logEvent($url.' is not cached in database '.$timeout.' '. $dbcache_lastmodified." ".time());
  575. }
  576. # add a small timeout, although the biggest timeout will exist in doing the DNS lookup,
  577. # so it won't make too much of a difference
  578. $request_parameters = array(
  579. 'timeout' => 10,
  580. 'allowRedirects' => 1,
  581. 'method' => 'HEAD',
  582. );
  583. $headreq =& new HTTP_Request($url,$request_parameters);
  584. $headreq->addHeader('User-Agent', 'phplist v'.VERSION.' (http://www.phplist.com)');
  585. if (!PEAR::isError($headreq->sendRequest(false))) {
  586. $code = $headreq->getResponseCode();
  587. if ($code != 200) {
  588. logEvent('Fetching '.$url.' failed, error code '.$code);
  589. return 0;
  590. }
  591. $header = $headreq->getResponseHeader();
  592. ## relying on the last modified header doesn't work for many pages
  593. ## use current time instead
  594. ## see http://mantis.phplist.com/view.php?id=7684
  595. # $lastmodified = strtotime($header["last-modified"]);
  596. $lastmodified = time();
  597. $cache = getPageCache($url,$lastmodified);
  598. if (!$cache) {
  599. $request_parameters['method'] = 'GET';
  600. $req =& new HTTP_Request($url,$request_parameters);
  601. $req->addHeader('User-Agent', 'phplist v'.VERSION.' (http://www.phplist.com)');
  602. logEvent('Fetching '.$url);
  603. if (!PEAR::isError($req->sendRequest(true))) {
  604. $content = $req->getResponseBody();
  605. $content = addAbsoluteResources($content,$url);
  606. logEvent('Fetching '.$url.' success');
  607. setPageCache($url,$lastmodified,$content);
  608. } else {
  609. logEvent('Fetching '.$url.' failed');
  610. return 0;
  611. }
  612. } else {
  613. logEvent($url.' was cached in database');
  614. $content = $cache;
  615. }
  616. } else {
  617. logEvent('Fetching '.$url.' failed');
  618. return 0;
  619. }
  620. $GLOBALS['urlcache'][$url] = array(
  621. 'fetched' => time(),
  622. 'content' => $content,
  623. );
  624. return $content;
  625. }
  626. function releaseLock($processid) {
  627. global $tables;
  628. if (!$processid) return;
  629. Sql_query("delete from {$tables["sendprocess"]} where id = $processid");
  630. }
  631. function cleanUrl($url,$disallowed_params = array('PHPSESSID')) {
  632. $parsed = @parse_url($url);
  633. $params = array();
  634. if (empty($parsed['query'])) {
  635. $parsed['query'] = '';
  636. }
  637. # hmm parse_str should take the delimiters as a parameter
  638. if (strpos($parsed['query'],'&amp;')) {
  639. $pairs = explode('&amp;',$parsed['query']);
  640. foreach ($pairs as $pair) {
  641. list($key,$val) = explode('=',$pair);
  642. $params[$key] = $val;
  643. }
  644. } else {
  645. parse_str($parsed['query'],$params);
  646. }
  647. $uri = !empty($parsed['scheme']) ? $parsed['scheme'].':'.((strtolower($parsed['scheme']) == 'mailto') ? '':'//'): '';
  648. $uri .= !empty($parsed['user']) ? $parsed['user'].(!empty($parsed['pass'])? ':'.$parsed['pass']:'').'@':'';
  649. $uri .= !empty($parsed['host']) ? $parsed['host'] : '';
  650. $uri .= !empty($parsed['port']) ? ':'.$parsed['port'] : '';
  651. $uri .= !empty($parsed['path']) ? $parsed['path'] : '';
  652. # $uri .= $parsed['query'] ? '?'.$parsed['query'] : '';
  653. $query = '';
  654. foreach ($params as $key => $val) {
  655. if (!in_array($key,$disallowed_params)) {
  656. //0008980: Link Conversion for Click Tracking. no = will be added if key is empty.
  657. $query .= $key . ( $val ? '=' . $val . '&' : '&' );
  658. }
  659. }
  660. $query = substr($query,0,-1);
  661. $uri .= $query ? '?'.$query : '';
  662. # if (!empty($params['p'])) {
  663. # $uri .= '?p='.$params['p'];
  664. # }
  665. $uri .= !empty($parsed['fragment']) ? '#'.$parsed['fragment'] : '';
  666. return $uri;
  667. }
  668. function adminName($id = 0) {
  669. if (!$id) {
  670. $id = $_SESSION["logindetails"]["id"];
  671. }
  672. if (is_object($GLOBALS["admin_auth"])) {
  673. return $GLOBALS["admin_auth"]->adminName($id);
  674. }
  675. $req = Sql_Fetch_Row_Query(sprintf('select loginname from %s where id = %d',$GLOBALS["tables"]["admin"],$id));
  676. return $req[0] ? $req[0] : "<font color=red>Nobody</font>";
  677. }
  678. //if (!function_exists("dbg")) {
  679. // function dbg($msg,$logfile = "") {
  680. // if (!$logfile) return;
  681. // $fp = @fopen($logfile,"a");
  682. // $line = "[".date("d M Y, H:i:s")."] ".getenv("REQUEST_URI").'('.$config["stats"]["number_of_queries"].") $msg \n";
  683. // @fwrite($fp,$line);
  684. // @fclose($fp);
  685. // }
  686. //}
  687. function addSubscriberStatistics($item = '',$amount,$list = 0) {
  688. switch (STATS_INTERVAL) {
  689. case 'monthly':
  690. # mark everything as the first day of the month
  691. $time = mktime(0,0,0,date('m'),1,date('Y'));
  692. break;
  693. case 'weekly':
  694. # mark everything for the first sunday of the week
  695. $time = mktime(0,0,0,date('m'),date('d') - date('w'),date('Y'));
  696. break;
  697. case 'daily':
  698. $time = mktime(0,0,0,date('m'),date('d'),date('Y'));
  699. break;
  700. }
  701. Sql_Query(sprintf('update %s set value = value + %d where unixdate = %d and item = "%s" and listid = %d',
  702. $GLOBALS['tables']['userstats'],$amount,$time,$item,$list));
  703. $done = Sql_Affected_Rows();
  704. if (!$done) {
  705. Sql_Query(sprintf('insert into %s set value = %d,unixdate = %d,item = "%s",listid = %d',
  706. $GLOBALS['tables']['userstats'],$amount,$time,$item,$list));
  707. }
  708. }
  709. function deleteBounce($id = 0) {
  710. if (!$id) return;
  711. $id = sprintf('%d',$id);
  712. Sql_query(sprintf('delete from %s where id = %d',$GLOBALS['tables']['bounce'],$id));
  713. Sql_query(sprintf('delete from %s where bounce = %d',$GLOBALS['tables']['user_message_bounce'],$id));
  714. Sql_query(sprintf('delete from %s where bounce = %d',$GLOBALS['tables']['bounceregex_bounce'],$id));
  715. }
  716. function reverse_htmlentities($mixed)
  717. {
  718. $htmltable = get_html_translation_table(HTML_ENTITIES);
  719. foreach($htmltable as $key => $value)
  720. {
  721. $mixed = ereg_replace(addslashes($value),$key,$mixed);
  722. }
  723. return $mixed;
  724. }
  725. function loadBounceRules($all = 0) {
  726. if ($all) {
  727. $status = '';
  728. } else {
  729. $status = ' where status = "active"';
  730. }
  731. $result = array();
  732. $req = Sql_Query(sprintf('select * from %s %s order by listorder',$GLOBALS['tables']['bounceregex'],$status));
  733. while ($row = Sql_Fetch_Array($req)) {
  734. if ($row['regex'] && $row['action']) {
  735. $result[$row['regex']] = array(
  736. 'action' => $row['action'],
  737. 'id' => $row['id']
  738. );
  739. }
  740. }
  741. return $result;
  742. }
  743. function matchedBounceRule($text,$activeonly = 0) {
  744. if ($activeonly) {
  745. $status = ' where status = "active"';
  746. } else {
  747. $status = '';
  748. }
  749. $req = Sql_Query(sprintf('select * from %s %s order by listorder',$GLOBALS['tables']['bounceregex'],$status));
  750. while ($row = Sql_Fetch_Array($req)) {
  751. $pattern = str_replace(' ','\s+',$row['regex']);
  752. # print "Trying to match ".$pattern;
  753. #print ' with '.$text;
  754. # print '<br/>';
  755. if (@preg_match('/'.preg_quote($pattern).'/iUm',$text)) {
  756. return $row['id'];
  757. } elseif (@preg_match('/'.$pattern.'/iUm',$text)) {
  758. return $row['id'];
  759. }
  760. }
  761. return '';
  762. }
  763. function matchBounceRules($text,$rules = array()) {
  764. if (!sizeof($rules)) {
  765. $rules = loadBounceRules();
  766. }
  767. foreach ($rules as $pattern => $rule) {
  768. $pattern = str_replace(' ','\s+',$pattern);
  769. if (@preg_match('/'.preg_quote($pattern).'/iUm',$text)) {
  770. return $rule;
  771. } elseif (@preg_match('/'.$pattern.'/iUm',$text)) {
  772. return $rule;
  773. } else {
  774. # print "Trying to match $pattern failed<br/>";
  775. }
  776. }
  777. return '';
  778. }
  779. function validateRssFrequency($freq = '') {
  780. if (!$freq) return '';
  781. if (in_array($freq,array_keys($GLOBALS['rssfrequencies']))) {
  782. return $freq;
  783. }
  784. return '';
  785. }
  786. function strip_newlines( $str, $placeholder = '' ) {
  787. $str = str_replace(chr(13) . chr(10), $placeholder , $str);
  788. $str = str_replace(chr(10), $placeholder , $str);
  789. $str = str_replace(chr(13), $placeholder , $str);
  790. return $str;
  791. }
  792. class timer {
  793. var $start;
  794. function timer() {
  795. $now = gettimeofday();
  796. $this->start = $now["sec"] * 1000000 + $now["usec"];
  797. }
  798. function elapsed($seconds = 0) {
  799. $now = gettimeofday();
  800. $end = $now["sec"] * 1000000 + $now["usec"];
  801. $elapsed = $end - $this->start;
  802. if ($seconds) {
  803. return $elapsed / 1000000;
  804. } else {
  805. return $elapsed;
  806. }
  807. }
  808. }
  809. ?>