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