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