Improves nl pages header for nl administrator.
[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 return XDB::fetchOneCell('SELECT COUNT(uid)
404 FROM newsletter_ins
405 WHERE nlid = {?}', $this->id);
406 }
407
408 /** Get the count of subscribers with non valid redirection.
409 */
410 public function lostSubscriberCount()
411 {
412 return XDB::fetchOneCell('SELECT COUNT(DISTINCT(n.uid))
413 FROM newsletter_ins AS n
414 INNER JOIN accounts AS a ON (n.uid = a.uid)
415 INNER JOIN account_types AS t ON (t.type = a.type)
416 LEFT JOIN email_redirect_account AS r ON (r.uid = a.uid AND r.flags = \'active\' AND r.broken_level < 3
417 AND r.type != \'imap\' AND r.type != \'homonym\')
418 WHERE n.nlid = {?} AND r.redirect IS NULL AND a.state = \'active\' AND FIND_IN_SET(\'mail\', t.perms)',
419 $this->id);
420 }
421
422 /** Get the number of subscribers to the NL whose last received mailing was $last.
423 * @p $last ID of the issue for which subscribers should be counted.
424 * @return Number of subscribers
425 */
426 public function subscriberCountForLast($last)
427 {
428 return XDB::fetchOneCell('SELECT COUNT(uid)
429 FROM newsletter_ins
430 WHERE nlid = {?} AND last = {?}', $this->id, $last);
431 }
432
433 /** Retrieve the list of newsletters a user has subscribed to
434 * @p $user User whose subscriptions should be retrieved (if null, use session user).
435 * @return Array of newsletter IDs
436 */
437 public static function getUserSubscriptions($user = null)
438 {
439 if (is_null($user)) {
440 $user = S::user();
441 }
442 $res = XDB::query('SELECT nlid
443 FROM newsletter_ins
444 WHERE uid = {?}',
445 $user->id());
446 return $res->fetchColumn();
447 }
448
449 /** Retrieve the UserFilterBuilder for subscribers to this NL.
450 * This is the place where NL-specific filters may be allowed or prevented.
451 * @p $envprefix Prefix to use for env fields (cf. UserFilterBuilder)
452 * @return A UserFilterBuilder object using the given env prefix
453 */
454 public function getSubscribersUFB($envprefix = '')
455 {
456 require_once 'ufbuilder.inc.php';
457 return new UFB_NewsLetter($this->criteria, $envprefix);
458 }
459
460 // }}}
461 // {{{ Permissions related functions
462
463 /** For later use: check whether a given user may subscribe to this newsletter.
464 * @p $user User whose access should be checked
465 * @return Boolean: whether the user may subscribe to the NL.
466 */
467 public function maySubscribe($user = null)
468 {
469 return true;
470 }
471
472 /** Whether a given user may edit this newsletter
473 * @p $uid UID of the user whose perms should be checked (if null, use current user)
474 * @return Boolean: whether the user may edit the NL
475 */
476 public function mayEdit($user = null)
477 {
478 if (is_null($user)) {
479 $user = S::user();
480 }
481 if ($user->checkPerms('admin')) {
482 return true;
483 }
484 $res = XDB::query('SELECT perms
485 FROM group_members
486 WHERE asso_id = {?} AND uid = {?}',
487 $this->group_id, $user->id());
488 return ($res->numRows() && $res->fetchOneCell() == 'admin');
489 }
490
491 /** Whether a given user may submit articles to this newsletter using X.org validation system
492 * @p $user User whose access should be checked (if null, use current user)
493 * @return Boolean: whether the user may submit articles
494 */
495 public function maySubmit($user = null)
496 {
497 // Submission of new articles is only enabled for the X.org NL (and forbidden when viewing issues on X.net)
498 return ($this->group == self::GROUP_XORG && !isset($GLOBALS['IS_XNET_SITE']));
499 }
500
501 // }}}
502 // {{{ Display-related functions: cssFile, tplFile, prefix, admin_prefix, admin_links_enabled, automatic_mailings_enabled
503
504 /** Get the name of the css file used to display this newsletter.
505 */
506 public function cssFile()
507 {
508 if ($this->custom_css) {
509 $base = $this->group;
510 } else {
511 $base = self::FORMAT_DEFAULT_GROUP;
512 }
513 return 'nl.' . $base . '.css';
514 }
515
516 /** Get the name of the template file used to display this newsletter.
517 */
518 public function tplFile()
519 {
520 if ($this->custom_css) {
521 $base = $this->group;
522 } else {
523 $base = self::FORMAT_DEFAULT_GROUP;
524 }
525 return 'newsletter/nl.' . $base . '.mail.tpl';
526 }
527
528 /** Get the prefix leading to the page for this NL
529 * Only X.org / AX / X groups may be seen on X.org.
530 */
531 public function prefix($enforce_xnet=true, $with_group=true)
532 {
533 if (!empty($GLOBALS['IS_XNET_SITE'])) {
534 if ($with_group) {
535 return $this->group . '/nl';
536 } else {
537 return 'nl';
538 }
539 }
540 switch ($this->group) {
541 case self::GROUP_XORG:
542 return 'nl';
543 case self::GROUP_AX:
544 return 'ax';
545 case self::GROUP_EP:
546 return 'epletter';
547 default:
548 // Don't display groups NLs on X.org
549 assert(!$enforce_xnet);
550 }
551 }
552
553 /** Get the prefix to use for all 'admin' pages of this NL.
554 */
555 public function adminPrefix($enforce_xnet=true, $with_group=true)
556 {
557 if (!empty($GLOBALS['IS_XNET_SITE'])) {
558 if ($with_group) {
559 return $this->group . '/admin/nl';
560 } else {
561 return 'admin/nl';
562 }
563 }
564 switch ($this->group) {
565 case self::GROUP_XORG:
566 return 'admin/newsletter';
567 case self::GROUP_AX:
568 return 'ax/admin';
569 case self::GROUP_EP:
570 return 'epletter/admin';
571 default:
572 // Don't display groups NLs on X.org
573 assert(!$enforce_xnet);
574 }
575 }
576
577 /** Get links for nl pages.
578 */
579 public function adminLinks()
580 {
581 return array(
582 'index' => array('link' => $this->prefix(), 'title' => 'Archives'),
583 'admin' => array('link' => $this->adminPrefix(), 'title' => 'Administrer')
584 );
585 }
586
587 /** Hack used to remove "admin" links on X.org page on X.net
588 * The 'admin' links are enabled for all pages, except for X.org when accessing NL through X.net
589 */
590 public function adminLinksEnabled()
591 {
592 return ($this->group != self::GROUP_XORG || !isset($GLOBALS['IS_XNET_SITE']));
593 }
594
595 /** Automatic mailings are disabled for X.org NL.
596 */
597 public function automaticMailingEnabled()
598 {
599 return $this->group != self::GROUP_XORG;
600 }
601
602 public function hasCustomCss()
603 {
604 return $this->custom_css;
605 }
606
607 public function canSyncWithGroup()
608 {
609 switch ($this->group) {
610 case self::GROUP_XORG:
611 case self::GROUP_AX:
612 case self::GROUP_EP:
613 return false;
614 default:
615 return true;
616 }
617 }
618
619 // }}}
620 }
621
622 // }}}
623
624 // {{{ class NLIssue
625
626 // A NLIssue is an issue of a given NewsLetter
627 class NLIssue
628 {
629 protected $nlid; // Id of the newsletter
630
631 const STATE_NEW = 'new'; // New, currently being edited
632 const STATE_PENDING = 'pending'; // Ready for mailing
633 const STATE_SENT = 'sent'; // Sent
634
635 public $nl; // Related NL
636
637 public $id; // Id of this issue of the newsletter
638 public $shortname; // Shortname for this issue
639 public $title; // Title of this issue
640 public $title_mail; // Title of the email
641 public $state; // State of the issue (one of the STATE_ values)
642 public $sufb; // Environment to use to generate the UFC through an UserFilterBuilder
643
644 public $date; // Date at which this issue was sent
645 public $send_before; // Date at which issue should be sent
646 public $head; // Foreword of the issue (or body for letters with no articles)
647 public $signature; // Signature of the letter
648 public $reply_to; // Adress to reply to the message (can be empty)
649 public $arts = array(); // Articles of the issue
650
651 const BATCH_SIZE = 60; // Number of emails to send every minute.
652
653 // {{{ Constructor, id-related functions
654
655 /** Build a NewsLetter.
656 * @p $id: ID of the issue (unique among all newsletters)
657 * @p $nl: Optional argument containing an already built NewsLetter object.
658 */
659 function __construct($id, $nl = null, $fetch_articles = true)
660 {
661 return $this->fetch($id, $nl, $fetch_articles);
662 }
663
664 protected function refresh()
665 {
666 return $this->fetch($this->id, $this->nl, false);
667 }
668
669 protected function fetch($id, $nl = null, $fetch_articles = true)
670 {
671 // Load this issue
672 $res = XDB::query('SELECT nlid, short_name, date, send_before, state, sufb_json,
673 title, mail_title, head, signature, reply_to
674 FROM newsletter_issues
675 WHERE id = {?}',
676 $id);
677 if (!$res->numRows()) {
678 throw new MailNotFound();
679 }
680 $issue = $res->fetchOneAssoc();
681 if ($nl && $nl->id == $issue['nlid']) {
682 $this->nl = $nl;
683 } else {
684 $this->nl = new NewsLetter($issue['nlid']);
685 }
686 $this->id = $id;
687 $this->nlid = $issue['nlid'];
688 $this->shortname = $issue['short_name'];
689 $this->date = $issue['date'];
690 $this->send_before = $issue['send_before'];
691 $this->state = $issue['state'];
692 $this->title = $issue['title'];
693 $this->title_mail = $issue['mail_title'];
694 $this->head = $issue['head'];
695 $this->signature = $issue['signature'];
696 $this->reply_to = $issue['reply_to'];
697 $this->sufb = $this->importJSonStoredUFB($issue['sufb_json']);
698
699 if ($fetch_articles) {
700 $this->fetchArticles();
701 }
702 }
703
704 protected function fetchArticles($force = false)
705 {
706 if (count($this->arts) && !$force) {
707 return;
708 }
709
710 // Load the articles
711 $res = XDB::iterRow(
712 'SELECT a.title, a.body, a.append, a.aid, a.cid, a.pos
713 FROM newsletter_art AS a
714 INNER JOIN newsletter_issues AS ni USING(id)
715 LEFT JOIN newsletter_cat AS c ON (a.cid = c.cid)
716 WHERE a.id = {?}
717 ORDER BY c.pos, a.pos',
718 $this->id);
719 while (list($title, $body, $append, $aid, $cid, $pos) = $res->next()) {
720 $this->arts[$cid][$aid] = new NLArticle($title, $body, $append, $aid, $cid, $pos);
721 }
722 }
723
724 protected function importJSonStoredUFB($json = null)
725 {
726 require_once 'ufbuilder.inc.php';
727 $ufb = $this->nl->getSubscribersUFB();
728 if (is_null($json)) {
729 return new StoredUserFilterBuilder($ufb, new PFC_True());
730 }
731 $export = json_decode($json, true);
732 if (is_null($export)) {
733 PlErrorReport::report("Invalid json while reading NL {$this->nlid}, issue {$this->id}: failed to import '''{$json}'''.");
734 return new StoredUserFilterBuilder($ufb, new PFC_True());
735 }
736 $sufb = new StoredUserFilterBuilder($ufb);
737 $sufb->fillFromExport($export);
738 return $sufb;
739 }
740
741 protected function exportStoredUFBAsJSon()
742 {
743 return json_encode($this->sufb->export());
744 }
745
746 public function id()
747 {
748 return is_null($this->shortname) ? $this->id : $this->shortname;
749 }
750
751 protected function selectId($where)
752 {
753 $res = XDB::query("SELECT IFNULL(ni.short_name, ni.id)
754 FROM newsletter_issues AS ni
755 WHERE ni.state != 'new' AND ni.nlid = {?} AND ${where}
756 LIMIT 1", $this->nl->id);
757 if ($res->numRows() != 1) {
758 return null;
759 }
760 return $res->fetchOneCell();
761 }
762
763 /** Delete this issue
764 * @return True if the issue could be deleted, false otherwise.
765 * Related articles will be deleted through cascading FKs.
766 * If this issue was the last issue for at least one subscriber, the deletion will be aborted.
767 */
768 public function delete()
769 {
770 if ($this->state == self::STATE_NEW) {
771 $res = XDB::query('SELECT COUNT(*)
772 FROM newsletter_ins
773 WHERE last = {?}', $this->id);
774 if ($res->fetchOneCell() > 0) {
775 return false;
776 }
777
778 return XDB::execute('DELETE FROM newsletter_issues
779 WHERE id = {?}', $this->id);
780 } else {
781 return false;
782 }
783 }
784
785 /** Schedule a mailing of this NL
786 * If the 'send_before' field was NULL, it is set to the current time.
787 * @return Boolean Whether the date could be set (false if trying to schedule an already sent NL)
788 */
789 public function scheduleMailing()
790 {
791 if ($this->state == self::STATE_NEW) {
792 $success = XDB::execute('UPDATE newsletter_issues
793 SET state = \'pending\', send_before = IFNULL(send_before, NOW())
794 WHERE id = {?}',
795 $this->id);
796 if ($success) {
797 global $globals;
798 $mailer = new PlMailer('newsletter/notify_scheduled.mail.tpl');
799 $mailer->assign('issue', $this);
800 $mailer->assign('base', $globals->baseurl);
801 $mailer->send();
802 $this->refresh();
803 }
804 return $success;
805 } else {
806 return false;
807 }
808 }
809
810 /** Cancel the scheduled mailing of this NL
811 * @return Boolean: whether the mailing could be cancelled.
812 */
813 public function cancelMailing()
814 {
815 if ($this->state == self::STATE_PENDING) {
816 $success = XDB::execute('UPDATE newsletter_issues
817 SET state = \'new\'
818 WHERE id = {?}', $this->id);
819 if ($success) {
820 $this->refresh();
821 }
822 return $success;
823 } else {
824 return false;
825 }
826 }
827
828 /** Helper function for smarty templates: is this issue editable ?
829 */
830 public function isEditable()
831 {
832 return $this->state == self::STATE_NEW;
833 }
834
835 /** Helper function for smarty templates: is the mailing of this issue scheduled ?
836 */
837 public function isPending()
838 {
839 return $this->state == self::STATE_PENDING;
840 }
841
842 /** Helper function for smarty templates: has this issue been sent ?
843 */
844 public function isSent()
845 {
846 return $this->state == self::STATE_SENT;
847 }
848
849 // }}}
850 // {{{ Navigation
851
852 private $id_prev = null;
853 private $id_next = null;
854 private $id_last = null;
855
856 /** Retrieve ID of the previous issue
857 * That value, once fetched, is cached in the private $id_prev variable.
858 * @return ID of the previous issue.
859 */
860 public function prev()
861 {
862 if (is_null($this->id_prev)) {
863 $this->id_prev = $this->selectId(XDB::format("ni.id < {?} ORDER BY ni.id DESC", $this->id));
864 }
865 return $this->id_prev;
866 }
867
868 /** Retrieve ID of the following issue
869 * That value, once fetched, is cached in the private $id_next variable.
870 * @return ID of the following issue.
871 */
872 public function next()
873 {
874 if (is_null($this->id_next)) {
875 $this->id_next = $this->selectId(XDB::format("ni.id > {?} ORDER BY ni.id", $this->id));
876 }
877 return $this->id_next;
878 }
879
880 /** Retrieve ID of the last issue
881 * That value, once fetched, is cached in the private $id_last variable.
882 * @return ID of the last issue.
883 */
884 public function last()
885 {
886 if (is_null($this->id_last)) {
887 try {
888 $this->id_last = $this->nl->getIssue('last')->id;
889 } catch (MailNotFound $e) {
890 $this->id_last = null;
891 }
892 }
893 return $this->id_last;
894 }
895
896 // }}}
897 // {{{ Edition, articles
898
899 const ERROR_INVALID_REPLY_TO = 'invalid_reply_to';
900 const ERROR_INVALID_SHORTNAME = 'invalid_shortname';
901 const ERROR_INVALID_UFC = 'invalid_ufc';
902 const ERROR_TOO_LONG_UFC = 'too_long_ufc';
903 const ERROR_SQL_SAVE = 'sql_error';
904
905 /** Save the global properties of this NL issue (title&co).
906 */
907 public function save()
908 {
909 $errors = array();
910
911 // Fill the list of fields to update
912 $fields = array(
913 'title' => $this->title,
914 'mail_title' => $this->title_mail,
915 'head' => $this->head,
916 'signature' => $this->signature,
917 );
918
919 if (!empty($this->reply_to) && !isvalid_email($this->reply_to)) {
920 $errors[] = self::ERROR_INVALID_REPLY_TO ;
921 } else {
922 $fields['reply_to'] = $this->reply_to;
923 }
924
925 if ($this->isEditable()) {
926 $fields['date'] = $this->date;
927 if (!preg_match('/^[-a-z0-9]+$/i', $this->shortname) || is_numeric($this->shortname)) {
928 $errors[] = self::ERROR_INVALID_SHORTNAME;
929 } else {
930 $fields['short_name'] = $this->shortname;
931 }
932 if ($this->sufb->isValid() || $this->sufb->isEmpty()) {
933 $fields['sufb_json'] = json_encode($this->sufb->export()->dict());
934 // If sufb_json is too long to be store, we do not store a truncated json and notify the user.
935 // The limit is LONGTEXT's one, ie 2^32 = 4294967296.
936 if (strlen($fields['sufb_json']) > 4294967295) {
937 $errors[] = self::ERROR_TOO_LONG_UFC;
938 }
939 } else {
940 $errors[] = self::ERROR_INVALID_UFC;
941 }
942
943 if ($this->nl->automaticMailingEnabled()) {
944 $fields['send_before'] = ($this->send_before ? $this->send_before : null);
945 }
946 }
947
948 if (count($errors)) {
949 return $errors;
950 }
951 $field_sets = array();
952 foreach ($fields as $key => $value) {
953 $field_sets[] = XDB::format($key . ' = {?}', $value);
954 }
955 XDB::execute('UPDATE newsletter_issues
956 SET ' . implode(', ', $field_sets) . '
957 WHERE id={?}',
958 $this->id);
959 if (XDB::affectedRows()) {
960 $this->refresh();
961 } else {
962 $errors[] = self::ERROR_SQL_SAVE;
963 }
964 return $errors;
965 }
966
967 /** Get an article by number
968 * @p $aid Article ID (among articles of the issue)
969 * @return A NLArticle object, or null if there is no article by that number
970 */
971 public function getArt($aid)
972 {
973 $this->fetchArticles();
974
975 foreach ($this->arts as $category => $artlist) {
976 if (isset($artlist[$aid])) {
977 return $artlist[$aid];
978 }
979 }
980 return null;
981 }
982
983 /** Save an article
984 * @p $a A reference to a NLArticle object (will be modified once saved)
985 */
986 public function saveArticle($a)
987 {
988 $this->fetchArticles();
989
990 // Prevent cid to be 0 (use NULL instead)
991 $a->cid = ($a->cid == 0) ? null : $a->cid;
992 if ($a->aid >= 0) {
993 // Article already exists in DB
994 XDB::execute('UPDATE newsletter_art
995 SET cid = {?}, pos = {?}, title = {?}, body = {?}, append = {?}
996 WHERE id = {?} AND aid = {?}',
997 $a->cid, $a->pos, $a->title, $a->body, $a->append, $this->id, $a->aid);
998 } else {
999 // New article
1000 XDB::startTransaction();
1001 list($aid, $pos) = XDB::fetchOneRow('SELECT MAX(aid) AS aid, MAX(pos) AS pos
1002 FROM newsletter_art AS a
1003 WHERE a.id = {?}',
1004 $this->id);
1005 $a->aid = ++$aid;
1006 $a->pos = ($a->pos ? $a->pos : ++$pos);
1007 XDB::execute('INSERT INTO newsletter_art (id, aid, cid, pos, title, body, append)
1008 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
1009 $this->id, $a->aid, $a->cid, $a->pos,
1010 $a->title, $a->body, $a->append);
1011 XDB::commit();
1012 }
1013 // Update local ID of article
1014 $this->arts[$a->aid] = $a;
1015 }
1016
1017 /** Delete an article by its ID
1018 * @p $aid ID of the article to delete
1019 */
1020 public function delArticle($aid)
1021 {
1022 $this->fetchArticles();
1023
1024 XDB::execute('DELETE FROM newsletter_art WHERE id={?} AND aid={?}', $this->id, $aid);
1025 foreach ($this->arts as $key=>$art) {
1026 unset($this->arts[$key][$aid]);
1027 }
1028 }
1029
1030 // }}}
1031 // {{{ Display
1032
1033 /** Retrieve the title of this issue
1034 * @p $mail Whether we want the normal title or the email subject
1035 * @return Title of the issue
1036 */
1037 public function title($mail = false)
1038 {
1039 return $mail ? $this->title_mail : $this->title;
1040 }
1041
1042 /** Retrieve the head of this issue
1043 * @p $user User for <dear> customization (may be null: no customization)
1044 * @p $type Either 'text' or 'html'
1045 * @return Formatted head of the issue.
1046 */
1047 public function head($user = null, $type = 'text')
1048 {
1049 if (is_null($user)) {
1050 return $this->head;
1051 } else {
1052 $head = $this->head;
1053 $head = str_replace(array('<cher>', '<prenom>', '<nom>'),
1054 array(($user->isFemale() ? 'Chère' : 'Cher'), $user->displayName(), ''),
1055 $head);
1056 return format_text($head, $type, 2, 64);
1057 }
1058 }
1059
1060 /** Retrieve the formatted signature of this issue.
1061 */
1062 public function signature($type = 'text')
1063 {
1064 return format_text($this->signature, $type, 2, 64);
1065 }
1066
1067 /** Get the title of a given category
1068 * @p $cid ID of the category to retrieve
1069 * @return Name of the category
1070 */
1071 public function category($cid)
1072 {
1073 return $this->nl->cats[$cid];
1074 }
1075
1076 /** Add required data to the given $page for proper CSS display
1077 * @p $page Smarty object
1078 * @return Either 'true' (if CSS was added to a page) or the raw CSS to add (when $page is null)
1079 */
1080 public function css($page = null)
1081 {
1082 if (!is_null($page)) {
1083 $page->addCssLink($this->nl->cssFile());
1084 return true;
1085 } else {
1086 $css = file_get_contents(dirname(__FILE__) . '/../htdocs/css/' . $this->nl->cssFile());
1087 return preg_replace('@/\*.*?\*/@us', '', $css);
1088 }
1089 }
1090
1091 /** Set up a smarty page for a 'text' mode render of the issue
1092 * @p $page Smarty object (using the $this->nl->tplFile() template)
1093 * @p $user User to use when rendering the template
1094 */
1095 public function toText($page, $user)
1096 {
1097 $this->fetchArticles();
1098
1099 $this->css($page);
1100 $page->assign('prefix', null);
1101 $page->assign('is_mail', false);
1102 $page->assign('mail_part', 'text');
1103 $page->assign('user', $user);
1104 $page->assign('hash', null);
1105 $this->assignData($page);
1106 }
1107
1108 /** Set up a smarty page for a 'html' mode render of the issue
1109 * @p $page Smarty object (using the $this->nl->tplFile() template)
1110 * @p $user User to use when rendering the template
1111 */
1112 public function toHtml($page, $user)
1113 {
1114 $this->fetchArticles();
1115
1116 $this->css($page);
1117 $page->assign('prefix', $this->nl->prefix() . '/show/' . $this->id());
1118 $page->assign('is_mail', false);
1119 $page->assign('mail_part', 'html');
1120 $page->assign('user', $user);
1121 $page->assign('hash', null);
1122 $this->assignData($page);
1123 }
1124
1125 /** Set all 'common' data for the page (those which are required for both web and email rendering)
1126 * @p $smarty Smarty object (e.g page) which should be filled
1127 */
1128 protected function assignData($smarty)
1129 {
1130 $this->fetchArticles();
1131
1132 $smarty->assign_by_ref('issue', $this);
1133 $smarty->assign_by_ref('nl', $this->nl);
1134 }
1135
1136 // }}}
1137 // {{{ Mailing
1138
1139 /** Check whether this issue is empty
1140 * An issue is empty if the email has no title (or the default one), or no articles and an empty head.
1141 */
1142 public function isEmpty()
1143 {
1144 return $this->title_mail == '' || $this->title_mail == 'to be continued' || (count($this->arts) == 0 && strlen($this->head) == 0);
1145 }
1146
1147 /** Retrieve the 'Send before' date, in a clean format.
1148 */
1149 public function getSendBeforeDate()
1150 {
1151 return strftime('%Y-%m-%d', strtotime($this->send_before));
1152 }
1153
1154 /** Retrieve the 'Send before' time (i.e hour), in a clean format.
1155 */
1156 public function getSendBeforeTime()
1157 {
1158 return strtotime($this->send_before);
1159 }
1160
1161 /** Create a hash based on some additional data
1162 * $line Line-specific data (to prevent two hashes generated at the same time to be the same)
1163 */
1164 protected static function createHash($line)
1165 {
1166 $hash = implode(time(), $line) . rand();
1167 $hash = md5($hash);
1168 return $hash;
1169 }
1170
1171 /** Send this issue to the given user, reusing an existing hash if provided.
1172 * @p $user User to whom the issue should be mailed
1173 * @p $hash Optional hash to use in the 'unsubscribe' link; if null, another one will be generated.
1174 */
1175 public function sendTo($user, $hash = null)
1176 {
1177 $this->fetchArticles();
1178
1179 if (is_null($hash)) {
1180 $hash = XDB::fetchOneCell("SELECT hash
1181 FROM newsletter_ins
1182 WHERE uid = {?} AND nlid = {?}",
1183 $user->id(), $this->nl->id);
1184 }
1185 if (is_null($hash)) {
1186 $hash = self::createHash(array($user->displayName(), $user->fullName(),
1187 $user->isFemale(), $user->isEmailFormatHtml(),
1188 rand(), "X.org rulez"));
1189 XDB::execute("UPDATE newsletter_ins as ni
1190 SET ni.hash = {?}
1191 WHERE ni.uid = {?} AND ni.nlid = {?}",
1192 $hash, $user->id(), $this->nl->id);
1193 }
1194
1195 $mailer = new PlMailer($this->nl->tplFile());
1196 $this->assignData($mailer);
1197 $mailer->assign('is_mail', true);
1198 $mailer->assign('user', $user);
1199 $mailer->assign('prefix', null);
1200 $mailer->assign('hash', $hash);
1201 if (!empty($this->reply_to)) {
1202 $mailer->addHeader('Reply-To', $this->reply_to);
1203 }
1204 $mailer->sendTo($user);
1205 }
1206
1207 /** Select a subset of subscribers which should receive the newsletter.
1208 * NL-Specific selections (not yet received, is subscribed) are done when sending.
1209 * @return A PlFilterCondition.
1210 */
1211 protected function getRecipientsUFC()
1212 {
1213 return $this->sufb->getUFC();
1214 }
1215
1216 /** Check whether a given user may see this issue.
1217 * @p $user User whose access should be checked
1218 * @return Whether he may access the issue
1219 */
1220 public function checkUser($user = null)
1221 {
1222 if ($user == null) {
1223 $user = S::user();
1224 }
1225 $uf = new UserFilter($this->getRecipientsUFC());
1226 return $uf->checkUser($user);
1227 }
1228
1229 /** Sent this issue to all valid recipients
1230 * @return Number of issues sent
1231 */
1232 public function sendToAll()
1233 {
1234 $this->fetchArticles();
1235
1236 XDB::execute('UPDATE newsletter_issues
1237 SET state = \'sent\', date=CURDATE()
1238 WHERE id = {?}',
1239 $this->id);
1240
1241 $ufc = new PFC_And($this->getRecipientsUFC(), new UFC_NLSubscribed($this->nl->id, $this->id), new UFC_HasValidEmail());
1242 $uf = new UserFilter($ufc, array(new UFO_IsAdmin(true), new UFO_Uid()));
1243 $limit = new PlLimit(self::BATCH_SIZE);
1244 $global_sent = array();
1245
1246 while (true) {
1247 $sent = array();
1248 $users = $uf->getUsers($limit);
1249 if (count($users) == 0) {
1250 break;
1251 }
1252 foreach ($users as $user) {
1253 if (array_key_exists($user->id(), $global_sent)) {
1254 Platal::page()->kill('Sending the same newsletter issue ' . $this->id . ' to user ' . $user->id() . ' twice, something must be wrong.');
1255 }
1256 $sent[] = $user->id();
1257 $global_sent[$user->id()] = true;
1258 $this->sendTo($user, $hash);
1259 }
1260 XDB::execute("UPDATE newsletter_ins
1261 SET last = {?}
1262 WHERE nlid = {?} AND uid IN {?}", $this->id, $this->nl->id, $sent);
1263
1264 sleep(60);
1265 }
1266 return count($global_sent);
1267 }
1268
1269 // }}}
1270 }
1271
1272 // }}}
1273 // {{{ class NLArticle
1274
1275 class NLArticle
1276 {
1277 // Maximum number of lines per article
1278 const MAX_LINES_PER_ARTICLE = 8;
1279 const MAX_CHARACTERS_PER_LINE = 68;
1280
1281 // {{{ properties
1282
1283 public $aid;
1284 public $cid;
1285 public $pos;
1286 public $title;
1287 public $body;
1288 public $append;
1289
1290 // }}}
1291 // {{{ constructor
1292
1293 function __construct($title='', $body='', $append='', $aid=-1, $cid=0, $pos=0)
1294 {
1295 $this->body = $body;
1296 $this->title = $title;
1297 $this->append = $append;
1298 $this->aid = $aid;
1299 $this->cid = $cid;
1300 $this->pos = $pos;
1301 }
1302
1303 // }}}
1304 // {{{ function title()
1305
1306 public function title()
1307 { return trim($this->title); }
1308
1309 // }}}
1310 // {{{ function body()
1311
1312 public function body()
1313 { return trim($this->body); }
1314
1315 // }}}
1316 // {{{ function append()
1317
1318 public function append()
1319 { return trim($this->append); }
1320
1321 // }}}
1322 // {{{ function toText()
1323
1324 public function toText($hash = null, $login = null)
1325 {
1326 $title = '*'.$this->title().'*';
1327 $body = MiniWiki::WikiToText($this->body, true);
1328 $app = MiniWiki::WikiToText($this->append, false, 4);
1329 $text = trim("$title\n\n$body\n\n$app")."\n";
1330 if (!is_null($hash) && !is_null($login)) {
1331 $text = str_replace('%HASH%', "$hash/$login", $text);
1332 } else {
1333 $text = str_replace('%HASH%', '', $text);
1334 }
1335 return $text;
1336 }
1337
1338 // }}}
1339 // {{{ function toHtml()
1340
1341 public function toHtml($hash = null, $login = null)
1342 {
1343 $title = "<h2 class='xorg_nl'><a id='art{$this->aid}'></a>".pl_entities($this->title()).'</h2>';
1344 $body = MiniWiki::WikiToHTML($this->body);
1345 $app = MiniWiki::WikiToHTML($this->append);
1346
1347 $art = "$title\n";
1348 $art .= "<div class='art'>\n$body\n";
1349 if ($app) {
1350 $art .= "<div class='app'>$app</div>";
1351 }
1352 $art .= "</div>\n";
1353 if (!is_null($hash) && !is_null($login)) {
1354 $art = str_replace('%HASH%', "$hash/$login", $art);
1355 } else {
1356 $art = str_replace('%HASH%', '', $art);
1357 }
1358
1359 return $art;
1360 }
1361
1362 // }}}
1363 // {{{ function check()
1364
1365 public function check()
1366 {
1367 $rest = $this->remain();
1368
1369 return $rest['remaining_lines'] >= 0;
1370 }
1371
1372 // }}}
1373 // {{{ function remain()
1374
1375 public function remain()
1376 {
1377 $text = MiniWiki::WikiToText($this->body);
1378 $array = explode("\n", wordwrap($text, self::MAX_CHARACTERS_PER_LINE));
1379 $lines_count = 0;
1380 foreach ($array as $line) {
1381 if (trim($line) != '') {
1382 ++$lines_count;
1383 }
1384 }
1385
1386 return array(
1387 'remaining_lines' => self::MAX_LINES_PER_ARTICLE - $lines_count,
1388 'remaining_characters_for_last_line' => self::MAX_CHARACTERS_PER_LINE - strlen($array[count($array) - 1])
1389 );
1390 }
1391 // }}}
1392 // {{{ function parseUrlsFromArticle()
1393
1394 protected function parseUrlsFromArticle()
1395 {
1396 $email_regex = '([a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+)';
1397 $url_regex = '((https?|ftp)://[a-zA-Z0-9._%#+/?=&~-]+)';
1398 $regex = '{' . $email_regex . '|' . $url_regex . '}i';
1399
1400 $matches = array();
1401 $body_matches = array();
1402 if (preg_match_all($regex, $this->body(), $body_matches)) {
1403 $matches = array_merge($matches, $body_matches[0]);
1404 }
1405
1406 $append_matches = array();
1407 if (preg_match_all($regex, $this->append(), $append_matches)) {
1408 $matches = array_merge($matches, $append_matches[0]);
1409 }
1410
1411 return $matches;
1412 }
1413
1414 // }}}
1415 // {{{ function getLinkIps()
1416
1417 public function getLinkIps(&$blacklist_host_resolution_count)
1418 {
1419 $matches = $this->parseUrlsFromArticle();
1420 $article_ips = array();
1421
1422 if (!empty($matches)) {
1423 global $globals;
1424
1425 foreach ($matches as $match) {
1426 $host = parse_url($match, PHP_URL_HOST);
1427 if ($host == '') {
1428 list(, $host) = explode('@', $match);
1429 }
1430
1431 if ($blacklist_host_resolution_count >= $globals->mail->blacklist_host_resolution_limit) {
1432 break;
1433 }
1434
1435 if (!preg_match('/^(' . str_replace(' ', '|', $globals->mail->domain_whitelist) . ')$/i', $host)) {
1436 $article_ips = array_merge($article_ips, array(gethostbyname($host) => $host));
1437 ++$blacklist_host_resolution_count;
1438 }
1439 }
1440 }
1441
1442 return $article_ips;
1443 }
1444
1445 // }}}
1446 }
1447
1448 // }}}
1449
1450 // {{{ Functions
1451
1452 function format_text($input, $format, $indent = 0, $width = 68)
1453 {
1454 if ($format == 'text') {
1455 return MiniWiki::WikiToText($input, true, $indent, $width, "title");
1456 }
1457 return MiniWiki::WikiToHTML($input, "title");
1458 }
1459
1460 // function enriched_to_text($input,$html=false,$just=false,$indent=0,$width=68)
1461
1462 // }}}
1463
1464 // vim:set et sw=4 sts=4 sws=4 enc=utf-8:
1465 ?>