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 links for nl pages.
624 public function adminLinks()
627 'index' => array('link' => $this->prefix(), 'title' => 'Archives'),
628 'admin' => array('link' => $this->adminPrefix(), 'title' => 'Administrer'),
629 'stats' => array('link' => $this->statPrefix(), 'title' => 'Statistiques')
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
636 public function adminLinksEnabled()
638 return ($this->group
!= self
::GROUP_XORG ||
!isset($GLOBALS['IS_XNET_SITE']));
641 /** Automatic mailings are disabled for X.org NL.
643 public function automaticMailingEnabled()
645 return $this->group
!= self
::GROUP_XORG
;
648 public function hasCustomCss()
650 switch ($this->group
) {
651 case self
::GROUP_XORG
:
652 case self
::GROUP_COMMUNITY
:
662 public function canSyncWithGroup()
664 switch ($this->group
) {
665 case self
::GROUP_XORG
:
666 case self
::GROUP_COMMUNITY
:
683 // A NLIssue is an issue of a given NewsLetter
686 protected $nlid; // Id of the newsletter
688 const STATE_NEW
= 'new'; // New, currently being edited
689 const STATE_PENDING
= 'pending'; // Ready for mailing
690 const STATE_SENT
= 'sent'; // Sent
692 public $nl; // Related NL
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
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
708 const BATCH_SIZE
= 60; // Number of emails to send every minute.
710 // {{{ Constructor, id-related functions
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.
716 function __construct($id, $nl = null
, $fetch_articles = true
)
718 return $this->fetch($id, $nl, $fetch_articles);
721 protected function refresh()
723 return $this->fetch($this->id
, $this->nl
, false
);
726 protected function fetch($id, $nl = null
, $fetch_articles = true
)
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
734 if (!$res->numRows()) {
735 throw new MailNotFound();
737 $issue = $res->fetchOneAssoc();
738 if ($nl && $nl->id
== $issue['nlid']) {
741 $this->nl
= new NewsLetter($issue['nlid']);
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']);
756 if ($fetch_articles) {
757 $this->fetchArticles();
761 protected function fetchArticles($force = false
)
763 if (count($this->arts
) && !$force) {
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)
774 ORDER BY c.pos, a.pos',
776 while (list($title, $body, $append, $aid, $cid, $pos) = $res->next()) {
777 $this->arts
[$cid][$aid] = new NLArticle($title, $body, $append, $aid, $cid, $pos);
781 protected function importJSonStoredUFB($json = null
)
783 require_once 'ufbuilder.inc.php';
784 $ufb = $this->nl
->getSubscribersUFB();
785 if (is_null($json)) {
786 return new StoredUserFilterBuilder($ufb, new PFC_True());
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());
793 $sufb = new StoredUserFilterBuilder($ufb);
794 $sufb->fillFromExport($export);
798 protected function exportStoredUFBAsJSon()
800 return json_encode($this->sufb
->export());
805 return is_null($this->shortname
) ?
$this->id
: $this->shortname
;
808 protected function selectId($where)
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) {
817 return $res->fetchOneCell();
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.
825 public function delete()
827 if ($this->state
== self
::STATE_NEW
) {
828 $res = XDB
::query('SELECT COUNT(*)
830 WHERE last = {?}', $this->id
);
831 if ($res->fetchOneCell() > 0) {
835 return XDB
::execute('DELETE FROM newsletter_issues
836 WHERE id = {?}', $this->id
);
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)
846 public function scheduleMailing()
848 if ($this->state
== self
::STATE_NEW
) {
849 $success = XDB
::execute('UPDATE newsletter_issues
850 SET state = \'pending\', send_before = IFNULL(send_before, NOW())
855 $mailer = new PlMailer('newsletter/notify_scheduled.mail.tpl');
856 $mailer->assign('issue', $this);
857 $mailer->assign('base', $globals->baseurl
);
867 /** Cancel the scheduled mailing of this NL
868 * @return Boolean: whether the mailing could be cancelled.
870 public function cancelMailing()
872 if ($this->state
== self
::STATE_PENDING
) {
873 $success = XDB
::execute('UPDATE newsletter_issues
875 WHERE id = {?}', $this->id
);
885 /** Helper function for smarty templates: is this issue editable ?
887 public function isEditable()
889 return $this->state
== self
::STATE_NEW
;
892 /** Helper function for smarty templates: is the mailing of this issue scheduled ?
894 public function isPending()
896 return $this->state
== self
::STATE_PENDING
;
899 /** Helper function for smarty templates: has this issue been sent ?
901 public function isSent()
903 return $this->state
== self
::STATE_SENT
;
909 private $id_prev = null
;
910 private $id_next = null
;
911 private $id_last = null
;
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.
917 public function prev()
919 if (is_null($this->id_prev
)) {
920 $this->id_prev
= $this->selectId(XDB
::format("ni.id < {?} ORDER BY ni.id DESC", $this->id
));
922 return $this->id_prev
;
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.
929 public function next()
931 if (is_null($this->id_next
)) {
932 $this->id_next
= $this->selectId(XDB
::format("ni.id > {?} ORDER BY ni.id", $this->id
));
934 return $this->id_next
;
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.
941 public function last()
943 if (is_null($this->id_last
)) {
945 $this->id_last
= $this->nl
->getIssue('last')->id
;
946 } catch (MailNotFound
$e) {
947 $this->id_last
= null
;
950 return $this->id_last
;
954 // {{{ Edition, articles
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';
962 /** Save the global properties of this NL issue (title&co).
964 public function save()
968 // Fill the list of fields to update
970 'title' => $this->title
,
971 'mail_title' => $this->title_mail
,
972 'head' => $this->head
,
973 'signature' => $this->signature
,
976 if (!empty($this->reply_to
) && !isvalid_email($this->reply_to
)) {
977 $errors[] = self
::ERROR_INVALID_REPLY_TO
;
979 $fields['reply_to'] = $this->reply_to
;
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
;
987 $fields['short_name'] = $this->shortname
;
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
;
997 $errors[] = self
::ERROR_INVALID_UFC
;
1000 if ($this->nl
->automaticMailingEnabled()) {
1001 $fields['send_before'] = ($this->send_before ?
$this->send_before
: null
);
1005 if (count($errors)) {
1008 $field_sets = array();
1009 foreach ($fields as $key => $value) {
1010 $field_sets[] = XDB
::format($key . ' = {?}', $value);
1012 XDB
::execute('UPDATE newsletter_issues
1013 SET ' . implode(', ', $field_sets) . '
1016 if (XDB
::affectedRows()) {
1019 $errors[] = self
::ERROR_SQL_SAVE
;
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
1028 public function getArt($aid)
1030 $this->fetchArticles();
1032 foreach ($this->arts
as $category => $artlist) {
1033 if (isset($artlist[$aid])) {
1034 return $artlist[$aid];
1041 * @p $a A reference to a NLArticle object (will be modified once saved)
1043 public function saveArticle($a)
1045 $this->fetchArticles();
1047 // Prevent cid to be 0 (use NULL instead)
1048 $a->cid
= ($a->cid
== 0) ? null
: $a->cid
;
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
);
1057 XDB
::startTransaction();
1058 list($aid, $pos) = XDB
::fetchOneRow('SELECT MAX(aid) AS aid, MAX(pos) AS pos
1059 FROM newsletter_art AS a
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
);
1070 // Update local ID of article
1071 $this->arts
[$a->aid
] = $a;
1074 /** Delete an article by its ID
1075 * @p $aid ID of the article to delete
1077 public function delArticle($aid)
1079 $this->fetchArticles();
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]);
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
1094 public function title($mail = false
)
1096 return $mail ?
$this->title_mail
: $this->title
;
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.
1104 public function head($user = null
, $type = 'text')
1106 if (is_null($user)) {
1109 $head = $this->head
;
1110 $head = str_replace(array('<cher>', '<prenom>', '<nom>'),
1111 array(($user->isFemale() ?
'Chère' : 'Cher'), $user->displayName(), ''),
1113 return format_text($head, $type, 2, 64);
1117 /** Retrieve the formatted signature of this issue.
1119 public function signature($type = 'text')
1121 return format_text($this->signature
, $type, 2, 64);
1124 /** Get the title of a given category
1125 * @p $cid ID of the category to retrieve
1126 * @return Name of the category
1128 public function category($cid)
1130 return $this->nl
->cats
[$cid];
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)
1137 public function css($page = null
)
1139 if (!is_null($page)) {
1140 $page->addCssLink($this->nl
->cssFile());
1143 $css = file_get_contents(dirname(__FILE__
) . '/../htdocs/css/' . $this->nl
->cssFile());
1144 return preg_replace('@/\*.*?\*/@us', '', $css);
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
1152 public function toText($page, $user)
1154 $this->fetchArticles();
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);
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
1169 public function toHtml($page, $user)
1171 $this->fetchArticles();
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);
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
1185 protected function assignData($smarty)
1187 $this->fetchArticles();
1189 $smarty->assign_by_ref('issue', $this);
1190 $smarty->assign_by_ref('nl', $this->nl
);
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.
1199 public function isEmpty()
1201 return $this->title_mail
== '' ||
$this->title_mail
== 'to be continued' ||
(count($this->arts
) == 0 && strlen($this->head
) == 0);
1204 /** Retrieve the 'Send before' date, in a clean format.
1206 public function getSendBeforeDate()
1208 return strftime('%Y-%m-%d', strtotime($this->send_before
));
1211 /** Retrieve the 'Send before' time (i.e hour), in a clean format.
1213 public function getSendBeforeTime()
1215 return strtotime($this->send_before
);
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)
1221 protected static function createHash($line)
1223 $hash = implode(time(), $line) . rand();
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.
1232 public function sendTo($user, $hash = null
)
1234 // Don't send email to users without an address
1235 // Note: this would never happen when using sendToAll
1236 if (!$user->bestEmail()) {
1240 $this->fetchArticles();
1242 if (is_null($hash)) {
1243 $hash = XDB
::fetchOneCell("SELECT hash
1245 WHERE uid = {?} AND nlid = {?}",
1246 $user->id(), $this->nl
->id
);
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
1254 WHERE ni.uid = {?} AND ni.nlid = {?}",
1255 $hash, $user->id(), $this->nl
->id
);
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
);
1267 $mailer->sendTo($user);
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.
1274 protected function getRecipientsUFC()
1276 return $this->sufb
->getUFC();
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
1283 public function checkUser($user = null
)
1285 if ($user == null
) {
1288 $uf = new UserFilter($this->getRecipientsUFC());
1289 return $uf->checkUser($user);
1292 /** Sent this issue to all valid recipients
1293 * @return Number of issues sent
1295 public function sendToAll()
1297 $this->fetchArticles();
1299 XDB
::execute('UPDATE newsletter_issues
1300 SET state = \'sent\', date=CURDATE()
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();
1311 $users = $uf->getUsers($limit);
1312 if (count($users) == 0) {
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.');
1319 $sent[] = $user->id();
1320 $global_sent[$user->id()] = true
;
1321 $this->sendTo($user, $hash);
1323 XDB
::execute("UPDATE newsletter_ins
1325 WHERE nlid = {?} AND uid IN {?}", $this->id
, $this->nl
->id
, $sent);
1329 return count($global_sent);
1336 // {{{ class NLArticle
1340 // Maximum number of lines per article
1341 const MAX_LINES_PER_ARTICLE
= 8;
1342 const MAX_CHARACTERS_PER_LINE
= 68;
1356 function __construct($title='', $body='', $append='', $aid=-1, $cid=0, $pos=0)
1358 $this->body
= $body;
1359 $this->title
= $title;
1360 $this->append
= $append;
1367 // {{{ function title()
1369 public function title()
1370 { return trim($this->title
); }
1373 // {{{ function body()
1375 public function body()
1376 { return trim($this->body
); }
1379 // {{{ function append()
1381 public function append()
1382 { return trim($this->append
); }
1385 // {{{ function toText()
1387 public function toText($hash = null
, $login = null
)
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);
1396 $text = str_replace('%HASH%', '', $text);
1402 // {{{ function toHtml()
1404 public function toHtml($hash = null
, $login = null
)
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
);
1411 $art .= "<div class='art'>\n$body\n";
1413 $art .= "<div class='app'>$app</div>";
1416 if (!is_null($hash) && !is_null($login)) {
1417 $art = str_replace('%HASH%', "$hash/$login", $art);
1419 $art = str_replace('%HASH%', '', $art);
1426 // {{{ function check()
1428 public function check()
1430 $rest = $this->remain();
1432 return $rest['remaining_lines'] >= 0;
1436 // {{{ function remain()
1438 public function remain()
1440 $text = MiniWiki
::WikiToText($this->body
);
1441 $array = explode("\n", wordwrap($text, self
::MAX_CHARACTERS_PER_LINE
));
1443 foreach ($array as $line) {
1444 if (trim($line) != '') {
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])
1455 // {{{ function parseUrlsFromArticle()
1457 protected function parseUrlsFromArticle()
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';
1464 $body_matches = array();
1465 if (preg_match_all($regex, $this->body(), $body_matches)) {
1466 $matches = array_merge($matches, $body_matches[0]);
1469 $append_matches = array();
1470 if (preg_match_all($regex, $this->append(), $append_matches)) {
1471 $matches = array_merge($matches, $append_matches[0]);
1478 // {{{ function getLinkIps()
1480 public function getLinkIps(&$blacklist_host_resolution_count)
1482 $matches = $this->parseUrlsFromArticle();
1483 $article_ips = array();
1485 if (!empty($matches)) {
1488 foreach ($matches as $match) {
1489 $host = parse_url($match, PHP_URL_HOST
);
1491 list(, $host) = explode('@', $match);
1494 if ($blacklist_host_resolution_count >= $globals->mail
->blacklist_host_resolution_limit
) {
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;
1505 return $article_ips;
1515 function format_text($input, $format, $indent = 0, $width = 68)
1517 if ($format == 'text') {
1518 return MiniWiki
::WikiToText($input, true
, $indent, $width, "title");
1520 return MiniWiki
::WikiToHTML($input, "title");
1523 // function enriched_to_text($input,$html=false,$just=false,$indent=0,$width=68)
1527 // vim:set et sw=4 sts=4 sws=4 fenc=utf-8: