Upgrade class_notification.php to use emails.php (untested)
[bugdar.git] / includes / class_notification.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Bugdar
5 || # Copyright ©2002-2007 Blue Static
6 || #
7 || # This program is free software; you can redistribute it and/or modify
8 || # it under the terms of the GNU General Public License as published by
9 || # the Free Software Foundation; version 2 of the License.
10 || #
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 || # more details.
15 || #
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
21
22 /**
23 * Notification Center
24 *
25 * This class determines which emails need to be sent out based on user
26 * options and bug changes, and then it sends said emails.
27 *
28 * @author Blue Static
29 * @copyright Copyright ©2002 - 2007, Blue Static
30 * @version $Revision$
31 * @package Bugdar
32 *
33 */
34 class NotificationCenter
35 {
36 /**
37 * Bug information
38 * @var array
39 */
40 private $bug = array();
41
42 /**
43 * Original bug data
44 * @var array
45 */
46 private $original = array();
47
48 /**
49 * Modified bug data
50 * @var array
51 */
52 private $modified = array();
53
54 /**
55 * Role list: a list of user IDs with their relations to the bug
56 * @var array
57 */
58 private $roles = array(
59 '-notapplicable-' => array(),
60 'reporter' => array(),
61 'assignee' => array(),
62 'favorite' => array(),
63 'voter' => array(),
64 'commenter' => array()
65 );
66
67 /**
68 * User cache list
69 * @var array
70 */
71 private $users = array();
72
73 /**
74 * A list of notices per-user that are combined together in NotificationCenter::finalize()
75 * @var array
76 */
77 private $notices = array();
78
79 /**
80 * Sets the bug data so that all methods in this class have access to
81 * it when sending emails.
82 *
83 * @param array Original bug data
84 * @param array Modified bug data
85 */
86 public function setBugData($original, $modified = array())
87 {
88 if (sizeof($modified) > 0)
89 {
90 $this->bug = $modified;
91 }
92 else
93 {
94 $this->bug = $original;
95 }
96
97 $this->original = $original;
98 $this->modified = $modified;
99
100 $this->roles['-notapplicable-'] = (sizeof($modified) > 0 ? array($original['assignedto'], $modified['assignedto']) : array($original['assignedto']));
101 $this->roles['reporter'] = array($original['userid']);
102 $this->roles['assignee'][] = (sizeof($modified) > 0 ? $modified['assignedto'] : $original['assignedto']);
103
104 $this->_fetchUserCache();
105 }
106
107 /**
108 * Fetches all the users who could be related to the bug and sticks
109 * their information into an array.
110 */
111 private function _fetchUserCache()
112 {
113 $newbuggers = BSApp::$db->query("SELECT userid FROM " . TABLE_PREFIX . "useremail WHERE relation = " . bugdar::$emailOptions['relations']['-notapplicable-'] . " AND mask & " . bugdar::$emailOptions['notifications']['newbug']);
114 foreach ($newbuggers as $newbug)
115 {
116 $this->roles['-notapplicable-']["$newbug[userid]"] = $newbug['userid'];
117 }
118
119 $favorites = BSApp::$db->query("SELECT userid FROM " . TABLE_PREFIX . "favorite WHERE bugid = " . BSApp::$input->clean($this->bug['bugid'], TYPE_UINT));
120 foreach ($favorites as $fav)
121 {
122 $this->roles['favorite']["$fav[userid]"] = $fav['userid'];
123 }
124
125 $voters = BSApp::$db->queryFirst("SELECT userids FROM " . TABLE_PREFIX . "vote WHERE bugid = " . BSApp::$input->clean($this->bug['bugid'], TYPE_UINT));
126 $this->roles['voter'] = preg_split('#,#', $voters['userids'], 0, PREG_SPLIT_NO_EMPTY);
127
128 $commenters = BSApp::$db->query("SELECT userid FROM " . TABLE_PREFIX . "comment WHERE bugid = " . BSApp::$input->clean($this->bug['bugid'], TYPE_UINT));
129 foreach ($commenters as $comment)
130 {
131 $this->roles['commenter']["$comment[userid]"] = $comment['userid'];
132 }
133
134 $masterids = array_merge($this->roles['-notapplicable-'], $this->roles['reporter'], $this->roles['assignee'], $this->roles['favorite'], $this->roles['voter'], $this->roles['commenter']);
135 $masterids = BSFunctions::array_strip_empty(array_unique($masterids));
136
137 if (is_array($masterids) && sizeof($masterids) > 0)
138 {
139 $userinfo = BSApp::$db->query("
140 SELECT user.*, useremail.*
141 FROM " . TABLE_PREFIX . "useremail AS useremail
142 LEFT JOIN " . TABLE_PREFIX . "user AS user
143 ON (user.userid = useremail.userid)
144 WHERE useremail.userid IN (" . implode(',', $masterids) . ")
145 ");
146 foreach ($userinfo as $user)
147 {
148 if (!is_array($this->users["$user[userid]"]))
149 {
150 $this->users["$user[userid]"] = $user;
151 unset($this->users["$user[userid]"]['mask'], $this->users["$user[userid]"]['relation']);
152 }
153 $this->users["$user[userid]"]['options']["$user[relation]"] = $user['mask'];
154 }
155 }
156 }
157
158 /**
159 * Sends the appropriate emails for changes to bugs. This function
160 * works a lot like the Logging class by taking BugAPI->record and
161 * BugAPI->values and then comparing the two arries and sending emails
162 * with the differences.
163 */
164 public function sendBugChangeNotice()
165 {
166 if (!isset($this->modified['bugid']))
167 {
168 return;
169 }
170
171 // fields with custom mask information
172 if ($this->original['assignedto'] != $this->modified['assignedto'])
173 {
174 if ($this->original['assignedto'] != '')
175 {
176 $this->_noticeNoLongerAssigned($this->original['assignedto']);
177 }
178 if ($this->modified['assignedto'] != '')
179 {
180 $this->_noticeNowAssigned($this->modified['assignedto']);
181 }
182 }
183 if ($this->original['status'] != $this->modified['status'])
184 {
185 $this->_noticeStatusChange($this->original['status'], $this->modified['status']);
186 }
187 if ($this->original['resolution'] != $this->modified['resolution'])
188 {
189 $this->_noticeResolutionChange($this->original['resolution'], $this->modified['resolution']);
190 }
191 if ($this->original['duplicates'] != $this->modified['duplicates'])
192 {
193 $this->_noticeDuplicatesChange($this->original['duplicates'], $this->modified['duplicates']);
194 }
195
196 // other standard fields that don't have custom masks
197 if ($this->original['severity'] != $this->modified['severity'])
198 {
199 $this->_noticeSeverityChange($this->original['severity'], $this->modified['severity']);
200 }
201 if ($this->original['priority'] != $this->modified['priority'])
202 {
203 $this->_noticePriorityChange($this->original['priority'], $this->modified['priority']);
204 }
205 if (($this->original['product'] != $this->modified['product']) || ($this->original['component'] != $this->modified['component']) || ($this->original['version'] != $this->modified['version']))
206 {
207 $this->_noticePCVChange(array($this->original['product'], $this->original['component'], $this->original['version']), array($this->modified['product'], $this->modified['component'], $this->modified['version']));
208 }
209
210 $dofields = array(
211 'summary' => -1,
212 'dependency' => -1,
213 'hidden' => -1
214 );
215 foreach ($dofields as $field => $lookup)
216 {
217 if ($this->original["$field"] != $this->modified["$field"])
218 {
219 $this->_noticeOtherChange($field, $this->original["$field"], $this->modified["$field"]);
220 }
221 }
222 }
223
224 /**
225 * Sends an email to the specified user ID that they are no longer the
226 * person assigned to the bug.
227 *
228 * @param integer User ID to send to
229 */
230 private function _noticeNoLongerAssigned($userid)
231 {
232 if ($this->users["$userid"]['options'][0] & bugdar::$emailOptions['notifications']['assignedto'] && in_array($userid, $this->roles['-notapplicable-']))
233 {
234 $user = construct_user_display(bugdar::$userinfo, false);
235
236 $email = get_email_text('notice_unassigned');
237 $this->notices["$userid"][] = sprintf($email['part'], $user);
238 }
239 }
240
241 /**
242 * Informs the user that they have been made the assignee of the bug.
243 *
244 * @param integer User ID
245 */
246 private function _noticeNowAssigned($userid)
247 {
248 if ($this->users["$userid"]['options'][0] & bugdar::$emailOptions['notifications']['assignedto'] && in_array($userid, $this->roles['-notapplicable-']))
249 {
250 $user = construct_user_display(bugdar::$userinfo, false);
251
252 $email = get_email_text('notice_assigned');
253 $this->notices["$userid"][] = sprintf($email['part'], $user);
254 }
255 }
256
257 /**
258 * Sends a message to inform users that the status has changed.
259 *
260 * @param integer Old status
261 * @param integer New status
262 */
263 private function _noticeStatusChange($old, $new)
264 {
265 $userlist = $this->_fetchUsersWithOnBit('statusresolve');
266
267 $old = bugdar::$datastore['status'][$old]['status'];
268 $new = bugdar::$datastore['status'][$new]['status'];
269
270 foreach ($userlist as $userid => $user)
271 {
272 $email = get_email_text('notice_status');
273 $this->notices["$user[userid]"][] = sprintf($email['part'], $new, $old);
274 }
275 }
276
277 /**
278 * Sends an email to inform users that the resolution has changed.
279 *
280 * @param integer Old resolution
281 * @param integer New resolution
282 */
283 private function _noticeResolutionChange($old, $new)
284 {
285 $userlist = $this->_fetchUsersWithOnBit('statusresolve');
286
287 $old = bugdar::$datastore['resolution'][$old]['resolution'];
288 $new = bugdar::$datastore['resolution'][$new]['resolution'];
289
290 foreach ($userlist as $userid => $user)
291 {
292 $email = get_email_text('notice_resolution');
293 $this->notices["$user[userid]"][] = sprintf($email['part'], $new, $old);
294 }
295 }
296
297 /**
298 * Informs users that the duplicates list has changed.
299 *
300 * @param string Old duplicates list
301 * @param string New duplicates list
302 */
303 private function _noticeDuplicatesChange($old, $new)
304 {
305 $userlist = $this->_fetchUsersWithOnBit('duplicates');
306
307 foreach ($userlist as $userid => $user)
308 {
309 $email = get_email_text('notice_duplicates');
310 $this->notices["$user[userid]"][] = sprintf($email['part'], $old, $new);
311 }
312 }
313
314 /**
315 * Sends an email to inform users that the severity has changed.
316 *
317 * @param integer Old severity
318 * @param integer New severity
319 */
320 private function _noticeSeverityChange($old, $new)
321 {
322 $userlist = $this->_fetchUsersWithOnBit('otherfield');
323
324 $old = bugdar::$datastore['severity'][$old]['severity'];
325 $new = bugdar::$datastore['severity'][$new]['severity'];
326
327 foreach ($userlist as $userid => $user)
328 {
329 $this->notices["$user[userid]"][] = sprintf($email['part'], $old, $new);
330 }
331 }
332
333 /**
334 * Informs users that the priority changed.
335 *
336 * @param integer Old priority
337 * @param integer New priority
338 */
339 private function _noticePriorityChange($old, $new)
340 {
341 $userlist = $this->_fetchUsersWithOnBit('otherfield');
342
343 $old = bugdar::$datastore['priority'][$old]['priority'];
344 $new = bugdar::$datastore['priority'][$new]['priority'];
345
346 foreach ($userlist as $userid => $user)
347 {
348 $email = get_email_text('notice_priority');
349 $this->notices["$user[userid]"][] = sprintf($email['part'], $old, $new);
350 }
351 }
352
353 /**
354 * Sends an email telling users that the product, component, or version
355 * has changed. This is done all at once because you really need to see
356 * the whole thing in the notice.
357 *
358 * @param array Original PCV
359 * @param array Modified PCV
360 */
361 private function _noticePCVChange($old, $new)
362 {
363 $userlist = $this->_fetchUsersWithOnBit('otherfield');
364
365 $products = &bugdar::$datastore['product'];
366 $versions = &bugdar::$datastore['version'];
367
368 $old = $products[$old[0]]['title'] . '/' . ($old[1] ? $products[$old[1]]['title'] . '/' : '') . $versions[$old[2]]['version'];
369 $new = $products[$new[0]]['title'] . '/' . ($new[1] ? $products[$new[1]]['title'] . '/' : '') . $versions[$new[2]]['version'];
370
371 foreach ($userlist as $userid => $user)
372 {
373 $email = get_email_text('notice_product');
374 $this->notices["$user[userid]"][] = sprintf($email['part'], $old, $new);
375 }
376 }
377
378 /**
379 * Sends the appropriate users information about a new comment being
380 * posted to the bug report.
381 *
382 * @param array CommentAPI->values array
383 */
384 public function sendNewCommentNotice($comment)
385 {
386 $userlist = $this->_fetchUsersWithOnBit('newcomment');
387 foreach ($userlist as $userid => $user)
388 {
389 $user = construct_user_display(bugdar::$userinfo, false);
390 $date = BSApp::$date->format(bugdar::$options['dateformat'], $comment['dateline']);
391
392 $email = get_email_text('notice_comment');
393 $this->notices["$userid"][] = sprintf($email['part'], $user, $date, $comment['comment']);
394 }
395 }
396
397 /**
398 * A notice for an individual field changing.
399 *
400 * @param string Field name
401 * @param mixed Original value
402 * @param mixed Modified value
403 */
404 private function _noticeOtherChange($name, $old, $new)
405 {
406 $userlist = $this->_fetchUsersWithOnBit('otherfield');
407 foreach ($userlist as $userid => $user)
408 {
409 $email = get_email_text('notice_other');
410 $this->notices["$user[userid]"][] = sprintf($email['part'], $name, $old, $new);
411 }
412 }
413
414 /**
415 * Sends appropriate users a notice when a new attachment has been
416 * added.
417 *
418 * @param array AttachmentAPI->values array
419 * @param array List of all attachments made obsolete
420 * @param array Newly-inserted attachment ID
421 */
422 public function sendNewAttachmentNotice($attachment, $obsolete, $id)
423 {
424 $userlist = $this->_fetchUsersWithOnBit('newattachment');
425 foreach ($userlist as $userid => $user)
426 {
427 $user = construct_user_display(bugdar::$userinfo, false);
428 $obsoletes = implode(', ', (array)$obsolete);
429
430 $email = get_email_text('notice_attachment');
431 $this->notices["$userid"][] = sprintf($email['part'], $user, $attachment['filename'], $attachment['description'], $attachment['filesize'], $obsoletes, bugdar::$options['trackerurl'], $attachment['attachmentid']);
432 }
433 }
434
435 /**
436 * Sends a new bug notification notice to all those who have the option
437 * turned no. This does not use fetchUsersWithOnBit() because a
438 * query is more effective.
439 *
440 * @param array Bug values array
441 * @param array Comment values array
442 */
443 public function sendNewBugNotice($bug, $comment)
444 {
445 $userinfo = BSApp::$db->query("
446 SELECT user.*, useremail.*
447 FROM " . TABLE_PREFIX . "useremail AS useremail
448 LEFT JOIN " . TABLE_PREFIX . "user AS user
449 ON (user.userid = useremail.userid)
450 WHERE useremail.relation = 0
451 AND useremail.mask & " . bugdar::$emailOptions['notifications']['newbug'] . "
452 ");
453 foreach ($userinfo as $userInfo)
454 {
455 if (!is_array($this->users["$userInfo[userid]"]))
456 {
457 $user = construct_user_display(bugdar::$userinfo, false);
458 $this->users["$userInfo[userid]"] = $userInfo;
459 $product = bugdar::$datastore['product']["$bug[product]"]['title'] . '/' . ($bug['component'] ? bugdar::$datastore['product']["$bug[component]"]['title'] . '/' : '') . bugdar::$datastore['version']["$bug[version]"]['version'];
460
461 $email = get_email_text('notice_new_bug');
462 $this->notices["$userInfo[userid]"][] = sprintf($email['part'], $bug['bugid'], $bug['summary'], $user, $product, $comment['comment']);
463 unset($this->users["$userInfo[userid]"]['mask'], $this->users["$userInfo[userid]"]['relation']);
464 }
465 $this->users["$userInfo[userid]"]['options']["$userInfo[relation]"] = $userInfo['mask'];
466 }
467 }
468
469 /**
470 * Generates an array of users who have a given email notification flag
471 * turned on in their bitfields.
472 *
473 * @param string Notification bitfield name
474 *
475 * @return array Array of users and their data
476 */
477 private function _fetchUsersWithOnBit($bitname)
478 {
479 $idlist = array();
480
481 foreach ($this->users as $user)
482 {
483 foreach (bugdar::$emailOptions['relations'] as $name => $bit)
484 {
485 if (in_array($user['userid'], $this->roles["$name"]) && $user['options']["$bit"] & bugdar::$emailOptions['notifications']["$bitname"])
486 {
487 $idlist[] = $user['userid'];
488 }
489 }
490 }
491
492 $masters = array_unique($idlist);
493
494 $return = array();
495 foreach ($masters as $userid)
496 {
497 $return["$userid"] = &$this->users["$userid"];
498 }
499
500 return $return;
501 }
502
503 /**
504 * Compiles and sends the actual emails to users.
505 */
506 public function finalize()
507 {
508 // get the current bug for permissions checks
509 $bug = BSApp::$db->query_first("SELECT * FROM " . TABLE_PREFIX . "bug WHERE bugid = " . $this->bug['bugid']);
510 foreach ($this->_notices as $userid => $noticelist)
511 {
512 if ($userid == bugdar::$userinfo['userid'])
513 {
514 BSApp::debug("skipping user $userid because they're the one doing the thing");
515 continue;
516 }
517
518 // we wouldn't want people who favorite bugs getting hidden notices
519 if (!check_bug_permissions($bug, $this->users["$userid"]))
520 {
521 BSApp::debug("skipping user $userid ({$this->users[$userid]['email']}) because of permissions");
522 continue;
523 }
524
525 $parts = implode("\n\n", $noticelist);
526
527 $email = get_email_text('bug_notification');
528
529 $body = sprintf($email['bodyText'], $this->users[$userid]['displayname'], bugdar::$options['trackertitle'], $this->bug['summary'], $this->bug['bugid'], bugdar::$options['trackerurl'], $parts);
530
531 $mail = new BSMail();
532 $mail->setSubject(sprintf($email['subject'], bugdar::$options['trackertitle'], $this->bug['summary']));
533 $mail->setBodyText($body);
534 $mail->setFromAddress(MAIL_FROM_ADDRESS);
535 $mail->setFromName(MAIL_FROM_NAME);
536
537 if (!empty($this->users["$userid"]['email']))
538 {
539 $mail->send($this->users["$userid"]['email'], $this->users["$userid"]['displayname']);
540 }
541 else
542 {
543 BSApp::debug("not sending an email to " . $userid . " because they don't have one?");
544 }
545 }
546 }
547
548 /**
549 * Returns the locale name from a given user ID
550 *
551 * @param integer User ID
552 *
553 * @return string Locale
554 */
555 private function _localeFromUserId($userid)
556 {
557 $langcode = bugdar::$datastore['language'][$this->users[$userid]['languageid']]['langcode'];
558 if (!$langcode)
559 {
560 $langcode = bugdar::$datastore['language'][bugdar::$options['defaultlanguage']]['langcode'];
561 }
562 return $langcode;
563 }
564 }
565
566 /*=====================================================================*\
567 || ###################################################################
568 || # $HeadURL$
569 || # $Id$
570 || ###################################################################
571 \*=====================================================================*/
572 ?>