2 /***************************************************************************
3 * Copyright (C) 2003-2011 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 protected $custom_css = false
;
42 // Base name to use instead of the group short name for NLs without a custom CSS
43 const FORMAT_DEFAULT_GROUP
= 'default';
45 // Diminutif of X.net groups with a specific NL view
46 const GROUP_XORG
= 'Polytechnique.org';
47 const GROUP_AX
= 'AX';
48 const GROUP_EP
= 'Ecole';
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.custom_css, 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->custom_css
= $data['custom_css'];
76 $this->criteria
= new PlFlagSet($data['criteria']);
78 // Load the categories
84 while (list($cid, $title) = $res->next()) {
85 $this->cats
[$cid] = $title;
89 /** Retrieve the NL associated with a given group.
90 * @p $group Short name of the group
91 * @return A NewsLetter object, or null if the group doesn't have a NL.
93 public static function forGroup($group)
95 $res = XDB
::query('SELECT nls.id
96 FROM newsletters AS nls
97 LEFT JOIN groups AS g ON (nls.group_id = g.id)
98 WHERE g.diminutif = {?}', $group);
99 if (!$res->numRows()) {
102 return new NewsLetter($res->fetchOneCell());
105 /** Retrieve all newsletters
106 * @return An array of $id => NewsLetter objects
108 public static function getAll($sort = 'id', $order = 'ASC')
110 $res = XDB
::fetchAllAssoc('SELECT n.id, g.nom AS group_name, n.name, n.custom_css, n.criteria, g.diminutif AS group_link
111 FROM newsletters AS n
112 INNER JOIN groups AS g ON (n.group_id = g.id)
113 ORDER BY ' . $sort . ' ' . $order);
118 // {{{ Issue retrieval
120 /** Retrieve all issues which should be sent
121 * @return An array of NLIssue objects to send (i.e state = 'new' and send_before <= today)
123 public static function getIssuesToSend()
125 $res = XDB
::query('SELECT id
126 FROM newsletter_issues
127 WHERE state = \'pending\' AND send_before <= NOW()');
129 foreach ($res->fetchColumn() as $id) {
130 $issues[$id] = new NLIssue($id);
135 /** Retrieve a given issue of this NewsLetter
136 * @p $name Name or ID of the issue to retrieve.
137 * @return A NLIssue object.
139 * $name may be either a short_name, an ID or the special value 'last' which
140 * selects the latest sent NL.
141 * If $name is null, this will retrieve the current pending NL.
143 public function getIssue($name = null
, $only_sent = true
)
146 if ($name == 'last') {
148 $where = 'state = \'sent\' AND ';
152 $res = XDB
::query('SELECT MAX(id)
153 FROM newsletter_issues
154 WHERE ' . $where . ' nlid = {?}',
157 $res = XDB
::query('SELECT id
158 FROM newsletter_issues
159 WHERE nlid = {?} AND (id = {?} OR short_name = {?})',
160 $this->id
, $name, $name);
162 if (!$res->numRows()) {
163 throw new MailNotFound();
165 $id = $res->fetchOneCell();
167 $query = XDB
::format('SELECT id
168 FROM newsletter_issues
169 WHERE nlid = {?} AND state = \'new\'
170 ORDER BY id DESC', $this->id
);
171 $res = XDB
::query($query);
172 if ($res->numRows()) {
173 $id = $res->fetchOneCell();
175 // Create a new, empty issue, and return it
176 $id = $this->createPending();
180 return new NLIssue($id, $this);
183 /** Create a new, empty, pending newsletter issue
184 * @p $nlid The id of the NL for which a new pending issue should be created.
185 * @return Id of the newly created issue.
187 public function createPending()
189 XDB
::execute('INSERT INTO newsletter_issues
190 SET nlid = {?}, state=\'new\', date=NOW(),
191 title=\'to be continued\',
192 mail_title=\'to be continued\'',
194 return XDB
::insertId();
197 /** Return all sent issues of this newsletter.
198 * @return An array of (id => NLIssue)
200 public function listSentIssues($check_user = false
, $user = null
)
202 if ($check_user && $user == null
) {
206 $res = XDB
::query('SELECT id
207 FROM newsletter_issues
208 WHERE nlid = {?} AND state = \'sent\'
209 ORDER BY date DESC', $this->id
);
211 foreach ($res->fetchColumn() as $id) {
212 $issue = new NLIssue($id, $this, false
);
213 if (!$check_user ||
$issue->checkUser($user)) {
214 $issues[$id] = $issue;
220 /** Return all issues of this newsletter, including invalid and sent.
221 * @return An array of (id => NLIssue)
223 public function listAllIssues()
225 $res = XDB
::query('SELECT id
226 FROM newsletter_issues
228 ORDER BY FIELD(state, \'pending\', \'new\') DESC, date DESC', $this->id
);
230 foreach ($res->fetchColumn() as $id) {
231 $issues[$id] = new NLIssue($id, $this, false
);
236 /** Return the latest pending issue of the newsletter.
237 * @p $create Whether to create an empty issue if no pending issue exist.
238 * @return Either null, or a NL object.
240 public function getPendingIssue($create = false
)
242 $res = XDB
::query('SELECT MAX(id)
243 FROM newsletter_issues
244 WHERE nlid = {?} AND state = \'new\'',
246 $id = $res->fetchOneCell();
248 return new NLIssue($id, $this);
249 } else if ($create) {
250 $id = $this->createPending();
251 return new NLIssue($id, $this);
257 /** Returns a list of either issues or articles corresponding to the search.
258 * @p $search The searched pattern.
259 * @p $field The fields where to search, if none given, search in all possible fields.
260 * @return The list of object found.
262 public function issueSearch($search, $field, $user)
264 $search = XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $search);
265 if ($field == self
::SEARCH_ALL
) {
266 $where = '(title ' . $search . ' OR mail_title ' . $search . ' OR head ' . $search . ' OR signature ' . $search . ')';
267 } elseif ($field == self
::SEARCH_TITLE
) {
268 $where = '(title ' . $search . ' OR mail_title ' . $search . ')';
270 $where = $field . $search;
272 $list = XDB
::fetchColumn('SELECT DISTINCT(id)
273 FROM newsletter_issues
274 WHERE nlid = {?} AND state = \'sent\' AND ' . $where . '
279 foreach ($list as $id) {
280 $issue = new NLIssue($id, $this, false
);
281 if ($issue->checkUser($user)) {
288 public function articleSearch($search, $field, $user)
290 $search = XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $search);
291 if ($field == self
::SEARCH_ALL
) {
292 $where = '(a.title ' . $search . ' OR a.body ' . $search . ' OR a.append ' . $search . ')';
294 $where = 'a.' . $field . $search;
296 $list = XDB
::fetchAllAssoc('SELECT i.short_name, a.aid, i.id, a.title
297 FROM newsletter_art AS a
298 INNER JOIN newsletter_issues AS i ON (a.id = i.id)
299 WHERE i.nlid = {?} AND i.state = \'sent\' AND ' . $where . '
301 ORDER BY i.date DESC, a.aid',
305 foreach ($list as $item) {
306 $issue = new NLIssue($item['id'], $this, false
);
307 if ($issue->checkUser($user)) {
315 // {{{ Subscription related function
317 /** Unsubscribe a user from this newsletter
318 * @p $uid UID to unsubscribe from the newsletter; if null, use current user.
319 * @p $hash True if the uid is actually a hash.
320 * @return True if the user was successfully unsubscribed.
322 public function unsubscribe($issue_id = null
, $uid = null
, $hash = false
)
324 if (is_null($uid) && $hash) {
325 // Unable to unsubscribe from an empty hash
328 $user = is_null($uid) ? S
::user()->id() : $uid;
329 $field = $hash ?
'hash' : 'uid';
330 $res = XDB
::query('SELECT uid
332 WHERE nlid = {?} AND ' . $field . ' = {?}',
334 if (!$res->numRows()) {
335 // No subscribed user with that UID/hash
338 $user = $res->fetchOneCell();
340 XDB
::execute('DELETE FROM newsletter_ins
341 WHERE nlid = {?} AND uid = {?}',
343 if (!is_null($issue_id)) {
344 XDB
::execute('UPDATE newsletter_issues
345 SET unsubscribe = unsubscribe + 1
352 /** Subscribe a user to a newsletter
353 * @p $user User to subscribe to the newsletter; if null, use current user.
355 public function subscribe($user = null
)
357 if (is_null($user)) {
360 if (self
::maySubscribe($user)) {
361 XDB
::execute('INSERT IGNORE INTO newsletter_ins (nlid, uid, last, hash)
362 VALUES ({?}, {?}, NULL, hash)',
363 $this->id
, $user->id());
367 /** Subscribe a batch of users to a newsletter.
368 * This skips 'maySubscribe' test.
370 * @p $user_ids Array of user IDs to subscribe to the newsletter.
372 public function bulkSubscribe($user_ids)
374 // TODO: use a 'bulkMaySubscribe'.
375 XDB
::execute('INSERT IGNORE INTO newsletter_ins (nlid, uid, last, hash)
376 SELECT {?}, a.uid, NULL, NULL
379 $this->id
, $user_ids);
382 /** Retrieve subscription state of a user
383 * @p $user Target user; if null, use current user.
384 * @return Boolean: true if the user has subscribed to the NL.
386 public function subscriptionState($user = null
)
388 if (is_null($user)) {
391 $res = XDB
::query('SELECT 1
393 WHERE nlid = {?} AND uid = {?}',
394 $this->id
, $user->id());
395 return ($res->numRows() == 1);
398 /** Get the count of subscribers to the NL.
399 * @return Number of subscribers.
401 public function subscriberCount()
403 return XDB
::fetchOneCell('SELECT COUNT(uid)
405 WHERE nlid = {?}', $this->id
);
408 /** Get the count of subscribers with non valid redirection.
410 public function lostSubscriberCount()
412 return XDB
::fetchOneCell('SELECT COUNT(DISTINCT(n.uid))
413 FROM newsletter_ins AS n
414 INNER JOIN accounts AS a ON (n.uid = a.uid)
415 INNER JOIN account_types AS t ON (t.type = a.type)
416 LEFT JOIN email_redirect_account AS r ON (r.uid = a.uid AND r.flags = \'active\' AND r.broken_level < 3
417 AND r.type != \'imap\' AND r.type != \'homonym\')
418 WHERE n.nlid = {?} AND r.redirect IS NULL AND a.state = \'active\' AND FIND_IN_SET(\'mail\', t.perms)',
422 /** Get the number of subscribers to the NL whose last received mailing was $last.
423 * @p $last ID of the issue for which subscribers should be counted.
424 * @return Number of subscribers
426 public function subscriberCountForLast($last)
428 return XDB
::fetchOneCell('SELECT COUNT(uid)
430 WHERE nlid = {?} AND last = {?}', $this->id
, $last);
433 /** Retrieve the list of newsletters a user has subscribed to
434 * @p $user User whose subscriptions should be retrieved (if null, use session user).
435 * @return Array of newsletter IDs
437 public static function getUserSubscriptions($user = null
)
439 if (is_null($user)) {
442 $res = XDB
::query('SELECT nlid
446 return $res->fetchColumn();
449 /** Retrieve the UserFilterBuilder for subscribers to this NL.
450 * This is the place where NL-specific filters may be allowed or prevented.
451 * @p $envprefix Prefix to use for env fields (cf. UserFilterBuilder)
452 * @return A UserFilterBuilder object using the given env prefix
454 public function getSubscribersUFB($envprefix = '')
456 require_once 'ufbuilder.inc.php';
457 return new UFB_NewsLetter($this->criteria
, $envprefix);
461 // {{{ Permissions related functions
463 /** For later use: check whether a given user may subscribe to this newsletter.
464 * @p $user User whose access should be checked
465 * @return Boolean: whether the user may subscribe to the NL.
467 public function maySubscribe($user = null
)
472 /** Whether a given user may edit this newsletter
473 * @p $uid UID of the user whose perms should be checked (if null, use current user)
474 * @return Boolean: whether the user may edit the NL
476 public function mayEdit($user = null
)
478 if (is_null($user)) {
481 if ($user->checkPerms('admin')) {
484 $res = XDB
::query('SELECT perms
486 WHERE asso_id = {?} AND uid = {?}',
487 $this->group_id
, $user->id());
488 return ($res->numRows() && $res->fetchOneCell() == 'admin');
491 /** Whether a given user may submit articles to this newsletter using X.org validation system
492 * @p $user User whose access should be checked (if null, use current user)
493 * @return Boolean: whether the user may submit articles
495 public function maySubmit($user = null
)
497 // Submission of new articles is only enabled for the X.org NL (and forbidden when viewing issues on X.net)
498 return ($this->group
== self
::GROUP_XORG
&& !isset($GLOBALS['IS_XNET_SITE']));
502 // {{{ Display-related functions: cssFile, tplFile, prefix, admin_prefix, admin_links_enabled, automatic_mailings_enabled
504 /** Get the name of the css file used to display this newsletter.
506 public function cssFile()
508 if ($this->custom_css
) {
509 $base = $this->group
;
511 $base = self
::FORMAT_DEFAULT_GROUP
;
513 return 'nl.' . $base . '.css';
516 /** Get the name of the template file used to display this newsletter.
518 public function tplFile()
520 if ($this->custom_css
) {
521 $base = $this->group
;
523 $base = self
::FORMAT_DEFAULT_GROUP
;
525 return 'newsletter/nl.' . $base . '.mail.tpl';
528 /** Get the prefix leading to the page for this NL
529 * Only X.org / AX / X groups may be seen on X.org.
531 public function prefix($enforce_xnet=true
, $with_group=true
)
533 if (!empty($GLOBALS['IS_XNET_SITE'])) {
535 return $this->group
. '/nl';
540 switch ($this->group
) {
541 case self
::GROUP_XORG
:
548 // Don't display groups NLs on X.org
549 assert(!$enforce_xnet);
553 /** Get the prefix to use for all 'admin' pages of this NL.
555 public function adminPrefix($enforce_xnet=true
, $with_group=true
)
557 if (!empty($GLOBALS['IS_XNET_SITE'])) {
559 return $this->group
. '/admin/nl';
564 switch ($this->group
) {
565 case self
::GROUP_XORG
:
566 return 'admin/newsletter';
570 return 'epletter/admin';
572 // Don't display groups NLs on X.org
573 assert(!$enforce_xnet);
577 /** Hack used to remove "admin" links on X.org page on X.net
578 * The 'admin' links are enabled for all pages, except for X.org when accessing NL through X.net
580 public function adminLinksEnabled()
582 return ($this->group
!= self
::GROUP_XORG ||
!isset($GLOBALS['IS_XNET_SITE']));
585 /** Automatic mailings are disabled for X.org NL.
587 public function automaticMailingEnabled()
589 return $this->group
!= self
::GROUP_XORG
;
592 public function hasCustomCss()
594 return $this->custom_css
;
597 public function canSyncWithGroup()
599 switch ($this->group
) {
600 case self
::GROUP_XORG
:
616 // A NLIssue is an issue of a given NewsLetter
619 protected $nlid; // Id of the newsletter
621 const STATE_NEW
= 'new'; // New, currently being edited
622 const STATE_PENDING
= 'pending'; // Ready for mailing
623 const STATE_SENT
= 'sent'; // Sent
625 public $nl; // Related NL
627 public $id; // Id of this issue of the newsletter
628 public $shortname; // Shortname for this issue
629 public $title; // Title of this issue
630 public $title_mail; // Title of the email
631 public $state; // State of the issue (one of the STATE_ values)
632 public $sufb; // Environment to use to generate the UFC through an UserFilterBuilder
634 public $date; // Date at which this issue was sent
635 public $send_before; // Date at which issue should be sent
636 public $head; // Foreword of the issue (or body for letters with no articles)
637 public $signature; // Signature of the letter
638 public $reply_to; // Adress to reply to the message (can be empty)
639 public $arts = array(); // Articles of the issue
641 const BATCH_SIZE
= 60; // Number of emails to send every minute.
643 // {{{ Constructor, id-related functions
645 /** Build a NewsLetter.
646 * @p $id: ID of the issue (unique among all newsletters)
647 * @p $nl: Optional argument containing an already built NewsLetter object.
649 function __construct($id, $nl = null
, $fetch_articles = true
)
651 return $this->fetch($id, $nl, $fetch_articles);
654 protected function refresh()
656 return $this->fetch($this->id
, $this->nl
, false
);
659 protected function fetch($id, $nl = null
, $fetch_articles = true
)
662 $res = XDB
::query('SELECT nlid, short_name, date, send_before, state, sufb_json,
663 title, mail_title, head, signature, reply_to
664 FROM newsletter_issues
667 if (!$res->numRows()) {
668 throw new MailNotFound();
670 $issue = $res->fetchOneAssoc();
671 if ($nl && $nl->id
== $issue['nlid']) {
674 $this->nl
= new NewsLetter($issue['nlid']);
677 $this->nlid
= $issue['nlid'];
678 $this->shortname
= $issue['short_name'];
679 $this->date
= $issue['date'];
680 $this->send_before
= $issue['send_before'];
681 $this->state
= $issue['state'];
682 $this->title
= $issue['title'];
683 $this->title_mail
= $issue['mail_title'];
684 $this->head
= $issue['head'];
685 $this->signature
= $issue['signature'];
686 $this->reply_to
= $issue['reply_to'];
687 $this->sufb
= $this->importJSonStoredUFB($issue['sufb_json']);
689 if ($fetch_articles) {
690 $this->fetchArticles();
694 protected function fetchArticles($force = false
)
696 if (count($this->arts
) && !$force) {
702 'SELECT a.title, a.body, a.append, a.aid, a.cid, a.pos
703 FROM newsletter_art AS a
704 INNER JOIN newsletter_issues AS ni USING(id)
705 LEFT JOIN newsletter_cat AS c ON (a.cid = c.cid)
707 ORDER BY c.pos, a.pos',
709 while (list($title, $body, $append, $aid, $cid, $pos) = $res->next()) {
710 $this->arts
[$cid][$aid] = new NLArticle($title, $body, $append, $aid, $cid, $pos);
714 protected function importJSonStoredUFB($json = null
)
716 require_once 'ufbuilder.inc.php';
717 $ufb = $this->nl
->getSubscribersUFB();
718 if (is_null($json)) {
719 return new StoredUserFilterBuilder($ufb, new PFC_True());
721 $export = json_decode($json, true
);
722 if (is_null($export)) {
723 PlErrorReport
::report("Invalid json while reading NL {$this->nlid}, issue {$this->id}: failed to import '''{$json}'''.");
724 return new StoredUserFilterBuilder($ufb, new PFC_True());
726 $sufb = new StoredUserFilterBuilder($ufb);
727 $sufb->fillFromExport($export);
731 protected function exportStoredUFBAsJSon()
733 return json_encode($this->sufb
->export());
738 return is_null($this->shortname
) ?
$this->id
: $this->shortname
;
741 protected function selectId($where)
743 $res = XDB
::query("SELECT IFNULL(ni.short_name, ni.id)
744 FROM newsletter_issues AS ni
745 WHERE ni.state != 'new' AND ni.nlid = {?} AND ${where}
746 LIMIT 1", $this->nl
->id
);
747 if ($res->numRows() != 1) {
750 return $res->fetchOneCell();
753 /** Delete this issue
754 * @return True if the issue could be deleted, false otherwise.
755 * Related articles will be deleted through cascading FKs.
756 * If this issue was the last issue for at least one subscriber, the deletion will be aborted.
758 public function delete()
760 if ($this->state
== self
::STATE_NEW
) {
761 $res = XDB
::query('SELECT COUNT(*)
763 WHERE last = {?}', $this->id
);
764 if ($res->fetchOneCell() > 0) {
768 return XDB
::execute('DELETE FROM newsletter_issues
769 WHERE id = {?}', $this->id
);
775 /** Schedule a mailing of this NL
776 * If the 'send_before' field was NULL, it is set to the current time.
777 * @return Boolean Whether the date could be set (false if trying to schedule an already sent NL)
779 public function scheduleMailing()
781 if ($this->state
== self
::STATE_NEW
) {
782 $success = XDB
::execute('UPDATE newsletter_issues
783 SET state = \'pending\', send_before = IFNULL(send_before, NOW())
788 $mailer = new PlMailer('newsletter/notify_scheduled.mail.tpl');
789 $mailer->assign('issue', $this);
790 $mailer->assign('base', $globals->baseurl
);
800 /** Cancel the scheduled mailing of this NL
801 * @return Boolean: whether the mailing could be cancelled.
803 public function cancelMailing()
805 if ($this->state
== self
::STATE_PENDING
) {
806 $success = XDB
::execute('UPDATE newsletter_issues
808 WHERE id = {?}', $this->id
);
818 /** Helper function for smarty templates: is this issue editable ?
820 public function isEditable()
822 return $this->state
== self
::STATE_NEW
;
825 /** Helper function for smarty templates: is the mailing of this issue scheduled ?
827 public function isPending()
829 return $this->state
== self
::STATE_PENDING
;
832 /** Helper function for smarty templates: has this issue been sent ?
834 public function isSent()
836 return $this->state
== self
::STATE_SENT
;
842 private $id_prev = null
;
843 private $id_next = null
;
844 private $id_last = null
;
846 /** Retrieve ID of the previous issue
847 * That value, once fetched, is cached in the private $id_prev variable.
848 * @return ID of the previous issue.
850 public function prev()
852 if (is_null($this->id_prev
)) {
853 $this->id_prev
= $this->selectId(XDB
::format("ni.id < {?} ORDER BY ni.id DESC", $this->id
));
855 return $this->id_prev
;
858 /** Retrieve ID of the following issue
859 * That value, once fetched, is cached in the private $id_next variable.
860 * @return ID of the following issue.
862 public function next()
864 if (is_null($this->id_next
)) {
865 $this->id_next
= $this->selectId(XDB
::format("ni.id > {?} ORDER BY ni.id", $this->id
));
867 return $this->id_next
;
870 /** Retrieve ID of the last issue
871 * That value, once fetched, is cached in the private $id_last variable.
872 * @return ID of the last issue.
874 public function last()
876 if (is_null($this->id_last
)) {
878 $this->id_last
= $this->nl
->getIssue('last')->id
;
879 } catch (MailNotFound
$e) {
880 $this->id_last
= null
;
883 return $this->id_last
;
887 // {{{ Edition, articles
889 const ERROR_INVALID_REPLY_TO
= 'invalid_reply_to';
890 const ERROR_INVALID_SHORTNAME
= 'invalid_shortname';
891 const ERROR_INVALID_UFC
= 'invalid_ufc';
892 const ERROR_TOO_LONG_UFC
= 'too_long_ufc';
893 const ERROR_SQL_SAVE
= 'sql_error';
895 /** Save the global properties of this NL issue (title&co).
897 public function save()
901 // Fill the list of fields to update
903 'title' => $this->title
,
904 'mail_title' => $this->title_mail
,
905 'head' => $this->head
,
906 'signature' => $this->signature
,
909 if (!empty($this->reply_to
) && !isvalid_email($this->reply_to
)) {
910 $errors[] = self
::ERROR_INVALID_REPLY_TO
;
912 $fields['reply_to'] = $this->reply_to
;
915 if ($this->isEditable()) {
916 $fields['date'] = $this->date
;
917 if (!preg_match('/^[-a-z0-9]+$/i', $this->shortname
) ||
is_numeric($this->shortname
)) {
918 $errors[] = self
::ERROR_INVALID_SHORTNAME
;
920 $fields['short_name'] = $this->shortname
;
922 if ($this->sufb
->isValid() ||
$this->sufb
->isEmpty()) {
923 $fields['sufb_json'] = json_encode($this->sufb
->export()->dict());
924 // If sufb_json is too long to be store, we do not store a truncated json and notify the user.
925 // The limit is LONGTEXT's one, ie 2^32 = 4294967296.
926 if (strlen($fields['sufb_json']) > 4294967295) {
927 $errors[] = self
::ERROR_TOO_LONG_UFC
;
930 $errors[] = self
::ERROR_INVALID_UFC
;
933 if ($this->nl
->automaticMailingEnabled()) {
934 $fields['send_before'] = ($this->send_before ?
$this->send_before
: null
);
938 if (count($errors)) {
941 $field_sets = array();
942 foreach ($fields as $key => $value) {
943 $field_sets[] = XDB
::format($key . ' = {?}', $value);
945 XDB
::execute('UPDATE newsletter_issues
946 SET ' . implode(', ', $field_sets) . '
949 if (XDB
::affectedRows()) {
952 $errors[] = self
::ERROR_SQL_SAVE
;
957 /** Get an article by number
958 * @p $aid Article ID (among articles of the issue)
959 * @return A NLArticle object, or null if there is no article by that number
961 public function getArt($aid)
963 $this->fetchArticles();
965 foreach ($this->arts
as $category => $artlist) {
966 if (isset($artlist[$aid])) {
967 return $artlist[$aid];
974 * @p $a A reference to a NLArticle object (will be modified once saved)
976 public function saveArticle($a)
978 $this->fetchArticles();
980 // Prevent cid to be 0 (use NULL instead)
981 $a->cid
= ($a->cid
== 0) ? null
: $a->cid
;
983 // Article already exists in DB
984 XDB
::execute('UPDATE newsletter_art
985 SET cid = {?}, pos = {?}, title = {?}, body = {?}, append = {?}
986 WHERE id = {?} AND aid = {?}',
987 $a->cid
, $a->pos
, $a->title
, $a->body
, $a->append
, $this->id
, $a->aid
);
990 XDB
::startTransaction();
991 list($aid, $pos) = XDB
::fetchOneRow('SELECT MAX(aid) AS aid, MAX(pos) AS pos
992 FROM newsletter_art AS a
996 $a->pos
= ($a->pos ?
$a->pos
: ++
$pos);
997 XDB
::execute('INSERT INTO newsletter_art (id, aid, cid, pos, title, body, append)
998 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
999 $this->id
, $a->aid
, $a->cid
, $a->pos
,
1000 $a->title
, $a->body
, $a->append
);
1003 // Update local ID of article
1004 $this->arts
[$a->aid
] = $a;
1007 /** Delete an article by its ID
1008 * @p $aid ID of the article to delete
1010 public function delArticle($aid)
1012 $this->fetchArticles();
1014 XDB
::execute('DELETE FROM newsletter_art WHERE id={?} AND aid={?}', $this->id
, $aid);
1015 foreach ($this->arts
as $key=>$art) {
1016 unset($this->arts
[$key][$aid]);
1023 /** Retrieve the title of this issue
1024 * @p $mail Whether we want the normal title or the email subject
1025 * @return Title of the issue
1027 public function title($mail = false
)
1029 return $mail ?
$this->title_mail
: $this->title
;
1032 /** Retrieve the head of this issue
1033 * @p $user User for <dear> customization (may be null: no customization)
1034 * @p $type Either 'text' or 'html'
1035 * @return Formatted head of the issue.
1037 public function head($user = null
, $type = 'text')
1039 if (is_null($user)) {
1042 $head = $this->head
;
1043 $head = str_replace(array('<cher>', '<prenom>', '<nom>'),
1044 array(($user->isFemale() ?
'Chère' : 'Cher'), $user->displayName(), ''),
1046 return format_text($head, $type, 2, 64);
1050 /** Retrieve the formatted signature of this issue.
1052 public function signature($type = 'text')
1054 return format_text($this->signature
, $type, 2, 64);
1057 /** Get the title of a given category
1058 * @p $cid ID of the category to retrieve
1059 * @return Name of the category
1061 public function category($cid)
1063 return $this->nl
->cats
[$cid];
1066 /** Add required data to the given $page for proper CSS display
1067 * @p $page Smarty object
1068 * @return Either 'true' (if CSS was added to a page) or the raw CSS to add (when $page is null)
1070 public function css($page = null
)
1072 if (!is_null($page)) {
1073 $page->addCssLink($this->nl
->cssFile());
1076 $css = file_get_contents(dirname(__FILE__
) . '/../htdocs/css/' . $this->nl
->cssFile());
1077 return preg_replace('@/\*.*?\*/@us', '', $css);
1081 /** Set up a smarty page for a 'text' mode render of the issue
1082 * @p $page Smarty object (using the $this->nl->tplFile() template)
1083 * @p $user User to use when rendering the template
1085 public function toText($page, $user)
1087 $this->fetchArticles();
1090 $page->assign('prefix', null
);
1091 $page->assign('is_mail', false
);
1092 $page->assign('mail_part', 'text');
1093 $page->assign('user', $user);
1094 $page->assign('hash', null
);
1095 $this->assignData($page);
1098 /** Set up a smarty page for a 'html' mode render of the issue
1099 * @p $page Smarty object (using the $this->nl->tplFile() template)
1100 * @p $user User to use when rendering the template
1102 public function toHtml($page, $user)
1104 $this->fetchArticles();
1107 $page->assign('prefix', $this->nl
->prefix() . '/show/' . $this->id());
1108 $page->assign('is_mail', false
);
1109 $page->assign('mail_part', 'html');
1110 $page->assign('user', $user);
1111 $page->assign('hash', null
);
1112 $this->assignData($page);
1115 /** Set all 'common' data for the page (those which are required for both web and email rendering)
1116 * @p $smarty Smarty object (e.g page) which should be filled
1118 protected function assignData($smarty)
1120 $this->fetchArticles();
1122 $smarty->assign_by_ref('issue', $this);
1123 $smarty->assign_by_ref('nl', $this->nl
);
1129 /** Check whether this issue is empty
1130 * An issue is empty if the email has no title (or the default one), or no articles and an empty head.
1132 public function isEmpty()
1134 return $this->title_mail
== '' ||
$this->title_mail
== 'to be continued' ||
(count($this->arts
) == 0 && strlen($this->head
) == 0);
1137 /** Retrieve the 'Send before' date, in a clean format.
1139 public function getSendBeforeDate()
1141 return strftime('%Y-%m-%d', strtotime($this->send_before
));
1144 /** Retrieve the 'Send before' time (i.e hour), in a clean format.
1146 public function getSendBeforeTime()
1148 return strtotime($this->send_before
);
1151 /** Create a hash based on some additional data
1152 * $line Line-specific data (to prevent two hashes generated at the same time to be the same)
1154 protected static function createHash($line)
1156 $hash = implode(time(), $line) . rand();
1161 /** Send this issue to the given user, reusing an existing hash if provided.
1162 * @p $user User to whom the issue should be mailed
1163 * @p $hash Optional hash to use in the 'unsubscribe' link; if null, another one will be generated.
1165 public function sendTo($user, $hash = null
)
1167 $this->fetchArticles();
1169 if (is_null($hash)) {
1170 $hash = XDB
::fetchOneCell("SELECT hash
1172 WHERE uid = {?} AND nlid = {?}",
1173 $user->id(), $this->nl
->id
);
1175 if (is_null($hash)) {
1176 $hash = self
::createHash(array($user->displayName(), $user->fullName(),
1177 $user->isFemale(), $user->isEmailFormatHtml(),
1178 rand(), "X.org rulez"));
1179 XDB
::execute("UPDATE newsletter_ins as ni
1181 WHERE ni.uid = {?} AND ni.nlid = {?}",
1182 $hash, $user->id(), $this->nl
->id
);
1185 $mailer = new PlMailer($this->nl
->tplFile());
1186 $this->assignData($mailer);
1187 $mailer->assign('is_mail', true
);
1188 $mailer->assign('user', $user);
1189 $mailer->assign('prefix', null
);
1190 $mailer->assign('hash', $hash);
1191 if (!empty($this->reply_to
)) {
1192 $mailer->addHeader('Reply-To', $this->reply_to
);
1194 $mailer->sendTo($user);
1197 /** Select a subset of subscribers which should receive the newsletter.
1198 * NL-Specific selections (not yet received, is subscribed) are done when sending.
1199 * @return A PlFilterCondition.
1201 protected function getRecipientsUFC()
1203 return $this->sufb
->getUFC();
1206 /** Check whether a given user may see this issue.
1207 * @p $user User whose access should be checked
1208 * @return Whether he may access the issue
1210 public function checkUser($user = null
)
1212 if ($user == null
) {
1215 $uf = new UserFilter($this->getRecipientsUFC());
1216 return $uf->checkUser($user);
1219 /** Sent this issue to all valid recipients
1220 * @return Number of issues sent
1222 public function sendToAll()
1224 $this->fetchArticles();
1226 XDB
::execute('UPDATE newsletter_issues
1227 SET state = \'sent\', date=CURDATE()
1231 $ufc = new PFC_And($this->getRecipientsUFC(), new UFC_NLSubscribed($this->nl
->id
, $this->id
), new UFC_HasValidEmail());
1232 $uf = new UserFilter($ufc, array(new UFO_IsAdmin(true
), new UFO_Uid()));
1233 $limit = new PlLimit(self
::BATCH_SIZE
);
1234 $global_sent = array();
1238 $users = $uf->getUsers($limit);
1239 if (count($users) == 0) {
1242 foreach ($users as $user) {
1243 if (array_key_exists($user->id(), $global_sent)) {
1244 Platal
::page()->kill('Sending the same newsletter issue ' . $this->id
. ' to user ' . $user->id() . ' twice, something must be wrong.');
1246 $sent[] = $user->id();
1247 $global_sent[$user->id()] = true
;
1248 $this->sendTo($user, $hash);
1250 XDB
::execute("UPDATE newsletter_ins
1252 WHERE nlid = {?} AND uid IN {?}", $this->id
, $this->nl
->id
, $sent);
1256 return count($global_sent);
1263 // {{{ class NLArticle
1267 // Maximum number of lines per article
1268 const MAX_LINES_PER_ARTICLE
= 8;
1269 const MAX_CHARACTERS_PER_LINE
= 68;
1283 function __construct($title='', $body='', $append='', $aid=-1, $cid=0, $pos=0)
1285 $this->body
= $body;
1286 $this->title
= $title;
1287 $this->append
= $append;
1294 // {{{ function title()
1296 public function title()
1297 { return trim($this->title
); }
1300 // {{{ function body()
1302 public function body()
1303 { return trim($this->body
); }
1306 // {{{ function append()
1308 public function append()
1309 { return trim($this->append
); }
1312 // {{{ function toText()
1314 public function toText($hash = null
, $login = null
)
1316 $title = '*'.$this->title().'*';
1317 $body = MiniWiki
::WikiToText($this->body
, true
);
1318 $app = MiniWiki
::WikiToText($this->append
, false
, 4);
1319 $text = trim("$title\n\n$body\n\n$app")."\n";
1320 if (!is_null($hash) && !is_null($login)) {
1321 $text = str_replace('%HASH%', "$hash/$login", $text);
1323 $text = str_replace('%HASH%', '', $text);
1329 // {{{ function toHtml()
1331 public function toHtml($hash = null
, $login = null
)
1333 $title = "<h2 class='xorg_nl'><a id='art{$this->aid}'></a>".pl_entities($this->title()).'</h2>';
1334 $body = MiniWiki
::WikiToHTML($this->body
);
1335 $app = MiniWiki
::WikiToHTML($this->append
);
1338 $art .= "<div class='art'>\n$body\n";
1340 $art .= "<div class='app'>$app</div>";
1343 if (!is_null($hash) && !is_null($login)) {
1344 $art = str_replace('%HASH%', "$hash/$login", $art);
1346 $art = str_replace('%HASH%', '', $art);
1353 // {{{ function check()
1355 public function check()
1357 $rest = $this->remain();
1359 return $rest['remaining_lines'] >= 0;
1363 // {{{ function remain()
1365 public function remain()
1367 $text = MiniWiki
::WikiToText($this->body
);
1368 $array = explode("\n", wordwrap($text, self
::MAX_CHARACTERS_PER_LINE
));
1370 foreach ($array as $line) {
1371 if (trim($line) != '') {
1377 'remaining_lines' => self
::MAX_LINES_PER_ARTICLE
- $lines_count,
1378 'remaining_characters_for_last_line' => self
::MAX_CHARACTERS_PER_LINE
- strlen($array[count($array) - 1])
1382 // {{{ function parseUrlsFromArticle()
1384 protected function parseUrlsFromArticle()
1386 $email_regex = '([a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+)';
1387 $url_regex = '((https?|ftp)://[a-zA-Z0-9._%#+/?=&~-]+)';
1388 $regex = '{' . $email_regex . '|' . $url_regex . '}i';
1391 $body_matches = array();
1392 if (preg_match_all($regex, $this->body(), $body_matches)) {
1393 $matches = array_merge($matches, $body_matches[0]);
1396 $append_matches = array();
1397 if (preg_match_all($regex, $this->append(), $append_matches)) {
1398 $matches = array_merge($matches, $append_matches[0]);
1405 // {{{ function getLinkIps()
1407 public function getLinkIps(&$blacklist_host_resolution_count)
1409 $matches = $this->parseUrlsFromArticle();
1410 $article_ips = array();
1412 if (!empty($matches)) {
1415 foreach ($matches as $match) {
1416 $host = parse_url($match, PHP_URL_HOST
);
1418 list(, $host) = explode('@', $match);
1421 if ($blacklist_host_resolution_count >= $globals->mail
->blacklist_host_resolution_limit
) {
1425 if (!preg_match('/^(' . str_replace(' ', '|', $globals->mail
->domain_whitelist
) . ')$/i', $host)) {
1426 $article_ips = array_merge($article_ips, array(gethostbyname($host) => $host));
1427 ++
$blacklist_host_resolution_count;
1432 return $article_ips;
1442 function format_text($input, $format, $indent = 0, $width = 68)
1444 if ($format == 'text') {
1445 return MiniWiki
::WikiToText($input, true
, $indent, $width, "title");
1447 return MiniWiki
::WikiToHTML($input, "title");
1450 // function enriched_to_text($input,$html=false,$just=false,$indent=0,$width=68)
1454 // vim:set et sw=4 sts=4 sws=4 enc=utf-8: