]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Add an inbox queue handler
[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
50     /* Static get */
51     function staticGet($k,$v=NULL) {
52         return Memcached_DataObject::staticGet('Notice',$k,$v);
53     }
54
55     /* the code above is auto generated do not remove the tag below */
56     ###END_AUTOCODE
57
58     function getProfile()
59     {
60         return Profile::staticGet('id', $this->profile_id);
61     }
62
63     function delete()
64     {
65         $this->blowCaches(true);
66         $this->blowFavesCache(true);
67         $this->blowSubsCache(true);
68
69         $this->query('BEGIN');
70         //Null any notices that are replies to this notice
71         $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
72         $related = array('Reply',
73                          'Fave',
74                          'Notice_tag',
75                          'Group_inbox',
76                          'Queue_item');
77         if (common_config('inboxes', 'enabled')) {
78             $related[] = 'Notice_inbox';
79         }
80         foreach ($related as $cls) {
81             $inst = new $cls();
82             $inst->notice_id = $this->id;
83             $inst->delete();
84         }
85         $result = parent::delete();
86         $this->query('COMMIT');
87     }
88
89     function saveTags()
90     {
91         /* extract all #hastags */
92         $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
93         if (!$count) {
94             return true;
95         }
96
97         /* Add them to the database */
98         foreach(array_unique($match[1]) as $hashtag) {
99             /* elide characters we don't want in the tag */
100             $this->saveTag($hashtag);
101         }
102         return true;
103     }
104
105     function saveTag($hashtag)
106     {
107         $hashtag = common_canonical_tag($hashtag);
108
109         $tag = new Notice_tag();
110         $tag->notice_id = $this->id;
111         $tag->tag = $hashtag;
112         $tag->created = $this->created;
113         $id = $tag->insert();
114
115         if (!$id) {
116             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
117                                               $last_error->message));
118             return;
119         }
120     }
121
122     static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
123
124         $profile = Profile::staticGet($profile_id);
125
126         $final =  common_shorten_links($content);
127
128         if (!$profile) {
129             common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
130             return _('Problem saving notice. Unknown user.');
131         }
132
133         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
134             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
135             return _('Too many notices too fast; take a breather and post again in a few minutes.');
136         }
137
138         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
139             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
140                         return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
141         }
142
143                 $banned = common_config('profile', 'banned');
144
145         if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
146             common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
147             return _('You are banned from posting notices on this site.');
148         }
149
150         $notice = new Notice();
151         $notice->profile_id = $profile_id;
152
153         $blacklist = common_config('public', 'blacklist');
154         $autosource = common_config('public', 'autosource');
155
156         # Blacklisted are non-false, but not 1, either
157
158         if (($blacklist && in_array($profile_id, $blacklist)) ||
159             ($source && $autosource && in_array($source, $autosource))) {
160             $notice->is_local = -1;
161         } else {
162             $notice->is_local = $is_local;
163         }
164
165                 $notice->query('BEGIN');
166
167                 $notice->reply_to = $reply_to;
168                 $notice->created = common_sql_now();
169                 $notice->content = $final;
170                 $notice->rendered = common_render_content($final, $notice);
171                 $notice->source = $source;
172                 $notice->uri = $uri;
173
174         if (Event::handle('StartNoticeSave', array(&$notice))) {
175
176             $id = $notice->insert();
177
178             if (!$id) {
179                 common_log_db_error($notice, 'INSERT', __FILE__);
180                 return _('Problem saving notice.');
181             }
182
183             # Update the URI after the notice is in the database
184             if (!$uri) {
185                 $orig = clone($notice);
186                 $notice->uri = common_notice_uri($notice);
187
188                 if (!$notice->update($orig)) {
189                     common_log_db_error($notice, 'UPDATE', __FILE__);
190                     return _('Problem saving notice.');
191                 }
192             }
193
194             # XXX: do we need to change this for remote users?
195
196             $notice->saveReplies();
197             $notice->saveTags();
198             $notice->saveGroups();
199
200             if (!common_config('queues', 'enabled')) {
201                 $notice->addToInboxes();
202             }
203
204             $notice->query('COMMIT');
205
206             Event::handle('EndNoticeSave', array($notice));
207         }
208
209         # Clear the cache for subscribed users, so they'll update at next request
210         # XXX: someone clever could prepend instead of clearing the cache
211
212         if (common_config('memcached', 'enabled')) {
213             if (common_config('queues', 'enabled')) {
214                 $notice->blowAuthorCaches();
215             } else {
216                 $notice->blowCaches();
217             }
218         }
219
220         return $notice;
221     }
222
223     static function checkDupes($profile_id, $content) {
224         $profile = Profile::staticGet($profile_id);
225         if (!$profile) {
226             return false;
227         }
228         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
229         if ($notice) {
230             $last = 0;
231             while ($notice->fetch()) {
232                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
233                     return true;
234                 } else if ($notice->content == $content) {
235                     return false;
236                 }
237             }
238         }
239         # If we get here, oldest item in cache window is not
240         # old enough for dupe limit; do direct check against DB
241         $notice = new Notice();
242         $notice->profile_id = $profile_id;
243         $notice->content = $content;
244         if (common_config('db','type') == 'pgsql')
245             $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
246         else
247             $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
248
249         $cnt = $notice->count();
250         return ($cnt == 0);
251     }
252
253     static function checkEditThrottle($profile_id) {
254         $profile = Profile::staticGet($profile_id);
255         if (!$profile) {
256             return false;
257         }
258         # Get the Nth notice
259         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
260         if ($notice && $notice->fetch()) {
261             # If the Nth notice was posted less than timespan seconds ago
262             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
263                 # Then we throttle
264                 return false;
265             }
266         }
267         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
268         return true;
269     }
270
271     function blowCaches($blowLast=false)
272     {
273         $this->blowSubsCache($blowLast);
274         $this->blowNoticeCache($blowLast);
275         $this->blowRepliesCache($blowLast);
276         $this->blowPublicCache($blowLast);
277         $this->blowTagCache($blowLast);
278         $this->blowGroupCache($blowLast);
279     }
280
281     function blowAuthorCaches($blowLast=false)
282     {
283         // Clear the user's cache
284         $cache = common_memcache();
285         if ($cache) {
286             $user = User::staticGet($this->profile_id);
287             if (!empty($user)) {
288                 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
289                 if ($blowLast) {
290                     $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
291                 }
292             }
293             $user->free();
294             unset($user);
295         }
296         $this->blowNoticeCache($blowLast);
297         $this->blowPublicCache($blowLast);
298     }
299
300     function blowGroupCache($blowLast=false)
301     {
302         $cache = common_memcache();
303         if ($cache) {
304             $group_inbox = new Group_inbox();
305             $group_inbox->notice_id = $this->id;
306             if ($group_inbox->find()) {
307                 while ($group_inbox->fetch()) {
308                     $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
309                     if ($blowLast) {
310                         $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
311                     }
312                     $member = new Group_member();
313                     $member->group_id = $group_inbox->group_id;
314                     if ($member->find()) {
315                         while ($member->fetch()) {
316                             $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
317                             if ($blowLast) {
318                                 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
319                             }
320                         }
321                     }
322                 }
323             }
324             $group_inbox->free();
325             unset($group_inbox);
326         }
327     }
328
329     function blowTagCache($blowLast=false)
330     {
331         $cache = common_memcache();
332         if ($cache) {
333             $tag = new Notice_tag();
334             $tag->notice_id = $this->id;
335             if ($tag->find()) {
336                 while ($tag->fetch()) {
337                     $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
338                     if ($blowLast) {
339                         $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
340                     }
341                 }
342             }
343             $tag->free();
344             unset($tag);
345         }
346     }
347
348     function blowSubsCache($blowLast=false)
349     {
350         $cache = common_memcache();
351         if ($cache) {
352             $user = new User();
353
354             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
355             $user->query('SELECT id ' .
356
357                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
358                          'WHERE subscription.subscribed = ' . $this->profile_id);
359
360             while ($user->fetch()) {
361                 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
362                 if ($blowLast) {
363                     $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
364                 }
365             }
366             $user->free();
367             unset($user);
368         }
369     }
370
371     function blowNoticeCache($blowLast=false)
372     {
373         if ($this->is_local) {
374             $cache = common_memcache();
375             if ($cache) {
376                 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
377                 if ($blowLast) {
378                     $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
379                 }
380             }
381         }
382     }
383
384     function blowRepliesCache($blowLast=false)
385     {
386         $cache = common_memcache();
387         if ($cache) {
388             $reply = new Reply();
389             $reply->notice_id = $this->id;
390             if ($reply->find()) {
391                 while ($reply->fetch()) {
392                     $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
393                     if ($blowLast) {
394                         $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
395                     }
396                 }
397             }
398             $reply->free();
399             unset($reply);
400         }
401     }
402
403     function blowPublicCache($blowLast=false)
404     {
405         if ($this->is_local == 1) {
406             $cache = common_memcache();
407             if ($cache) {
408                 $cache->delete(common_cache_key('public'));
409                 if ($blowLast) {
410                     $cache->delete(common_cache_key('public').';last');
411                 }
412             }
413         }
414     }
415
416     function blowFavesCache($blowLast=false)
417     {
418         $cache = common_memcache();
419         if ($cache) {
420             $fave = new Fave();
421             $fave->notice_id = $this->id;
422             if ($fave->find()) {
423                 while ($fave->fetch()) {
424                     $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
425                     if ($blowLast) {
426                         $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
427                     }
428                 }
429             }
430             $fave->free();
431             unset($fave);
432         }
433     }
434
435     # XXX: too many args; we need to move to named params or even a separate
436     # class for notice streams
437
438     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
439
440         if (common_config('memcached', 'enabled')) {
441
442             # Skip the cache if this is a since, since_id or before_id qry
443             if ($since_id > 0 || $before_id > 0 || $since) {
444                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
445             } else {
446                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
447             }
448         }
449
450         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
451     }
452
453     static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
454
455         $needAnd = false;
456         $needWhere = true;
457
458         if (preg_match('/\bWHERE\b/i', $qry)) {
459             $needWhere = false;
460             $needAnd = true;
461         }
462
463         if ($since_id > 0) {
464
465             if ($needWhere) {
466                 $qry .= ' WHERE ';
467                 $needWhere = false;
468             } else {
469                 $qry .= ' AND ';
470             }
471
472             $qry .= ' notice.id > ' . $since_id;
473         }
474
475         if ($before_id > 0) {
476
477             if ($needWhere) {
478                 $qry .= ' WHERE ';
479                 $needWhere = false;
480             } else {
481                 $qry .= ' AND ';
482             }
483
484             $qry .= ' notice.id < ' . $before_id;
485         }
486
487         if ($since) {
488
489             if ($needWhere) {
490                 $qry .= ' WHERE ';
491                 $needWhere = false;
492             } else {
493                 $qry .= ' AND ';
494             }
495
496             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
497         }
498
499         # Allow ORDER override
500
501         if ($order) {
502             $qry .= $order;
503         } else {
504             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
505         }
506
507         if (common_config('db','type') == 'pgsql') {
508             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
509         } else {
510             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
511         }
512
513         $notice = new Notice();
514
515         $notice->query($qry);
516
517         return $notice;
518     }
519
520     # XXX: this is pretty long and should probably be broken up into
521     # some helper functions
522
523     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
524
525         # If outside our cache window, just go to the DB
526
527         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
528             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
529         }
530
531         # Get the cache; if we can't, just go to the DB
532
533         $cache = common_memcache();
534
535         if (!$cache) {
536             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
537         }
538
539         # Get the notices out of the cache
540
541         $notices = $cache->get(common_cache_key($cachekey));
542
543         # On a cache hit, return a DB-object-like wrapper
544
545         if ($notices !== false) {
546             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
547             return $wrapper;
548         }
549
550         # If the cache was invalidated because of new data being
551         # added, we can try and just get the new stuff. We keep an additional
552         # copy of the data at the key + ';last'
553
554         # No cache hit. Try to get the *last* cached version
555
556         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
557
558         if ($last_notices) {
559
560             # Reverse-chron order, so last ID is last.
561
562             $last_id = $last_notices[0]->id;
563
564             # XXX: this assumes monotonically increasing IDs; a fair
565             # bet with our DB.
566
567             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
568                                                   $last_id, null, $order, null);
569
570             if ($new_notice) {
571                 $new_notices = array();
572                 while ($new_notice->fetch()) {
573                     $new_notices[] = clone($new_notice);
574                 }
575                 $new_notice->free();
576                 $notices = array_slice(array_merge($new_notices, $last_notices),
577                                        0, NOTICE_CACHE_WINDOW);
578
579                 # Store the array in the cache for next time
580
581                 $result = $cache->set(common_cache_key($cachekey), $notices);
582                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
583
584                 # return a wrapper of the array for use now
585
586                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
587             }
588         }
589
590         # Otherwise, get the full cache window out of the DB
591
592         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
593
594         # If there are no hits, just return the value
595
596         if (!$notice) {
597             return $notice;
598         }
599
600         # Pack results into an array
601
602         $notices = array();
603
604         while ($notice->fetch()) {
605             $notices[] = clone($notice);
606         }
607
608         $notice->free();
609
610         # Store the array in the cache for next time
611
612         $result = $cache->set(common_cache_key($cachekey), $notices);
613         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
614
615         # return a wrapper of the array for use now
616
617         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
618
619         return $wrapper;
620     }
621
622     function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
623     {
624
625         $parts = array();
626
627         $qry = 'SELECT * FROM notice ';
628
629         if (common_config('public', 'localonly')) {
630             $parts[] = 'is_local = 1';
631         } else {
632             # -1 == blacklisted
633             $parts[] = 'is_local != -1';
634         }
635
636         if ($parts) {
637             $qry .= ' WHERE ' . implode(' AND ', $parts);
638         }
639
640         return Notice::getStream($qry,
641                                  'public',
642                                  $offset, $limit, $since_id, $before_id, null, $since);
643     }
644
645     function addToInboxes()
646     {
647         $enabled = common_config('inboxes', 'enabled');
648
649         if ($enabled === true || $enabled === 'transitional') {
650             $inbox = new Notice_inbox();
651             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
652             $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
653               "SELECT $UT.id, " . $this->id . ", '" . $this->created . "' " .
654               "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
655               'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
656               'AND NOT EXISTS (SELECT user_id, notice_id ' .
657               'FROM notice_inbox ' .
658               "WHERE user_id = $UT.id " .
659               'AND notice_id = ' . $this->id . ' )';
660             if ($enabled === 'transitional') {
661                 $qry .= " AND $UT.inboxed = 1";
662             }
663             $inbox->query($qry);
664         }
665         return;
666     }
667
668     function saveGroups()
669     {
670         $enabled = common_config('inboxes', 'enabled');
671         if ($enabled !== true && $enabled !== 'transitional') {
672             return;
673         }
674
675         /* extract all !group */
676         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
677                                 strtolower($this->content),
678                                 $match);
679         if (!$count) {
680             return true;
681         }
682
683         $profile = $this->getProfile();
684
685         /* Add them to the database */
686
687         foreach (array_unique($match[1]) as $nickname) {
688             /* XXX: remote groups. */
689             $group = User_group::staticGet('nickname', $nickname);
690
691             if (!$group) {
692                 continue;
693             }
694
695             // we automatically add a tag for every group name, too
696
697             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
698                                            'notice_id' => $this->id));
699
700             if (is_null($tag)) {
701                 $this->saveTag($nickname);
702             }
703
704             if ($profile->isMember($group)) {
705
706                 $gi = new Group_inbox();
707
708                 $gi->group_id  = $group->id;
709                 $gi->notice_id = $this->id;
710                 $gi->created   = common_sql_now();
711
712                 $result = $gi->insert();
713
714                 if (!$result) {
715                     common_log_db_error($gi, 'INSERT', __FILE__);
716                 }
717
718                 // FIXME: do this in an offline daemon
719
720                 $inbox = new Notice_inbox();
721                 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
722                 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
723                   "SELECT $UT.id, " . $this->id . ", '" . $this->created . "', 2 " .
724                   "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
725                   'WHERE group_member.group_id = ' . $group->id . ' ' .
726                   'AND NOT EXISTS (SELECT user_id, notice_id ' .
727                   'FROM notice_inbox ' .
728                   "WHERE user_id = $UT.id " .
729                   'AND notice_id = ' . $this->id . ' )';
730                 if ($enabled === 'transitional') {
731                     $qry .= " AND $UT.inboxed = 1";
732                 }
733                 $result = $inbox->query($qry);
734             }
735         }
736     }
737
738     function saveReplies()
739     {
740         // Alternative reply format
741         $tname = false;
742         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
743             $tname = $match[1];
744         }
745         // extract all @messages
746         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
747
748         $names = array();
749
750         if ($cnt || $tname) {
751             // XXX: is there another way to make an array copy?
752             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
753         }
754
755         $sender = Profile::staticGet($this->profile_id);
756
757         $replied = array();
758
759         // store replied only for first @ (what user/notice what the reply directed,
760         // we assume first @ is it)
761
762         for ($i=0; $i<count($names); $i++) {
763             $nickname = $names[$i];
764             $recipient = common_relative_profile($sender, $nickname, $this->created);
765             if (!$recipient) {
766                 continue;
767             }
768             if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
769                 $reply_for = $recipient;
770                 $recipient_notice = $reply_for->getCurrentNotice();
771                 if ($recipient_notice) {
772                     $orig = clone($this);
773                     $this->reply_to = $recipient_notice->id;
774                     $this->update($orig);
775                 }
776             }
777             // Don't save replies from blocked profile to local user
778             $recipient_user = User::staticGet('id', $recipient->id);
779             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
780                 continue;
781             }
782             $reply = new Reply();
783             $reply->notice_id = $this->id;
784             $reply->profile_id = $recipient->id;
785             $id = $reply->insert();
786             if (!$id) {
787                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
788                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
789                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
790                 return;
791             } else {
792                 $replied[$recipient->id] = 1;
793             }
794         }
795
796         // Hash format replies, too
797         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
798         if ($cnt) {
799             foreach ($match[1] as $tag) {
800                 $tagged = Profile_tag::getTagged($sender->id, $tag);
801                 foreach ($tagged as $t) {
802                     if (!$replied[$t->id]) {
803                         // Don't save replies from blocked profile to local user
804                         $t_user = User::staticGet('id', $t->id);
805                         if ($t_user && $t_user->hasBlocked($sender)) {
806                             continue;
807                         }
808                         $reply = new Reply();
809                         $reply->notice_id = $this->id;
810                         $reply->profile_id = $t->id;
811                         $id = $reply->insert();
812                         if (!$id) {
813                             common_log_db_error($reply, 'INSERT', __FILE__);
814                             return;
815                         } else {
816                             $replied[$recipient->id] = 1;
817                         }
818                     }
819                 }
820             }
821         }
822
823         foreach (array_keys($replied) as $recipient) {
824             $user = User::staticGet('id', $recipient);
825             if ($user) {
826                 mail_notify_attn($user, $this);
827             }
828         }
829     }
830
831     function asAtomEntry($namespace=false, $source=false)
832     {
833         $profile = $this->getProfile();
834
835         $xs = new XMLStringer(true);
836
837         if ($namespace) {
838             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
839                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
840         } else {
841             $attrs = array();
842         }
843
844         $xs->elementStart('entry', $attrs);
845
846         if ($source) {
847             $xs->elementStart('source');
848             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
849             $xs->element('link', array('href' => $profile->profileurl));
850             $user = User::staticGet('id', $profile->id);
851             if (!empty($user)) {
852                 $atom_feed = common_local_url('api',
853                                               array('apiaction' => 'statuses',
854                                                     'method' => 'user_timeline',
855                                                     'argument' => $profile->nickname.'.atom'));
856                 $xs->element('link', array('rel' => 'self',
857                                            'type' => 'application/atom+xml',
858                                            'href' => $profile->profileurl));
859                 $xs->element('link', array('rel' => 'license',
860                                            'href' => common_config('license', 'url')));
861             }
862
863             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
864         }
865
866         $xs->elementStart('author');
867         $xs->element('name', null, $profile->nickname);
868         $xs->element('uri', null, $profile->profileurl);
869         $xs->elementEnd('author');
870
871         if ($source) {
872             $xs->elementEnd('source');
873         }
874
875         $xs->element('title', null, $this->content);
876         $xs->element('summary', null, $this->content);
877
878         $xs->element('link', array('rel' => 'alternate',
879                                    'href' => $this->bestUrl()));
880
881         $xs->element('id', null, $this->uri);
882
883         $xs->element('published', null, common_date_w3dtf($this->created));
884         $xs->element('updated', null, common_date_w3dtf($this->modified));
885
886         if ($this->reply_to) {
887             $reply_notice = Notice::staticGet('id', $this->reply_to);
888             if (!empty($reply_notice)) {
889                 $xs->element('link', array('rel' => 'related',
890                                            'href' => $reply_notice->bestUrl()));
891                 $xs->element('thr:in-reply-to',
892                              array('ref' => $reply_notice->uri,
893                                    'href' => $reply_notice->bestUrl()));
894             }
895         }
896
897         $xs->element('content', array('type' => 'html'), $this->rendered);
898
899         $tag = new Notice_tag();
900         $tag->notice_id = $this->id;
901         if ($tag->find()) {
902             while ($tag->fetch()) {
903                 $xs->element('category', array('term' => $tag->tag));
904             }
905         }
906         $tag->free();
907
908         $xs->elementEnd('entry');
909
910         return $xs->getString();
911     }
912
913     function bestUrl()
914     {
915         if (!empty($this->url)) {
916             return $this->url;
917         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
918             return $this->uri;
919         } else {
920             return common_local_url('shownotice',
921                                     array('notice' => $this->id));
922         }
923     }
924 }