]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Upstream changes to OAuth.php
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 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 Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('LACONICA')) { exit(1); }
21
22 /**
23  * Table Definition for notice
24  */
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
26
27 /* We keep the first three 20-notice pages, plus one for pagination check,
28  * in the memcached cache. */
29
30 define('NOTICE_CACHE_WINDOW', 61);
31
32 class Notice extends Memcached_DataObject
33 {
34     ###START_AUTOCODE
35     /* the code below is auto generated do not remove the above tag */
36
37     public $__table = 'notice';                          // table name
38     public $id;                              // int(4)  primary_key not_null
39     public $profile_id;                      // int(4)   not_null
40     public $uri;                             // varchar(255)  unique_key
41     public $content;                         // varchar(140)
42     public $rendered;                        // text()
43     public $url;                             // varchar(255)
44     public $created;                         // datetime()   not_null
45     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
46     public $reply_to;                        // int(4)
47     public $is_local;                        // tinyint(1)
48     public $source;                          // varchar(32)
49     public $conversation;                    // int(4)
50
51     /* Static get */
52     function staticGet($k,$v=NULL) {
53         return Memcached_DataObject::staticGet('Notice',$k,$v);
54     }
55
56     /* the code above is auto generated do not remove the tag below */
57     ###END_AUTOCODE
58
59     function getProfile()
60     {
61         return Profile::staticGet('id', $this->profile_id);
62     }
63
64     function delete()
65     {
66         $this->blowCaches(true);
67         $this->blowFavesCache(true);
68         $this->blowSubsCache(true);
69
70         $this->query('BEGIN');
71         $related = array('Reply',
72                          'Fave',
73                          'Notice_tag',
74                          'Group_inbox',
75                          'Queue_item');
76         if (common_config('inboxes', 'enabled')) {
77             $related[] = 'Notice_inbox';
78         }
79         foreach ($related as $cls) {
80             $inst = new $cls();
81             $inst->notice_id = $this->id;
82             $inst->delete();
83         }
84         $result = parent::delete();
85         $this->query('COMMIT');
86     }
87
88     function saveTags()
89     {
90         /* extract all #hastags */
91         $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
92         if (!$count) {
93             return true;
94         }
95
96         /* Add them to the database */
97         foreach(array_unique($match[1]) as $hashtag) {
98             /* elide characters we don't want in the tag */
99             $this->saveTag($hashtag);
100         }
101         return true;
102     }
103
104     function saveTag($hashtag)
105     {
106         $hashtag = common_canonical_tag($hashtag);
107
108         $tag = new Notice_tag();
109         $tag->notice_id = $this->id;
110         $tag->tag = $hashtag;
111         $tag->created = $this->created;
112         $id = $tag->insert();
113
114         if (!$id) {
115             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
116                                               $last_error->message));
117             return;
118         }
119     }
120
121     static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
122
123         $profile = Profile::staticGet($profile_id);
124
125         if (!$profile) {
126             common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
127             return _('Problem saving notice. Unknown user.');
128         }
129
130         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
131             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
132             return _('Too many notices too fast; take a breather and post again in a few minutes.');
133         }
134
135         $banned = common_config('profile', 'banned');
136
137         if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
138             common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
139             return _('You are banned from posting notices on this site.');
140         }
141
142         $notice = new Notice();
143         $notice->profile_id = $profile_id;
144
145         $blacklist = common_config('public', 'blacklist');
146         $autosource = common_config('public', 'autosource');
147
148         # Blacklisted are non-false, but not 1, either
149
150         if (($blacklist && in_array($profile_id, $blacklist)) ||
151             ($source && $autosource && in_array($source, $autosource))) {
152             $notice->is_local = -1;
153         } else {
154             $notice->is_local = $is_local;
155         }
156
157                 $notice->query('BEGIN');
158
159         $notice->created = common_sql_now();
160         $notice->content = common_shorten_links($content);
161         $notice->rendered = common_render_content($notice->content, $notice);
162         $notice->source = $source;
163         $notice->uri = $uri;
164
165         if (!empty($reply_to)) {
166             $reply_notice = Notice::staticGet('id', $reply_to);
167             if (!empty($reply_notice)) {
168                 $notice->reply_to = $reply_to;
169                 $notice->conversation = $reply_notice->conversation;
170             }
171         }
172
173         if (Event::handle('StartNoticeSave', array(&$notice))) {
174
175             $id = $notice->insert();
176
177             if (!$id) {
178                 common_log_db_error($notice, 'INSERT', __FILE__);
179                 return _('Problem saving notice.');
180             }
181
182             # Update the URI after the notice is in the database
183             if (!$uri) {
184                 $orig = clone($notice);
185                 $notice->uri = common_notice_uri($notice);
186
187                 if (!$notice->update($orig)) {
188                     common_log_db_error($notice, 'UPDATE', __FILE__);
189                     return _('Problem saving notice.');
190                 }
191             }
192
193             # XXX: do we need to change this for remote users?
194
195             $notice->saveReplies();
196             $notice->saveTags();
197             $notice->saveGroups();
198
199             $notice->addToInboxes();
200             $notice->query('COMMIT');
201
202             Event::handle('EndNoticeSave', array($notice));
203         }
204
205         # Clear the cache for subscribed users, so they'll update at next request
206         # XXX: someone clever could prepend instead of clearing the cache
207
208         if (common_config('memcached', 'enabled')) {
209             $notice->blowCaches();
210         }
211
212         return $notice;
213     }
214
215     static function checkEditThrottle($profile_id) {
216         $profile = Profile::staticGet($profile_id);
217         if (!$profile) {
218             return false;
219         }
220         # Get the Nth notice
221         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
222         if ($notice && $notice->fetch()) {
223             # If the Nth notice was posted less than timespan seconds ago
224             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
225                 # Then we throttle
226                 return false;
227             }
228         }
229         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
230         return true;
231     }
232
233     function blowCaches($blowLast=false)
234     {
235         $this->blowSubsCache($blowLast);
236         $this->blowNoticeCache($blowLast);
237         $this->blowRepliesCache($blowLast);
238         $this->blowPublicCache($blowLast);
239         $this->blowTagCache($blowLast);
240         $this->blowGroupCache($blowLast);
241     }
242
243     function blowGroupCache($blowLast=false)
244     {
245         $cache = common_memcache();
246         if ($cache) {
247             $group_inbox = new Group_inbox();
248             $group_inbox->notice_id = $this->id;
249             if ($group_inbox->find()) {
250                 while ($group_inbox->fetch()) {
251                     $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
252                     if ($blowLast) {
253                         $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
254                     }
255                     $member = new Group_member();
256                     $member->group_id = $group_inbox->group_id;
257                     if ($member->find()) {
258                         while ($member->fetch()) {
259                             $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
260                             if ($blowLast) {
261                                 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
262                             }
263                         }
264                     }
265                 }
266             }
267             $group_inbox->free();
268             unset($group_inbox);
269         }
270     }
271
272     function blowTagCache($blowLast=false)
273     {
274         $cache = common_memcache();
275         if ($cache) {
276             $tag = new Notice_tag();
277             $tag->notice_id = $this->id;
278             if ($tag->find()) {
279                 while ($tag->fetch()) {
280                     $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
281                     if ($blowLast) {
282                         $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
283                     }
284                 }
285             }
286             $tag->free();
287             unset($tag);
288         }
289     }
290
291     function blowSubsCache($blowLast=false)
292     {
293         $cache = common_memcache();
294         if ($cache) {
295             $user = new User();
296
297             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
298             $user->query('SELECT id ' .
299
300                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
301                          'WHERE subscription.subscribed = ' . $this->profile_id);
302
303             while ($user->fetch()) {
304                 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
305                 if ($blowLast) {
306                     $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
307                 }
308             }
309             $user->free();
310             unset($user);
311         }
312     }
313
314     function blowNoticeCache($blowLast=false)
315     {
316         if ($this->is_local) {
317             $cache = common_memcache();
318             if ($cache) {
319                 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
320                 if ($blowLast) {
321                     $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
322                 }
323             }
324         }
325     }
326
327     function blowRepliesCache($blowLast=false)
328     {
329         $cache = common_memcache();
330         if ($cache) {
331             $reply = new Reply();
332             $reply->notice_id = $this->id;
333             if ($reply->find()) {
334                 while ($reply->fetch()) {
335                     $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
336                     if ($blowLast) {
337                         $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
338                     }
339                 }
340             }
341             $reply->free();
342             unset($reply);
343         }
344     }
345
346     function blowPublicCache($blowLast=false)
347     {
348         if ($this->is_local == 1) {
349             $cache = common_memcache();
350             if ($cache) {
351                 $cache->delete(common_cache_key('public'));
352                 if ($blowLast) {
353                     $cache->delete(common_cache_key('public').';last');
354                 }
355             }
356         }
357     }
358
359     function blowFavesCache($blowLast=false)
360     {
361         $cache = common_memcache();
362         if ($cache) {
363             $fave = new Fave();
364             $fave->notice_id = $this->id;
365             if ($fave->find()) {
366                 while ($fave->fetch()) {
367                     $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
368                     if ($blowLast) {
369                         $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
370                     }
371                 }
372             }
373             $fave->free();
374             unset($fave);
375         }
376     }
377
378     # XXX: too many args; we need to move to named params or even a separate
379     # class for notice streams
380
381     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
382
383         if (common_config('memcached', 'enabled')) {
384
385             # Skip the cache if this is a since, since_id or before_id qry
386             if ($since_id > 0 || $before_id > 0 || $since) {
387                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
388             } else {
389                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
390             }
391         }
392
393         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
394     }
395
396     static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
397
398         $needAnd = false;
399         $needWhere = true;
400
401         if (preg_match('/\bWHERE\b/i', $qry)) {
402             $needWhere = false;
403             $needAnd = true;
404         }
405
406         if ($since_id > 0) {
407
408             if ($needWhere) {
409                 $qry .= ' WHERE ';
410                 $needWhere = false;
411             } else {
412                 $qry .= ' AND ';
413             }
414
415             $qry .= ' notice.id > ' . $since_id;
416         }
417
418         if ($before_id > 0) {
419
420             if ($needWhere) {
421                 $qry .= ' WHERE ';
422                 $needWhere = false;
423             } else {
424                 $qry .= ' AND ';
425             }
426
427             $qry .= ' notice.id < ' . $before_id;
428         }
429
430         if ($since) {
431
432             if ($needWhere) {
433                 $qry .= ' WHERE ';
434                 $needWhere = false;
435             } else {
436                 $qry .= ' AND ';
437             }
438
439             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
440         }
441
442         # Allow ORDER override
443
444         if ($order) {
445             $qry .= $order;
446         } else {
447             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
448         }
449
450         if (common_config('db','type') == 'pgsql') {
451             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
452         } else {
453             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
454         }
455
456         $notice = new Notice();
457
458         $notice->query($qry);
459
460         return $notice;
461     }
462
463     # XXX: this is pretty long and should probably be broken up into
464     # some helper functions
465
466     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
467
468         # If outside our cache window, just go to the DB
469
470         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
471             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
472         }
473
474         # Get the cache; if we can't, just go to the DB
475
476         $cache = common_memcache();
477
478         if (!$cache) {
479             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
480         }
481
482         # Get the notices out of the cache
483
484         $notices = $cache->get(common_cache_key($cachekey));
485
486         # On a cache hit, return a DB-object-like wrapper
487
488         if ($notices !== false) {
489             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
490             return $wrapper;
491         }
492
493         # If the cache was invalidated because of new data being
494         # added, we can try and just get the new stuff. We keep an additional
495         # copy of the data at the key + ';last'
496
497         # No cache hit. Try to get the *last* cached version
498
499         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
500
501         if ($last_notices) {
502
503             # Reverse-chron order, so last ID is last.
504
505             $last_id = $last_notices[0]->id;
506
507             # XXX: this assumes monotonically increasing IDs; a fair
508             # bet with our DB.
509
510             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
511                                                   $last_id, null, $order, null);
512
513             if ($new_notice) {
514                 $new_notices = array();
515                 while ($new_notice->fetch()) {
516                     $new_notices[] = clone($new_notice);
517                 }
518                 $new_notice->free();
519                 $notices = array_slice(array_merge($new_notices, $last_notices),
520                                        0, NOTICE_CACHE_WINDOW);
521
522                 # Store the array in the cache for next time
523
524                 $result = $cache->set(common_cache_key($cachekey), $notices);
525                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
526
527                 # return a wrapper of the array for use now
528
529                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
530             }
531         }
532
533         # Otherwise, get the full cache window out of the DB
534
535         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
536
537         # If there are no hits, just return the value
538
539         if (!$notice) {
540             return $notice;
541         }
542
543         # Pack results into an array
544
545         $notices = array();
546
547         while ($notice->fetch()) {
548             $notices[] = clone($notice);
549         }
550
551         $notice->free();
552
553         # Store the array in the cache for next time
554
555         $result = $cache->set(common_cache_key($cachekey), $notices);
556         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
557
558         # return a wrapper of the array for use now
559
560         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
561
562         return $wrapper;
563     }
564
565     function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
566     {
567
568         $parts = array();
569
570         $qry = 'SELECT * FROM notice ';
571
572         if (common_config('public', 'localonly')) {
573             $parts[] = 'is_local = 1';
574         } else {
575             # -1 == blacklisted
576             $parts[] = 'is_local != -1';
577         }
578
579         if ($parts) {
580             $qry .= ' WHERE ' . implode(' AND ', $parts);
581         }
582
583         return Notice::getStream($qry,
584                                  'public',
585                                  $offset, $limit, $since_id, $before_id, null, $since);
586     }
587
588     function addToInboxes()
589     {
590         $enabled = common_config('inboxes', 'enabled');
591
592         if ($enabled === true || $enabled === 'transitional') {
593             $inbox = new Notice_inbox();
594             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
595             $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
596               "SELECT $UT.id, " . $this->id . ", '" . $this->created . "' " .
597               "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
598               'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
599               'AND NOT EXISTS (SELECT user_id, notice_id ' .
600               'FROM notice_inbox ' .
601               "WHERE user_id = $UT.id " .
602               'AND notice_id = ' . $this->id . ' )';
603             if ($enabled === 'transitional') {
604                 $qry .= " AND $UT.inboxed = 1";
605             }
606             $inbox->query($qry);
607         }
608         return;
609     }
610
611     function saveGroups()
612     {
613         $enabled = common_config('inboxes', 'enabled');
614         if ($enabled !== true && $enabled !== 'transitional') {
615             return;
616         }
617
618         /* extract all !group */
619         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
620                                 strtolower($this->content),
621                                 $match);
622         if (!$count) {
623             return true;
624         }
625
626         $profile = $this->getProfile();
627
628         /* Add them to the database */
629
630         foreach (array_unique($match[1]) as $nickname) {
631             /* XXX: remote groups. */
632             $group = User_group::staticGet('nickname', $nickname);
633
634             if (!$group) {
635                 continue;
636             }
637
638             // we automatically add a tag for every group name, too
639
640             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
641                                            'notice_id' => $this->id));
642
643             if (is_null($tag)) {
644                 $this->saveTag($nickname);
645             }
646
647             if ($profile->isMember($group)) {
648
649                 $gi = new Group_inbox();
650
651                 $gi->group_id  = $group->id;
652                 $gi->notice_id = $this->id;
653                 $gi->created   = common_sql_now();
654
655                 $result = $gi->insert();
656
657                 if (!$result) {
658                     common_log_db_error($gi, 'INSERT', __FILE__);
659                 }
660
661                 // FIXME: do this in an offline daemon
662
663                 $inbox = new Notice_inbox();
664                 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
665                 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
666                   "SELECT $UT.id, " . $this->id . ", '" . $this->created . "', 2 " .
667                   "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
668                   'WHERE group_member.group_id = ' . $group->id . ' ' .
669                   'AND NOT EXISTS (SELECT user_id, notice_id ' .
670                   'FROM notice_inbox ' .
671                   "WHERE user_id = $UT.id " .
672                   'AND notice_id = ' . $this->id . ' )';
673                 if ($enabled === 'transitional') {
674                     $qry .= " AND $UT.inboxed = 1";
675                 }
676                 $result = $inbox->query($qry);
677             }
678         }
679     }
680
681     function saveReplies()
682     {
683         // Alternative reply format
684         $tname = false;
685         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
686             $tname = $match[1];
687         }
688         // extract all @messages
689         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
690
691         $names = array();
692
693         if ($cnt || $tname) {
694             // XXX: is there another way to make an array copy?
695             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
696         }
697
698         $sender = Profile::staticGet($this->profile_id);
699
700         $replied = array();
701
702         // store replied only for first @ (what user/notice what the reply directed,
703         // we assume first @ is it)
704
705         for ($i=0; $i<count($names); $i++) {
706             $nickname = $names[$i];
707             $recipient = common_relative_profile($sender, $nickname, $this->created);
708             if (!$recipient) {
709                 continue;
710             }
711             if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
712                 $reply_for = $recipient;
713                 $recipient_notice = $reply_for->getCurrentNotice();
714                 if ($recipient_notice) {
715                     $orig = clone($this);
716                     $this->reply_to = $recipient_notice->id;
717                     $this->conversation = $recipient_notice->conversation;
718                     $this->update($orig);
719                 }
720             }
721             // Don't save replies from blocked profile to local user
722             $recipient_user = User::staticGet('id', $recipient->id);
723             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
724                 continue;
725             }
726             $reply = new Reply();
727             $reply->notice_id = $this->id;
728             $reply->profile_id = $recipient->id;
729             $id = $reply->insert();
730             if (!$id) {
731                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
732                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
733                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
734                 return;
735             } else {
736                 $replied[$recipient->id] = 1;
737             }
738         }
739
740         // Hash format replies, too
741         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
742         if ($cnt) {
743             foreach ($match[1] as $tag) {
744                 $tagged = Profile_tag::getTagged($sender->id, $tag);
745                 foreach ($tagged as $t) {
746                     if (!$replied[$t->id]) {
747                         // Don't save replies from blocked profile to local user
748                         $t_user = User::staticGet('id', $t->id);
749                         if ($t_user && $t_user->hasBlocked($sender)) {
750                             continue;
751                         }
752                         $reply = new Reply();
753                         $reply->notice_id = $this->id;
754                         $reply->profile_id = $t->id;
755                         $id = $reply->insert();
756                         if (!$id) {
757                             common_log_db_error($reply, 'INSERT', __FILE__);
758                             return;
759                         } else {
760                             $replied[$recipient->id] = 1;
761                         }
762                     }
763                 }
764             }
765         }
766
767         // If it's not a reply, make it the root of a new conversation
768
769         if (empty($this->conversation)) {
770             $orig = clone($this);
771             $this->conversation = $this->id;
772             $this->update($orig);
773         }
774
775         foreach (array_keys($replied) as $recipient) {
776             $user = User::staticGet('id', $recipient);
777             if ($user) {
778                 mail_notify_attn($user, $this);
779             }
780         }
781     }
782 }