Grey submit button on send mail page after click.
[platal.git] / include / newsletter.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2014 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 // {{{ class MailNotFound
23
24 class MailNotFound extends Exception {
25 }
26
27 // }}}
28
29 // {{{ class NewsLetter
30
31 class NewsLetter
32 {
33 public $id; // ID of the NL (in table newsletters)
34 public $group; // Short name of the group corresponding to the NL
35 public $group_id; // ID of that group
36 public $name; // Name of the NL (e.g "Lettre de Polytechnique.org", ...)
37 public $cats; // List of all categories for this NL
38 public $criteria; // PlFlagSet of allowed filters for recipient selection
39
40 // Base name to use instead of the group short name for NLs without a custom CSS
41 const FORMAT_DEFAULT_GROUP = 'default';
42
43 // Diminutif of X.net groups with a specific NL view
44 const GROUP_XORG = 'Polytechnique.org';
45 const GROUP_COMMUNITY = 'Annonces';
46 const GROUP_AX = 'AX';
47 const GROUP_EP = 'Ecole';
48 const GROUP_FX = 'FX';
49
50 // Searches on mutiple fields
51 const SEARCH_ALL = 'all';
52 const SEARCH_TITLE = 'title';
53
54
55 // {{{ Constructor, NewsLetter retrieval (forGroup, getAll)
56
57 public function __construct($id)
58 {
59 // Load NL data
60 $res = XDB::query('SELECT nls.group_id, g.diminutif AS group_name,
61 nls.name AS nl_name, nls.criteria
62 FROM newsletters AS nls
63 LEFT JOIN groups AS g ON (nls.group_id = g.id)
64 WHERE nls.id = {?}',
65 $id);
66 if (!$res->numRows()) {
67 throw new MailNotFound();
68 }
69
70 $data = $res->fetchOneAssoc();
71 $this->id = $id;
72 $this->group_id = $data['group_id'];
73 $this->group = $data['group_name'];
74 $this->name = $data['nl_name'];
75 $this->criteria = new PlFlagSet($data['criteria']);
76
77 // Load the categories
78 $res = XDB::iterRow(
79 'SELECT cid, title
80 FROM newsletter_cat
81 WHERE nlid = {?}
82 ORDER BY pos', $id);
83 while (list($cid, $title) = $res->next()) {
84 $this->cats[$cid] = $title;
85 }
86 }
87
88 /** Retrieve the NL associated with a given group.
89 * @p $group Short name of the group
90 * @return A NewsLetter object, or null if the group doesn't have a NL.
91 */
92 public static function forGroup($group)
93 {
94 $res = XDB::query('SELECT nls.id
95 FROM newsletters AS nls
96 LEFT JOIN groups AS g ON (nls.group_id = g.id)
97 WHERE g.diminutif = {?}', $group);
98 if (!$res->numRows()) {
99 return null;
100 }
101 return new NewsLetter($res->fetchOneCell());
102 }
103
104 /** Retrieve all newsletters
105 * @return An array of $id => NewsLetter objects
106 */
107 public static function getAll($sort = 'id', $order = 'ASC')
108 {
109 $res = XDB::fetchAllAssoc('SELECT n.id, g.nom AS group_name, n.name, n.criteria, g.diminutif AS group_link
110 FROM newsletters AS n
111 INNER JOIN groups AS g ON (n.group_id = g.id)
112 ORDER BY ' . $sort . ' ' . $order);
113 return $res;
114 }
115
116 // }}}
117 // {{{ Issue retrieval
118
119 /** Retrieve all issues which should be sent
120 * @return An array of NLIssue objects to send (i.e state = 'new' and send_before <= today)
121 */
122 public static function getIssuesToSend()
123 {
124 $res = XDB::query('SELECT id
125 FROM newsletter_issues
126 WHERE state = \'pending\' AND send_before <= NOW()');
127 $issues = array();
128 foreach ($res->fetchColumn() as $id) {
129 $issues[$id] = new NLIssue($id);
130 }
131 return $issues;
132 }
133
134 /** Retrieve a given issue of this NewsLetter
135 * @p $name Name or ID of the issue to retrieve.
136 * @return A NLIssue object.
137 *
138 * $name may be either a short_name, an ID or the special value 'last' which
139 * selects the latest sent NL.
140 * If $name is null, this will retrieve the current pending NL.
141 */
142 public function getIssue($name = null, $only_sent = true)
143 {
144 if ($name) {
145 if ($name == 'last') {
146 if ($only_sent) {
147 $where = 'state = \'sent\' AND ';
148 } else {
149 $where = '';
150 }
151 $res = XDB::query('SELECT MAX(id)
152 FROM newsletter_issues
153 WHERE ' . $where . ' nlid = {?}',
154 $this->id);
155 } else {
156 $res = XDB::query('SELECT id
157 FROM newsletter_issues
158 WHERE nlid = {?} AND (id = {?} OR short_name = {?})',
159 $this->id, $name, $name);
160 }
161 if (!$res->numRows()) {
162 throw new MailNotFound();
163 }
164 $id = $res->fetchOneCell();
165 } else {
166 $query = XDB::format('SELECT id
167 FROM newsletter_issues
168 WHERE nlid = {?} AND state = \'new\'
169 ORDER BY id DESC', $this->id);
170 $res = XDB::query($query);
171 if ($res->numRows()) {
172 $id = $res->fetchOneCell();
173 } else {
174 // Create a new, empty issue, and return it
175 $id = $this->createPending();
176 }
177 }
178
179 return new NLIssue($id, $this);
180 }
181
182 /** Create a new, empty, pending newsletter issue
183 * @p $nlid The id of the NL for which a new pending issue should be created.
184 * @return Id of the newly created issue.
185 */
186 public function createPending()
187 {
188 XDB::execute('INSERT INTO newsletter_issues
189 SET nlid = {?}, state=\'new\', date=NOW(),
190 title=\'to be continued\',
191 mail_title=\'to be continued\'',
192 $this->id);
193 return XDB::insertId();
194 }
195
196 /** Return all sent issues of this newsletter.
197 * @return An array of (id => NLIssue)
198 */
199 public function listSentIssues($check_user = false, $user = null)
200 {
201 if ($check_user && $user == null) {
202 $user = S::user();
203 }
204
205 $res = XDB::query('SELECT id
206 FROM newsletter_issues
207 WHERE nlid = {?} AND state = \'sent\'
208 ORDER BY date DESC', $this->id);
209 $issues = array();
210 foreach ($res->fetchColumn() as $id) {
211 $issue = new NLIssue($id, $this, false);
212 if (!$check_user || $issue->checkUser($user)) {
213 $issues[$id] = $issue;
214 }
215 }
216 return $issues;
217 }
218
219 /** Return all issues of this newsletter, including invalid and sent.
220 * @return An array of (id => NLIssue)
221 */
222 public function listAllIssues()
223 {
224 $res = XDB::query('SELECT id
225 FROM newsletter_issues
226 WHERE nlid = {?}
227 ORDER BY FIELD(state, \'pending\', \'new\') DESC, date DESC', $this->id);
228 $issues = array();
229 foreach ($res->fetchColumn() as $id) {
230 $issues[$id] = new NLIssue($id, $this, false);
231 }
232 return $issues;
233 }
234
235 /** Return the latest pending issue of the newsletter.
236 * @p $create Whether to create an empty issue if no pending issue exist.
237 * @return Either null, or a NL object.
238 */
239 public function getPendingIssue($create = false)
240 {
241 $res = XDB::query('SELECT MAX(id)
242 FROM newsletter_issues
243 WHERE nlid = {?} AND state = \'new\'',
244 $this->id);
245 $id = $res->fetchOneCell();
246 if ($id != null) {
247 return new NLIssue($id, $this);
248 } else if ($create) {
249 $id = $this->createPending();
250 return new NLIssue($id, $this);
251 } else {
252 return null;
253 }
254 }
255
256 /** Returns a list of either issues or articles corresponding to the search.
257 * @p $search The searched pattern.
258 * @p $field The fields where to search, if none given, search in all possible fields.
259 * @return The list of object found.
260 */
261 public function issueSearch($search, $field, $user)
262 {
263 $search = XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $search);
264 if ($field == self::SEARCH_ALL) {
265 $where = '(title ' . $search . ' OR mail_title ' . $search . ' OR head ' . $search . ' OR signature ' . $search . ')';
266 } elseif ($field == self::SEARCH_TITLE) {
267 $where = '(title ' . $search . ' OR mail_title ' . $search . ')';
268 } else {
269 $where = $field . $search;
270 }
271 $list = XDB::fetchColumn('SELECT DISTINCT(id)
272 FROM newsletter_issues
273 WHERE nlid = {?} AND state = \'sent\' AND ' . $where . '
274 ORDER BY date DESC',
275 $this->id);
276
277 $issues = array();
278 foreach ($list as $id) {
279 $issue = new NLIssue($id, $this, false);
280 if ($issue->checkUser($user)) {
281 $issues[] = $issue;
282 }
283 }
284 return $issues;
285 }
286
287 public function articleSearch($search, $field, $user)
288 {
289 $search = XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $search);
290 if ($field == self::SEARCH_ALL) {
291 $where = '(a.title ' . $search . ' OR a.body ' . $search . ' OR a.append ' . $search . ')';
292 } else {
293 $where = 'a.' . $field . $search;
294 }
295 $list = XDB::fetchAllAssoc('SELECT i.short_name, a.aid, i.id, a.title
296 FROM newsletter_art AS a
297 INNER JOIN newsletter_issues AS i ON (a.id = i.id)
298 WHERE i.nlid = {?} AND i.state = \'sent\' AND ' . $where . '
299 GROUP BY a.id, a.aid
300 ORDER BY i.date DESC, a.aid',
301 $this->id);
302
303 $articles = array();
304 foreach ($list as $item) {
305 $issue = new NLIssue($item['id'], $this, false);
306 if ($issue->checkUser($user)) {
307 $articles[] = $item;
308 }
309 }
310 return $articles;
311 }
312
313 // }}}
314 // {{{ Subscription related function
315
316 /** Unsubscribe a user from this newsletter
317 * @p $uid UID to unsubscribe from the newsletter; if null, use current user.
318 * @p $hash True if the uid is actually a hash.
319 * @return True if the user was successfully unsubscribed.
320 */
321 public function unsubscribe($issue_id = null, $uid = null, $hash = false)
322 {
323 if (is_null($uid) && $hash) {
324 // Unable to unsubscribe from an empty hash
325 return false;
326 }
327 $user = is_null($uid) ? S::user()->id() : $uid;
328 $field = $hash ? 'hash' : 'uid';
329 $res = XDB::query('SELECT uid
330 FROM newsletter_ins
331 WHERE nlid = {?} AND ' . $field . ' = {?}',
332 $this->id, $user);
333 if (!$res->numRows()) {
334 // No subscribed user with that UID/hash
335 return false;
336 }
337 $user = $res->fetchOneCell();
338
339 XDB::execute('DELETE FROM newsletter_ins
340 WHERE nlid = {?} AND uid = {?}',
341 $this->id, $user);
342 if (!is_null($issue_id)) {
343 XDB::execute('UPDATE newsletter_issues
344 SET unsubscribe = unsubscribe + 1
345 WHERE id = {?}',
346 $id);
347 }
348 return true;
349 }
350
351 /** Subscribe a user to a newsletter
352 * @p $user User to subscribe to the newsletter; if null, use current user.
353 */
354 public function subscribe($user = null)
355 {
356 if (is_null($user)) {
357 $user = S::user();
358 }
359 if (self::maySubscribe($user)) {
360 XDB::execute('INSERT IGNORE INTO newsletter_ins (nlid, uid, last, hash)
361 VALUES ({?}, {?}, NULL, hash)',
362 $this->id, $user->id());
363 }
364 }
365
366 /** Subscribe a batch of users to a newsletter.
367 * This skips 'maySubscribe' test.
368 *
369 * @p $user_ids Array of user IDs to subscribe to the newsletter.
370 */
371 public function bulkSubscribe($user_ids)
372 {
373 // TODO: use a 'bulkMaySubscribe'.
374 XDB::execute('INSERT IGNORE INTO newsletter_ins (nlid, uid, last, hash)
375 SELECT {?}, a.uid, NULL, NULL
376 FROM accounts AS a
377 WHERE a.uid IN {?}',
378 $this->id, $user_ids);
379 }
380
381 /** Retrieve subscription state of a user
382 * @p $user Target user; if null, use current user.
383 * @return Boolean: true if the user has subscribed to the NL.
384 */
385 public function subscriptionState($user = null)
386 {
387 if (is_null($user)) {
388 $user = S::user();
389 }
390 $res = XDB::query('SELECT 1
391 FROM newsletter_ins
392 WHERE nlid = {?} AND uid = {?}',
393 $this->id, $user->id());
394 return ($res->numRows() == 1);
395 }
396
397 /** Get the count of subscribers to the NL.
398 * @return Number of subscribers.
399 */
400 public function subscriberCount($lost = null, $sex = null, $grade = null, $first_promo = null, $last_promo = null)
401 {
402 $cond = new PFC_And(new UFC_NLSubscribed($this->id));
403 if (!is_null($sex)) {
404 $cond->addChild(new UFC_Sex($sex));
405 }
406 if (!is_null($grade)) {
407 $cond->addChild(new UFC_Promo('>=', $grade, $first_promo));
408 $cond->addChild(new UFC_Promo('<=', $grade, $last_promo));
409 }
410 if (!($lost === null)) {
411 if ($lost === true) {
412 $cond->addChild(new PFC_Not(new UFC_HasEmailRedirect()));
413 } else {
414 $cond->addChild(new UFC_HasEmailRedirect());
415 }
416 }
417 $uf = new UserFilter($cond);
418 return $uf->getTotalCount();
419 }
420
421 /** Get the count of subscribers with non valid redirection.
422 */
423 public function lostSubscriberCount($sex = null)
424 {
425 return $this->subscriberCount(true, $sex);
426 }
427
428 /** Get the number of subscribers to the NL whose last received mailing was $last.
429 * @p $last ID of the issue for which subscribers should be counted.
430 * @return Number of subscribers
431 */
432 public function subscriberCountForLast($last)
433 {
434 return XDB::fetchOneCell('SELECT COUNT(uid)
435 FROM newsletter_ins
436 WHERE nlid = {?} AND last = {?}', $this->id, $last);
437 }
438
439 /** Retrieve the list of newsletters a user has subscribed to
440 * @p $user User whose subscriptions should be retrieved (if null, use session user).
441 * @return Array of newsletter IDs
442 */
443 public static function getUserSubscriptions($user = null)
444 {
445 if (is_null($user)) {
446 $user = S::user();
447 }
448 $res = XDB::query('SELECT nlid
449 FROM newsletter_ins
450 WHERE uid = {?}',
451 $user->id());
452 return $res->fetchColumn();
453 }
454
455 /** Retrieve the UserFilterBuilder for subscribers to this NL.
456 * This is the place where NL-specific filters may be allowed or prevented.
457 * @p $envprefix Prefix to use for env fields (cf. UserFilterBuilder)
458 * @return A UserFilterBuilder object using the given env prefix
459 */
460 public function getSubscribersUFB($envprefix = '')
461 {
462 require_once 'ufbuilder.inc.php';
463 return new UFB_NewsLetter($this->criteria, $envprefix);
464 }
465
466 // }}}
467 // {{{ Permissions related functions
468
469 /** For later use: check whether a given user may subscribe to this newsletter.
470 * @p $user User whose access should be checked
471 * @return Boolean: whether the user may subscribe to the NL.
472 */
473 public function maySubscribe($user = null)
474 {
475 return true;
476 }
477
478 /** Whether a given user may edit this newsletter
479 * @p $uid UID of the user whose perms should be checked (if null, use current user)
480 * @return Boolean: whether the user may edit the NL
481 */
482 public function mayEdit($user = null)
483 {
484 if (is_null($user)) {
485 $user = S::user();
486 }
487 if ($user->checkPerms('admin')) {
488 return true;
489 }
490 $res = XDB::query('SELECT perms
491 FROM group_members
492 WHERE asso_id = {?} AND uid = {?}',
493 $this->group_id, $user->id());
494 return ($res->numRows() && $res->fetchOneCell() == 'admin');
495 }
496
497 /** Whether a given user may submit articles to this newsletter using X.org validation system
498 * @p $user User whose access should be checked (if null, use current user)
499 * @return Boolean: whether the user may submit articles
500 */
501 public function maySubmit($user = null)
502 {
503 // Submission of new articles is only enabled for the X.org NL and the
504 // community letter (and forbidden when viewing issues on X.net)
505 return (
506 ($this->group == self::GROUP_XORG || $this->group == self::GROUP_COMMUNITY)
507 && !isset($GLOBALS['IS_XNET_SITE']));
508 }
509
510 // }}}
511 // {{{ Display-related functions: cssFile, tplFile, prefix, admin_prefix, admin_links_enabled, automatic_mailings_enabled
512
513 /** Get the name of the css file used to display this newsletter.
514 */
515 public function cssFile()
516 {
517 if ($this->hasCustomCss()) {
518 $base = $this->group;
519 } else {
520 $base = self::FORMAT_DEFAULT_GROUP;
521 }
522 return 'nl.' . $base . '.css';
523 }
524
525 /** Get the name of the template file used to display this newsletter.
526 */
527 public function tplFile()
528 {
529 if ($this->hasCustomCss()) {
530 $base = $this->group;
531 } else {
532 $base = self::FORMAT_DEFAULT_GROUP;
533 }
534 return 'newsletter/nl.' . $base . '.mail.tpl';
535 }
536
537 /** Get the prefix leading to the page for this NL
538 * Only X.org / AX / X groups may be seen on X.org.
539 */
540 public function prefix($enforce_xnet=true, $with_group=true)
541 {
542 if (!empty($GLOBALS['IS_XNET_SITE'])) {
543 if ($with_group) {
544 return $this->group . '/nl';
545 } else {
546 return 'nl';
547 }
548 }
549 switch ($this->group) {
550 case self::GROUP_XORG:
551 return 'nl';
552 case self::GROUP_COMMUNITY:
553 return 'comletter';
554 case self::GROUP_AX:
555 return 'ax';
556 case self::GROUP_EP:
557 return 'epletter';
558 case self::GROUP_FX:
559 return 'fxletter';
560 default:
561 // Don't display groups NLs on X.org
562 assert(!$enforce_xnet);
563 }
564 }
565
566 /** Get the prefix to use for all 'admin' pages of this NL.
567 */
568 public function adminPrefix($enforce_xnet=true, $with_group=true)
569 {
570 if (!empty($GLOBALS['IS_XNET_SITE'])) {
571 if ($with_group) {
572 return $this->group . '/admin/nl';
573 } else {
574 return 'admin/nl';
575 }
576 }
577 switch ($this->group) {
578 case self::GROUP_XORG:
579 return 'admin/newsletter';
580 case self::GROUP_COMMUNITY:
581 return 'comletter/admin';
582 case self::GROUP_AX:
583 return 'ax/admin';
584 case self::GROUP_EP:
585 return 'epletter/admin';
586 case self::GROUP_FX:
587 return 'fxletter/admin';
588 default:
589 // Don't display groups NLs on X.org
590 assert(!$enforce_xnet);
591 }
592 }
593
594 /** Get the prefix to use for all 'stat' pages of this NL.
595 */
596 public function statPrefix($enforce_xnet = true, $with_group = true)
597 {
598 if (!empty($GLOBALS['IS_XNET_SITE'])) {
599 if ($with_group) {
600 return $this->group . '/stat/nl';
601 } else {
602 return 'stat/nl';
603 }
604 }
605 switch ($this->group) {
606 case self::GROUP_XORG:
607 return 'stat/newsletter';
608 case self::GROUP_COMMUNITY:
609 return 'comletter/stat';
610 case self::GROUP_AX:
611 return 'ax/stat';
612 case self::GROUP_EP:
613 return 'epletter/stat';
614 case self::GROUP_FX:
615 return 'fxletter/stat';
616 default:
617 // Don't display groups NLs on X.org
618 assert(!$enforce_xnet);
619 }
620 }
621
622 /** Get links for nl pages.
623 */
624 public function adminLinks()
625 {
626 return array(
627 'index' => array('link' => $this->prefix(), 'title' => 'Archives'),
628 'admin' => array('link' => $this->adminPrefix(), 'title' => 'Administrer'),
629 'stats' => array('link' => $this->statPrefix(), 'title' => 'Statistiques')
630 );
631 }
632
633 /** Hack used to remove "admin" links on X.org page on X.net
634 * The 'admin' links are enabled for all pages, except for X.org when accessing NL through X.net
635 */
636 public function adminLinksEnabled()
637 {
638 return ($this->group != self::GROUP_XORG || !isset($GLOBALS['IS_XNET_SITE']));
639 }
640
641 /** Automatic mailings are disabled for X.org NL.
642 */
643 public function automaticMailingEnabled()
644 {
645 return $this->group != self::GROUP_XORG;
646 }
647
648 public function hasCustomCss()
649 {
650 switch ($this->group) {
651 case self::GROUP_XORG:
652 case self::GROUP_COMMUNITY:
653 case self::GROUP_AX:
654 case self::GROUP_EP:
655 case self::GROUP_FX:
656 return true;
657 default:
658 return false;
659 }
660 }
661
662 public function canSyncWithGroup()
663 {
664 switch ($this->group) {
665 case self::GROUP_XORG:
666 case self::GROUP_COMMUNITY:
667 case self::GROUP_AX:
668 case self::GROUP_EP:
669 case self::GROUP_FX:
670 return false;
671 default:
672 return true;
673 }
674 }
675
676 // }}}
677 }
678
679 // }}}
680
681 // {{{ class NLIssue
682
683 // A NLIssue is an issue of a given NewsLetter
684 class NLIssue
685 {
686 protected $nlid; // Id of the newsletter
687
688 const STATE_NEW = 'new'; // New, currently being edited
689 const STATE_PENDING = 'pending'; // Ready for mailing
690 const STATE_SENT = 'sent'; // Sent
691
692 public $nl; // Related NL
693
694 public $id; // Id of this issue of the newsletter
695 public $shortname; // Shortname for this issue
696 public $title; // Title of this issue
697 public $title_mail; // Title of the email
698 public $state; // State of the issue (one of the STATE_ values)
699 public $sufb; // Environment to use to generate the UFC through an UserFilterBuilder
700
701 public $date; // Date at which this issue was sent
702 public $send_before; // Date at which issue should be sent
703 public $head; // Foreword of the issue (or body for letters with no articles)
704 public $signature; // Signature of the letter
705 public $reply_to; // Adress to reply to the message (can be empty)
706 public $arts = array(); // Articles of the issue
707
708 const BATCH_SIZE = 60; // Number of emails to send every minute.
709
710 // {{{ Constructor, id-related functions
711
712 /** Build a NewsLetter.
713 * @p $id: ID of the issue (unique among all newsletters)
714 * @p $nl: Optional argument containing an already built NewsLetter object.
715 */
716 function __construct($id, $nl = null, $fetch_articles = true)
717 {
718 return $this->fetch($id, $nl, $fetch_articles);
719 }
720
721 protected function refresh()
722 {
723 return $this->fetch($this->id, $this->nl, false);
724 }
725
726 protected function fetch($id, $nl = null, $fetch_articles = true)
727 {
728 // Load this issue
729 $res = XDB::query('SELECT nlid, short_name, date, send_before, state, sufb_json,
730 title, mail_title, head, signature, reply_to
731 FROM newsletter_issues
732 WHERE id = {?}',
733 $id);
734 if (!$res->numRows()) {
735 throw new MailNotFound();
736 }
737 $issue = $res->fetchOneAssoc();
738 if ($nl && $nl->id == $issue['nlid']) {
739 $this->nl = $nl;
740 } else {
741 $this->nl = new NewsLetter($issue['nlid']);
742 }
743 $this->id = $id;
744 $this->nlid = $issue['nlid'];
745 $this->shortname = $issue['short_name'];
746 $this->date = $issue['date'];
747 $this->send_before = $issue['send_before'];
748 $this->state = $issue['state'];
749 $this->title = $issue['title'];
750 $this->title_mail = $issue['mail_title'];
751 $this->head = $issue['head'];
752 $this->signature = $issue['signature'];
753 $this->reply_to = $issue['reply_to'];
754 $this->sufb = $this->importJSonStoredUFB($issue['sufb_json']);
755
756 if ($fetch_articles) {
757 $this->fetchArticles();
758 }
759 }
760
761 protected function fetchArticles($force = false)
762 {
763 if (count($this->arts) && !$force) {
764 return;
765 }
766
767 // Load the articles
768 $res = XDB::iterRow(
769 'SELECT a.title, a.body, a.append, a.aid, a.cid, a.pos
770 FROM newsletter_art AS a
771 INNER JOIN newsletter_issues AS ni USING(id)
772 LEFT JOIN newsletter_cat AS c ON (a.cid = c.cid)
773 WHERE a.id = {?}
774 ORDER BY c.pos, a.pos',
775 $this->id);
776 while (list($title, $body, $append, $aid, $cid, $pos) = $res->next()) {
777 $this->arts[$cid][$aid] = new NLArticle($title, $body, $append, $aid, $cid, $pos);
778 }
779 }
780
781 protected function importJSonStoredUFB($json = null)
782 {
783 require_once 'ufbuilder.inc.php';
784 $ufb = $this->nl->getSubscribersUFB();
785 if (is_null($json)) {
786 return new StoredUserFilterBuilder($ufb, new PFC_True());
787 }
788 $export = json_decode($json, true);
789 if (is_null($export)) {
790 PlErrorReport::report("Invalid json while reading NL {$this->nlid}, issue {$this->id}: failed to import '''{$json}'''.");
791 return new StoredUserFilterBuilder($ufb, new PFC_True());
792 }
793 $sufb = new StoredUserFilterBuilder($ufb);
794 $sufb->fillFromExport($export);
795 return $sufb;
796 }
797
798 protected function exportStoredUFBAsJSon()
799 {
800 return json_encode($this->sufb->export());
801 }
802
803 public function id()
804 {
805 return is_null($this->shortname) ? $this->id : $this->shortname;
806 }
807
808 protected function selectId($where)
809 {
810 $res = XDB::query("SELECT IFNULL(ni.short_name, ni.id)
811 FROM newsletter_issues AS ni
812 WHERE ni.state != 'new' AND ni.nlid = {?} AND ${where}
813 LIMIT 1", $this->nl->id);
814 if ($res->numRows() != 1) {
815 return null;
816 }
817 return $res->fetchOneCell();
818 }
819
820 /** Delete this issue
821 * @return True if the issue could be deleted, false otherwise.
822 * Related articles will be deleted through cascading FKs.
823 * If this issue was the last issue for at least one subscriber, the deletion will be aborted.
824 */
825 public function delete()
826 {
827 if ($this->state == self::STATE_NEW) {
828 $res = XDB::query('SELECT COUNT(*)
829 FROM newsletter_ins
830 WHERE last = {?}', $this->id);
831 if ($res->fetchOneCell() > 0) {
832 return false;
833 }
834
835 return XDB::execute('DELETE FROM newsletter_issues
836 WHERE id = {?}', $this->id);
837 } else {
838 return false;
839 }
840 }
841
842 /** Schedule a mailing of this NL
843 * If the 'send_before' field was NULL, it is set to the current time.
844 * @return Boolean Whether the date could be set (false if trying to schedule an already sent NL)
845 */
846 public function scheduleMailing()
847 {
848 if ($this->state == self::STATE_NEW) {
849 $success = XDB::execute('UPDATE newsletter_issues
850 SET state = \'pending\', send_before = IFNULL(send_before, NOW())
851 WHERE id = {?}',
852 $this->id);
853 if ($success) {
854 global $globals;
855 $mailer = new PlMailer('newsletter/notify_scheduled.mail.tpl');
856 $mailer->assign('issue', $this);
857 $mailer->assign('base', $globals->baseurl);
858 $mailer->send();
859 $this->refresh();
860 }
861 return $success;
862 } else {
863 return false;
864 }
865 }
866
867 /** Cancel the scheduled mailing of this NL
868 * @return Boolean: whether the mailing could be cancelled.
869 */
870 public function cancelMailing()
871 {
872 if ($this->state == self::STATE_PENDING) {
873 $success = XDB::execute('UPDATE newsletter_issues
874 SET state = \'new\'
875 WHERE id = {?}', $this->id);
876 if ($success) {
877 $this->refresh();
878 }
879 return $success;
880 } else {
881 return false;
882 }
883 }
884
885 /** Helper function for smarty templates: is this issue editable ?
886 */
887 public function isEditable()
888 {
889 return $this->state == self::STATE_NEW;
890 }
891
892 /** Helper function for smarty templates: is the mailing of this issue scheduled ?
893 */
894 public function isPending()
895 {
896 return $this->state == self::STATE_PENDING;
897 }
898
899 /** Helper function for smarty templates: has this issue been sent ?
900 */
901 public function isSent()
902 {
903 return $this->state == self::STATE_SENT;
904 }
905
906 // }}}
907 // {{{ Navigation
908
909 private $id_prev = null;
910 private $id_next = null;
911 private $id_last = null;
912
913 /** Retrieve ID of the previous issue
914 * That value, once fetched, is cached in the private $id_prev variable.
915 * @return ID of the previous issue.
916 */
917 public function prev()
918 {
919 if (is_null($this->id_prev)) {
920 $this->id_prev = $this->selectId(XDB::format("ni.id < {?} ORDER BY ni.id DESC", $this->id));
921 }
922 return $this->id_prev;
923 }
924
925 /** Retrieve ID of the following issue
926 * That value, once fetched, is cached in the private $id_next variable.
927 * @return ID of the following issue.
928 */
929 public function next()
930 {
931 if (is_null($this->id_next)) {
932 $this->id_next = $this->selectId(XDB::format("ni.id > {?} ORDER BY ni.id", $this->id));
933 }
934 return $this->id_next;
935 }
936
937 /** Retrieve ID of the last issue
938 * That value, once fetched, is cached in the private $id_last variable.
939 * @return ID of the last issue.
940 */
941 public function last()
942 {
943 if (is_null($this->id_last)) {
944 try {
945 $this->id_last = $this->nl->getIssue('last')->id;
946 } catch (MailNotFound $e) {
947 $this->id_last = null;
948 }
949 }
950 return $this->id_last;
951 }
952
953 // }}}
954 // {{{ Edition, articles
955
956 const ERROR_INVALID_REPLY_TO = 'invalid_reply_to';
957 const ERROR_INVALID_SHORTNAME = 'invalid_shortname';
958 const ERROR_INVALID_UFC = 'invalid_ufc';
959 const ERROR_TOO_LONG_UFC = 'too_long_ufc';
960 const ERROR_SQL_SAVE = 'sql_error';
961
962 /** Save the global properties of this NL issue (title&co).
963 */
964 public function save()
965 {
966 $errors = array();
967
968 // Fill the list of fields to update
969 $fields = array(
970 'title' => $this->title,
971 'mail_title' => $this->title_mail,
972 'head' => $this->head,
973 'signature' => $this->signature,
974 );
975
976 if (!empty($this->reply_to) && !isvalid_email($this->reply_to)) {
977 $errors[] = self::ERROR_INVALID_REPLY_TO ;
978 } else {
979 $fields['reply_to'] = $this->reply_to;
980 }
981
982 if ($this->isEditable()) {
983 $fields['date'] = $this->date;
984 if (!preg_match('/^[-a-z0-9]+$/i', $this->shortname) || is_numeric($this->shortname)) {
985 $errors[] = self::ERROR_INVALID_SHORTNAME;
986 } else {
987 $fields['short_name'] = $this->shortname;
988 }
989 if ($this->sufb->isValid() || $this->sufb->isEmpty()) {
990 $fields['sufb_json'] = json_encode($this->sufb->export()->dict());
991 // If sufb_json is too long to be store, we do not store a truncated json and notify the user.
992 // The limit is LONGTEXT's one, ie 2^32 = 4294967296.
993 if (strlen($fields['sufb_json']) > 4294967295) {
994 $errors[] = self::ERROR_TOO_LONG_UFC;
995 }
996 } else {
997 $errors[] = self::ERROR_INVALID_UFC;
998 }
999
1000 if ($this->nl->automaticMailingEnabled()) {
1001 $fields['send_before'] = ($this->send_before ? $this->send_before : null);
1002 }
1003 }
1004
1005 if (count($errors)) {
1006 return $errors;
1007 }
1008 $field_sets = array();
1009 foreach ($fields as $key => $value) {
1010 $field_sets[] = XDB::format($key . ' = {?}', $value);
1011 }
1012 XDB::execute('UPDATE newsletter_issues
1013 SET ' . implode(', ', $field_sets) . '
1014 WHERE id={?}',
1015 $this->id);
1016 if (XDB::affectedRows()) {
1017 $this->refresh();
1018 } else {
1019 $errors[] = self::ERROR_SQL_SAVE;
1020 }
1021 return $errors;
1022 }
1023
1024 /** Get an article by number
1025 * @p $aid Article ID (among articles of the issue)
1026 * @return A NLArticle object, or null if there is no article by that number
1027 */
1028 public function getArt($aid)
1029 {
1030 $this->fetchArticles();
1031
1032 foreach ($this->arts as $category => $artlist) {
1033 if (isset($artlist[$aid])) {
1034 return $artlist[$aid];
1035 }
1036 }
1037 return null;
1038 }
1039
1040 /** Save an article
1041 * @p $a A reference to a NLArticle object (will be modified once saved)
1042 */
1043 public function saveArticle($a)
1044 {
1045 $this->fetchArticles();
1046
1047 // Prevent cid to be 0 (use NULL instead)
1048 $a->cid = ($a->cid == 0) ? null : $a->cid;
1049 if ($a->aid >= 0) {
1050 // Article already exists in DB
1051 XDB::execute('UPDATE newsletter_art
1052 SET cid = {?}, pos = {?}, title = {?}, body = {?}, append = {?}
1053 WHERE id = {?} AND aid = {?}',
1054 $a->cid, $a->pos, $a->title, $a->body, $a->append, $this->id, $a->aid);
1055 } else {
1056 // New article
1057 XDB::startTransaction();
1058 list($aid, $pos) = XDB::fetchOneRow('SELECT MAX(aid) AS aid, MAX(pos) AS pos
1059 FROM newsletter_art AS a
1060 WHERE a.id = {?}',
1061 $this->id);
1062 $a->aid = ++$aid;
1063 $a->pos = ($a->pos ? $a->pos : ++$pos);
1064 XDB::execute('INSERT INTO newsletter_art (id, aid, cid, pos, title, body, append)
1065 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
1066 $this->id, $a->aid, $a->cid, $a->pos,
1067 $a->title, $a->body, $a->append);
1068 XDB::commit();
1069 }
1070 // Update local ID of article
1071 $this->arts[$a->aid] = $a;
1072 }
1073
1074 /** Delete an article by its ID
1075 * @p $aid ID of the article to delete
1076 */
1077 public function delArticle($aid)
1078 {
1079 $this->fetchArticles();
1080
1081 XDB::execute('DELETE FROM newsletter_art WHERE id={?} AND aid={?}', $this->id, $aid);
1082 foreach ($this->arts as $key=>$art) {
1083 unset($this->arts[$key][$aid]);
1084 }
1085 }
1086
1087 // }}}
1088 // {{{ Display
1089
1090 /** Retrieve the title of this issue
1091 * @p $mail Whether we want the normal title or the email subject
1092 * @return Title of the issue
1093 */
1094 public function title($mail = false)
1095 {
1096 return $mail ? $this->title_mail : $this->title;
1097 }
1098
1099 /** Retrieve the head of this issue
1100 * @p $user User for <dear> customization (may be null: no customization)
1101 * @p $type Either 'text' or 'html'
1102 * @return Formatted head of the issue.
1103 */
1104 public function head($user = null, $type = 'text')
1105 {
1106 if (is_null($user)) {
1107 return $this->head;
1108 } else {
1109 $head = $this->head;
1110 $head = str_replace(array('<cher>', '<prenom>', '<nom>'),
1111 array(($user->isFemale() ? 'Chère' : 'Cher'), $user->displayName(), ''),
1112 $head);
1113 return format_text($head, $type, 2, 64);
1114 }
1115 }
1116
1117 /** Retrieve the formatted signature of this issue.
1118 */
1119 public function signature($type = 'text')
1120 {
1121 return format_text($this->signature, $type, 2, 64);
1122 }
1123
1124 /** Get the title of a given category
1125 * @p $cid ID of the category to retrieve
1126 * @return Name of the category
1127 */
1128 public function category($cid)
1129 {
1130 return $this->nl->cats[$cid];
1131 }
1132
1133 /** Add required data to the given $page for proper CSS display
1134 * @p $page Smarty object
1135 * @return Either 'true' (if CSS was added to a page) or the raw CSS to add (when $page is null)
1136 */
1137 public function css($page = null)
1138 {
1139 if (!is_null($page)) {
1140 $page->addCssLink($this->nl->cssFile());
1141 return true;
1142 } else {
1143 $css = file_get_contents(dirname(__FILE__) . '/../htdocs/css/' . $this->nl->cssFile());
1144 return preg_replace('@/\*.*?\*/@us', '', $css);
1145 }
1146 }
1147
1148 /** Set up a smarty page for a 'text' mode render of the issue
1149 * @p $page Smarty object (using the $this->nl->tplFile() template)
1150 * @p $user User to use when rendering the template
1151 */
1152 public function toText($page, $user)
1153 {
1154 $this->fetchArticles();
1155
1156 $this->css($page);
1157 $page->assign('prefix', null);
1158 $page->assign('is_mail', false);
1159 $page->assign('mail_part', 'text');
1160 $page->assign('user', $user);
1161 $page->assign('hash', null);
1162 $this->assignData($page);
1163 }
1164
1165 /** Set up a smarty page for a 'html' mode render of the issue
1166 * @p $page Smarty object (using the $this->nl->tplFile() template)
1167 * @p $user User to use when rendering the template
1168 */
1169 public function toHtml($page, $user)
1170 {
1171 $this->fetchArticles();
1172
1173 $this->css($page);
1174 $page->assign('prefix', $this->nl->prefix() . '/show/' . $this->id());
1175 $page->assign('is_mail', false);
1176 $page->assign('mail_part', 'html');
1177 $page->assign('user', $user);
1178 $page->assign('hash', null);
1179 $this->assignData($page);
1180 }
1181
1182 /** Set all 'common' data for the page (those which are required for both web and email rendering)
1183 * @p $smarty Smarty object (e.g page) which should be filled
1184 */
1185 protected function assignData($smarty)
1186 {
1187 $this->fetchArticles();
1188
1189 $smarty->assign_by_ref('issue', $this);
1190 $smarty->assign_by_ref('nl', $this->nl);
1191 }
1192
1193 // }}}
1194 // {{{ Mailing
1195
1196 /** Check whether this issue is empty
1197 * An issue is empty if the email has no title (or the default one), or no articles and an empty head.
1198 */
1199 public function isEmpty()
1200 {
1201 return $this->title_mail == '' || $this->title_mail == 'to be continued' || (count($this->arts) == 0 && strlen($this->head) == 0);
1202 }
1203
1204 /** Retrieve the 'Send before' date, in a clean format.
1205 */
1206 public function getSendBeforeDate()
1207 {
1208 return strftime('%Y-%m-%d', strtotime($this->send_before));
1209 }
1210
1211 /** Retrieve the 'Send before' time (i.e hour), in a clean format.
1212 */
1213 public function getSendBeforeTime()
1214 {
1215 return strtotime($this->send_before);
1216 }
1217
1218 /** Create a hash based on some additional data
1219 * $line Line-specific data (to prevent two hashes generated at the same time to be the same)
1220 */
1221 protected static function createHash($line)
1222 {
1223 $hash = implode(time(), $line) . rand();
1224 $hash = md5($hash);
1225 return $hash;
1226 }
1227
1228 /** Send this issue to the given user, reusing an existing hash if provided.
1229 * @p $user User to whom the issue should be mailed
1230 * @p $hash Optional hash to use in the 'unsubscribe' link; if null, another one will be generated.
1231 */
1232 public function sendTo($user, $hash = null)
1233 {
1234 // Don't send email to users without an address
1235 // Note: this would never happen when using sendToAll
1236 if (!$user->bestEmail()) {
1237 return;
1238 }
1239
1240 $this->fetchArticles();
1241
1242 if (is_null($hash)) {
1243 $hash = XDB::fetchOneCell("SELECT hash
1244 FROM newsletter_ins
1245 WHERE uid = {?} AND nlid = {?}",
1246 $user->id(), $this->nl->id);
1247 }
1248 if (is_null($hash)) {
1249 $hash = self::createHash(array($user->displayName(), $user->fullName(),
1250 $user->isFemale(), $user->isEmailFormatHtml(),
1251 rand(), "X.org rulez"));
1252 XDB::execute("UPDATE newsletter_ins as ni
1253 SET ni.hash = {?}
1254 WHERE ni.uid = {?} AND ni.nlid = {?}",
1255 $hash, $user->id(), $this->nl->id);
1256 }
1257
1258 $mailer = new PlMailer($this->nl->tplFile());
1259 $this->assignData($mailer);
1260 $mailer->assign('is_mail', true);
1261 $mailer->assign('user', $user);
1262 $mailer->assign('prefix', null);
1263 $mailer->assign('hash', $hash);
1264 if (!empty($this->reply_to)) {
1265 $mailer->addHeader('Reply-To', $this->reply_to);
1266 }
1267 $mailer->sendTo($user);
1268 }
1269
1270 /** Select a subset of subscribers which should receive the newsletter.
1271 * NL-Specific selections (not yet received, is subscribed) are done when sending.
1272 * @return A PlFilterCondition.
1273 */
1274 protected function getRecipientsUFC()
1275 {
1276 return $this->sufb->getUFC();
1277 }
1278
1279 /** Check whether a given user may see this issue.
1280 * @p $user User whose access should be checked
1281 * @return Whether he may access the issue
1282 */
1283 public function checkUser($user = null)
1284 {
1285 if ($user == null) {
1286 $user = S::user();
1287 }
1288 $uf = new UserFilter($this->getRecipientsUFC());
1289 return $uf->checkUser($user);
1290 }
1291
1292 /** Sent this issue to all valid recipients
1293 * @return Number of issues sent
1294 */
1295 public function sendToAll()
1296 {
1297 $this->fetchArticles();
1298
1299 XDB::execute('UPDATE newsletter_issues
1300 SET state = \'sent\', date=CURDATE()
1301 WHERE id = {?}',
1302 $this->id);
1303
1304 $ufc = new PFC_And($this->getRecipientsUFC(), new UFC_NLSubscribed($this->nl->id, $this->id), new UFC_HasValidEmail());
1305 $uf = new UserFilter($ufc, array(new UFO_IsAdmin(true), new UFO_Uid()));
1306 $limit = new PlLimit(self::BATCH_SIZE);
1307 $global_sent = array();
1308
1309 while (true) {
1310 $sent = array();
1311 $users = $uf->getUsers($limit);
1312 if (count($users) == 0) {
1313 break;
1314 }
1315 foreach ($users as $user) {
1316 if (array_key_exists($user->id(), $global_sent)) {
1317 Platal::page()->kill('Sending the same newsletter issue ' . $this->id . ' to user ' . $user->id() . ' twice, something must be wrong.');
1318 }
1319 $sent[] = $user->id();
1320 $global_sent[$user->id()] = true;
1321 $this->sendTo($user, $hash);
1322 }
1323 XDB::execute("UPDATE newsletter_ins
1324 SET last = {?}
1325 WHERE nlid = {?} AND uid IN {?}", $this->id, $this->nl->id, $sent);
1326
1327 sleep(60);
1328 }
1329 return count($global_sent);
1330 }
1331
1332 // }}}
1333 }
1334
1335 // }}}
1336 // {{{ class NLArticle
1337
1338 class NLArticle
1339 {
1340 // Maximum number of lines per article
1341 const MAX_LINES_PER_ARTICLE = 8;
1342 const MAX_CHARACTERS_PER_LINE = 68;
1343
1344 // {{{ properties
1345
1346 public $aid;
1347 public $cid;
1348 public $pos;
1349 public $title;
1350 public $body;
1351 public $append;
1352
1353 // }}}
1354 // {{{ constructor
1355
1356 function __construct($title='', $body='', $append='', $aid=-1, $cid=0, $pos=0)
1357 {
1358 $this->body = $body;
1359 $this->title = $title;
1360 $this->append = $append;
1361 $this->aid = $aid;
1362 $this->cid = $cid;
1363 $this->pos = $pos;
1364 }
1365
1366 // }}}
1367 // {{{ function title()
1368
1369 public function title()
1370 { return trim($this->title); }
1371
1372 // }}}
1373 // {{{ function body()
1374
1375 public function body()
1376 { return trim($this->body); }
1377
1378 // }}}
1379 // {{{ function append()
1380
1381 public function append()
1382 { return trim($this->append); }
1383
1384 // }}}
1385 // {{{ function toText()
1386
1387 public function toText($hash = null, $login = null)
1388 {
1389 $title = '*'.$this->title().'*';
1390 $body = MiniWiki::WikiToText($this->body, true);
1391 $app = MiniWiki::WikiToText($this->append, false, 4);
1392 $text = trim("$title\n\n$body\n\n$app")."\n";
1393 if (!is_null($hash) && !is_null($login)) {
1394 $text = str_replace('%HASH%', "$hash/$login", $text);
1395 } else {
1396 $text = str_replace('%HASH%', '', $text);
1397 }
1398 return $text;
1399 }
1400
1401 // }}}
1402 // {{{ function toHtml()
1403
1404 public function toHtml($hash = null, $login = null)
1405 {
1406 $title = "<h2 class='xorg_nl'><a id='art{$this->aid}'></a>".pl_entities($this->title()).'</h2>';
1407 $body = MiniWiki::WikiToHTML($this->body);
1408 $app = MiniWiki::WikiToHTML($this->append);
1409
1410 $art = "$title\n";
1411 $art .= "<div class='art'>\n$body\n";
1412 if ($app) {
1413 $art .= "<div class='app'>$app</div>";
1414 }
1415 $art .= "</div>\n";
1416 if (!is_null($hash) && !is_null($login)) {
1417 $art = str_replace('%HASH%', "$hash/$login", $art);
1418 } else {
1419 $art = str_replace('%HASH%', '', $art);
1420 }
1421
1422 return $art;
1423 }
1424
1425 // }}}
1426 // {{{ function check()
1427
1428 public function check()
1429 {
1430 $rest = $this->remain();
1431
1432 return $rest['remaining_lines'] >= 0;
1433 }
1434
1435 // }}}
1436 // {{{ function remain()
1437
1438 public function remain()
1439 {
1440 $text = MiniWiki::WikiToText($this->body);
1441 $array = explode("\n", wordwrap($text, self::MAX_CHARACTERS_PER_LINE));
1442 $lines_count = 0;
1443 foreach ($array as $line) {
1444 if (trim($line) != '') {
1445 ++$lines_count;
1446 }
1447 }
1448
1449 return array(
1450 'remaining_lines' => self::MAX_LINES_PER_ARTICLE - $lines_count,
1451 'remaining_characters_for_last_line' => self::MAX_CHARACTERS_PER_LINE - strlen($array[count($array) - 1])
1452 );
1453 }
1454 // }}}
1455 // {{{ function parseUrlsFromArticle()
1456
1457 protected function parseUrlsFromArticle()
1458 {
1459 $email_regex = '([a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+)';
1460 $url_regex = '((https?|ftp)://[a-zA-Z0-9._%#+/?=&~-]+)';
1461 $regex = '{' . $email_regex . '|' . $url_regex . '}i';
1462
1463 $matches = array();
1464 $body_matches = array();
1465 if (preg_match_all($regex, $this->body(), $body_matches)) {
1466 $matches = array_merge($matches, $body_matches[0]);
1467 }
1468
1469 $append_matches = array();
1470 if (preg_match_all($regex, $this->append(), $append_matches)) {
1471 $matches = array_merge($matches, $append_matches[0]);
1472 }
1473
1474 return $matches;
1475 }
1476
1477 // }}}
1478 // {{{ function getLinkIps()
1479
1480 public function getLinkIps(&$blacklist_host_resolution_count)
1481 {
1482 $matches = $this->parseUrlsFromArticle();
1483 $article_ips = array();
1484
1485 if (!empty($matches)) {
1486 global $globals;
1487
1488 foreach ($matches as $match) {
1489 $host = parse_url($match, PHP_URL_HOST);
1490 if ($host == '') {
1491 list(, $host) = explode('@', $match);
1492 }
1493
1494 if ($blacklist_host_resolution_count >= $globals->mail->blacklist_host_resolution_limit) {
1495 break;
1496 }
1497
1498 if (!preg_match('/^(' . str_replace(' ', '|', $globals->mail->domain_whitelist) . ')$/i', $host)) {
1499 $article_ips = array_merge($article_ips, array(gethostbyname($host) => $host));
1500 ++$blacklist_host_resolution_count;
1501 }
1502 }
1503 }
1504
1505 return $article_ips;
1506 }
1507
1508 // }}}
1509 }
1510
1511 // }}}
1512
1513 // {{{ Functions
1514
1515 function format_text($input, $format, $indent = 0, $width = 68)
1516 {
1517 if ($format == 'text') {
1518 return MiniWiki::WikiToText($input, true, $indent, $width, "title");
1519 }
1520 return MiniWiki::WikiToHTML($input, "title");
1521 }
1522
1523 // function enriched_to_text($input,$html=false,$just=false,$indent=0,$width=68)
1524
1525 // }}}
1526
1527 // vim:set et sw=4 sts=4 sws=4 fenc=utf-8:
1528 ?>