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($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 = {?}',
348 /** Subscribe a user to a newsletter
349 * @p $user User to subscribe to the newsletter; if null, use current user.
351 public function subscribe($user = null
)
353 if (is_null($user)) {
356 if (self
::maySubscribe($user)) {
357 XDB
::execute('INSERT IGNORE INTO newsletter_ins (nlid, uid, last, hash)
358 VALUES ({?}, {?}, NULL, hash)',
359 $this->id
, $user->id());
363 /** Retrieve subscription state of a user
364 * @p $user Target user; if null, use current user.
365 * @return Boolean: true if the user has subscribed to the NL.
367 public function subscriptionState($user = null
)
369 if (is_null($user)) {
372 $res = XDB
::query('SELECT 1
374 WHERE nlid = {?} AND uid = {?}',
375 $this->id
, $user->id());
376 return ($res->numRows() == 1);
379 /** Get the count of subscribers to the NL.
380 * @return Number of subscribers.
382 public function subscriberCount()
384 return XDB
::fetchOneCell('SELECT COUNT(uid)
386 WHERE nlid = {?}', $this->id
);
389 /** Get the number of subscribers to the NL whose last received mailing was $last.
390 * @p $last ID of the issue for which subscribers should be counted.
391 * @return Number of subscribers
393 public function subscriberCountForLast($last)
395 return XDB
::fetchOneCell('SELECT COUNT(uid)
397 WHERE nlid = {?} AND last = {?}', $this->id
, $last);
400 /** Retrieve the list of newsletters a user has subscribed to
401 * @p $user User whose subscriptions should be retrieved (if null, use session user).
402 * @return Array of newsletter IDs
404 public static function getUserSubscriptions($user = null
)
406 if (is_null($user)) {
409 $res = XDB
::query('SELECT nlid
413 return $res->fetchColumn();
416 /** Retrieve the UserFilterBuilder for subscribers to this NL.
417 * This is the place where NL-specific filters may be allowed or prevented.
418 * @p $envprefix Prefix to use for env fields (cf. UserFilterBuilder)
419 * @return A UserFilterBuilder object using the given env prefix
421 public function getSubscribersUFB($envprefix = '')
423 require_once 'ufbuilder.inc.php';
424 return new UFB_NewsLetter($this->criteria
, $envprefix);
428 // {{{ Permissions related functions
430 /** For later use: check whether a given user may subscribe to this newsletter.
431 * @p $user User whose access should be checked
432 * @return Boolean: whether the user may subscribe to the NL.
434 public function maySubscribe($user = null
)
439 /** Whether a given user may edit this newsletter
440 * @p $uid UID of the user whose perms should be checked (if null, use current user)
441 * @return Boolean: whether the user may edit the NL
443 public function mayEdit($user = null
)
445 if (is_null($user)) {
448 if ($user->checkPerms('admin')) {
451 $res = XDB
::query('SELECT perms
453 WHERE asso_id = {?} AND uid = {?}',
454 $this->group_id
, $user->id());
455 return ($res->numRows() && $res->fetchOneCell() == 'admin');
458 /** Whether a given user may submit articles to this newsletter using X.org validation system
459 * @p $user User whose access should be checked (if null, use current user)
460 * @return Boolean: whether the user may submit articles
462 public function maySubmit($user = null
)
464 // Submission of new articles is only enabled for the X.org NL (and forbidden when viewing issues on X.net)
465 return ($this->group
== self
::GROUP_XORG
&& !isset($GLOBALS['IS_XNET_SITE']));
469 // {{{ Display-related functions: cssFile, tplFile, prefix, admin_prefix, admin_links_enabled, automatic_mailings_enabled
471 /** Get the name of the css file used to display this newsletter.
473 public function cssFile()
475 if ($this->custom_css
) {
476 $base = $this->group
;
478 $base = self
::FORMAT_DEFAULT_GROUP
;
480 return 'nl.' . $base . '.css';
483 /** Get the name of the template file used to display this newsletter.
485 public function tplFile()
487 if ($this->custom_css
) {
488 $base = $this->group
;
490 $base = self
::FORMAT_DEFAULT_GROUP
;
492 return 'newsletter/nl.' . $base . '.mail.tpl';
495 /** Get the prefix leading to the page for this NL
496 * Only X.org / AX / X groups may be seen on X.org.
498 public function prefix($enforce_xnet=true
)
500 if (!empty($GLOBALS['IS_XNET_SITE'])) {
501 return $this->group
. '/nl';
503 switch ($this->group
) {
504 case self
::GROUP_XORG
:
511 // Don't display groups NLs on X.org
512 assert(!$enforce_xnet);
516 /** Get the prefix to use for all 'admin' pages of this NL.
518 public function adminPrefix($enforce_xnet=true
)
520 if (!empty($GLOBALS['IS_XNET_SITE'])) {
521 return $this->group
. '/admin/nl';
523 switch ($this->group
) {
524 case self
::GROUP_XORG
:
525 return 'admin/newsletter';
529 return 'epletter/admin';
531 // Don't display groups NLs on X.org
532 assert(!$enforce_xnet);
536 /** Hack used to remove "admin" links on X.org page on X.net
537 * The 'admin' links are enabled for all pages, except for X.org when accessing NL through X.net
539 public function adminLinksEnabled()
541 return ($this->group
!= self
::GROUP_XORG ||
!isset($GLOBALS['IS_XNET_SITE']));
544 /** Automatic mailings are disabled for X.org NL.
546 public function automaticMailingEnabled()
548 return $this->group
!= self
::GROUP_XORG
;
551 public function hasCustomCss()
553 return $this->custom_css
;
563 // A NLIssue is an issue of a given NewsLetter
566 protected $nlid; // Id of the newsletter
568 const STATE_NEW
= 'new'; // New, currently being edited
569 const STATE_PENDING
= 'pending'; // Ready for mailing
570 const STATE_SENT
= 'sent'; // Sent
572 public $nl; // Related NL
574 public $id; // Id of this issue of the newsletter
575 public $shortname; // Shortname for this issue
576 public $title; // Title of this issue
577 public $title_mail; // Title of the email
578 public $state; // State of the issue (one of the STATE_ values)
579 public $sufb; // Environment to use to generate the UFC through an UserFilterBuilder
581 public $date; // Date at which this issue was sent
582 public $send_before; // Date at which issue should be sent
583 public $head; // Foreword of the issue (or body for letters with no articles)
584 public $signature; // Signature of the letter
585 public $arts = array(); // Articles of the issue
587 const BATCH_SIZE
= 60; // Number of emails to send every minute.
589 // {{{ Constructor, id-related functions
591 /** Build a NewsLetter.
592 * @p $id: ID of the issue (unique among all newsletters)
593 * @p $nl: Optional argument containing an already built NewsLetter object.
595 function __construct($id, $nl = null
, $fetch_articles = true
)
597 return $this->fetch($id, $nl, $fetch_articles);
600 protected function refresh()
602 return $this->fetch($this->id
, $this->nl
, false
);
605 protected function fetch($id, $nl = null
, $fetch_articles = true
)
608 $res = XDB
::query('SELECT nlid, short_name, date, send_before, state, sufb_json,
609 title, mail_title, head, signature
610 FROM newsletter_issues
613 if (!$res->numRows()) {
614 throw new MailNotFound();
616 $issue = $res->fetchOneAssoc();
617 if ($nl && $nl->id
== $issue['nlid']) {
620 $this->nl
= new NewsLetter($issue['nlid']);
623 $this->shortname
= $issue['short_name'];
624 $this->date
= $issue['date'];
625 $this->send_before
= $issue['send_before'];
626 $this->state
= $issue['state'];
627 $this->title
= $issue['title'];
628 $this->title_mail
= $issue['mail_title'];
629 $this->head
= $issue['head'];
630 $this->signature
= $issue['signature'];
631 $this->sufb
= $this->importJSonStoredUFB($issue['sufb_json']);
633 if ($fetch_articles) {
634 $this->fetchArticles();
638 protected function fetchArticles($force = false
)
640 if (count($this->arts
) && !$force) {
646 'SELECT a.title, a.body, a.append, a.aid, a.cid, a.pos
647 FROM newsletter_art AS a
648 INNER JOIN newsletter_issues AS ni USING(id)
649 LEFT JOIN newsletter_cat AS c ON (a.cid = c.cid)
651 ORDER BY c.pos, a.pos',
653 while (list($title, $body, $append, $aid, $cid, $pos) = $res->next()) {
654 $this->arts
[$cid][$aid] = new NLArticle($title, $body, $append, $aid, $cid, $pos);
658 protected function importJSonStoredUFB($json = null
)
660 require_once 'ufbuilder.inc.php';
661 $ufb = $this->nl
->getSubscribersUFB();
662 if (is_null($json)) {
663 return new StoredUserFilterBuilder($ufb, new PFC_True());
665 $export = json_decode($json, true
);
666 if (is_null($export)) {
667 PlErrorReport
::report("Invalid json while reading NL {$this->nlid}, issue {$this->id}: failed to import '''{$json}'''.");
668 return new StoredUserFilterBuilder($ufb, new PFC_True());
670 $sufb = new StoredUserFilterBuilder($ufb);
671 $sufb->fillFromExport($export);
675 protected function exportStoredUFBAsJSon()
677 return json_encode($this->sufb
->export());
682 return is_null($this->shortname
) ?
$this->id
: $this->shortname
;
685 protected function selectId($where)
687 $res = XDB
::query("SELECT IFNULL(ni.short_name, ni.id)
688 FROM newsletter_issues AS ni
689 WHERE ni.state != 'new' AND ni.nlid = {?} AND ${where}
690 LIMIT 1", $this->nl
->id
);
691 if ($res->numRows() != 1) {
694 return $res->fetchOneCell();
697 /** Delete this issue
698 * @return True if the issue could be deleted, false otherwise.
699 * Related articles will be deleted through cascading FKs.
700 * If this issue was the last issue for at least one subscriber, the deletion will be aborted.
702 public function delete()
704 if ($this->state
== self
::STATE_NEW
) {
705 $res = XDB
::query('SELECT COUNT(*)
707 WHERE last = {?}', $this->id
);
708 if ($res->fetchOneCell() > 0) {
712 return XDB
::execute('DELETE FROM newsletter_issues
713 WHERE id = {?}', $this->id
);
719 /** Schedule a mailing of this NL
720 * If the 'send_before' field was NULL, it is set to the current time.
721 * @return Boolean Whether the date could be set (false if trying to schedule an already sent NL)
723 public function scheduleMailing()
725 if ($this->state
== self
::STATE_NEW
) {
726 $success = XDB
::execute('UPDATE newsletter_issues
727 SET state = \'pending\', send_before = IFNULL(send_before, NOW())
732 $mailer = new PlMailer('newsletter/notify_scheduled.mail.tpl');
733 $mailer->assign('issue', $this);
734 $mailer->assign('base', $globals->baseurl
);
744 /** Cancel the scheduled mailing of this NL
745 * @return Boolean: whether the mailing could be cancelled.
747 public function cancelMailing()
749 if ($this->state
== self
::STATE_PENDING
) {
750 $success = XDB
::execute('UPDATE newsletter_issues
752 WHERE id = {?}', $this->id
);
762 /** Helper function for smarty templates: is this issue editable ?
764 public function isEditable()
766 return $this->state
== self
::STATE_NEW
;
769 /** Helper function for smarty templates: is the mailing of this issue scheduled ?
771 public function isPending()
773 return $this->state
== self
::STATE_PENDING
;
776 /** Helper function for smarty templates: has this issue been sent ?
778 public function isSent()
780 return $this->state
== self
::STATE_SENT
;
786 private $id_prev = null
;
787 private $id_next = null
;
788 private $id_last = null
;
790 /** Retrieve ID of the previous issue
791 * That value, once fetched, is cached in the private $id_prev variable.
792 * @return ID of the previous issue.
794 public function prev()
796 if (is_null($this->id_prev
)) {
797 $this->id_prev
= $this->selectId(XDB
::format("ni.id < {?} ORDER BY ni.id DESC", $this->id
));
799 return $this->id_prev
;
802 /** Retrieve ID of the following issue
803 * That value, once fetched, is cached in the private $id_next variable.
804 * @return ID of the following issue.
806 public function next()
808 if (is_null($this->id_next
)) {
809 $this->id_next
= $this->selectId(XDB
::format("ni.id > {?} ORDER BY ni.id", $this->id
));
811 return $this->id_next
;
814 /** Retrieve ID of the last issue
815 * That value, once fetched, is cached in the private $id_last variable.
816 * @return ID of the last issue.
818 public function last()
820 if (is_null($this->id_last
)) {
821 $this->id_last
= $this->nl
->getIssue('last')->id
;
823 return $this->id_last
;
827 // {{{ Edition, articles
829 const ERROR_INVALID_SHORTNAME
= 'invalid_shortname';
830 const ERROR_INVALID_UFC
= 'invalid_ufc';
831 const ERROR_SQL_SAVE
= 'sql_error';
833 /** Save the global properties of this NL issue (title&co).
835 public function save()
839 // Fill the list of fields to update
841 'title' => $this->title
,
842 'mail_title' => $this->title_mail
,
843 'head' => $this->head
,
844 'signature' => $this->signature
,
847 if ($this->isEditable()) {
848 $fields['date'] = $this->date
;
849 if (!preg_match('/^[-a-z0-9]+$/i', $this->shortname
) ||
is_numeric($this->shortname
)) {
850 $errors[] = self
::ERROR_INVALID_SHORTNAME
;
852 $fields['short_name'] = $this->shortname
;
854 if ($this->sufb
->isValid() ||
$this->sufb
->isEmpty()) {
855 $fields['sufb_json'] = json_encode($this->sufb
->export()->dict());
857 $errors[] = self
::ERROR_INVALID_UFC
;
860 if ($this->nl
->automaticMailingEnabled()) {
861 $fields['send_before'] = ($this->send_before ?
$this->send_before
: null
);
865 if (count($errors)) {
868 $field_sets = array();
869 foreach ($fields as $key => $value) {
870 $field_sets[] = XDB
::format($key . ' = {?}', $value);
872 XDB
::execute('UPDATE newsletter_issues
873 SET ' . implode(', ', $field_sets) . '
876 if (XDB
::affectedRows()) {
879 $errors[] = self
::ERROR_SQL_SAVE
;
884 /** Get an article by number
885 * @p $aid Article ID (among articles of the issue)
886 * @return A NLArticle object, or null if there is no article by that number
888 public function getArt($aid)
890 $this->fetchArticles();
892 foreach ($this->arts
as $category => $artlist) {
893 if (isset($artlist[$aid])) {
894 return $artlist[$aid];
901 * @p $a A reference to a NLArticle object (will be modified once saved)
903 public function saveArticle($a)
905 $this->fetchArticles();
907 // Prevent cid to be 0 (use NULL instead)
908 $a->cid
= ($a->cid
== 0) ? null
: $a->cid
;
910 // Article already exists in DB
911 XDB
::execute('UPDATE newsletter_art
912 SET cid = {?}, pos = {?}, title = {?}, body = {?}, append = {?}
913 WHERE id = {?} AND aid = {?}',
914 $a->cid
, $a->pos
, $a->title
, $a->body
, $a->append
, $this->id
, $a->aid
);
917 XDB
::startTransaction();
918 list($aid, $pos) = XDB
::fetchOneRow('SELECT MAX(aid) AS aid, MAX(pos) AS pos
919 FROM newsletter_art AS a
923 $a->pos
= ($a->pos ?
$a->pos
: ++
$pos);
924 XDB
::execute('INSERT INTO newsletter_art (id, aid, cid, pos, title, body, append)
925 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
926 $this->id
, $a->aid
, $a->cid
, $a->pos
,
927 $a->title
, $a->body
, $a->append
);
930 // Update local ID of article
931 $this->arts
[$a->aid
] = $a;
934 /** Delete an article by its ID
935 * @p $aid ID of the article to delete
937 public function delArticle($aid)
939 $this->fetchArticles();
941 XDB
::execute('DELETE FROM newsletter_art WHERE id={?} AND aid={?}', $this->id
, $aid);
942 foreach ($this->arts
as $key=>$art) {
943 unset($this->arts
[$key][$aid]);
950 /** Retrieve the title of this issue
951 * @p $mail Whether we want the normal title or the email subject
952 * @return Title of the issue
954 public function title($mail = false
)
956 return $mail ?
$this->title_mail
: $this->title
;
959 /** Retrieve the head of this issue
960 * @p $user User for <dear> customization (may be null: no customization)
961 * @p $type Either 'text' or 'html'
962 * @return Formatted head of the issue.
964 public function head($user = null
, $type = 'text')
966 if (is_null($user)) {
970 $head = str_replace(array('<cher>', '<prenom>', '<nom>'),
971 array(($user->isFemale() ?
'Chère' : 'Cher'), $user->displayName(), ''),
973 return format_text($head, $type, 2, 64);
977 /** Retrieve the formatted signature of this issue.
979 public function signature($type = 'text')
981 return format_text($this->signature
, $type, 2, 64);
984 /** Get the title of a given category
985 * @p $cid ID of the category to retrieve
986 * @return Name of the category
988 public function category($cid)
990 return $this->nl
->cats
[$cid];
993 /** Add required data to the given $page for proper CSS display
994 * @p $page Smarty object
995 * @return Either 'true' (if CSS was added to a page) or the raw CSS to add (when $page is null)
997 public function css($page = null
)
999 if (!is_null($page)) {
1000 $page->addCssLink($this->nl
->cssFile());
1003 $css = file_get_contents(dirname(__FILE__
) . '/../htdocs/css/' . $this->nl
->cssFile());
1004 return preg_replace('@/\*.*?\*/@us', '', $css);
1008 /** Set up a smarty page for a 'text' mode render of the issue
1009 * @p $page Smarty object (using the $this->nl->tplFile() template)
1010 * @p $user User to use when rendering the template
1012 public function toText($page, $user)
1014 $this->fetchArticles();
1017 $page->assign('prefix', null
);
1018 $page->assign('is_mail', false
);
1019 $page->assign('mail_part', 'text');
1020 $page->assign('user', $user);
1021 $page->assign('hash', null
);
1022 $this->assignData($page);
1025 /** Set up a smarty page for a 'html' mode render of the issue
1026 * @p $page Smarty object (using the $this->nl->tplFile() template)
1027 * @p $user User to use when rendering the template
1029 public function toHtml($page, $user)
1031 $this->fetchArticles();
1034 $page->assign('prefix', $this->nl
->prefix() . '/show/' . $this->id());
1035 $page->assign('is_mail', false
);
1036 $page->assign('mail_part', 'html');
1037 $page->assign('user', $user);
1038 $page->assign('hash', null
);
1039 $this->assignData($page);
1042 /** Set all 'common' data for the page (those which are required for both web and email rendering)
1043 * @p $smarty Smarty object (e.g page) which should be filled
1045 protected function assignData($smarty)
1047 $this->fetchArticles();
1049 $smarty->assign_by_ref('issue', $this);
1050 $smarty->assign_by_ref('nl', $this->nl
);
1056 /** Check whether this issue is empty
1057 * An issue is empty if the email has no title (or the default one), or no articles and an empty head.
1059 public function isEmpty()
1061 return $this->title_mail
== '' ||
$this->title_mail
== 'to be continued' ||
(count($this->arts
) == 0 && strlen($this->head
) == 0);
1064 /** Retrieve the 'Send before' date, in a clean format.
1066 public function getSendBeforeDate()
1068 return strftime('%Y-%m-%d', strtotime($this->send_before
));
1071 /** Retrieve the 'Send before' time (i.e hour), in a clean format.
1073 public function getSendBeforeTime()
1075 return strtotime($this->send_before
);
1078 /** Create a hash based on some additional data
1079 * $line Line-specific data (to prevent two hashes generated at the same time to be the same)
1081 protected static function createHash($line)
1083 $hash = implode(time(), $line) . rand();
1088 /** Send this issue to the given user, reusing an existing hash if provided.
1089 * @p $user User to whom the issue should be mailed
1090 * @p $hash Optional hash to use in the 'unsubscribe' link; if null, another one will be generated.
1092 public function sendTo($user, $hash = null
)
1094 $this->fetchArticles();
1096 if (is_null($hash)) {
1097 $hash = XDB
::fetchOneCell("SELECT hash
1099 WHERE uid = {?} AND nlid = {?}",
1100 $user->id(), $this->nl
->id
);
1102 if (is_null($hash)) {
1103 $hash = self
::createHash(array($user->displayName(), $user->fullName(),
1104 $user->isFemale(), $user->isEmailFormatHtml(),
1105 rand(), "X.org rulez"));
1106 XDB
::execute("UPDATE newsletter_ins as ni
1108 WHERE ni.uid = {?} AND ni.nlid = {?}",
1109 $hash, $user->id(), $this->nl
->id
);
1112 $mailer = new PlMailer($this->nl
->tplFile());
1113 $this->assignData($mailer);
1114 $mailer->assign('is_mail', true
);
1115 $mailer->assign('user', $user);
1116 $mailer->assign('prefix', null
);
1117 $mailer->assign('hash', $hash);
1118 $mailer->sendTo($user);
1121 /** Select a subset of subscribers which should receive the newsletter.
1122 * NL-Specific selections (not yet received, is subscribed) are done when sending.
1123 * @return A PlFilterCondition.
1125 protected function getRecipientsUFC()
1127 return $this->sufb
->getUFC();
1130 /** Check whether a given user may see this issue.
1131 * @p $user User whose access should be checked
1132 * @return Whether he may access the issue
1134 public function checkUser($user = null
)
1136 if ($user == null
) {
1139 $uf = new UserFilter($this->getRecipientsUFC());
1140 return $uf->checkUser($user);
1143 /** Sent this issue to all valid recipients
1144 * @return Number of issues sent
1146 public function sendToAll()
1148 $this->fetchArticles();
1150 XDB
::execute('UPDATE newsletter_issues
1151 SET state = \'sent\', date=CURDATE()
1155 $ufc = new PFC_And($this->getRecipientsUFC(), new UFC_NLSubscribed($this->nl
->id
, $this->id
), new UFC_HasValidEmail());
1157 $uf = new UserFilter($ufc, array(new UFO_IsAdmin(), new UFO_Uid()));
1158 $limit = new PlLimit(self
::BATCH_SIZE
);
1162 $users = $uf->getUsers($limit);
1163 if (count($users) == 0) {
1164 return $emailsCount;
1166 foreach ($users as $user) {
1167 $sent[] = $user->id();
1168 $this->sendTo($user, $hash);
1171 XDB
::execute("UPDATE newsletter_ins
1173 WHERE nlid = {?} AND uid IN {?}", $this->id
, $this->nl
->id
, $sent);
1177 return $emailsCount;
1184 // {{{ class NLArticle
1188 // Maximum number of lines per article
1189 const MAX_LINES_PER_ARTICLE
= 8;
1190 const MAX_CHARACTERS_PER_LINE
= 68;
1204 function __construct($title='', $body='', $append='', $aid=-1, $cid=0, $pos=0)
1206 $this->body
= $body;
1207 $this->title
= $title;
1208 $this->append
= $append;
1215 // {{{ function title()
1217 public function title()
1218 { return trim($this->title
); }
1221 // {{{ function body()
1223 public function body()
1224 { return trim($this->body
); }
1227 // {{{ function append()
1229 public function append()
1230 { return trim($this->append
); }
1233 // {{{ function toText()
1235 public function toText($hash = null
, $login = null
)
1237 $title = '*'.$this->title().'*';
1238 $body = MiniWiki
::WikiToText($this->body
, true
);
1239 $app = MiniWiki
::WikiToText($this->append
, false
, 4);
1240 $text = trim("$title\n\n$body\n\n$app")."\n";
1241 if (!is_null($hash) && !is_null($login)) {
1242 $text = str_replace('%HASH%', "$hash/$login", $text);
1244 $text = str_replace('%HASH%', '', $text);
1250 // {{{ function toHtml()
1252 public function toHtml($hash = null
, $login = null
)
1254 $title = "<h2 class='xorg_nl'><a id='art{$this->aid}'></a>".pl_entities($this->title()).'</h2>';
1255 $body = MiniWiki
::WikiToHTML($this->body
);
1256 $app = MiniWiki
::WikiToHTML($this->append
);
1259 $art .= "<div class='art'>\n$body\n";
1261 $art .= "<div class='app'>$app</div>";
1264 if (!is_null($hash) && !is_null($login)) {
1265 $art = str_replace('%HASH%', "$hash/$login", $art);
1267 $art = str_replace('%HASH%', '', $art);
1274 // {{{ function check()
1276 public function check()
1278 $rest = $this->remain();
1280 return $rest['remaining_lines'] >= 0;
1284 // {{{ function remain()
1286 public function remain()
1288 $text = MiniWiki
::WikiToText($this->body
);
1289 $array = explode("\n", wordwrap($text, self
::MAX_CHARACTERS_PER_LINE
));
1291 foreach ($array as $line) {
1292 if (trim($line) != '') {
1298 'remaining_lines' => self
::MAX_LINES_PER_ARTICLE
- $lines_count,
1299 'remaining_characters_for_last_line' => self
::MAX_CHARACTERS_PER_LINE
- strlen($array[count($array) - 1])
1303 // {{{ function parseUrlsFromArticle()
1305 protected function parseUrlsFromArticle()
1307 $email_regex = '([a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+)';
1308 $url_regex = '((https?|ftp)://[a-zA-Z0-9._%#+/?=&~-]+)';
1309 $regex = '{' . $email_regex . '|' . $url_regex . '}i';
1312 $body_matches = array();
1313 if (preg_match_all($regex, $this->body(), $body_matches)) {
1314 $matches = array_merge($matches, $body_matches[0]);
1317 $append_matches = array();
1318 if (preg_match_all($regex, $this->append(), $append_matches)) {
1319 $matches = array_merge($matches, $append_matches[0]);
1326 // {{{ function getLinkIps()
1328 public function getLinkIps(&$blacklist_host_resolution_count)
1330 $matches = $this->parseUrlsFromArticle();
1331 $article_ips = array();
1333 if (!empty($matches)) {
1336 foreach ($matches as $match) {
1337 $host = parse_url($match, PHP_URL_HOST
);
1339 list(, $host) = explode('@', $match);
1342 if ($blacklist_host_resolution_count >= $globals->mail
->blacklist_host_resolution_limit
) {
1346 if (!preg_match('/^(' . str_replace(' ', '|', $globals->mail
->domain_whitelist
) . ')$/i', $host)) {
1347 $article_ips = array_merge($article_ips, array(gethostbyname($host) => $host));
1348 ++
$blacklist_host_resolution_count;
1353 return $article_ips;
1363 function format_text($input, $format, $indent = 0, $width = 68)
1365 if ($format == 'text') {
1366 return MiniWiki
::WikiToText($input, true
, $indent, $width, "title");
1368 return MiniWiki
::WikiToHTML($input, "title");
1371 // function enriched_to_text($input,$html=false,$just=false,$indent=0,$width=68)
1375 // vim:set et sw=4 sts=4 sws=4 enc=utf-8: