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 /** Retrieve subscription state of a user
370 * @p $user Target user; if null, use current user.
371 * @return Boolean: true if the user has subscribed to the NL.
373 public function subscriptionState($user = null
)
375 if (is_null($user)) {
378 $res = XDB
::query('SELECT 1
380 WHERE nlid = {?} AND uid = {?}',
381 $this->id
, $user->id());
382 return ($res->numRows() == 1);
385 /** Get the count of subscribers to the NL.
386 * @return Number of subscribers.
388 public function subscriberCount()
390 return XDB
::fetchOneCell('SELECT COUNT(uid)
392 WHERE nlid = {?}', $this->id
);
395 /** Get the number of subscribers to the NL whose last received mailing was $last.
396 * @p $last ID of the issue for which subscribers should be counted.
397 * @return Number of subscribers
399 public function subscriberCountForLast($last)
401 return XDB
::fetchOneCell('SELECT COUNT(uid)
403 WHERE nlid = {?} AND last = {?}', $this->id
, $last);
406 /** Retrieve the list of newsletters a user has subscribed to
407 * @p $user User whose subscriptions should be retrieved (if null, use session user).
408 * @return Array of newsletter IDs
410 public static function getUserSubscriptions($user = null
)
412 if (is_null($user)) {
415 $res = XDB
::query('SELECT nlid
419 return $res->fetchColumn();
422 /** Retrieve the UserFilterBuilder for subscribers to this NL.
423 * This is the place where NL-specific filters may be allowed or prevented.
424 * @p $envprefix Prefix to use for env fields (cf. UserFilterBuilder)
425 * @return A UserFilterBuilder object using the given env prefix
427 public function getSubscribersUFB($envprefix = '')
429 require_once 'ufbuilder.inc.php';
430 return new UFB_NewsLetter($this->criteria
, $envprefix);
434 // {{{ Permissions related functions
436 /** For later use: check whether a given user may subscribe to this newsletter.
437 * @p $user User whose access should be checked
438 * @return Boolean: whether the user may subscribe to the NL.
440 public function maySubscribe($user = null
)
445 /** Whether a given user may edit this newsletter
446 * @p $uid UID of the user whose perms should be checked (if null, use current user)
447 * @return Boolean: whether the user may edit the NL
449 public function mayEdit($user = null
)
451 if (is_null($user)) {
454 if ($user->checkPerms('admin')) {
457 $res = XDB
::query('SELECT perms
459 WHERE asso_id = {?} AND uid = {?}',
460 $this->group_id
, $user->id());
461 return ($res->numRows() && $res->fetchOneCell() == 'admin');
464 /** Whether a given user may submit articles to this newsletter using X.org validation system
465 * @p $user User whose access should be checked (if null, use current user)
466 * @return Boolean: whether the user may submit articles
468 public function maySubmit($user = null
)
470 // Submission of new articles is only enabled for the X.org NL (and forbidden when viewing issues on X.net)
471 return ($this->group
== self
::GROUP_XORG
&& !isset($GLOBALS['IS_XNET_SITE']));
475 // {{{ Display-related functions: cssFile, tplFile, prefix, admin_prefix, admin_links_enabled, automatic_mailings_enabled
477 /** Get the name of the css file used to display this newsletter.
479 public function cssFile()
481 if ($this->custom_css
) {
482 $base = $this->group
;
484 $base = self
::FORMAT_DEFAULT_GROUP
;
486 return 'nl.' . $base . '.css';
489 /** Get the name of the template file used to display this newsletter.
491 public function tplFile()
493 if ($this->custom_css
) {
494 $base = $this->group
;
496 $base = self
::FORMAT_DEFAULT_GROUP
;
498 return 'newsletter/nl.' . $base . '.mail.tpl';
501 /** Get the prefix leading to the page for this NL
502 * Only X.org / AX / X groups may be seen on X.org.
504 public function prefix($enforce_xnet=true
)
506 if (!empty($GLOBALS['IS_XNET_SITE'])) {
507 return $this->group
. '/nl';
509 switch ($this->group
) {
510 case self
::GROUP_XORG
:
517 // Don't display groups NLs on X.org
518 assert(!$enforce_xnet);
522 /** Get the prefix to use for all 'admin' pages of this NL.
524 public function adminPrefix($enforce_xnet=true
)
526 if (!empty($GLOBALS['IS_XNET_SITE'])) {
527 return $this->group
. '/admin/nl';
529 switch ($this->group
) {
530 case self
::GROUP_XORG
:
531 return 'admin/newsletter';
535 return 'epletter/admin';
537 // Don't display groups NLs on X.org
538 assert(!$enforce_xnet);
542 /** Hack used to remove "admin" links on X.org page on X.net
543 * The 'admin' links are enabled for all pages, except for X.org when accessing NL through X.net
545 public function adminLinksEnabled()
547 return ($this->group
!= self
::GROUP_XORG ||
!isset($GLOBALS['IS_XNET_SITE']));
550 /** Automatic mailings are disabled for X.org NL.
552 public function automaticMailingEnabled()
554 return $this->group
!= self
::GROUP_XORG
;
557 public function hasCustomCss()
559 return $this->custom_css
;
569 // A NLIssue is an issue of a given NewsLetter
572 protected $nlid; // Id of the newsletter
574 const STATE_NEW
= 'new'; // New, currently being edited
575 const STATE_PENDING
= 'pending'; // Ready for mailing
576 const STATE_SENT
= 'sent'; // Sent
578 public $nl; // Related NL
580 public $id; // Id of this issue of the newsletter
581 public $shortname; // Shortname for this issue
582 public $title; // Title of this issue
583 public $title_mail; // Title of the email
584 public $state; // State of the issue (one of the STATE_ values)
585 public $sufb; // Environment to use to generate the UFC through an UserFilterBuilder
587 public $date; // Date at which this issue was sent
588 public $send_before; // Date at which issue should be sent
589 public $head; // Foreword of the issue (or body for letters with no articles)
590 public $signature; // Signature of the letter
591 public $arts = array(); // Articles of the issue
593 const BATCH_SIZE
= 60; // Number of emails to send every minute.
595 // {{{ Constructor, id-related functions
597 /** Build a NewsLetter.
598 * @p $id: ID of the issue (unique among all newsletters)
599 * @p $nl: Optional argument containing an already built NewsLetter object.
601 function __construct($id, $nl = null
, $fetch_articles = true
)
603 return $this->fetch($id, $nl, $fetch_articles);
606 protected function refresh()
608 return $this->fetch($this->id
, $this->nl
, false
);
611 protected function fetch($id, $nl = null
, $fetch_articles = true
)
614 $res = XDB
::query('SELECT nlid, short_name, date, send_before, state, sufb_json,
615 title, mail_title, head, signature
616 FROM newsletter_issues
619 if (!$res->numRows()) {
620 throw new MailNotFound();
622 $issue = $res->fetchOneAssoc();
623 if ($nl && $nl->id
== $issue['nlid']) {
626 $this->nl
= new NewsLetter($issue['nlid']);
629 $this->nlid
= $issue['nlid'];
630 $this->shortname
= $issue['short_name'];
631 $this->date
= $issue['date'];
632 $this->send_before
= $issue['send_before'];
633 $this->state
= $issue['state'];
634 $this->title
= $issue['title'];
635 $this->title_mail
= $issue['mail_title'];
636 $this->head
= $issue['head'];
637 $this->signature
= $issue['signature'];
638 $this->sufb
= $this->importJSonStoredUFB($issue['sufb_json']);
640 if ($fetch_articles) {
641 $this->fetchArticles();
645 protected function fetchArticles($force = false
)
647 if (count($this->arts
) && !$force) {
653 'SELECT a.title, a.body, a.append, a.aid, a.cid, a.pos
654 FROM newsletter_art AS a
655 INNER JOIN newsletter_issues AS ni USING(id)
656 LEFT JOIN newsletter_cat AS c ON (a.cid = c.cid)
658 ORDER BY c.pos, a.pos',
660 while (list($title, $body, $append, $aid, $cid, $pos) = $res->next()) {
661 $this->arts
[$cid][$aid] = new NLArticle($title, $body, $append, $aid, $cid, $pos);
665 protected function importJSonStoredUFB($json = null
)
667 require_once 'ufbuilder.inc.php';
668 $ufb = $this->nl
->getSubscribersUFB();
669 if (is_null($json)) {
670 return new StoredUserFilterBuilder($ufb, new PFC_True());
672 $export = json_decode($json, true
);
673 if (is_null($export)) {
674 PlErrorReport
::report("Invalid json while reading NL {$this->nlid}, issue {$this->id}: failed to import '''{$json}'''.");
675 return new StoredUserFilterBuilder($ufb, new PFC_True());
677 $sufb = new StoredUserFilterBuilder($ufb);
678 $sufb->fillFromExport($export);
682 protected function exportStoredUFBAsJSon()
684 return json_encode($this->sufb
->export());
689 return is_null($this->shortname
) ?
$this->id
: $this->shortname
;
692 protected function selectId($where)
694 $res = XDB
::query("SELECT IFNULL(ni.short_name, ni.id)
695 FROM newsletter_issues AS ni
696 WHERE ni.state != 'new' AND ni.nlid = {?} AND ${where}
697 LIMIT 1", $this->nl
->id
);
698 if ($res->numRows() != 1) {
701 return $res->fetchOneCell();
704 /** Delete this issue
705 * @return True if the issue could be deleted, false otherwise.
706 * Related articles will be deleted through cascading FKs.
707 * If this issue was the last issue for at least one subscriber, the deletion will be aborted.
709 public function delete()
711 if ($this->state
== self
::STATE_NEW
) {
712 $res = XDB
::query('SELECT COUNT(*)
714 WHERE last = {?}', $this->id
);
715 if ($res->fetchOneCell() > 0) {
719 return XDB
::execute('DELETE FROM newsletter_issues
720 WHERE id = {?}', $this->id
);
726 /** Schedule a mailing of this NL
727 * If the 'send_before' field was NULL, it is set to the current time.
728 * @return Boolean Whether the date could be set (false if trying to schedule an already sent NL)
730 public function scheduleMailing()
732 if ($this->state
== self
::STATE_NEW
) {
733 $success = XDB
::execute('UPDATE newsletter_issues
734 SET state = \'pending\', send_before = IFNULL(send_before, NOW())
739 $mailer = new PlMailer('newsletter/notify_scheduled.mail.tpl');
740 $mailer->assign('issue', $this);
741 $mailer->assign('base', $globals->baseurl
);
751 /** Cancel the scheduled mailing of this NL
752 * @return Boolean: whether the mailing could be cancelled.
754 public function cancelMailing()
756 if ($this->state
== self
::STATE_PENDING
) {
757 $success = XDB
::execute('UPDATE newsletter_issues
759 WHERE id = {?}', $this->id
);
769 /** Helper function for smarty templates: is this issue editable ?
771 public function isEditable()
773 return $this->state
== self
::STATE_NEW
;
776 /** Helper function for smarty templates: is the mailing of this issue scheduled ?
778 public function isPending()
780 return $this->state
== self
::STATE_PENDING
;
783 /** Helper function for smarty templates: has this issue been sent ?
785 public function isSent()
787 return $this->state
== self
::STATE_SENT
;
793 private $id_prev = null
;
794 private $id_next = null
;
795 private $id_last = null
;
797 /** Retrieve ID of the previous issue
798 * That value, once fetched, is cached in the private $id_prev variable.
799 * @return ID of the previous issue.
801 public function prev()
803 if (is_null($this->id_prev
)) {
804 $this->id_prev
= $this->selectId(XDB
::format("ni.id < {?} ORDER BY ni.id DESC", $this->id
));
806 return $this->id_prev
;
809 /** Retrieve ID of the following issue
810 * That value, once fetched, is cached in the private $id_next variable.
811 * @return ID of the following issue.
813 public function next()
815 if (is_null($this->id_next
)) {
816 $this->id_next
= $this->selectId(XDB
::format("ni.id > {?} ORDER BY ni.id", $this->id
));
818 return $this->id_next
;
821 /** Retrieve ID of the last issue
822 * That value, once fetched, is cached in the private $id_last variable.
823 * @return ID of the last issue.
825 public function last()
827 if (is_null($this->id_last
)) {
828 $this->id_last
= $this->nl
->getIssue('last')->id
;
830 return $this->id_last
;
834 // {{{ Edition, articles
836 const ERROR_INVALID_SHORTNAME
= 'invalid_shortname';
837 const ERROR_INVALID_UFC
= 'invalid_ufc';
838 const ERROR_TOO_LONG_UFC
= 'too_long_ufc';
839 const ERROR_SQL_SAVE
= 'sql_error';
841 /** Save the global properties of this NL issue (title&co).
843 public function save()
847 // Fill the list of fields to update
849 'title' => $this->title
,
850 'mail_title' => $this->title_mail
,
851 'head' => $this->head
,
852 'signature' => $this->signature
,
855 if ($this->isEditable()) {
856 $fields['date'] = $this->date
;
857 if (!preg_match('/^[-a-z0-9]+$/i', $this->shortname
) ||
is_numeric($this->shortname
)) {
858 $errors[] = self
::ERROR_INVALID_SHORTNAME
;
860 $fields['short_name'] = $this->shortname
;
862 if ($this->sufb
->isValid() ||
$this->sufb
->isEmpty()) {
863 $fields['sufb_json'] = json_encode($this->sufb
->export()->dict());
864 // If sufb_json is too long to be store, we do not store a truncated json and notify the user.
865 // The limit is LONGTEXT's one, ie 2^32 = 4294967296.
866 if (strlen($fields['sufb_json']) > 4294967295) {
867 $errors[] = self
::ERROR_TOO_LONG_UFC
;
870 $errors[] = self
::ERROR_INVALID_UFC
;
873 if ($this->nl
->automaticMailingEnabled()) {
874 $fields['send_before'] = ($this->send_before ?
$this->send_before
: null
);
878 if (count($errors)) {
881 $field_sets = array();
882 foreach ($fields as $key => $value) {
883 $field_sets[] = XDB
::format($key . ' = {?}', $value);
885 XDB
::execute('UPDATE newsletter_issues
886 SET ' . implode(', ', $field_sets) . '
889 if (XDB
::affectedRows()) {
892 $errors[] = self
::ERROR_SQL_SAVE
;
897 /** Get an article by number
898 * @p $aid Article ID (among articles of the issue)
899 * @return A NLArticle object, or null if there is no article by that number
901 public function getArt($aid)
903 $this->fetchArticles();
905 foreach ($this->arts
as $category => $artlist) {
906 if (isset($artlist[$aid])) {
907 return $artlist[$aid];
914 * @p $a A reference to a NLArticle object (will be modified once saved)
916 public function saveArticle($a)
918 $this->fetchArticles();
920 // Prevent cid to be 0 (use NULL instead)
921 $a->cid
= ($a->cid
== 0) ? null
: $a->cid
;
923 // Article already exists in DB
924 XDB
::execute('UPDATE newsletter_art
925 SET cid = {?}, pos = {?}, title = {?}, body = {?}, append = {?}
926 WHERE id = {?} AND aid = {?}',
927 $a->cid
, $a->pos
, $a->title
, $a->body
, $a->append
, $this->id
, $a->aid
);
930 XDB
::startTransaction();
931 list($aid, $pos) = XDB
::fetchOneRow('SELECT MAX(aid) AS aid, MAX(pos) AS pos
932 FROM newsletter_art AS a
936 $a->pos
= ($a->pos ?
$a->pos
: ++
$pos);
937 XDB
::execute('INSERT INTO newsletter_art (id, aid, cid, pos, title, body, append)
938 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
939 $this->id
, $a->aid
, $a->cid
, $a->pos
,
940 $a->title
, $a->body
, $a->append
);
943 // Update local ID of article
944 $this->arts
[$a->aid
] = $a;
947 /** Delete an article by its ID
948 * @p $aid ID of the article to delete
950 public function delArticle($aid)
952 $this->fetchArticles();
954 XDB
::execute('DELETE FROM newsletter_art WHERE id={?} AND aid={?}', $this->id
, $aid);
955 foreach ($this->arts
as $key=>$art) {
956 unset($this->arts
[$key][$aid]);
963 /** Retrieve the title of this issue
964 * @p $mail Whether we want the normal title or the email subject
965 * @return Title of the issue
967 public function title($mail = false
)
969 return $mail ?
$this->title_mail
: $this->title
;
972 /** Retrieve the head of this issue
973 * @p $user User for <dear> customization (may be null: no customization)
974 * @p $type Either 'text' or 'html'
975 * @return Formatted head of the issue.
977 public function head($user = null
, $type = 'text')
979 if (is_null($user)) {
983 $head = str_replace(array('<cher>', '<prenom>', '<nom>'),
984 array(($user->isFemale() ?
'Chère' : 'Cher'), $user->displayName(), ''),
986 return format_text($head, $type, 2, 64);
990 /** Retrieve the formatted signature of this issue.
992 public function signature($type = 'text')
994 return format_text($this->signature
, $type, 2, 64);
997 /** Get the title of a given category
998 * @p $cid ID of the category to retrieve
999 * @return Name of the category
1001 public function category($cid)
1003 return $this->nl
->cats
[$cid];
1006 /** Add required data to the given $page for proper CSS display
1007 * @p $page Smarty object
1008 * @return Either 'true' (if CSS was added to a page) or the raw CSS to add (when $page is null)
1010 public function css($page = null
)
1012 if (!is_null($page)) {
1013 $page->addCssLink($this->nl
->cssFile());
1016 $css = file_get_contents(dirname(__FILE__
) . '/../htdocs/css/' . $this->nl
->cssFile());
1017 return preg_replace('@/\*.*?\*/@us', '', $css);
1021 /** Set up a smarty page for a 'text' mode render of the issue
1022 * @p $page Smarty object (using the $this->nl->tplFile() template)
1023 * @p $user User to use when rendering the template
1025 public function toText($page, $user)
1027 $this->fetchArticles();
1030 $page->assign('prefix', null
);
1031 $page->assign('is_mail', false
);
1032 $page->assign('mail_part', 'text');
1033 $page->assign('user', $user);
1034 $page->assign('hash', null
);
1035 $this->assignData($page);
1038 /** Set up a smarty page for a 'html' mode render of the issue
1039 * @p $page Smarty object (using the $this->nl->tplFile() template)
1040 * @p $user User to use when rendering the template
1042 public function toHtml($page, $user)
1044 $this->fetchArticles();
1047 $page->assign('prefix', $this->nl
->prefix() . '/show/' . $this->id());
1048 $page->assign('is_mail', false
);
1049 $page->assign('mail_part', 'html');
1050 $page->assign('user', $user);
1051 $page->assign('hash', null
);
1052 $this->assignData($page);
1055 /** Set all 'common' data for the page (those which are required for both web and email rendering)
1056 * @p $smarty Smarty object (e.g page) which should be filled
1058 protected function assignData($smarty)
1060 $this->fetchArticles();
1062 $smarty->assign_by_ref('issue', $this);
1063 $smarty->assign_by_ref('nl', $this->nl
);
1069 /** Check whether this issue is empty
1070 * An issue is empty if the email has no title (or the default one), or no articles and an empty head.
1072 public function isEmpty()
1074 return $this->title_mail
== '' ||
$this->title_mail
== 'to be continued' ||
(count($this->arts
) == 0 && strlen($this->head
) == 0);
1077 /** Retrieve the 'Send before' date, in a clean format.
1079 public function getSendBeforeDate()
1081 return strftime('%Y-%m-%d', strtotime($this->send_before
));
1084 /** Retrieve the 'Send before' time (i.e hour), in a clean format.
1086 public function getSendBeforeTime()
1088 return strtotime($this->send_before
);
1091 /** Create a hash based on some additional data
1092 * $line Line-specific data (to prevent two hashes generated at the same time to be the same)
1094 protected static function createHash($line)
1096 $hash = implode(time(), $line) . rand();
1101 /** Send this issue to the given user, reusing an existing hash if provided.
1102 * @p $user User to whom the issue should be mailed
1103 * @p $hash Optional hash to use in the 'unsubscribe' link; if null, another one will be generated.
1105 public function sendTo($user, $hash = null
)
1107 $this->fetchArticles();
1109 if (is_null($hash)) {
1110 $hash = XDB
::fetchOneCell("SELECT hash
1112 WHERE uid = {?} AND nlid = {?}",
1113 $user->id(), $this->nl
->id
);
1115 if (is_null($hash)) {
1116 $hash = self
::createHash(array($user->displayName(), $user->fullName(),
1117 $user->isFemale(), $user->isEmailFormatHtml(),
1118 rand(), "X.org rulez"));
1119 XDB
::execute("UPDATE newsletter_ins as ni
1121 WHERE ni.uid = {?} AND ni.nlid = {?}",
1122 $hash, $user->id(), $this->nl
->id
);
1125 $mailer = new PlMailer($this->nl
->tplFile());
1126 $this->assignData($mailer);
1127 $mailer->assign('is_mail', true
);
1128 $mailer->assign('user', $user);
1129 $mailer->assign('prefix', null
);
1130 $mailer->assign('hash', $hash);
1131 $mailer->sendTo($user);
1134 /** Select a subset of subscribers which should receive the newsletter.
1135 * NL-Specific selections (not yet received, is subscribed) are done when sending.
1136 * @return A PlFilterCondition.
1138 protected function getRecipientsUFC()
1140 return $this->sufb
->getUFC();
1143 /** Check whether a given user may see this issue.
1144 * @p $user User whose access should be checked
1145 * @return Whether he may access the issue
1147 public function checkUser($user = null
)
1149 if ($user == null
) {
1152 $uf = new UserFilter($this->getRecipientsUFC());
1153 return $uf->checkUser($user);
1156 /** Sent this issue to all valid recipients
1157 * @return Number of issues sent
1159 public function sendToAll()
1161 $this->fetchArticles();
1163 XDB
::execute('UPDATE newsletter_issues
1164 SET state = \'sent\', date=CURDATE()
1168 $ufc = new PFC_And($this->getRecipientsUFC(), new UFC_NLSubscribed($this->nl
->id
, $this->id
), new UFC_HasValidEmail());
1170 $uf = new UserFilter($ufc, array(new UFO_IsAdmin(), new UFO_Uid()));
1171 $limit = new PlLimit(self
::BATCH_SIZE
);
1175 $users = $uf->getUsers($limit);
1176 if (count($users) == 0) {
1177 return $emailsCount;
1179 foreach ($users as $user) {
1180 $sent[] = $user->id();
1181 $this->sendTo($user, $hash);
1184 XDB
::execute("UPDATE newsletter_ins
1186 WHERE nlid = {?} AND uid IN {?}", $this->id
, $this->nl
->id
, $sent);
1190 return $emailsCount;
1197 // {{{ class NLArticle
1201 // Maximum number of lines per article
1202 const MAX_LINES_PER_ARTICLE
= 8;
1203 const MAX_CHARACTERS_PER_LINE
= 68;
1217 function __construct($title='', $body='', $append='', $aid=-1, $cid=0, $pos=0)
1219 $this->body
= $body;
1220 $this->title
= $title;
1221 $this->append
= $append;
1228 // {{{ function title()
1230 public function title()
1231 { return trim($this->title
); }
1234 // {{{ function body()
1236 public function body()
1237 { return trim($this->body
); }
1240 // {{{ function append()
1242 public function append()
1243 { return trim($this->append
); }
1246 // {{{ function toText()
1248 public function toText($hash = null
, $login = null
)
1250 $title = '*'.$this->title().'*';
1251 $body = MiniWiki
::WikiToText($this->body
, true
);
1252 $app = MiniWiki
::WikiToText($this->append
, false
, 4);
1253 $text = trim("$title\n\n$body\n\n$app")."\n";
1254 if (!is_null($hash) && !is_null($login)) {
1255 $text = str_replace('%HASH%', "$hash/$login", $text);
1257 $text = str_replace('%HASH%', '', $text);
1263 // {{{ function toHtml()
1265 public function toHtml($hash = null
, $login = null
)
1267 $title = "<h2 class='xorg_nl'><a id='art{$this->aid}'></a>".pl_entities($this->title()).'</h2>';
1268 $body = MiniWiki
::WikiToHTML($this->body
);
1269 $app = MiniWiki
::WikiToHTML($this->append
);
1272 $art .= "<div class='art'>\n$body\n";
1274 $art .= "<div class='app'>$app</div>";
1277 if (!is_null($hash) && !is_null($login)) {
1278 $art = str_replace('%HASH%', "$hash/$login", $art);
1280 $art = str_replace('%HASH%', '', $art);
1287 // {{{ function check()
1289 public function check()
1291 $rest = $this->remain();
1293 return $rest['remaining_lines'] >= 0;
1297 // {{{ function remain()
1299 public function remain()
1301 $text = MiniWiki
::WikiToText($this->body
);
1302 $array = explode("\n", wordwrap($text, self
::MAX_CHARACTERS_PER_LINE
));
1304 foreach ($array as $line) {
1305 if (trim($line) != '') {
1311 'remaining_lines' => self
::MAX_LINES_PER_ARTICLE
- $lines_count,
1312 'remaining_characters_for_last_line' => self
::MAX_CHARACTERS_PER_LINE
- strlen($array[count($array) - 1])
1316 // {{{ function parseUrlsFromArticle()
1318 protected function parseUrlsFromArticle()
1320 $email_regex = '([a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+)';
1321 $url_regex = '((https?|ftp)://[a-zA-Z0-9._%#+/?=&~-]+)';
1322 $regex = '{' . $email_regex . '|' . $url_regex . '}i';
1325 $body_matches = array();
1326 if (preg_match_all($regex, $this->body(), $body_matches)) {
1327 $matches = array_merge($matches, $body_matches[0]);
1330 $append_matches = array();
1331 if (preg_match_all($regex, $this->append(), $append_matches)) {
1332 $matches = array_merge($matches, $append_matches[0]);
1339 // {{{ function getLinkIps()
1341 public function getLinkIps(&$blacklist_host_resolution_count)
1343 $matches = $this->parseUrlsFromArticle();
1344 $article_ips = array();
1346 if (!empty($matches)) {
1349 foreach ($matches as $match) {
1350 $host = parse_url($match, PHP_URL_HOST
);
1352 list(, $host) = explode('@', $match);
1355 if ($blacklist_host_resolution_count >= $globals->mail
->blacklist_host_resolution_limit
) {
1359 if (!preg_match('/^(' . str_replace(' ', '|', $globals->mail
->domain_whitelist
) . ')$/i', $host)) {
1360 $article_ips = array_merge($article_ips, array(gethostbyname($host) => $host));
1361 ++
$blacklist_host_resolution_count;
1366 return $article_ips;
1376 function format_text($input, $format, $indent = 0, $width = 68)
1378 if ($format == 'text') {
1379 return MiniWiki
::WikiToText($input, true
, $indent, $width, "title");
1381 return MiniWiki
::WikiToHTML($input, "title");
1384 // function enriched_to_text($input,$html=false,$just=false,$indent=0,$width=68)
1388 // vim:set et sw=4 sts=4 sws=4 enc=utf-8: