Uses UserFilters to count NL members.
[platal.git] / include / newsletter.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
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. *
10 * *
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. *
15 * *
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 *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 // {{{ class MailNotFound
23
24 class MailNotFound extends Exception {
25 }
26
27 // }}}
28
29 // {{{ class NewsLetter
30
31 class NewsLetter
32 {
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
39
40 protected $custom_css = false;
41
42 // Base name to use instead of the group short name for NLs without a custom CSS
43 const FORMAT_DEFAULT_GROUP = 'default';
44
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';
49
50 // Searches on mutiple fields
51 const SEARCH_ALL = 'all';
52 const SEARCH_TITLE = 'title';
53
54
55 // {{{ Constructor, NewsLetter retrieval (forGroup, getAll)
56
57 public function __construct($id)
58 {
59 // Load NL data
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)
64 WHERE nls.id = {?}',
65 $id);
66 if (!$res->numRows()) {
67 throw new MailNotFound();
68 }
69
70 $data = $res->fetchOneAssoc();
71 $this->id = $id;
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']);
77
78 // Load the categories
79 $res = XDB::iterRow(
80 'SELECT cid, title
81 FROM newsletter_cat
82 WHERE nlid = {?}
83 ORDER BY pos', $id);
84 while (list($cid, $title) = $res->next()) {
85 $this->cats[$cid] = $title;
86 }
87 }
88
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.
92 */
93 public static function forGroup($group)
94 {
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()) {
100 return null;
101 }
102 return new NewsLetter($res->fetchOneCell());
103 }
104
105 /** Retrieve all newsletters
106 * @return An array of $id => NewsLetter objects
107 */
108 public static function getAll($sort = 'id', $order = 'ASC')
109 {
110 $res = XDB::fetchAllAssoc('SELECT n.id, g.nom AS group_name, n.name, n.custom_css, n.criteria, g.diminutif AS group_link
111 FROM newsletters AS n
112 INNER JOIN groups AS g ON (n.group_id = g.id)
113 ORDER BY ' . $sort . ' ' . $order);
114 return $res;
115 }
116
117 // }}}
118 // {{{ Issue retrieval
119
120 /** Retrieve all issues which should be sent
121 * @return An array of NLIssue objects to send (i.e state = 'new' and send_before <= today)
122 */
123 public static function getIssuesToSend()
124 {
125 $res = XDB::query('SELECT id
126 FROM newsletter_issues
127 WHERE state = \'pending\' AND send_before <= NOW()');
128 $issues = array();
129 foreach ($res->fetchColumn() as $id) {
130 $issues[$id] = new NLIssue($id);
131 }
132 return $issues;
133 }
134
135 /** Retrieve a given issue of this NewsLetter
136 * @p $name Name or ID of the issue to retrieve.
137 * @return A NLIssue object.
138 *
139 * $name may be either a short_name, an ID or the special value 'last' which
140 * selects the latest sent NL.
141 * If $name is null, this will retrieve the current pending NL.
142 */
143 public function getIssue($name = null, $only_sent = true)
144 {
145 if ($name) {
146 if ($name == 'last') {
147 if ($only_sent) {
148 $where = 'state = \'sent\' AND ';
149 } else {
150 $where = '';
151 }
152 $res = XDB::query('SELECT MAX(id)
153 FROM newsletter_issues
154 WHERE ' . $where . ' nlid = {?}',
155 $this->id);
156 } else {
157 $res = XDB::query('SELECT id
158 FROM newsletter_issues
159 WHERE nlid = {?} AND (id = {?} OR short_name = {?})',
160 $this->id, $name, $name);
161 }
162 if (!$res->numRows()) {
163 throw new MailNotFound();
164 }
165 $id = $res->fetchOneCell();
166 } else {
167 $query = XDB::format('SELECT id
168 FROM newsletter_issues
169 WHERE nlid = {?} AND state = \'new\'
170 ORDER BY id DESC', $this->id);
171 $res = XDB::query($query);
172 if ($res->numRows()) {
173 $id = $res->fetchOneCell();
174 } else {
175 // Create a new, empty issue, and return it
176 $id = $this->createPending();
177 }
178 }
179
180 return new NLIssue($id, $this);
181 }
182
183 /** Create a new, empty, pending newsletter issue
184 * @p $nlid The id of the NL for which a new pending issue should be created.
185 * @return Id of the newly created issue.
186 */
187 public function createPending()
188 {
189 XDB::execute('INSERT INTO newsletter_issues
190 SET nlid = {?}, state=\'new\', date=NOW(),
191 title=\'to be continued\',
192 mail_title=\'to be continued\'',
193 $this->id);
194 return XDB::insertId();
195 }
196
197 /** Return all sent issues of this newsletter.
198 * @return An array of (id => NLIssue)
199 */
200 public function listSentIssues($check_user = false, $user = null)
201 {
202 if ($check_user && $user == null) {
203 $user = S::user();
204 }
205
206 $res = XDB::query('SELECT id
207 FROM newsletter_issues
208 WHERE nlid = {?} AND state = \'sent\'
209 ORDER BY date DESC', $this->id);
210 $issues = array();
211 foreach ($res->fetchColumn() as $id) {
212 $issue = new NLIssue($id, $this, false);
213 if (!$check_user || $issue->checkUser($user)) {
214 $issues[$id] = $issue;
215 }
216 }
217 return $issues;
218 }
219
220 /** Return all issues of this newsletter, including invalid and sent.
221 * @return An array of (id => NLIssue)
222 */
223 public function listAllIssues()
224 {
225 $res = XDB::query('SELECT id
226 FROM newsletter_issues
227 WHERE nlid = {?}
228 ORDER BY FIELD(state, \'pending\', \'new\') DESC, date DESC', $this->id);
229 $issues = array();
230 foreach ($res->fetchColumn() as $id) {
231 $issues[$id] = new NLIssue($id, $this, false);
232 }
233 return $issues;
234 }
235
236 /** Return the latest pending issue of the newsletter.
237 * @p $create Whether to create an empty issue if no pending issue exist.
238 * @return Either null, or a NL object.
239 */
240 public function getPendingIssue($create = false)
241 {
242 $res = XDB::query('SELECT MAX(id)
243 FROM newsletter_issues
244 WHERE nlid = {?} AND state = \'new\'',
245 $this->id);
246 $id = $res->fetchOneCell();
247 if ($id != null) {
248 return new NLIssue($id, $this);
249 } else if ($create) {
250 $id = $this->createPending();
251 return new NLIssue($id, $this);
252 } else {
253 return null;
254 }
255 }
256
257 /** Returns a list of either issues or articles corresponding to the search.
258 * @p $search The searched pattern.
259 * @p $field The fields where to search, if none given, search in all possible fields.
260 * @return The list of object found.
261 */
262 public function issueSearch($search, $field, $user)
263 {
264 $search = XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $search);
265 if ($field == self::SEARCH_ALL) {
266 $where = '(title ' . $search . ' OR mail_title ' . $search . ' OR head ' . $search . ' OR signature ' . $search . ')';
267 } elseif ($field == self::SEARCH_TITLE) {
268 $where = '(title ' . $search . ' OR mail_title ' . $search . ')';
269 } else {
270 $where = $field . $search;
271 }
272 $list = XDB::fetchColumn('SELECT DISTINCT(id)
273 FROM newsletter_issues
274 WHERE nlid = {?} AND state = \'sent\' AND ' . $where . '
275 ORDER BY date DESC',
276 $this->id);
277
278 $issues = array();
279 foreach ($list as $id) {
280 $issue = new NLIssue($id, $this, false);
281 if ($issue->checkUser($user)) {
282 $issues[] = $issue;
283 }
284 }
285 return $issues;
286 }
287
288 public function articleSearch($search, $field, $user)
289 {
290 $search = XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $search);
291 if ($field == self::SEARCH_ALL) {
292 $where = '(a.title ' . $search . ' OR a.body ' . $search . ' OR a.append ' . $search . ')';
293 } else {
294 $where = 'a.' . $field . $search;
295 }
296 $list = XDB::fetchAllAssoc('SELECT i.short_name, a.aid, i.id, a.title
297 FROM newsletter_art AS a
298 INNER JOIN newsletter_issues AS i ON (a.id = i.id)
299 WHERE i.nlid = {?} AND i.state = \'sent\' AND ' . $where . '
300 GROUP BY a.id, a.aid
301 ORDER BY i.date DESC, a.aid',
302 $this->id);
303
304 $articles = array();
305 foreach ($list as $item) {
306 $issue = new NLIssue($item['id'], $this, false);
307 if ($issue->checkUser($user)) {
308 $articles[] = $item;
309 }
310 }
311 return $articles;
312 }
313
314 // }}}
315 // {{{ Subscription related function
316
317 /** Unsubscribe a user from this newsletter
318 * @p $uid UID to unsubscribe from the newsletter; if null, use current user.
319 * @p $hash True if the uid is actually a hash.
320 * @return True if the user was successfully unsubscribed.
321 */
322 public function unsubscribe($issue_id = null, $uid = null, $hash = false)
323 {
324 if (is_null($uid) && $hash) {
325 // Unable to unsubscribe from an empty hash
326 return false;
327 }
328 $user = is_null($uid) ? S::user()->id() : $uid;
329 $field = $hash ? 'hash' : 'uid';
330 $res = XDB::query('SELECT uid
331 FROM newsletter_ins
332 WHERE nlid = {?} AND ' . $field . ' = {?}',
333 $this->id, $user);
334 if (!$res->numRows()) {
335 // No subscribed user with that UID/hash
336 return false;
337 }
338 $user = $res->fetchOneCell();
339
340 XDB::execute('DELETE FROM newsletter_ins
341 WHERE nlid = {?} AND uid = {?}',
342 $this->id, $user);
343 if (!is_null($issue_id)) {
344 XDB::execute('UPDATE newsletter_issues
345 SET unsubscribe = unsubscribe + 1
346 WHERE id = {?}',
347 $id);
348 }
349 return true;
350 }
351
352 /** Subscribe a user to a newsletter
353 * @p $user User to subscribe to the newsletter; if null, use current user.
354 */
355 public function subscribe($user = null)
356 {
357 if (is_null($user)) {
358 $user = S::user();
359 }
360 if (self::maySubscribe($user)) {
361 XDB::execute('INSERT IGNORE INTO newsletter_ins (nlid, uid, last, hash)
362 VALUES ({?}, {?}, NULL, hash)',
363 $this->id, $user->id());
364 }
365 }
366
367 /** Subscribe a batch of users to a newsletter.
368 * This skips 'maySubscribe' test.
369 *
370 * @p $user_ids Array of user IDs to subscribe to the newsletter.
371 */
372 public function bulkSubscribe($user_ids)
373 {
374 // TODO: use a 'bulkMaySubscribe'.
375 XDB::execute('INSERT IGNORE INTO newsletter_ins (nlid, uid, last, hash)
376 SELECT {?}, a.uid, NULL, NULL
377 FROM accounts AS a
378 WHERE a.uid IN {?}',
379 $this->id, $user_ids);
380 }
381
382 /** Retrieve subscription state of a user
383 * @p $user Target user; if null, use current user.
384 * @return Boolean: true if the user has subscribed to the NL.
385 */
386 public function subscriptionState($user = null)
387 {
388 if (is_null($user)) {
389 $user = S::user();
390 }
391 $res = XDB::query('SELECT 1
392 FROM newsletter_ins
393 WHERE nlid = {?} AND uid = {?}',
394 $this->id, $user->id());
395 return ($res->numRows() == 1);
396 }
397
398 /** Get the count of subscribers to the NL.
399 * @return Number of subscribers.
400 */
401 public function subscriberCount()
402 {
403 $uf = new UserFilter(new UFC_NLSubscribed($this->id));
404 return $uf->getTotalCount();
405 }
406
407 /** Get the count of subscribers with non valid redirection.
408 */
409 public function lostSubscriberCount()
410 {
411 $uf = new UserFilter(new PFC_And(new UFC_NLSubscribed($this->id), new PFC_Not(new UFC_HasEmailRedirect())));
412 return $uf->getTotalCount();
413 }
414
415 /** Get the number of subscribers to the NL whose last received mailing was $last.
416 * @p $last ID of the issue for which subscribers should be counted.
417 * @return Number of subscribers
418 */
419 public function subscriberCountForLast($last)
420 {
421 return XDB::fetchOneCell('SELECT COUNT(uid)
422 FROM newsletter_ins
423 WHERE nlid = {?} AND last = {?}', $this->id, $last);
424 }
425
426 /** Retrieve the list of newsletters a user has subscribed to
427 * @p $user User whose subscriptions should be retrieved (if null, use session user).
428 * @return Array of newsletter IDs
429 */
430 public static function getUserSubscriptions($user = null)
431 {
432 if (is_null($user)) {
433 $user = S::user();
434 }
435 $res = XDB::query('SELECT nlid
436 FROM newsletter_ins
437 WHERE uid = {?}',
438 $user->id());
439 return $res->fetchColumn();
440 }
441
442 /** Retrieve the UserFilterBuilder for subscribers to this NL.
443 * This is the place where NL-specific filters may be allowed or prevented.
444 * @p $envprefix Prefix to use for env fields (cf. UserFilterBuilder)
445 * @return A UserFilterBuilder object using the given env prefix
446 */
447 public function getSubscribersUFB($envprefix = '')
448 {
449 require_once 'ufbuilder.inc.php';
450 return new UFB_NewsLetter($this->criteria, $envprefix);
451 }
452
453 // }}}
454 // {{{ Permissions related functions
455
456 /** For later use: check whether a given user may subscribe to this newsletter.
457 * @p $user User whose access should be checked
458 * @return Boolean: whether the user may subscribe to the NL.
459 */
460 public function maySubscribe($user = null)
461 {
462 return true;
463 }
464
465 /** Whether a given user may edit this newsletter
466 * @p $uid UID of the user whose perms should be checked (if null, use current user)
467 * @return Boolean: whether the user may edit the NL
468 */
469 public function mayEdit($user = null)
470 {
471 if (is_null($user)) {
472 $user = S::user();
473 }
474 if ($user->checkPerms('admin')) {
475 return true;
476 }
477 $res = XDB::query('SELECT perms
478 FROM group_members
479 WHERE asso_id = {?} AND uid = {?}',
480 $this->group_id, $user->id());
481 return ($res->numRows() && $res->fetchOneCell() == 'admin');
482 }
483
484 /** Whether a given user may submit articles to this newsletter using X.org validation system
485 * @p $user User whose access should be checked (if null, use current user)
486 * @return Boolean: whether the user may submit articles
487 */
488 public function maySubmit($user = null)
489 {
490 // Submission of new articles is only enabled for the X.org NL (and forbidden when viewing issues on X.net)
491 return ($this->group == self::GROUP_XORG && !isset($GLOBALS['IS_XNET_SITE']));
492 }
493
494 // }}}
495 // {{{ Display-related functions: cssFile, tplFile, prefix, admin_prefix, admin_links_enabled, automatic_mailings_enabled
496
497 /** Get the name of the css file used to display this newsletter.
498 */
499 public function cssFile()
500 {
501 if ($this->custom_css) {
502 $base = $this->group;
503 } else {
504 $base = self::FORMAT_DEFAULT_GROUP;
505 }
506 return 'nl.' . $base . '.css';
507 }
508
509 /** Get the name of the template file used to display this newsletter.
510 */
511 public function tplFile()
512 {
513 if ($this->custom_css) {
514 $base = $this->group;
515 } else {
516 $base = self::FORMAT_DEFAULT_GROUP;
517 }
518 return 'newsletter/nl.' . $base . '.mail.tpl';
519 }
520
521 /** Get the prefix leading to the page for this NL
522 * Only X.org / AX / X groups may be seen on X.org.
523 */
524 public function prefix($enforce_xnet=true, $with_group=true)
525 {
526 if (!empty($GLOBALS['IS_XNET_SITE'])) {
527 if ($with_group) {
528 return $this->group . '/nl';
529 } else {
530 return 'nl';
531 }
532 }
533 switch ($this->group) {
534 case self::GROUP_XORG:
535 return 'nl';
536 case self::GROUP_AX:
537 return 'ax';
538 case self::GROUP_EP:
539 return 'epletter';
540 default:
541 // Don't display groups NLs on X.org
542 assert(!$enforce_xnet);
543 }
544 }
545
546 /** Get the prefix to use for all 'admin' pages of this NL.
547 */
548 public function adminPrefix($enforce_xnet=true, $with_group=true)
549 {
550 if (!empty($GLOBALS['IS_XNET_SITE'])) {
551 if ($with_group) {
552 return $this->group . '/admin/nl';
553 } else {
554 return 'admin/nl';
555 }
556 }
557 switch ($this->group) {
558 case self::GROUP_XORG:
559 return 'admin/newsletter';
560 case self::GROUP_AX:
561 return 'ax/admin';
562 case self::GROUP_EP:
563 return 'epletter/admin';
564 default:
565 // Don't display groups NLs on X.org
566 assert(!$enforce_xnet);
567 }
568 }
569
570 /** Get links for nl pages.
571 */
572 public function adminLinks()
573 {
574 return array(
575 'index' => array('link' => $this->prefix(), 'title' => 'Archives'),
576 'admin' => array('link' => $this->adminPrefix(), 'title' => 'Administrer')
577 );
578 }
579
580 /** Hack used to remove "admin" links on X.org page on X.net
581 * The 'admin' links are enabled for all pages, except for X.org when accessing NL through X.net
582 */
583 public function adminLinksEnabled()
584 {
585 return ($this->group != self::GROUP_XORG || !isset($GLOBALS['IS_XNET_SITE']));
586 }
587
588 /** Automatic mailings are disabled for X.org NL.
589 */
590 public function automaticMailingEnabled()
591 {
592 return $this->group != self::GROUP_XORG;
593 }
594
595 public function hasCustomCss()
596 {
597 return $this->custom_css;
598 }
599
600 public function canSyncWithGroup()
601 {
602 switch ($this->group) {
603 case self::GROUP_XORG:
604 case self::GROUP_AX:
605 case self::GROUP_EP:
606 return false;
607 default:
608 return true;
609 }
610 }
611
612 // }}}
613 }
614
615 // }}}
616
617 // {{{ class NLIssue
618
619 // A NLIssue is an issue of a given NewsLetter
620 class NLIssue
621 {
622 protected $nlid; // Id of the newsletter
623
624 const STATE_NEW = 'new'; // New, currently being edited
625 const STATE_PENDING = 'pending'; // Ready for mailing
626 const STATE_SENT = 'sent'; // Sent
627
628 public $nl; // Related NL
629
630 public $id; // Id of this issue of the newsletter
631 public $shortname; // Shortname for this issue
632 public $title; // Title of this issue
633 public $title_mail; // Title of the email
634 public $state; // State of the issue (one of the STATE_ values)
635 public $sufb; // Environment to use to generate the UFC through an UserFilterBuilder
636
637 public $date; // Date at which this issue was sent
638 public $send_before; // Date at which issue should be sent
639 public $head; // Foreword of the issue (or body for letters with no articles)
640 public $signature; // Signature of the letter
641 public $reply_to; // Adress to reply to the message (can be empty)
642 public $arts = array(); // Articles of the issue
643
644 const BATCH_SIZE = 60; // Number of emails to send every minute.
645
646 // {{{ Constructor, id-related functions
647
648 /** Build a NewsLetter.
649 * @p $id: ID of the issue (unique among all newsletters)
650 * @p $nl: Optional argument containing an already built NewsLetter object.
651 */
652 function __construct($id, $nl = null, $fetch_articles = true)
653 {
654 return $this->fetch($id, $nl, $fetch_articles);
655 }
656
657 protected function refresh()
658 {
659 return $this->fetch($this->id, $this->nl, false);
660 }
661
662 protected function fetch($id, $nl = null, $fetch_articles = true)
663 {
664 // Load this issue
665 $res = XDB::query('SELECT nlid, short_name, date, send_before, state, sufb_json,
666 title, mail_title, head, signature, reply_to
667 FROM newsletter_issues
668 WHERE id = {?}',
669 $id);
670 if (!$res->numRows()) {
671 throw new MailNotFound();
672 }
673 $issue = $res->fetchOneAssoc();
674 if ($nl && $nl->id == $issue['nlid']) {
675 $this->nl = $nl;
676 } else {
677 $this->nl = new NewsLetter($issue['nlid']);
678 }
679 $this->id = $id;
680 $this->nlid = $issue['nlid'];
681 $this->shortname = $issue['short_name'];
682 $this->date = $issue['date'];
683 $this->send_before = $issue['send_before'];
684 $this->state = $issue['state'];
685 $this->title = $issue['title'];
686 $this->title_mail = $issue['mail_title'];
687 $this->head = $issue['head'];
688 $this->signature = $issue['signature'];
689 $this->reply_to = $issue['reply_to'];
690 $this->sufb = $this->importJSonStoredUFB($issue['sufb_json']);
691
692 if ($fetch_articles) {
693 $this->fetchArticles();
694 }
695 }
696
697 protected function fetchArticles($force = false)
698 {
699 if (count($this->arts) && !$force) {
700 return;
701 }
702
703 // Load the articles
704 $res = XDB::iterRow(
705 'SELECT a.title, a.body, a.append, a.aid, a.cid, a.pos
706 FROM newsletter_art AS a
707 INNER JOIN newsletter_issues AS ni USING(id)
708 LEFT JOIN newsletter_cat AS c ON (a.cid = c.cid)
709 WHERE a.id = {?}
710 ORDER BY c.pos, a.pos',
711 $this->id);
712 while (list($title, $body, $append, $aid, $cid, $pos) = $res->next()) {
713 $this->arts[$cid][$aid] = new NLArticle($title, $body, $append, $aid, $cid, $pos);
714 }
715 }
716
717 protected function importJSonStoredUFB($json = null)
718 {
719 require_once 'ufbuilder.inc.php';
720 $ufb = $this->nl->getSubscribersUFB();
721 if (is_null($json)) {
722 return new StoredUserFilterBuilder($ufb, new PFC_True());
723 }
724 $export = json_decode($json, true);
725 if (is_null($export)) {
726 PlErrorReport::report("Invalid json while reading NL {$this->nlid}, issue {$this->id}: failed to import '''{$json}'''.");
727 return new StoredUserFilterBuilder($ufb, new PFC_True());
728 }
729 $sufb = new StoredUserFilterBuilder($ufb);
730 $sufb->fillFromExport($export);
731 return $sufb;
732 }
733
734 protected function exportStoredUFBAsJSon()
735 {
736 return json_encode($this->sufb->export());
737 }
738
739 public function id()
740 {
741 return is_null($this->shortname) ? $this->id : $this->shortname;
742 }
743
744 protected function selectId($where)
745 {
746 $res = XDB::query("SELECT IFNULL(ni.short_name, ni.id)
747 FROM newsletter_issues AS ni
748 WHERE ni.state != 'new' AND ni.nlid = {?} AND ${where}
749 LIMIT 1", $this->nl->id);
750 if ($res->numRows() != 1) {
751 return null;
752 }
753 return $res->fetchOneCell();
754 }
755
756 /** Delete this issue
757 * @return True if the issue could be deleted, false otherwise.
758 * Related articles will be deleted through cascading FKs.
759 * If this issue was the last issue for at least one subscriber, the deletion will be aborted.
760 */
761 public function delete()
762 {
763 if ($this->state == self::STATE_NEW) {
764 $res = XDB::query('SELECT COUNT(*)
765 FROM newsletter_ins
766 WHERE last = {?}', $this->id);
767 if ($res->fetchOneCell() > 0) {
768 return false;
769 }
770
771 return XDB::execute('DELETE FROM newsletter_issues
772 WHERE id = {?}', $this->id);
773 } else {
774 return false;
775 }
776 }
777
778 /** Schedule a mailing of this NL
779 * If the 'send_before' field was NULL, it is set to the current time.
780 * @return Boolean Whether the date could be set (false if trying to schedule an already sent NL)
781 */
782 public function scheduleMailing()
783 {
784 if ($this->state == self::STATE_NEW) {
785 $success = XDB::execute('UPDATE newsletter_issues
786 SET state = \'pending\', send_before = IFNULL(send_before, NOW())
787 WHERE id = {?}',
788 $this->id);
789 if ($success) {
790 global $globals;
791 $mailer = new PlMailer('newsletter/notify_scheduled.mail.tpl');
792 $mailer->assign('issue', $this);
793 $mailer->assign('base', $globals->baseurl);
794 $mailer->send();
795 $this->refresh();
796 }
797 return $success;
798 } else {
799 return false;
800 }
801 }
802
803 /** Cancel the scheduled mailing of this NL
804 * @return Boolean: whether the mailing could be cancelled.
805 */
806 public function cancelMailing()
807 {
808 if ($this->state == self::STATE_PENDING) {
809 $success = XDB::execute('UPDATE newsletter_issues
810 SET state = \'new\'
811 WHERE id = {?}', $this->id);
812 if ($success) {
813 $this->refresh();
814 }
815 return $success;
816 } else {
817 return false;
818 }
819 }
820
821 /** Helper function for smarty templates: is this issue editable ?
822 */
823 public function isEditable()
824 {
825 return $this->state == self::STATE_NEW;
826 }
827
828 /** Helper function for smarty templates: is the mailing of this issue scheduled ?
829 */
830 public function isPending()
831 {
832 return $this->state == self::STATE_PENDING;
833 }
834
835 /** Helper function for smarty templates: has this issue been sent ?
836 */
837 public function isSent()
838 {
839 return $this->state == self::STATE_SENT;
840 }
841
842 // }}}
843 // {{{ Navigation
844
845 private $id_prev = null;
846 private $id_next = null;
847 private $id_last = null;
848
849 /** Retrieve ID of the previous issue
850 * That value, once fetched, is cached in the private $id_prev variable.
851 * @return ID of the previous issue.
852 */
853 public function prev()
854 {
855 if (is_null($this->id_prev)) {
856 $this->id_prev = $this->selectId(XDB::format("ni.id < {?} ORDER BY ni.id DESC", $this->id));
857 }
858 return $this->id_prev;
859 }
860
861 /** Retrieve ID of the following issue
862 * That value, once fetched, is cached in the private $id_next variable.
863 * @return ID of the following issue.
864 */
865 public function next()
866 {
867 if (is_null($this->id_next)) {
868 $this->id_next = $this->selectId(XDB::format("ni.id > {?} ORDER BY ni.id", $this->id));
869 }
870 return $this->id_next;
871 }
872
873 /** Retrieve ID of the last issue
874 * That value, once fetched, is cached in the private $id_last variable.
875 * @return ID of the last issue.
876 */
877 public function last()
878 {
879 if (is_null($this->id_last)) {
880 try {
881 $this->id_last = $this->nl->getIssue('last')->id;
882 } catch (MailNotFound $e) {
883 $this->id_last = null;
884 }
885 }
886 return $this->id_last;
887 }
888
889 // }}}
890 // {{{ Edition, articles
891
892 const ERROR_INVALID_REPLY_TO = 'invalid_reply_to';
893 const ERROR_INVALID_SHORTNAME = 'invalid_shortname';
894 const ERROR_INVALID_UFC = 'invalid_ufc';
895 const ERROR_TOO_LONG_UFC = 'too_long_ufc';
896 const ERROR_SQL_SAVE = 'sql_error';
897
898 /** Save the global properties of this NL issue (title&co).
899 */
900 public function save()
901 {
902 $errors = array();
903
904 // Fill the list of fields to update
905 $fields = array(
906 'title' => $this->title,
907 'mail_title' => $this->title_mail,
908 'head' => $this->head,
909 'signature' => $this->signature,
910 );
911
912 if (!empty($this->reply_to) && !isvalid_email($this->reply_to)) {
913 $errors[] = self::ERROR_INVALID_REPLY_TO ;
914 } else {
915 $fields['reply_to'] = $this->reply_to;
916 }
917
918 if ($this->isEditable()) {
919 $fields['date'] = $this->date;
920 if (!preg_match('/^[-a-z0-9]+$/i', $this->shortname) || is_numeric($this->shortname)) {
921 $errors[] = self::ERROR_INVALID_SHORTNAME;
922 } else {
923 $fields['short_name'] = $this->shortname;
924 }
925 if ($this->sufb->isValid() || $this->sufb->isEmpty()) {
926 $fields['sufb_json'] = json_encode($this->sufb->export()->dict());
927 // If sufb_json is too long to be store, we do not store a truncated json and notify the user.
928 // The limit is LONGTEXT's one, ie 2^32 = 4294967296.
929 if (strlen($fields['sufb_json']) > 4294967295) {
930 $errors[] = self::ERROR_TOO_LONG_UFC;
931 }
932 } else {
933 $errors[] = self::ERROR_INVALID_UFC;
934 }
935
936 if ($this->nl->automaticMailingEnabled()) {
937 $fields['send_before'] = ($this->send_before ? $this->send_before : null);
938 }
939 }
940
941 if (count($errors)) {
942 return $errors;
943 }
944 $field_sets = array();
945 foreach ($fields as $key => $value) {
946 $field_sets[] = XDB::format($key . ' = {?}', $value);
947 }
948 XDB::execute('UPDATE newsletter_issues
949 SET ' . implode(', ', $field_sets) . '
950 WHERE id={?}',
951 $this->id);
952 if (XDB::affectedRows()) {
953 $this->refresh();
954 } else {
955 $errors[] = self::ERROR_SQL_SAVE;
956 }
957 return $errors;
958 }
959
960 /** Get an article by number
961 * @p $aid Article ID (among articles of the issue)
962 * @return A NLArticle object, or null if there is no article by that number
963 */
964 public function getArt($aid)
965 {
966 $this->fetchArticles();
967
968 foreach ($this->arts as $category => $artlist) {
969 if (isset($artlist[$aid])) {
970 return $artlist[$aid];
971 }
972 }
973 return null;
974 }
975
976 /** Save an article
977 * @p $a A reference to a NLArticle object (will be modified once saved)
978 */
979 public function saveArticle($a)
980 {
981 $this->fetchArticles();
982
983 // Prevent cid to be 0 (use NULL instead)
984 $a->cid = ($a->cid == 0) ? null : $a->cid;
985 if ($a->aid >= 0) {
986 // Article already exists in DB
987 XDB::execute('UPDATE newsletter_art
988 SET cid = {?}, pos = {?}, title = {?}, body = {?}, append = {?}
989 WHERE id = {?} AND aid = {?}',
990 $a->cid, $a->pos, $a->title, $a->body, $a->append, $this->id, $a->aid);
991 } else {
992 // New article
993 XDB::startTransaction();
994 list($aid, $pos) = XDB::fetchOneRow('SELECT MAX(aid) AS aid, MAX(pos) AS pos
995 FROM newsletter_art AS a
996 WHERE a.id = {?}',
997 $this->id);
998 $a->aid = ++$aid;
999 $a->pos = ($a->pos ? $a->pos : ++$pos);
1000 XDB::execute('INSERT INTO newsletter_art (id, aid, cid, pos, title, body, append)
1001 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
1002 $this->id, $a->aid, $a->cid, $a->pos,
1003 $a->title, $a->body, $a->append);
1004 XDB::commit();
1005 }
1006 // Update local ID of article
1007 $this->arts[$a->aid] = $a;
1008 }
1009
1010 /** Delete an article by its ID
1011 * @p $aid ID of the article to delete
1012 */
1013 public function delArticle($aid)
1014 {
1015 $this->fetchArticles();
1016
1017 XDB::execute('DELETE FROM newsletter_art WHERE id={?} AND aid={?}', $this->id, $aid);
1018 foreach ($this->arts as $key=>$art) {
1019 unset($this->arts[$key][$aid]);
1020 }
1021 }
1022
1023 // }}}
1024 // {{{ Display
1025
1026 /** Retrieve the title of this issue
1027 * @p $mail Whether we want the normal title or the email subject
1028 * @return Title of the issue
1029 */
1030 public function title($mail = false)
1031 {
1032 return $mail ? $this->title_mail : $this->title;
1033 }
1034
1035 /** Retrieve the head of this issue
1036 * @p $user User for <dear> customization (may be null: no customization)
1037 * @p $type Either 'text' or 'html'
1038 * @return Formatted head of the issue.
1039 */
1040 public function head($user = null, $type = 'text')
1041 {
1042 if (is_null($user)) {
1043 return $this->head;
1044 } else {
1045 $head = $this->head;
1046 $head = str_replace(array('<cher>', '<prenom>', '<nom>'),
1047 array(($user->isFemale() ? 'Chère' : 'Cher'), $user->displayName(), ''),
1048 $head);
1049 return format_text($head, $type, 2, 64);
1050 }
1051 }
1052
1053 /** Retrieve the formatted signature of this issue.
1054 */
1055 public function signature($type = 'text')
1056 {
1057 return format_text($this->signature, $type, 2, 64);
1058 }
1059
1060 /** Get the title of a given category
1061 * @p $cid ID of the category to retrieve
1062 * @return Name of the category
1063 */
1064 public function category($cid)
1065 {
1066 return $this->nl->cats[$cid];
1067 }
1068
1069 /** Add required data to the given $page for proper CSS display
1070 * @p $page Smarty object
1071 * @return Either 'true' (if CSS was added to a page) or the raw CSS to add (when $page is null)
1072 */
1073 public function css($page = null)
1074 {
1075 if (!is_null($page)) {
1076 $page->addCssLink($this->nl->cssFile());
1077 return true;
1078 } else {
1079 $css = file_get_contents(dirname(__FILE__) . '/../htdocs/css/' . $this->nl->cssFile());
1080 return preg_replace('@/\*.*?\*/@us', '', $css);
1081 }
1082 }
1083
1084 /** Set up a smarty page for a 'text' mode render of the issue
1085 * @p $page Smarty object (using the $this->nl->tplFile() template)
1086 * @p $user User to use when rendering the template
1087 */
1088 public function toText($page, $user)
1089 {
1090 $this->fetchArticles();
1091
1092 $this->css($page);
1093 $page->assign('prefix', null);
1094 $page->assign('is_mail', false);
1095 $page->assign('mail_part', 'text');
1096 $page->assign('user', $user);
1097 $page->assign('hash', null);
1098 $this->assignData($page);
1099 }
1100
1101 /** Set up a smarty page for a 'html' mode render of the issue
1102 * @p $page Smarty object (using the $this->nl->tplFile() template)
1103 * @p $user User to use when rendering the template
1104 */
1105 public function toHtml($page, $user)
1106 {
1107 $this->fetchArticles();
1108
1109 $this->css($page);
1110 $page->assign('prefix', $this->nl->prefix() . '/show/' . $this->id());
1111 $page->assign('is_mail', false);
1112 $page->assign('mail_part', 'html');
1113 $page->assign('user', $user);
1114 $page->assign('hash', null);
1115 $this->assignData($page);
1116 }
1117
1118 /** Set all 'common' data for the page (those which are required for both web and email rendering)
1119 * @p $smarty Smarty object (e.g page) which should be filled
1120 */
1121 protected function assignData($smarty)
1122 {
1123 $this->fetchArticles();
1124
1125 $smarty->assign_by_ref('issue', $this);
1126 $smarty->assign_by_ref('nl', $this->nl);
1127 }
1128
1129 // }}}
1130 // {{{ Mailing
1131
1132 /** Check whether this issue is empty
1133 * An issue is empty if the email has no title (or the default one), or no articles and an empty head.
1134 */
1135 public function isEmpty()
1136 {
1137 return $this->title_mail == '' || $this->title_mail == 'to be continued' || (count($this->arts) == 0 && strlen($this->head) == 0);
1138 }
1139
1140 /** Retrieve the 'Send before' date, in a clean format.
1141 */
1142 public function getSendBeforeDate()
1143 {
1144 return strftime('%Y-%m-%d', strtotime($this->send_before));
1145 }
1146
1147 /** Retrieve the 'Send before' time (i.e hour), in a clean format.
1148 */
1149 public function getSendBeforeTime()
1150 {
1151 return strtotime($this->send_before);
1152 }
1153
1154 /** Create a hash based on some additional data
1155 * $line Line-specific data (to prevent two hashes generated at the same time to be the same)
1156 */
1157 protected static function createHash($line)
1158 {
1159 $hash = implode(time(), $line) . rand();
1160 $hash = md5($hash);
1161 return $hash;
1162 }
1163
1164 /** Send this issue to the given user, reusing an existing hash if provided.
1165 * @p $user User to whom the issue should be mailed
1166 * @p $hash Optional hash to use in the 'unsubscribe' link; if null, another one will be generated.
1167 */
1168 public function sendTo($user, $hash = null)
1169 {
1170 $this->fetchArticles();
1171
1172 if (is_null($hash)) {
1173 $hash = XDB::fetchOneCell("SELECT hash
1174 FROM newsletter_ins
1175 WHERE uid = {?} AND nlid = {?}",
1176 $user->id(), $this->nl->id);
1177 }
1178 if (is_null($hash)) {
1179 $hash = self::createHash(array($user->displayName(), $user->fullName(),
1180 $user->isFemale(), $user->isEmailFormatHtml(),
1181 rand(), "X.org rulez"));
1182 XDB::execute("UPDATE newsletter_ins as ni
1183 SET ni.hash = {?}
1184 WHERE ni.uid = {?} AND ni.nlid = {?}",
1185 $hash, $user->id(), $this->nl->id);
1186 }
1187
1188 $mailer = new PlMailer($this->nl->tplFile());
1189 $this->assignData($mailer);
1190 $mailer->assign('is_mail', true);
1191 $mailer->assign('user', $user);
1192 $mailer->assign('prefix', null);
1193 $mailer->assign('hash', $hash);
1194 if (!empty($this->reply_to)) {
1195 $mailer->addHeader('Reply-To', $this->reply_to);
1196 }
1197 $mailer->sendTo($user);
1198 }
1199
1200 /** Select a subset of subscribers which should receive the newsletter.
1201 * NL-Specific selections (not yet received, is subscribed) are done when sending.
1202 * @return A PlFilterCondition.
1203 */
1204 protected function getRecipientsUFC()
1205 {
1206 return $this->sufb->getUFC();
1207 }
1208
1209 /** Check whether a given user may see this issue.
1210 * @p $user User whose access should be checked
1211 * @return Whether he may access the issue
1212 */
1213 public function checkUser($user = null)
1214 {
1215 if ($user == null) {
1216 $user = S::user();
1217 }
1218 $uf = new UserFilter($this->getRecipientsUFC());
1219 return $uf->checkUser($user);
1220 }
1221
1222 /** Sent this issue to all valid recipients
1223 * @return Number of issues sent
1224 */
1225 public function sendToAll()
1226 {
1227 $this->fetchArticles();
1228
1229 XDB::execute('UPDATE newsletter_issues
1230 SET state = \'sent\', date=CURDATE()
1231 WHERE id = {?}',
1232 $this->id);
1233
1234 $ufc = new PFC_And($this->getRecipientsUFC(), new UFC_NLSubscribed($this->nl->id, $this->id), new UFC_HasValidEmail());
1235 $uf = new UserFilter($ufc, array(new UFO_IsAdmin(true), new UFO_Uid()));
1236 $limit = new PlLimit(self::BATCH_SIZE);
1237 $global_sent = array();
1238
1239 while (true) {
1240 $sent = array();
1241 $users = $uf->getUsers($limit);
1242 if (count($users) == 0) {
1243 break;
1244 }
1245 foreach ($users as $user) {
1246 if (array_key_exists($user->id(), $global_sent)) {
1247 Platal::page()->kill('Sending the same newsletter issue ' . $this->id . ' to user ' . $user->id() . ' twice, something must be wrong.');
1248 }
1249 $sent[] = $user->id();
1250 $global_sent[$user->id()] = true;
1251 $this->sendTo($user, $hash);
1252 }
1253 XDB::execute("UPDATE newsletter_ins
1254 SET last = {?}
1255 WHERE nlid = {?} AND uid IN {?}", $this->id, $this->nl->id, $sent);
1256
1257 sleep(60);
1258 }
1259 return count($global_sent);
1260 }
1261
1262 // }}}
1263 }
1264
1265 // }}}
1266 // {{{ class NLArticle
1267
1268 class NLArticle
1269 {
1270 // Maximum number of lines per article
1271 const MAX_LINES_PER_ARTICLE = 8;
1272 const MAX_CHARACTERS_PER_LINE = 68;
1273
1274 // {{{ properties
1275
1276 public $aid;
1277 public $cid;
1278 public $pos;
1279 public $title;
1280 public $body;
1281 public $append;
1282
1283 // }}}
1284 // {{{ constructor
1285
1286 function __construct($title='', $body='', $append='', $aid=-1, $cid=0, $pos=0)
1287 {
1288 $this->body = $body;
1289 $this->title = $title;
1290 $this->append = $append;
1291 $this->aid = $aid;
1292 $this->cid = $cid;
1293 $this->pos = $pos;
1294 }
1295
1296 // }}}
1297 // {{{ function title()
1298
1299 public function title()
1300 { return trim($this->title); }
1301
1302 // }}}
1303 // {{{ function body()
1304
1305 public function body()
1306 { return trim($this->body); }
1307
1308 // }}}
1309 // {{{ function append()
1310
1311 public function append()
1312 { return trim($this->append); }
1313
1314 // }}}
1315 // {{{ function toText()
1316
1317 public function toText($hash = null, $login = null)
1318 {
1319 $title = '*'.$this->title().'*';
1320 $body = MiniWiki::WikiToText($this->body, true);
1321 $app = MiniWiki::WikiToText($this->append, false, 4);
1322 $text = trim("$title\n\n$body\n\n$app")."\n";
1323 if (!is_null($hash) && !is_null($login)) {
1324 $text = str_replace('%HASH%', "$hash/$login", $text);
1325 } else {
1326 $text = str_replace('%HASH%', '', $text);
1327 }
1328 return $text;
1329 }
1330
1331 // }}}
1332 // {{{ function toHtml()
1333
1334 public function toHtml($hash = null, $login = null)
1335 {
1336 $title = "<h2 class='xorg_nl'><a id='art{$this->aid}'></a>".pl_entities($this->title()).'</h2>';
1337 $body = MiniWiki::WikiToHTML($this->body);
1338 $app = MiniWiki::WikiToHTML($this->append);
1339
1340 $art = "$title\n";
1341 $art .= "<div class='art'>\n$body\n";
1342 if ($app) {
1343 $art .= "<div class='app'>$app</div>";
1344 }
1345 $art .= "</div>\n";
1346 if (!is_null($hash) && !is_null($login)) {
1347 $art = str_replace('%HASH%', "$hash/$login", $art);
1348 } else {
1349 $art = str_replace('%HASH%', '', $art);
1350 }
1351
1352 return $art;
1353 }
1354
1355 // }}}
1356 // {{{ function check()
1357
1358 public function check()
1359 {
1360 $rest = $this->remain();
1361
1362 return $rest['remaining_lines'] >= 0;
1363 }
1364
1365 // }}}
1366 // {{{ function remain()
1367
1368 public function remain()
1369 {
1370 $text = MiniWiki::WikiToText($this->body);
1371 $array = explode("\n", wordwrap($text, self::MAX_CHARACTERS_PER_LINE));
1372 $lines_count = 0;
1373 foreach ($array as $line) {
1374 if (trim($line) != '') {
1375 ++$lines_count;
1376 }
1377 }
1378
1379 return array(
1380 'remaining_lines' => self::MAX_LINES_PER_ARTICLE - $lines_count,
1381 'remaining_characters_for_last_line' => self::MAX_CHARACTERS_PER_LINE - strlen($array[count($array) - 1])
1382 );
1383 }
1384 // }}}
1385 // {{{ function parseUrlsFromArticle()
1386
1387 protected function parseUrlsFromArticle()
1388 {
1389 $email_regex = '([a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+)';
1390 $url_regex = '((https?|ftp)://[a-zA-Z0-9._%#+/?=&~-]+)';
1391 $regex = '{' . $email_regex . '|' . $url_regex . '}i';
1392
1393 $matches = array();
1394 $body_matches = array();
1395 if (preg_match_all($regex, $this->body(), $body_matches)) {
1396 $matches = array_merge($matches, $body_matches[0]);
1397 }
1398
1399 $append_matches = array();
1400 if (preg_match_all($regex, $this->append(), $append_matches)) {
1401 $matches = array_merge($matches, $append_matches[0]);
1402 }
1403
1404 return $matches;
1405 }
1406
1407 // }}}
1408 // {{{ function getLinkIps()
1409
1410 public function getLinkIps(&$blacklist_host_resolution_count)
1411 {
1412 $matches = $this->parseUrlsFromArticle();
1413 $article_ips = array();
1414
1415 if (!empty($matches)) {
1416 global $globals;
1417
1418 foreach ($matches as $match) {
1419 $host = parse_url($match, PHP_URL_HOST);
1420 if ($host == '') {
1421 list(, $host) = explode('@', $match);
1422 }
1423
1424 if ($blacklist_host_resolution_count >= $globals->mail->blacklist_host_resolution_limit) {
1425 break;
1426 }
1427
1428 if (!preg_match('/^(' . str_replace(' ', '|', $globals->mail->domain_whitelist) . ')$/i', $host)) {
1429 $article_ips = array_merge($article_ips, array(gethostbyname($host) => $host));
1430 ++$blacklist_host_resolution_count;
1431 }
1432 }
1433 }
1434
1435 return $article_ips;
1436 }
1437
1438 // }}}
1439 }
1440
1441 // }}}
1442
1443 // {{{ Functions
1444
1445 function format_text($input, $format, $indent = 0, $width = 68)
1446 {
1447 if ($format == 'text') {
1448 return MiniWiki::WikiToText($input, true, $indent, $width, "title");
1449 }
1450 return MiniWiki::WikiToHTML($input, "title");
1451 }
1452
1453 // function enriched_to_text($input,$html=false,$just=false,$indent=0,$width=68)
1454
1455 // }}}
1456
1457 // vim:set et sw=4 sts=4 sws=4 enc=utf-8:
1458 ?>