2 /***************************************************************************
3 * Copyright (C) 2003-2014 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 // {{{ class MailNotFound
24 class MailNotFound
extends Exception
{
29 // {{{ class NewsLetter
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
40 // Base name to use instead of the group short name for NLs without a custom CSS
41 const FORMAT_DEFAULT_GROUP
= 'default';
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';
50 // Searches on mutiple fields
51 const SEARCH_ALL
= 'all';
52 const SEARCH_TITLE
= 'title';
55 // {{{ Constructor, NewsLetter retrieval (forGroup, getAll)
57 public function __construct($id)
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)
66 if (!$res->numRows()) {
67 throw new MailNotFound();
70 $data = $res->fetchOneAssoc();
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']);
77 // Load the categories
83 while (list($cid, $title) = $res->next()) {
84 $this->cats
[$cid] = $title;
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.
92 public static function forGroup($group)
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()) {
101 return new NewsLetter($res->fetchOneCell());
104 /** Retrieve all newsletters
105 * @return An array of $id => NewsLetter objects
107 public static function getAll($sort = 'id', $order = 'ASC')
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);
117 // {{{ Issue retrieval
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)
122 public static function getIssuesToSend()
124 $res = XDB
::query('SELECT id
125 FROM newsletter_issues
126 WHERE state = \'pending\' AND send_before <= NOW()');
128 foreach ($res->fetchColumn() as $id) {
129 $issues[$id] = new NLIssue($id);
134 /** Retrieve a given issue of this NewsLetter
135 * @p $name Name or ID of the issue to retrieve.
136 * @return A NLIssue object.
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.
142 public function getIssue($name = null
, $only_sent = true
)
145 if ($name == 'last') {
147 $where = 'state = \'sent\' AND ';
151 $res = XDB
::query('SELECT MAX(id)
152 FROM newsletter_issues
153 WHERE ' . $where . ' nlid = {?}',
156 $res = XDB
::query('SELECT id
157 FROM newsletter_issues
158 WHERE nlid = {?} AND (id = {?} OR short_name = {?})',
159 $this->id
, $name, $name);
161 if (!$res->numRows()) {
162 throw new MailNotFound();
164 $id = $res->fetchOneCell();
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();
174 // Create a new, empty issue, and return it
175 $id = $this->createPending();
179 return new NLIssue($id, $this);
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.
186 public function createPending()
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\'',
193 return XDB
::insertId();
196 /** Return all sent issues of this newsletter.
197 * @return An array of (id => NLIssue)
199 public function listSentIssues($check_user = false
, $user = null
)
201 if ($check_user && $user == null
) {
205 $res = XDB
::query('SELECT id
206 FROM newsletter_issues
207 WHERE nlid = {?} AND state = \'sent\'
208 ORDER BY date DESC', $this->id
);
210 foreach ($res->fetchColumn() as $id) {
211 $issue = new NLIssue($id, $this, false
);
212 if (!$check_user ||
$issue->checkUser($user)) {
213 $issues[$id] = $issue;
219 /** Return all issues of this newsletter, including invalid and sent.
220 * @return An array of (id => NLIssue)
222 public function listAllIssues()
224 $res = XDB
::query('SELECT id
225 FROM newsletter_issues
227 ORDER BY FIELD(state, \'pending\', \'new\') DESC, date DESC', $this->id
);
229 foreach ($res->fetchColumn() as $id) {
230 $issues[$id] = new NLIssue($id, $this, false
);
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.
239 public function getPendingIssue($create = false
)
241 $res = XDB
::query('SELECT MAX(id)
242 FROM newsletter_issues
243 WHERE nlid = {?} AND state = \'new\'',
245 $id = $res->fetchOneCell();
247 return new NLIssue($id, $this);
248 } else if ($create) {
249 $id = $this->createPending();
250 return new NLIssue($id, $this);
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.
261 public function issueSearch($search, $field, $user)
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 . ')';
269 $where = $field . $search;
271 $list = XDB
::fetchColumn('SELECT DISTINCT(id)
272 FROM newsletter_issues
273 WHERE nlid = {?} AND state = \'sent\' AND ' . $where . '
278 foreach ($list as $id) {
279 $issue = new NLIssue($id, $this, false
);
280 if ($issue->checkUser($user)) {
287 public function articleSearch($search, $field, $user)
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 . ')';
293 $where = 'a.' . $field . $search;
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 . '
300 ORDER BY i.date DESC, a.aid',
304 foreach ($list as $item) {
305 $issue = new NLIssue($item['id'], $this, false
);
306 if ($issue->checkUser($user)) {
314 // {{{ Subscription related function
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.
321 public function unsubscribe($issue_id = null
, $uid = null
, $hash = false
)
323 if (is_null($uid) && $hash) {
324 // Unable to unsubscribe from an empty hash
327 $user = is_null($uid) ? S
::user()->id() : $uid;
328 $field = $hash ?
'hash' : 'uid';
329 $res = XDB
::query('SELECT uid
331 WHERE nlid = {?} AND ' . $field . ' = {?}',
333 if (!$res->numRows()) {
334 // No subscribed user with that UID/hash
337 $user = $res->fetchOneCell();
339 XDB
::execute('DELETE FROM newsletter_ins
340 WHERE nlid = {?} AND uid = {?}',
342 if (!is_null($issue_id)) {
343 XDB
::execute('UPDATE newsletter_issues
344 SET unsubscribe = unsubscribe + 1
351 /** Subscribe a user to a newsletter
352 * @p $user User to subscribe to the newsletter; if null, use current user.
354 public function subscribe($user = null
)
356 if (is_null($user)) {
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());
366 /** Subscribe a batch of users to a newsletter.
367 * This skips 'maySubscribe' test.
369 * @p $user_ids Array of user IDs to subscribe to the newsletter.
371 public function bulkSubscribe($user_ids)
373 // TODO: use a 'bulkMaySubscribe'.
374 XDB
::execute('INSERT IGNORE INTO newsletter_ins (nlid, uid, last, hash)
375 SELECT {?}, a.uid, NULL, NULL
378 $this->id
, $user_ids);
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.
385 public function subscriptionState($user = null
)
387 if (is_null($user)) {
390 $res = XDB
::query('SELECT 1
392 WHERE nlid = {?} AND uid = {?}',
393 $this->id
, $user->id());
394 return ($res->numRows() == 1);
397 /** Get the count of subscribers to the NL.
398 * @return Number of subscribers.
400 public function subscriberCount($lost = null
, $sex = null
, $grade = null
, $first_promo = null
, $last_promo = null
)
402 $cond = new PFC_And(new UFC_NLSubscribed($this->id
));
403 if (!is_null($sex)) {
404 $cond->addChild(new UFC_Sex($sex));
406 if (!is_null($grade)) {
407 $cond->addChild(new UFC_Promo('>=', $grade, $first_promo));
408 $cond->addChild(new UFC_Promo('<=', $grade, $last_promo));
410 if (!($lost === null
)) {
411 if ($lost === true
) {
412 $cond->addChild(new PFC_Not(new UFC_HasEmailRedirect()));
414 $cond->addChild(new UFC_HasEmailRedirect());
417 $uf = new UserFilter($cond);
418 return $uf->getTotalCount();
421 /** Get the count of subscribers with non valid redirection.
423 public function lostSubscriberCount($sex = null
)
425 return $this->subscriberCount(true
, $sex);
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
432 public function subscriberCountForLast($last)
434 return XDB
::fetchOneCell('SELECT COUNT(uid)
436 WHERE nlid = {?} AND last = {?}', $this->id
, $last);
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
443 public static function getUserSubscriptions($user = null
)
445 if (is_null($user)) {
448 $res = XDB
::query('SELECT nlid
452 return $res->fetchColumn();
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
460 public function getSubscribersUFB($envprefix = '')
462 require_once 'ufbuilder.inc.php';
463 return new UFB_NewsLetter($this->criteria
, $envprefix);
467 // {{{ Permissions related functions
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.
473 public function maySubscribe($user = null
)
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
482 public function mayEdit($user = null
)
484 if (is_null($user)) {
487 if ($user->checkPerms('admin')) {
490 $res = XDB
::query('SELECT perms
492 WHERE asso_id = {?} AND uid = {?}',
493 $this->group_id
, $user->id());
494 return ($res->numRows() && $res->fetchOneCell() == 'admin');
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
501 public function maySubmit($user = null
)
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)
506 ($this->group
== self
::GROUP_XORG ||
$this->group
== self
::GROUP_COMMUNITY
)
507 && !isset($GLOBALS['IS_XNET_SITE']));
511 // {{{ Display-related functions: cssFile, tplFile, prefix, admin_prefix, admin_links_enabled, automatic_mailings_enabled
513 /** Get the name of the css file used to display this newsletter.
515 public function cssFile()
517 if ($this->hasCustomCss()) {
518 $base = $this->group
;
520 $base = self
::FORMAT_DEFAULT_GROUP
;
522 return 'nl.' . $base . '.css';
525 /** Get the name of the template file used to display this newsletter.
527 public function tplFile()
529 if ($this->hasCustomCss()) {
530 $base = $this->group
;
532 $base = self
::FORMAT_DEFAULT_GROUP
;
534 return 'newsletter/nl.' . $base . '.mail.tpl';
537 /** Get the prefix leading to the page for this NL
538 * Only X.org / AX / X groups may be seen on X.org.
540 public function prefix($enforce_xnet=true
, $with_group=true
)
542 if (!empty($GLOBALS['IS_XNET_SITE'])) {
544 return $this->group
. '/nl';
549 switch ($this->group
) {
550 case self
::GROUP_XORG
:
552 case self
::GROUP_COMMUNITY
:
561 // Don't display groups NLs on X.org
562 assert(!$enforce_xnet);
566 /** Get the prefix to use for all 'admin' pages of this NL.
568 public function adminPrefix($enforce_xnet=true
, $with_group=true
)
570 if (!empty($GLOBALS['IS_XNET_SITE'])) {
572 return $this->group
. '/admin/nl';
577 switch ($this->group
) {
578 case self
::GROUP_XORG
:
579 return 'admin/newsletter';
580 case self
::GROUP_COMMUNITY
:
581 return 'comletter/admin';
585 return 'epletter/admin';
587 return 'fxletter/admin';
589 // Don't display groups NLs on X.org
590 assert(!$enforce_xnet);
594 /** Get the prefix to use for all 'stat' pages of this NL.
596 public function statPrefix($enforce_xnet = true
, $with_group = true
)
598 if (!empty($GLOBALS['IS_XNET_SITE'])) {
600 return $this->group
. '/stat/nl';
605 switch ($this->group
) {
606 case self
::GROUP_XORG
:
607 return 'stat/newsletter';
608 case self
::GROUP_COMMUNITY
:
609 return 'comletter/stat';
613 return 'epletter/stat';
615 return 'fxletter/stat';
617 // Don't display groups NLs on X.org
618 assert(!$enforce_xnet);
622 /** Get a full URL to a newsletter
624 public function fullUrl()
626 switch ($this->group
) {
627 case self
::GROUP_XORG
:
628 return 'https://www.polytechnique.org/nl';
629 case self
::GROUP_COMMUNITY
:
630 return 'https://www.polytechnique.org/comletter';
632 return 'https://www.polytechnique.org/ax';
634 return 'https://www.polytechnique.org/epletter';
636 return 'https://www.polytechnique.org/fxletter';
638 return 'http://www.polytechnique.net/' . $this->group
. '/nl';
642 /** Get links for nl pages.
644 public function adminLinks()
647 'index' => array('link' => $this->prefix(), 'title' => 'Archives'),
648 'admin' => array('link' => $this->adminPrefix(), 'title' => 'Administrer'),
649 'stats' => array('link' => $this->statPrefix(), 'title' => 'Statistiques')
653 /** Hack used to remove "admin" links on X.org page on X.net
654 * The 'admin' links are enabled for all pages, except for X.org when accessing NL through X.net
656 public function adminLinksEnabled()
658 return ($this->group
!= self
::GROUP_XORG ||
!isset($GLOBALS['IS_XNET_SITE']));
661 /** Automatic mailings are disabled for X.org NL.
663 public function automaticMailingEnabled()
665 return $this->group
!= self
::GROUP_XORG
;
668 public function hasCustomCss()
670 switch ($this->group
) {
671 case self
::GROUP_XORG
:
672 case self
::GROUP_COMMUNITY
:
682 public function canSyncWithGroup()
684 switch ($this->group
) {
685 case self
::GROUP_XORG
:
686 case self
::GROUP_COMMUNITY
:
703 // A NLIssue is an issue of a given NewsLetter
706 protected $nlid; // Id of the newsletter
708 const STATE_NEW
= 'new'; // New, currently being edited
709 const STATE_PENDING
= 'pending'; // Ready for mailing
710 const STATE_SENT
= 'sent'; // Sent
712 public $nl; // Related NL
714 public $id; // Id of this issue of the newsletter
715 public $shortname; // Shortname for this issue
716 public $title; // Title of this issue
717 public $title_mail; // Title of the email
718 public $state; // State of the issue (one of the STATE_ values)
719 public $sufb; // Environment to use to generate the UFC through an UserFilterBuilder
721 public $date; // Date at which this issue was sent
722 public $send_before; // Date at which issue should be sent
723 public $head; // Foreword of the issue (or body for letters with no articles)
724 public $signature; // Signature of the letter
725 public $reply_to; // Adress to reply to the message (can be empty)
726 public $arts = array(); // Articles of the issue
728 const BATCH_SIZE
= 60; // Number of emails to send every minute.
730 // {{{ Constructor, id-related functions
732 /** Build a NewsLetter.
733 * @p $id: ID of the issue (unique among all newsletters)
734 * @p $nl: Optional argument containing an already built NewsLetter object.
736 function __construct($id, $nl = null
, $fetch_articles = true
)
738 return $this->fetch($id, $nl, $fetch_articles);
741 protected function refresh()
743 return $this->fetch($this->id
, $this->nl
, false
);
746 protected function fetch($id, $nl = null
, $fetch_articles = true
)
749 $res = XDB
::query('SELECT nlid, short_name, date, send_before, state, sufb_json,
750 title, mail_title, head, signature, reply_to
751 FROM newsletter_issues
754 if (!$res->numRows()) {
755 throw new MailNotFound();
757 $issue = $res->fetchOneAssoc();
758 if ($nl && $nl->id
== $issue['nlid']) {
761 $this->nl
= new NewsLetter($issue['nlid']);
764 $this->nlid
= $issue['nlid'];
765 $this->shortname
= $issue['short_name'];
766 $this->date
= $issue['date'];
767 $this->send_before
= $issue['send_before'];
768 $this->state
= $issue['state'];
769 $this->title
= $issue['title'];
770 $this->title_mail
= $issue['mail_title'];
771 $this->head
= $issue['head'];
772 $this->signature
= $issue['signature'];
773 $this->reply_to
= $issue['reply_to'];
774 $this->sufb
= $this->importJSonStoredUFB($issue['sufb_json']);
776 if ($fetch_articles) {
777 $this->fetchArticles();
781 protected function fetchArticles($force = false
)
783 if (count($this->arts
) && !$force) {
789 'SELECT a.title, a.body, a.append, a.aid, a.cid, a.pos
790 FROM newsletter_art AS a
791 INNER JOIN newsletter_issues AS ni USING(id)
792 LEFT JOIN newsletter_cat AS c ON (a.cid = c.cid)
794 ORDER BY c.pos, a.pos',
796 while (list($title, $body, $append, $aid, $cid, $pos) = $res->next()) {
797 $this->arts
[$cid][$aid] = new NLArticle($title, $body, $append, $aid, $cid, $pos);
801 protected function importJSonStoredUFB($json = null
)
803 require_once 'ufbuilder.inc.php';
804 $ufb = $this->nl
->getSubscribersUFB();
805 if (is_null($json)) {
806 return new StoredUserFilterBuilder($ufb, new PFC_True());
808 $export = json_decode($json, true
);
809 if (is_null($export)) {
810 PlErrorReport
::report("Invalid json while reading NL {$this->nlid}, issue {$this->id}: failed to import '''{$json}'''.");
811 return new StoredUserFilterBuilder($ufb, new PFC_True());
813 $sufb = new StoredUserFilterBuilder($ufb);
814 $sufb->fillFromExport($export);
818 protected function exportStoredUFBAsJSon()
820 return json_encode($this->sufb
->export());
825 return is_null($this->shortname
) ?
$this->id
: $this->shortname
;
828 protected function selectId($where)
830 $res = XDB
::query("SELECT IFNULL(ni.short_name, ni.id)
831 FROM newsletter_issues AS ni
832 WHERE ni.state != 'new' AND ni.nlid = {?} AND ${where}
833 LIMIT 1", $this->nl
->id
);
834 if ($res->numRows() != 1) {
837 return $res->fetchOneCell();
840 /** Delete this issue
841 * @return True if the issue could be deleted, false otherwise.
842 * Related articles will be deleted through cascading FKs.
843 * If this issue was the last issue for at least one subscriber, the deletion will be aborted.
845 public function delete()
847 if ($this->state
== self
::STATE_NEW
) {
848 $res = XDB
::query('SELECT COUNT(*)
850 WHERE last = {?}', $this->id
);
851 if ($res->fetchOneCell() > 0) {
855 return XDB
::execute('DELETE FROM newsletter_issues
856 WHERE id = {?}', $this->id
);
862 /** Schedule a mailing of this NL
863 * If the 'send_before' field was NULL, it is set to the current time.
864 * @return Boolean Whether the date could be set (false if trying to schedule an already sent NL)
866 public function scheduleMailing()
868 if ($this->state
== self
::STATE_NEW
) {
869 $success = XDB
::execute('UPDATE newsletter_issues
870 SET state = \'pending\', send_before = IFNULL(send_before, NOW())
875 $mailer = new PlMailer('newsletter/notify_scheduled.mail.tpl');
876 $mailer->assign('issue', $this);
877 $mailer->assign('base', $globals->baseurl
);
887 /** Cancel the scheduled mailing of this NL
888 * @return Boolean: whether the mailing could be cancelled.
890 public function cancelMailing()
892 if ($this->state
== self
::STATE_PENDING
) {
893 $success = XDB
::execute('UPDATE newsletter_issues
895 WHERE id = {?}', $this->id
);
905 /** Helper function for smarty templates: is this issue editable ?
907 public function isEditable()
909 return $this->state
== self
::STATE_NEW
;
912 /** Helper function for smarty templates: is the mailing of this issue scheduled ?
914 public function isPending()
916 return $this->state
== self
::STATE_PENDING
;
919 /** Helper function for smarty templates: has this issue been sent ?
921 public function isSent()
923 return $this->state
== self
::STATE_SENT
;
929 private $id_prev = null
;
930 private $id_next = null
;
931 private $id_last = null
;
933 /** Retrieve ID of the previous issue
934 * That value, once fetched, is cached in the private $id_prev variable.
935 * @return ID of the previous issue.
937 public function prev()
939 if (is_null($this->id_prev
)) {
940 $this->id_prev
= $this->selectId(XDB
::format("ni.id < {?} ORDER BY ni.id DESC", $this->id
));
942 return $this->id_prev
;
945 /** Retrieve ID of the following issue
946 * That value, once fetched, is cached in the private $id_next variable.
947 * @return ID of the following issue.
949 public function next()
951 if (is_null($this->id_next
)) {
952 $this->id_next
= $this->selectId(XDB
::format("ni.id > {?} ORDER BY ni.id", $this->id
));
954 return $this->id_next
;
957 /** Retrieve ID of the last issue
958 * That value, once fetched, is cached in the private $id_last variable.
959 * @return ID of the last issue.
961 public function last()
963 if (is_null($this->id_last
)) {
965 $this->id_last
= $this->nl
->getIssue('last')->id
;
966 } catch (MailNotFound
$e) {
967 $this->id_last
= null
;
970 return $this->id_last
;
974 // {{{ Edition, articles
976 const ERROR_INVALID_REPLY_TO
= 'invalid_reply_to';
977 const ERROR_INVALID_SHORTNAME
= 'invalid_shortname';
978 const ERROR_INVALID_UFC
= 'invalid_ufc';
979 const ERROR_TOO_LONG_UFC
= 'too_long_ufc';
980 const ERROR_SQL_SAVE
= 'sql_error';
982 /** Save the global properties of this NL issue (title&co).
984 public function save()
988 // Fill the list of fields to update
990 'title' => $this->title
,
991 'mail_title' => $this->title_mail
,
992 'head' => $this->head
,
993 'signature' => $this->signature
,
996 if (!empty($this->reply_to
) && !isvalid_email($this->reply_to
)) {
997 $errors[] = self
::ERROR_INVALID_REPLY_TO
;
999 $fields['reply_to'] = $this->reply_to
;
1002 if ($this->isEditable()) {
1003 $fields['date'] = $this->date
;
1004 if (!preg_match('/^[-a-z0-9]+$/i', $this->shortname
) ||
is_numeric($this->shortname
)) {
1005 $errors[] = self
::ERROR_INVALID_SHORTNAME
;
1007 $fields['short_name'] = $this->shortname
;
1009 if ($this->sufb
->isValid() ||
$this->sufb
->isEmpty()) {
1010 $fields['sufb_json'] = json_encode($this->sufb
->export()->dict());
1011 // If sufb_json is too long to be store, we do not store a truncated json and notify the user.
1012 // The limit is LONGTEXT's one, ie 2^32 = 4294967296.
1013 if (strlen($fields['sufb_json']) > 4294967295) {
1014 $errors[] = self
::ERROR_TOO_LONG_UFC
;
1017 $errors[] = self
::ERROR_INVALID_UFC
;
1020 if ($this->nl
->automaticMailingEnabled()) {
1021 $fields['send_before'] = ($this->send_before ?
$this->send_before
: null
);
1025 if (count($errors)) {
1028 $field_sets = array();
1029 foreach ($fields as $key => $value) {
1030 $field_sets[] = XDB
::format($key . ' = {?}', $value);
1032 XDB
::execute('UPDATE newsletter_issues
1033 SET ' . implode(', ', $field_sets) . '
1036 if (XDB
::affectedRows()) {
1039 $errors[] = self
::ERROR_SQL_SAVE
;
1044 /** Get an article by number
1045 * @p $aid Article ID (among articles of the issue)
1046 * @return A NLArticle object, or null if there is no article by that number
1048 public function getArt($aid)
1050 $this->fetchArticles();
1052 foreach ($this->arts
as $category => $artlist) {
1053 if (isset($artlist[$aid])) {
1054 return $artlist[$aid];
1061 * @p $a A reference to a NLArticle object (will be modified once saved)
1063 public function saveArticle($a)
1065 $this->fetchArticles();
1067 // Prevent cid to be 0 (use NULL instead)
1068 $a->cid
= ($a->cid
== 0) ? null
: $a->cid
;
1070 // Article already exists in DB
1071 XDB
::execute('UPDATE newsletter_art
1072 SET cid = {?}, pos = {?}, title = {?}, body = {?}, append = {?}
1073 WHERE id = {?} AND aid = {?}',
1074 $a->cid
, $a->pos
, $a->title
, $a->body
, $a->append
, $this->id
, $a->aid
);
1077 XDB
::startTransaction();
1078 list($aid, $pos) = XDB
::fetchOneRow('SELECT MAX(aid) AS aid, MAX(pos) AS pos
1079 FROM newsletter_art AS a
1083 $a->pos
= ($a->pos ?
$a->pos
: ++
$pos);
1084 XDB
::execute('INSERT INTO newsletter_art (id, aid, cid, pos, title, body, append)
1085 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
1086 $this->id
, $a->aid
, $a->cid
, $a->pos
,
1087 $a->title
, $a->body
, $a->append
);
1090 // Update local ID of article
1091 $this->arts
[$a->aid
] = $a;
1094 /** Delete an article by its ID
1095 * @p $aid ID of the article to delete
1097 public function delArticle($aid)
1099 $this->fetchArticles();
1101 XDB
::execute('DELETE FROM newsletter_art WHERE id={?} AND aid={?}', $this->id
, $aid);
1102 foreach ($this->arts
as $key=>$art) {
1103 unset($this->arts
[$key][$aid]);
1110 /** Retrieve the title of this issue
1111 * @p $mail Whether we want the normal title or the email subject
1112 * @return Title of the issue
1114 public function title($mail = false
)
1116 return $mail ?
$this->title_mail
: $this->title
;
1119 /** Retrieve the head of this issue
1120 * @p $user User for <dear> customization (may be null: no customization)
1121 * @p $type Either 'text' or 'html'
1122 * @return Formatted head of the issue.
1124 public function head($user = null
, $type = 'text')
1126 if (is_null($user)) {
1129 $head = $this->head
;
1130 $head = str_replace(array('<cher>', '<prenom>', '<nom>'),
1131 array(($user->isFemale() ?
'Chère' : 'Cher'), $user->displayName(), ''),
1133 return format_text($head, $type, 2, 64);
1137 /** Retrieve the formatted signature of this issue.
1139 public function signature($type = 'text')
1141 return format_text($this->signature
, $type, 2, 64);
1144 /** Get the title of a given category
1145 * @p $cid ID of the category to retrieve
1146 * @return Name of the category
1148 public function category($cid)
1150 return $this->nl
->cats
[$cid];
1153 /** Add required data to the given $page for proper CSS display
1154 * @p $page Smarty object
1155 * @return Either 'true' (if CSS was added to a page) or the raw CSS to add (when $page is null)
1157 public function css($page = null
)
1159 if (!is_null($page)) {
1160 $page->addCssLink($this->nl
->cssFile());
1163 $css = file_get_contents(dirname(__FILE__
) . '/../htdocs/css/' . $this->nl
->cssFile());
1164 return preg_replace('@/\*.*?\*/@us', '', $css);
1168 /** Set up a smarty page for a 'text' mode render of the issue
1169 * @p $page Smarty object (using the $this->nl->tplFile() template)
1170 * @p $user User to use when rendering the template
1172 public function toText($page, $user)
1174 $this->fetchArticles();
1177 $page->assign('prefix', null
);
1178 $page->assign('is_mail', false
);
1179 $page->assign('mail_part', 'text');
1180 $page->assign('user', $user);
1181 $page->assign('hash', null
);
1182 $this->assignData($page);
1185 /** Set up a smarty page for a 'html' mode render of the issue
1186 * @p $page Smarty object (using the $this->nl->tplFile() template)
1187 * @p $user User to use when rendering the template
1189 public function toHtml($page, $user)
1191 $this->fetchArticles();
1194 $page->assign('prefix', $this->nl
->prefix() . '/show/' . $this->id());
1195 $page->assign('is_mail', false
);
1196 $page->assign('mail_part', 'html');
1197 $page->assign('user', $user);
1198 $page->assign('hash', null
);
1199 $this->assignData($page);
1202 /** Set all 'common' data for the page (those which are required for both web and email rendering)
1203 * @p $smarty Smarty object (e.g page) which should be filled
1205 protected function assignData($smarty)
1207 $this->fetchArticles();
1209 $smarty->assign_by_ref('issue', $this);
1210 $smarty->assign_by_ref('nl', $this->nl
);
1216 /** Check whether this issue is empty
1217 * An issue is empty if the email has no title (or the default one), or no articles and an empty head.
1219 public function isEmpty()
1221 return $this->title_mail
== '' ||
$this->title_mail
== 'to be continued' ||
(count($this->arts
) == 0 && strlen($this->head
) == 0);
1224 /** Retrieve the 'Send before' date, in a clean format.
1226 public function getSendBeforeDate()
1228 return strftime('%Y-%m-%d', strtotime($this->send_before
));
1231 /** Retrieve the 'Send before' time (i.e hour), in a clean format.
1233 public function getSendBeforeTime()
1235 return strtotime($this->send_before
);
1238 /** Create a hash based on some additional data
1239 * $line Line-specific data (to prevent two hashes generated at the same time to be the same)
1241 protected static function createHash($line)
1243 $hash = implode(time(), $line) . rand();
1248 /** Send this issue to the given user, reusing an existing hash if provided.
1249 * @p $user User to whom the issue should be mailed
1250 * @p $hash Optional hash to use in the 'unsubscribe' link; if null, another one will be generated.
1252 public function sendTo($user, $hash = null
)
1256 // Don't send email to users without an address
1257 // Note: this would never happen when using sendToAll
1258 if (!$user->bestEmail()) {
1262 $this->fetchArticles();
1264 if (is_null($hash)) {
1265 $hash = XDB
::fetchOneCell("SELECT hash
1267 WHERE uid = {?} AND nlid = {?}",
1268 $user->id(), $this->nl
->id
);
1270 if (is_null($hash)) {
1271 $hash = self
::createHash(array($user->displayName(), $user->fullName(),
1272 $user->isFemale(), $user->isEmailFormatHtml(),
1273 rand(), "X.org rulez"));
1274 XDB
::execute("UPDATE newsletter_ins as ni
1276 WHERE ni.uid = {?} AND ni.nlid = {?}",
1277 $hash, $user->id(), $this->nl
->id
);
1280 $mailer = new PlMailer($this->nl
->tplFile());
1281 $this->assignData($mailer);
1282 $mailer->assign('is_mail', true
);
1283 $mailer->assign('user', $user);
1284 $mailer->assign('prefix', null
);
1285 $mailer->assign('hash', $hash);
1286 if (!empty($this->reply_to
)) {
1287 $mailer->addHeader('Reply-To', $this->reply_to
);
1290 // Add mailing list headers
1291 // Note: "Precedence: bulk" is known to cause issues on some clients
1292 $mailer->addHeader('Precedence', 'list');
1294 $mailer->addHeader('List-Id', $this->nl
->group
.
1295 ' <' . $this->nl
->group
. '.newsletter.' . $globals->mail
->domain
. '>');
1297 $listurl = $this->nl
->fullUrl();
1298 $mailer->addHeader('List-Unsubscribe', '<' . $listurl . '/out/nohash/' . $this->id
. '>');
1299 $mailer->addHeader('List-Subscribe', '<' . $listurl. '/in/nohash/' . $this->id
. '>');
1300 $mailer->addHeader('List-Archive', '<' . $listurl . '>');
1301 $mailer->addHeader('List-Help', '<' . $listurl . '>');
1302 $mailer->addHeader('List-Owner', '<mailto:support@' . $globals->mail
->domain
. '>');
1304 $mailer->sendTo($user);
1307 /** Select a subset of subscribers which should receive the newsletter.
1308 * NL-Specific selections (not yet received, is subscribed) are done when sending.
1309 * @return A PlFilterCondition.
1311 protected function getRecipientsUFC()
1313 return $this->sufb
->getUFC();
1316 /** Check whether a given user may see this issue.
1317 * @p $user User whose access should be checked
1318 * @return Whether he may access the issue
1320 public function checkUser($user = null
)
1322 if ($user == null
) {
1325 $uf = new UserFilter($this->getRecipientsUFC());
1326 return $uf->checkUser($user);
1329 /** Sent this issue to all valid recipients
1330 * @return Number of issues sent
1332 public function sendToAll()
1334 $this->fetchArticles();
1336 XDB
::execute('UPDATE newsletter_issues
1337 SET state = \'sent\', date=CURDATE()
1341 // Every minute, select BATCH_SIZE users who:
1342 // * are subscribed to the newsletter
1343 // * have not yet been mailed this issue of the newsletter
1344 // * have a valid email address
1345 // ... and send them the current issue.
1346 // Once a mail is sent, newsletter_ins is updated to prevent selecting again the same user a minute later.
1347 $ufc = new PFC_And($this->getRecipientsUFC(), new UFC_NLSubscribed($this->nl
->id
, $this->id
), new UFC_HasValidEmail());
1348 $uf = new UserFilter($ufc, array(new UFO_IsAdmin(true
), new UFO_Uid()));
1349 $limit = new PlLimit(self
::BATCH_SIZE
);
1350 $global_sent = array();
1353 $users = $uf->getUsers($limit);
1354 if (count($users) == 0) {
1357 foreach ($users as $user) {
1358 if (array_key_exists($user->id(), $global_sent)) {
1359 // Such a condition may happen if an user:
1360 // 1. was mailed the issue,
1361 // 2. unsubscribed the newsletter,
1362 // 3. subscribed again before the sending was done.
1363 // Such a case is reported by mail to people who monitor the website.
1364 // If you are reading this comment because of such a mail and the lines above explain what happened,
1365 // you only need to reset the state of the issue to "pending".
1366 // A cron script will then restart the mailing from where it stopped and only the problematic user will reveive the issue twice.
1367 Platal
::page()->kill('Sending the same newsletter issue ' . $this->id
. ' to user ' . $user->id() . ' twice, something must be wrong.');
1369 $sent[] = $user->id();
1370 $global_sent[$user->id()] = true
;
1371 $this->sendTo($user, $hash);
1373 XDB
::execute("UPDATE newsletter_ins
1375 WHERE nlid = {?} AND uid IN {?}", $this->id
, $this->nl
->id
, $sent);
1379 return count($global_sent);
1386 // {{{ class NLArticle
1390 // Maximum number of lines per article
1391 const MAX_LINES_PER_ARTICLE
= 8;
1392 const MAX_CHARACTERS_PER_LINE
= 68;
1406 function __construct($title='', $body='', $append='', $aid=-1, $cid=0, $pos=0)
1408 $this->body
= $body;
1409 $this->title
= $title;
1410 $this->append
= $append;
1417 // {{{ function title()
1419 public function title()
1420 { return trim($this->title
); }
1423 // {{{ function body()
1425 public function body()
1426 { return trim($this->body
); }
1429 // {{{ function append()
1431 public function append()
1432 { return trim($this->append
); }
1435 // {{{ function toText()
1437 public function toText($hash = null
, $login = null
)
1439 $title = '*'.$this->title().'*';
1440 $body = MiniWiki
::WikiToText($this->body
, true
);
1441 $app = MiniWiki
::WikiToText($this->append
, false
, 4);
1442 $text = trim("$title\n\n$body\n\n$app")."\n";
1443 if (!is_null($hash) && !is_null($login)) {
1444 $text = str_replace('%HASH%', "$hash/$login", $text);
1446 $text = str_replace('%HASH%', '', $text);
1452 // {{{ function toHtml()
1454 public function toHtml($hash = null
, $login = null
)
1456 $title = "<h2 class='xorg_nl'><a id='art{$this->aid}'></a>".pl_entities($this->title()).'</h2>';
1457 $body = MiniWiki
::WikiToHTML($this->body
);
1458 $app = MiniWiki
::WikiToHTML($this->append
);
1461 $art .= "<div class='art'>\n$body\n";
1463 $art .= "<div class='app'>$app</div>";
1466 if (!is_null($hash) && !is_null($login)) {
1467 $art = str_replace('%HASH%', "$hash/$login", $art);
1469 $art = str_replace('%HASH%', '', $art);
1476 // {{{ function check()
1478 public function check()
1480 $rest = $this->remain();
1482 return $rest['remaining_lines'] >= 0;
1486 // {{{ function remain()
1488 public function remain()
1490 $text = MiniWiki
::WikiToText($this->body
);
1491 $array = explode("\n", wordwrap($text, self
::MAX_CHARACTERS_PER_LINE
));
1493 foreach ($array as $line) {
1494 if (trim($line) != '') {
1500 'remaining_lines' => self
::MAX_LINES_PER_ARTICLE
- $lines_count,
1501 'remaining_characters_for_last_line' => self
::MAX_CHARACTERS_PER_LINE
- strlen($array[count($array) - 1])
1505 // {{{ function parseUrlsFromArticle()
1507 protected function parseUrlsFromArticle()
1509 $email_regex = '([a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+)';
1510 $url_regex = '((https?|ftp)://[a-zA-Z0-9._%#+/?=&~-]+)';
1511 $regex = '{' . $email_regex . '|' . $url_regex . '}i';
1514 $body_matches = array();
1515 if (preg_match_all($regex, $this->body(), $body_matches)) {
1516 $matches = array_merge($matches, $body_matches[0]);
1519 $append_matches = array();
1520 if (preg_match_all($regex, $this->append(), $append_matches)) {
1521 $matches = array_merge($matches, $append_matches[0]);
1528 // {{{ function getLinkIps()
1530 public function getLinkIps(&$blacklist_host_resolution_count)
1532 $matches = $this->parseUrlsFromArticle();
1533 $article_ips = array();
1535 if (!empty($matches)) {
1538 foreach ($matches as $match) {
1539 $host = parse_url($match, PHP_URL_HOST
);
1541 list(, $host) = explode('@', $match);
1544 if ($blacklist_host_resolution_count >= $globals->mail
->blacklist_host_resolution_limit
) {
1548 if (!preg_match('/^(' . str_replace(' ', '|', $globals->mail
->domain_whitelist
) . ')$/i', $host)) {
1549 $article_ips = array_merge($article_ips, array(gethostbyname($host) => $host));
1550 ++
$blacklist_host_resolution_count;
1555 return $article_ips;
1565 function format_text($input, $format, $indent = 0, $width = 68)
1567 if ($format == 'text') {
1568 return MiniWiki
::WikiToText($input, true
, $indent, $width, "title");
1570 return MiniWiki
::WikiToHTML($input, "title");
1573 // function enriched_to_text($input,$html=false,$just=false,$indent=0,$width=68)
1577 // vim:set et sw=4 sts=4 sws=4 fenc=utf-8: