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