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()
110 $res = XDB
::query('SELECT id
113 foreach ($res->fetchColumn() as $id) {
114 $nls[$id] = new NewsLetter($id);
120 // {{{ Issue retrieval
122 /** Retrieve all issues which should be sent
123 * @return An array of NLIssue objects to send (i.e state = 'new' and send_before <= today)
125 public static function getIssuesToSend()
127 $res = XDB
::query('SELECT id
128 FROM newsletter_issues
129 WHERE state = \'pending\' AND send_before <= NOW()');
131 foreach ($res->fetchColumn() as $id) {
132 $issues[$id] = new NLIssue($id);
137 /** Retrieve a given issue of this NewsLetter
138 * @p $name Name or ID of the issue to retrieve.
139 * @return A NLIssue object.
141 * $name may be either a short_name, an ID or the special value 'last' which
142 * selects the latest sent NL.
143 * If $name is null, this will retrieve the current pending NL.
145 public function getIssue($name = null
, $only_sent = true
)
148 if ($name == 'last') {
150 $where = 'state = \'sent\' AND ';
154 $res = XDB
::query('SELECT MAX(id)
155 FROM newsletter_issues
156 WHERE ' . $where . ' nlid = {?}',
159 $res = XDB
::query('SELECT id
160 FROM newsletter_issues
161 WHERE nlid = {?} AND (id = {?} OR short_name = {?})',
162 $this->id
, $name, $name);
164 if (!$res->numRows()) {
165 throw new MailNotFound();
167 $id = $res->fetchOneCell();
169 $query = XDB
::format('SELECT id
170 FROM newsletter_issues
171 WHERE nlid = {?} AND state = \'new\'
172 ORDER BY id DESC', $this->id
);
173 $res = XDB
::query($query);
174 if ($res->numRows()) {
175 $id = $res->fetchOneCell();
177 // Create a new, empty issue, and return it
178 $id = $this->createPending();
182 return new NLIssue($id, $this);
185 /** Create a new, empty, pending newsletter issue
186 * @p $nlid The id of the NL for which a new pending issue should be created.
187 * @return Id of the newly created issue.
189 public function createPending()
191 XDB
::execute('INSERT INTO newsletter_issues
192 SET nlid = {?}, state=\'new\', date=NOW(),
193 title=\'to be continued\',
194 mail_title=\'to be continued\'',
196 return XDB
::insertId();
199 /** Return all sent issues of this newsletter.
200 * @return An array of (id => NLIssue)
202 public function listSentIssues($check_user = false
, $user = null
)
204 if ($check_user && $user == null
) {
208 $res = XDB
::query('SELECT id
209 FROM newsletter_issues
210 WHERE nlid = {?} AND state = \'sent\'
211 ORDER BY date DESC', $this->id
);
213 foreach ($res->fetchColumn() as $id) {
214 $issue = new NLIssue($id, $this, false
);
215 if (!$check_user ||
$issue->checkUser($user)) {
216 $issues[$id] = $issue;
222 /** Return all issues of this newsletter, including invalid and sent.
223 * @return An array of (id => NLIssue)
225 public function listAllIssues()
227 $res = XDB
::query('SELECT id
228 FROM newsletter_issues
230 ORDER BY FIELD(state, \'pending\', \'new\') DESC, date DESC', $this->id
);
232 foreach ($res->fetchColumn() as $id) {
233 $issues[$id] = new NLIssue($id, $this, false
);
238 /** Return the latest pending issue of the newsletter.
239 * @p $create Whether to create an empty issue if no pending issue exist.
240 * @return Either null, or a NL object.
242 public function getPendingIssue($create = false
)
244 $res = XDB
::query('SELECT MAX(id)
245 FROM newsletter_issues
246 WHERE nlid = {?} AND state = \'new\'',
248 $id = $res->fetchOneCell();
250 return new NLIssue($id, $this);
251 } else if ($create) {
252 $id = $this->createPending();
253 return new NLIssue($id, $this);
259 /** Returns a list of either issues or articles corresponding to the search.
260 * @p $search The searched pattern.
261 * @p $field The fields where to search, if none given, search in all possible fields.
262 * @return The list of object found.
264 public function issueSearch($search, $field, $user)
266 $search = XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $search);
267 if ($field == self
::SEARCH_ALL
) {
268 $where = '(title ' . $search . ' OR mail_title ' . $search . ' OR head ' . $search . ' OR signature ' . $search . ')';
269 } elseif ($field == self
::SEARCH_TITLE
) {
270 $where = '(title ' . $search . ' OR mail_title ' . $search . ')';
272 $where = $field . $search;
274 $list = XDB
::fetchColumn('SELECT DISTINCT(id)
275 FROM newsletter_issues
276 WHERE nlid = {?} AND state = \'sent\' AND ' . $where . '
281 foreach ($list as $id) {
282 $issue = new NLIssue($id, $this, false
);
283 if ($issue->checkUser($user)) {
290 public function articleSearch($search, $field, $user)
292 $search = XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $search);
293 if ($field == self
::SEARCH_ALL
) {
294 $where = '(a.title ' . $search . ' OR a.body ' . $search . ' OR a.append ' . $search . ')';
296 $where = 'a.' . $field . $search;
298 $list = XDB
::fetchAllAssoc('SELECT i.short_name, a.aid, i.id, a.title
299 FROM newsletter_art AS a
300 INNER JOIN newsletter_issues AS i ON (a.id = i.id)
301 WHERE i.nlid = {?} AND i.state = \'sent\' AND ' . $where . '
303 ORDER BY i.date DESC, a.aid',
307 foreach ($list as $item) {
308 $issue = new NLIssue($item['id'], $this, false
);
309 if ($issue->checkUser($user)) {
317 // {{{ Subscription related function
319 /** Unsubscribe a user from this newsletter
320 * @p $uid UID to unsubscribe from the newsletter; if null, use current user.
321 * @p $hash True if the uid is actually a hash.
322 * @return True if the user was successfully unsubscribed.
324 public function unsubscribe($issue_id = null
, $uid = null
, $hash = false
)
326 if (is_null($uid) && $hash) {
327 // Unable to unsubscribe from an empty hash
330 $user = is_null($uid) ? S
::user()->id() : $uid;
331 $field = $hash ?
'hash' : 'uid';
332 $res = XDB
::query('SELECT uid
334 WHERE nlid = {?} AND ' . $field . ' = {?}',
336 if (!$res->numRows()) {
337 // No subscribed user with that UID/hash
340 $user = $res->fetchOneCell();
342 XDB
::execute('DELETE FROM newsletter_ins
343 WHERE nlid = {?} AND uid = {?}',
345 if (!is_null($issue_id)) {
346 XDB
::execute('UPDATE newsletter_issues
347 SET unsubscribe = unsubscribe + 1
354 /** Subscribe a user to a newsletter
355 * @p $user User to subscribe to the newsletter; if null, use current user.
357 public function subscribe($user = null
)
359 if (is_null($user)) {
362 if (self
::maySubscribe($user)) {
363 XDB
::execute('INSERT IGNORE INTO newsletter_ins (nlid, uid, last, hash)
364 VALUES ({?}, {?}, NULL, hash)',
365 $this->id
, $user->id());
369 /** Subscribe a batch of users to a newsletter.
370 * This skips 'maySubscribe' test.
372 * @p $user_ids Array of user IDs to subscribe to the newsletter.
374 public function bulkSubscribe($user_ids)
376 // TODO: use a 'bulkMaySubscribe'.
377 XDB
::execute('INSERT IGNORE INTO newsletter_ins (nlid, uid, last, hash)
378 SELECT {?}, a.uid, NULL, NULL
381 $this->id
, $user_ids);
384 /** Retrieve subscription state of a user
385 * @p $user Target user; if null, use current user.
386 * @return Boolean: true if the user has subscribed to the NL.
388 public function subscriptionState($user = null
)
390 if (is_null($user)) {
393 $res = XDB
::query('SELECT 1
395 WHERE nlid = {?} AND uid = {?}',
396 $this->id
, $user->id());
397 return ($res->numRows() == 1);
400 /** Get the count of subscribers to the NL.
401 * @return Number of subscribers.
403 public function subscriberCount()
405 return XDB
::fetchOneCell('SELECT COUNT(uid)
407 WHERE nlid = {?}', $this->id
);
410 /** Get the count of subscribers with non valid redirection.
412 public function lostSubscriberCount()
414 return XDB
::fetchOneCell('SELECT COUNT(DISTINCT(n.uid))
415 FROM newsletter_ins AS n
416 INNER JOIN accounts AS a ON (n.uid = a.uid)
417 INNER JOIN account_types AS t ON (t.type = a.type)
418 LEFT JOIN email_redirect_account AS r ON (r.uid = a.uid AND r.flags = \'active\' AND r.broken_level < 3
419 AND r.type != \'imap\' AND r.type != \'homonym\')
420 WHERE n.nlid = {?} AND r.redirect IS NULL AND a.state = \'active\' AND FIND_IN_SET(\'mail\', t.perms)',
424 /** Get the number of subscribers to the NL whose last received mailing was $last.
425 * @p $last ID of the issue for which subscribers should be counted.
426 * @return Number of subscribers
428 public function subscriberCountForLast($last)
430 return XDB
::fetchOneCell('SELECT COUNT(uid)
432 WHERE nlid = {?} AND last = {?}', $this->id
, $last);
435 /** Retrieve the list of newsletters a user has subscribed to
436 * @p $user User whose subscriptions should be retrieved (if null, use session user).
437 * @return Array of newsletter IDs
439 public static function getUserSubscriptions($user = null
)
441 if (is_null($user)) {
444 $res = XDB
::query('SELECT nlid
448 return $res->fetchColumn();
451 /** Retrieve the UserFilterBuilder for subscribers to this NL.
452 * This is the place where NL-specific filters may be allowed or prevented.
453 * @p $envprefix Prefix to use for env fields (cf. UserFilterBuilder)
454 * @return A UserFilterBuilder object using the given env prefix
456 public function getSubscribersUFB($envprefix = '')
458 require_once 'ufbuilder.inc.php';
459 return new UFB_NewsLetter($this->criteria
, $envprefix);
463 // {{{ Permissions related functions
465 /** For later use: check whether a given user may subscribe to this newsletter.
466 * @p $user User whose access should be checked
467 * @return Boolean: whether the user may subscribe to the NL.
469 public function maySubscribe($user = null
)
474 /** Whether a given user may edit this newsletter
475 * @p $uid UID of the user whose perms should be checked (if null, use current user)
476 * @return Boolean: whether the user may edit the NL
478 public function mayEdit($user = null
)
480 if (is_null($user)) {
483 if ($user->checkPerms('admin')) {
486 $res = XDB
::query('SELECT perms
488 WHERE asso_id = {?} AND uid = {?}',
489 $this->group_id
, $user->id());
490 return ($res->numRows() && $res->fetchOneCell() == 'admin');
493 /** Whether a given user may submit articles to this newsletter using X.org validation system
494 * @p $user User whose access should be checked (if null, use current user)
495 * @return Boolean: whether the user may submit articles
497 public function maySubmit($user = null
)
499 // Submission of new articles is only enabled for the X.org NL (and forbidden when viewing issues on X.net)
500 return ($this->group
== self
::GROUP_XORG
&& !isset($GLOBALS['IS_XNET_SITE']));
504 // {{{ Display-related functions: cssFile, tplFile, prefix, admin_prefix, admin_links_enabled, automatic_mailings_enabled
506 /** Get the name of the css file used to display this newsletter.
508 public function cssFile()
510 if ($this->custom_css
) {
511 $base = $this->group
;
513 $base = self
::FORMAT_DEFAULT_GROUP
;
515 return 'nl.' . $base . '.css';
518 /** Get the name of the template file used to display this newsletter.
520 public function tplFile()
522 if ($this->custom_css
) {
523 $base = $this->group
;
525 $base = self
::FORMAT_DEFAULT_GROUP
;
527 return 'newsletter/nl.' . $base . '.mail.tpl';
530 /** Get the prefix leading to the page for this NL
531 * Only X.org / AX / X groups may be seen on X.org.
533 public function prefix($enforce_xnet=true
, $with_group=true
)
535 if (!empty($GLOBALS['IS_XNET_SITE'])) {
537 return $this->group
. '/nl';
542 switch ($this->group
) {
543 case self
::GROUP_XORG
:
550 // Don't display groups NLs on X.org
551 assert(!$enforce_xnet);
555 /** Get the prefix to use for all 'admin' pages of this NL.
557 public function adminPrefix($enforce_xnet=true
, $with_group=true
)
559 if (!empty($GLOBALS['IS_XNET_SITE'])) {
561 return $this->group
. '/admin/nl';
566 switch ($this->group
) {
567 case self
::GROUP_XORG
:
568 return 'admin/newsletter';
572 return 'epletter/admin';
574 // Don't display groups NLs on X.org
575 assert(!$enforce_xnet);
579 /** Hack used to remove "admin" links on X.org page on X.net
580 * The 'admin' links are enabled for all pages, except for X.org when accessing NL through X.net
582 public function adminLinksEnabled()
584 return ($this->group
!= self
::GROUP_XORG ||
!isset($GLOBALS['IS_XNET_SITE']));
587 /** Automatic mailings are disabled for X.org NL.
589 public function automaticMailingEnabled()
591 return $this->group
!= self
::GROUP_XORG
;
594 public function hasCustomCss()
596 return $this->custom_css
;
599 public function canSyncWithGroup()
601 switch ($this->group
) {
602 case self
::GROUP_XORG
:
618 // A NLIssue is an issue of a given NewsLetter
621 protected $nlid; // Id of the newsletter
623 const STATE_NEW
= 'new'; // New, currently being edited
624 const STATE_PENDING
= 'pending'; // Ready for mailing
625 const STATE_SENT
= 'sent'; // Sent
627 public $nl; // Related NL
629 public $id; // Id of this issue of the newsletter
630 public $shortname; // Shortname for this issue
631 public $title; // Title of this issue
632 public $title_mail; // Title of the email
633 public $state; // State of the issue (one of the STATE_ values)
634 public $sufb; // Environment to use to generate the UFC through an UserFilterBuilder
636 public $date; // Date at which this issue was sent
637 public $send_before; // Date at which issue should be sent
638 public $head; // Foreword of the issue (or body for letters with no articles)
639 public $signature; // Signature of the letter
640 public $arts = array(); // Articles of the issue
642 const BATCH_SIZE
= 60; // Number of emails to send every minute.
644 // {{{ Constructor, id-related functions
646 /** Build a NewsLetter.
647 * @p $id: ID of the issue (unique among all newsletters)
648 * @p $nl: Optional argument containing an already built NewsLetter object.
650 function __construct($id, $nl = null
, $fetch_articles = true
)
652 return $this->fetch($id, $nl, $fetch_articles);
655 protected function refresh()
657 return $this->fetch($this->id
, $this->nl
, false
);
660 protected function fetch($id, $nl = null
, $fetch_articles = true
)
663 $res = XDB
::query('SELECT nlid, short_name, date, send_before, state, sufb_json,
664 title, mail_title, head, signature
665 FROM newsletter_issues
668 if (!$res->numRows()) {
669 throw new MailNotFound();
671 $issue = $res->fetchOneAssoc();
672 if ($nl && $nl->id
== $issue['nlid']) {
675 $this->nl
= new NewsLetter($issue['nlid']);
678 $this->nlid
= $issue['nlid'];
679 $this->shortname
= $issue['short_name'];
680 $this->date
= $issue['date'];
681 $this->send_before
= $issue['send_before'];
682 $this->state
= $issue['state'];
683 $this->title
= $issue['title'];
684 $this->title_mail
= $issue['mail_title'];
685 $this->head
= $issue['head'];
686 $this->signature
= $issue['signature'];
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_SHORTNAME
= 'invalid_shortname';
890 const ERROR_INVALID_UFC
= 'invalid_ufc';
891 const ERROR_TOO_LONG_UFC
= 'too_long_ufc';
892 const ERROR_SQL_SAVE
= 'sql_error';
894 /** Save the global properties of this NL issue (title&co).
896 public function save()
900 // Fill the list of fields to update
902 'title' => $this->title
,
903 'mail_title' => $this->title_mail
,
904 'head' => $this->head
,
905 'signature' => $this->signature
,
908 if ($this->isEditable()) {
909 $fields['date'] = $this->date
;
910 if (!preg_match('/^[-a-z0-9]+$/i', $this->shortname
) ||
is_numeric($this->shortname
)) {
911 $errors[] = self
::ERROR_INVALID_SHORTNAME
;
913 $fields['short_name'] = $this->shortname
;
915 if ($this->sufb
->isValid() ||
$this->sufb
->isEmpty()) {
916 $fields['sufb_json'] = json_encode($this->sufb
->export()->dict());
917 // If sufb_json is too long to be store, we do not store a truncated json and notify the user.
918 // The limit is LONGTEXT's one, ie 2^32 = 4294967296.
919 if (strlen($fields['sufb_json']) > 4294967295) {
920 $errors[] = self
::ERROR_TOO_LONG_UFC
;
923 $errors[] = self
::ERROR_INVALID_UFC
;
926 if ($this->nl
->automaticMailingEnabled()) {
927 $fields['send_before'] = ($this->send_before ?
$this->send_before
: null
);
931 if (count($errors)) {
934 $field_sets = array();
935 foreach ($fields as $key => $value) {
936 $field_sets[] = XDB
::format($key . ' = {?}', $value);
938 XDB
::execute('UPDATE newsletter_issues
939 SET ' . implode(', ', $field_sets) . '
942 if (XDB
::affectedRows()) {
945 $errors[] = self
::ERROR_SQL_SAVE
;
950 /** Get an article by number
951 * @p $aid Article ID (among articles of the issue)
952 * @return A NLArticle object, or null if there is no article by that number
954 public function getArt($aid)
956 $this->fetchArticles();
958 foreach ($this->arts
as $category => $artlist) {
959 if (isset($artlist[$aid])) {
960 return $artlist[$aid];
967 * @p $a A reference to a NLArticle object (will be modified once saved)
969 public function saveArticle($a)
971 $this->fetchArticles();
973 // Prevent cid to be 0 (use NULL instead)
974 $a->cid
= ($a->cid
== 0) ? null
: $a->cid
;
976 // Article already exists in DB
977 XDB
::execute('UPDATE newsletter_art
978 SET cid = {?}, pos = {?}, title = {?}, body = {?}, append = {?}
979 WHERE id = {?} AND aid = {?}',
980 $a->cid
, $a->pos
, $a->title
, $a->body
, $a->append
, $this->id
, $a->aid
);
983 XDB
::startTransaction();
984 list($aid, $pos) = XDB
::fetchOneRow('SELECT MAX(aid) AS aid, MAX(pos) AS pos
985 FROM newsletter_art AS a
989 $a->pos
= ($a->pos ?
$a->pos
: ++
$pos);
990 XDB
::execute('INSERT INTO newsletter_art (id, aid, cid, pos, title, body, append)
991 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
992 $this->id
, $a->aid
, $a->cid
, $a->pos
,
993 $a->title
, $a->body
, $a->append
);
996 // Update local ID of article
997 $this->arts
[$a->aid
] = $a;
1000 /** Delete an article by its ID
1001 * @p $aid ID of the article to delete
1003 public function delArticle($aid)
1005 $this->fetchArticles();
1007 XDB
::execute('DELETE FROM newsletter_art WHERE id={?} AND aid={?}', $this->id
, $aid);
1008 foreach ($this->arts
as $key=>$art) {
1009 unset($this->arts
[$key][$aid]);
1016 /** Retrieve the title of this issue
1017 * @p $mail Whether we want the normal title or the email subject
1018 * @return Title of the issue
1020 public function title($mail = false
)
1022 return $mail ?
$this->title_mail
: $this->title
;
1025 /** Retrieve the head of this issue
1026 * @p $user User for <dear> customization (may be null: no customization)
1027 * @p $type Either 'text' or 'html'
1028 * @return Formatted head of the issue.
1030 public function head($user = null
, $type = 'text')
1032 if (is_null($user)) {
1035 $head = $this->head
;
1036 $head = str_replace(array('<cher>', '<prenom>', '<nom>'),
1037 array(($user->isFemale() ?
'Chère' : 'Cher'), $user->displayName(), ''),
1039 return format_text($head, $type, 2, 64);
1043 /** Retrieve the formatted signature of this issue.
1045 public function signature($type = 'text')
1047 return format_text($this->signature
, $type, 2, 64);
1050 /** Get the title of a given category
1051 * @p $cid ID of the category to retrieve
1052 * @return Name of the category
1054 public function category($cid)
1056 return $this->nl
->cats
[$cid];
1059 /** Add required data to the given $page for proper CSS display
1060 * @p $page Smarty object
1061 * @return Either 'true' (if CSS was added to a page) or the raw CSS to add (when $page is null)
1063 public function css($page = null
)
1065 if (!is_null($page)) {
1066 $page->addCssLink($this->nl
->cssFile());
1069 $css = file_get_contents(dirname(__FILE__
) . '/../htdocs/css/' . $this->nl
->cssFile());
1070 return preg_replace('@/\*.*?\*/@us', '', $css);
1074 /** Set up a smarty page for a 'text' mode render of the issue
1075 * @p $page Smarty object (using the $this->nl->tplFile() template)
1076 * @p $user User to use when rendering the template
1078 public function toText($page, $user)
1080 $this->fetchArticles();
1083 $page->assign('prefix', null
);
1084 $page->assign('is_mail', false
);
1085 $page->assign('mail_part', 'text');
1086 $page->assign('user', $user);
1087 $page->assign('hash', null
);
1088 $this->assignData($page);
1091 /** Set up a smarty page for a 'html' mode render of the issue
1092 * @p $page Smarty object (using the $this->nl->tplFile() template)
1093 * @p $user User to use when rendering the template
1095 public function toHtml($page, $user)
1097 $this->fetchArticles();
1100 $page->assign('prefix', $this->nl
->prefix() . '/show/' . $this->id());
1101 $page->assign('is_mail', false
);
1102 $page->assign('mail_part', 'html');
1103 $page->assign('user', $user);
1104 $page->assign('hash', null
);
1105 $this->assignData($page);
1108 /** Set all 'common' data for the page (those which are required for both web and email rendering)
1109 * @p $smarty Smarty object (e.g page) which should be filled
1111 protected function assignData($smarty)
1113 $this->fetchArticles();
1115 $smarty->assign_by_ref('issue', $this);
1116 $smarty->assign_by_ref('nl', $this->nl
);
1122 /** Check whether this issue is empty
1123 * An issue is empty if the email has no title (or the default one), or no articles and an empty head.
1125 public function isEmpty()
1127 return $this->title_mail
== '' ||
$this->title_mail
== 'to be continued' ||
(count($this->arts
) == 0 && strlen($this->head
) == 0);
1130 /** Retrieve the 'Send before' date, in a clean format.
1132 public function getSendBeforeDate()
1134 return strftime('%Y-%m-%d', strtotime($this->send_before
));
1137 /** Retrieve the 'Send before' time (i.e hour), in a clean format.
1139 public function getSendBeforeTime()
1141 return strtotime($this->send_before
);
1144 /** Create a hash based on some additional data
1145 * $line Line-specific data (to prevent two hashes generated at the same time to be the same)
1147 protected static function createHash($line)
1149 $hash = implode(time(), $line) . rand();
1154 /** Send this issue to the given user, reusing an existing hash if provided.
1155 * @p $user User to whom the issue should be mailed
1156 * @p $hash Optional hash to use in the 'unsubscribe' link; if null, another one will be generated.
1158 public function sendTo($user, $hash = null
)
1160 $this->fetchArticles();
1162 if (is_null($hash)) {
1163 $hash = XDB
::fetchOneCell("SELECT hash
1165 WHERE uid = {?} AND nlid = {?}",
1166 $user->id(), $this->nl
->id
);
1168 if (is_null($hash)) {
1169 $hash = self
::createHash(array($user->displayName(), $user->fullName(),
1170 $user->isFemale(), $user->isEmailFormatHtml(),
1171 rand(), "X.org rulez"));
1172 XDB
::execute("UPDATE newsletter_ins as ni
1174 WHERE ni.uid = {?} AND ni.nlid = {?}",
1175 $hash, $user->id(), $this->nl
->id
);
1178 $mailer = new PlMailer($this->nl
->tplFile());
1179 $this->assignData($mailer);
1180 $mailer->assign('is_mail', true
);
1181 $mailer->assign('user', $user);
1182 $mailer->assign('prefix', null
);
1183 $mailer->assign('hash', $hash);
1184 $mailer->sendTo($user);
1187 /** Select a subset of subscribers which should receive the newsletter.
1188 * NL-Specific selections (not yet received, is subscribed) are done when sending.
1189 * @return A PlFilterCondition.
1191 protected function getRecipientsUFC()
1193 return $this->sufb
->getUFC();
1196 /** Check whether a given user may see this issue.
1197 * @p $user User whose access should be checked
1198 * @return Whether he may access the issue
1200 public function checkUser($user = null
)
1202 if ($user == null
) {
1205 $uf = new UserFilter($this->getRecipientsUFC());
1206 return $uf->checkUser($user);
1209 /** Sent this issue to all valid recipients
1210 * @return Number of issues sent
1212 public function sendToAll()
1214 $this->fetchArticles();
1216 XDB
::execute('UPDATE newsletter_issues
1217 SET state = \'sent\', date=CURDATE()
1221 $ufc = new PFC_And($this->getRecipientsUFC(), new UFC_NLSubscribed($this->nl
->id
, $this->id
), new UFC_HasValidEmail());
1222 $uf = new UserFilter($ufc, array(new UFO_IsAdmin(), new UFO_Uid()));
1223 $limit = new PlLimit(self
::BATCH_SIZE
);
1224 $global_sent = array();
1228 $users = $uf->getUsers($limit);
1229 if (count($users) == 0) {
1232 foreach ($users as $user) {
1233 if (array_key_exists($user->id(), $global_sent)) {
1234 Platal
::kill('Sending the same newsletter issue ' . $this->id
. ' to user ' . $user->id() . ' twice, something must be wrong.');
1236 $sent[] = $user->id();
1237 $global_sent[$user->id()] = true
;
1238 $this->sendTo($user, $hash);
1240 XDB
::execute("UPDATE newsletter_ins
1242 WHERE nlid = {?} AND uid IN {?}", $this->id
, $this->nl
->id
, $sent);
1246 return count($global_sent);
1253 // {{{ class NLArticle
1257 // Maximum number of lines per article
1258 const MAX_LINES_PER_ARTICLE
= 8;
1259 const MAX_CHARACTERS_PER_LINE
= 68;
1273 function __construct($title='', $body='', $append='', $aid=-1, $cid=0, $pos=0)
1275 $this->body
= $body;
1276 $this->title
= $title;
1277 $this->append
= $append;
1284 // {{{ function title()
1286 public function title()
1287 { return trim($this->title
); }
1290 // {{{ function body()
1292 public function body()
1293 { return trim($this->body
); }
1296 // {{{ function append()
1298 public function append()
1299 { return trim($this->append
); }
1302 // {{{ function toText()
1304 public function toText($hash = null
, $login = null
)
1306 $title = '*'.$this->title().'*';
1307 $body = MiniWiki
::WikiToText($this->body
, true
);
1308 $app = MiniWiki
::WikiToText($this->append
, false
, 4);
1309 $text = trim("$title\n\n$body\n\n$app")."\n";
1310 if (!is_null($hash) && !is_null($login)) {
1311 $text = str_replace('%HASH%', "$hash/$login", $text);
1313 $text = str_replace('%HASH%', '', $text);
1319 // {{{ function toHtml()
1321 public function toHtml($hash = null
, $login = null
)
1323 $title = "<h2 class='xorg_nl'><a id='art{$this->aid}'></a>".pl_entities($this->title()).'</h2>';
1324 $body = MiniWiki
::WikiToHTML($this->body
);
1325 $app = MiniWiki
::WikiToHTML($this->append
);
1328 $art .= "<div class='art'>\n$body\n";
1330 $art .= "<div class='app'>$app</div>";
1333 if (!is_null($hash) && !is_null($login)) {
1334 $art = str_replace('%HASH%', "$hash/$login", $art);
1336 $art = str_replace('%HASH%', '', $art);
1343 // {{{ function check()
1345 public function check()
1347 $rest = $this->remain();
1349 return $rest['remaining_lines'] >= 0;
1353 // {{{ function remain()
1355 public function remain()
1357 $text = MiniWiki
::WikiToText($this->body
);
1358 $array = explode("\n", wordwrap($text, self
::MAX_CHARACTERS_PER_LINE
));
1360 foreach ($array as $line) {
1361 if (trim($line) != '') {
1367 'remaining_lines' => self
::MAX_LINES_PER_ARTICLE
- $lines_count,
1368 'remaining_characters_for_last_line' => self
::MAX_CHARACTERS_PER_LINE
- strlen($array[count($array) - 1])
1372 // {{{ function parseUrlsFromArticle()
1374 protected function parseUrlsFromArticle()
1376 $email_regex = '([a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+)';
1377 $url_regex = '((https?|ftp)://[a-zA-Z0-9._%#+/?=&~-]+)';
1378 $regex = '{' . $email_regex . '|' . $url_regex . '}i';
1381 $body_matches = array();
1382 if (preg_match_all($regex, $this->body(), $body_matches)) {
1383 $matches = array_merge($matches, $body_matches[0]);
1386 $append_matches = array();
1387 if (preg_match_all($regex, $this->append(), $append_matches)) {
1388 $matches = array_merge($matches, $append_matches[0]);
1395 // {{{ function getLinkIps()
1397 public function getLinkIps(&$blacklist_host_resolution_count)
1399 $matches = $this->parseUrlsFromArticle();
1400 $article_ips = array();
1402 if (!empty($matches)) {
1405 foreach ($matches as $match) {
1406 $host = parse_url($match, PHP_URL_HOST
);
1408 list(, $host) = explode('@', $match);
1411 if ($blacklist_host_resolution_count >= $globals->mail
->blacklist_host_resolution_limit
) {
1415 if (!preg_match('/^(' . str_replace(' ', '|', $globals->mail
->domain_whitelist
) . ')$/i', $host)) {
1416 $article_ips = array_merge($article_ips, array(gethostbyname($host) => $host));
1417 ++
$blacklist_host_resolution_count;
1422 return $article_ips;
1432 function format_text($input, $format, $indent = 0, $width = 68)
1434 if ($format == 'text') {
1435 return MiniWiki
::WikiToText($input, true
, $indent, $width, "title");
1437 return MiniWiki
::WikiToHTML($input, "title");
1440 // function enriched_to_text($input,$html=false,$just=false,$indent=0,$width=68)
1444 // vim:set et sw=4 sts=4 sws=4 enc=utf-8: