]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
New algorithm for reply_to saving
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, Control Yourself, 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 define('NOTICE_LOCAL_PUBLIC', 1);
33 define('NOTICE_REMOTE_OMB', 0);
34 define('NOTICE_LOCAL_NONPUBLIC', -1);
35
36 define('MAX_BOXCARS', 128);
37
38 class Notice extends Memcached_DataObject
39 {
40     ###START_AUTOCODE
41     /* the code below is auto generated do not remove the above tag */
42
43     public $__table = 'notice';                          // table name
44     public $id;                              // int(4)  primary_key not_null
45     public $profile_id;                      // int(4)   not_null
46     public $uri;                             // varchar(255)  unique_key
47     public $content;                         // varchar(140)
48     public $rendered;                        // text()
49     public $url;                             // varchar(255)
50     public $created;                         // datetime()   not_null
51     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
52     public $reply_to;                        // int(4)
53     public $is_local;                        // tinyint(1)
54     public $source;                          // varchar(32)
55     public $conversation;                    // int(4)
56
57     /* Static get */
58     function staticGet($k,$v=NULL) {
59         return Memcached_DataObject::staticGet('Notice',$k,$v);
60     }
61
62     /* the code above is auto generated do not remove the tag below */
63     ###END_AUTOCODE
64
65     const GATEWAY = -2;
66
67     function getProfile()
68     {
69         return Profile::staticGet('id', $this->profile_id);
70     }
71
72     function delete()
73     {
74         $this->blowCaches(true);
75         $this->blowFavesCache(true);
76         $this->blowSubsCache(true);
77
78         $this->query('BEGIN');
79         //Null any notices that are replies to this notice
80         $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
81         $related = array('Reply',
82                          'Fave',
83                          'Notice_tag',
84                          'Group_inbox',
85                          'Queue_item');
86         if (common_config('inboxes', 'enabled')) {
87             $related[] = 'Notice_inbox';
88         }
89         foreach ($related as $cls) {
90             $inst = new $cls();
91             $inst->notice_id = $this->id;
92             $inst->delete();
93         }
94         $result = parent::delete();
95         $this->query('COMMIT');
96     }
97
98     function saveTags()
99     {
100         /* extract all #hastags */
101         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
102         if (!$count) {
103             return true;
104         }
105
106         //turn each into their canonical tag
107         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
108         $hashtags = array();
109         for($i=0; $i<count($match[1]); $i++) {
110             $hashtags[] = common_canonical_tag($match[1][$i]);
111         }
112
113         /* Add them to the database */
114         foreach(array_unique($hashtags) as $hashtag) {
115             /* elide characters we don't want in the tag */
116             $this->saveTag($hashtag);
117         }
118         return true;
119     }
120
121     function saveTag($hashtag)
122     {
123         $tag = new Notice_tag();
124         $tag->notice_id = $this->id;
125         $tag->tag = $hashtag;
126         $tag->created = $this->created;
127         $id = $tag->insert();
128
129         if (!$id) {
130             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
131                                               $last_error->message));
132             return;
133         }
134     }
135
136     static function saveNew($profile_id, $content, $source=null,
137                             $is_local=1, $reply_to=null, $uri=null, $created=null) {
138
139         $profile = Profile::staticGet($profile_id);
140
141         $final = common_shorten_links($content);
142
143         if (mb_strlen($final) > 140) {
144             common_log(LOG_INFO, 'Rejecting notice that is too long.');
145             return _('Problem saving notice. Too long.');
146         }
147
148         if (!$profile) {
149             common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
150             return _('Problem saving notice. Unknown user.');
151         }
152
153         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
154             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
155             return _('Too many notices too fast; take a breather and post again in a few minutes.');
156         }
157
158         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
159             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
160                         return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
161         }
162
163                 $banned = common_config('profile', 'banned');
164
165         if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
166             common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
167             return _('You are banned from posting notices on this site.');
168         }
169
170         $notice = new Notice();
171         $notice->profile_id = $profile_id;
172
173         $blacklist = common_config('public', 'blacklist');
174         $autosource = common_config('public', 'autosource');
175
176         # Blacklisted are non-false, but not 1, either
177
178         if (($blacklist && in_array($profile_id, $blacklist)) ||
179             ($source && $autosource && in_array($source, $autosource))) {
180             $notice->is_local = -1;
181         } else {
182             $notice->is_local = $is_local;
183         }
184
185         if (!empty($created)) {
186             $notice->created = $created;
187         } else {
188             $notice->created = common_sql_now();
189         }
190
191                 $notice->content = $final;
192                 $notice->rendered = common_render_content($final, $notice);
193                 $notice->source = $source;
194                 $notice->uri = $uri;
195
196                 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
197
198         if (!empty($notice->reply_to)) {
199             $reply = Notice::staticGet('id', $notice->reply_to);
200             $notice->conversation = $reply->conversation;
201         }
202
203         if (Event::handle('StartNoticeSave', array(&$notice))) {
204
205             // XXX: some of these functions write to the DB
206
207             $notice->query('BEGIN');
208
209             $id = $notice->insert();
210
211             if (!$id) {
212                 common_log_db_error($notice, 'INSERT', __FILE__);
213                 return _('Problem saving notice.');
214             }
215
216             // Update ID-dependent columns: URI, conversation
217
218             $orig = clone($notice);
219
220             $changed = false;
221
222             if (empty($uri)) {
223                 $notice->uri = common_notice_uri($notice);
224                 $changed = true;
225             }
226
227             // If it's not part of a conversation, it's
228             // the beginning of a new conversation.
229
230             if (empty($notice->conversation)) {
231                 $notice->conversation = $notice->id;
232                 $changed = true;
233             }
234
235             if ($changed) {
236                 if (!$notice->update($orig)) {
237                     common_log_db_error($notice, 'UPDATE', __FILE__);
238                     return _('Problem saving notice.');
239                 }
240             }
241
242             // XXX: do we need to change this for remote users?
243
244             $notice->saveReplies();
245             $notice->saveTags();
246
247             $notice->addToInboxes();
248
249             $notice->saveUrls();
250
251             // FIXME: why do we have to re-render the content?
252             // Remove this if it's not necessary.
253
254             $orig2 = clone($notice);
255
256             $notice->rendered = common_render_content($final, $notice);
257             if (!$notice->update($orig2)) {
258                 common_log_db_error($notice, 'UPDATE', __FILE__);
259                 return _('Problem saving notice.');
260             }
261
262             $notice->query('COMMIT');
263
264             Event::handle('EndNoticeSave', array($notice));
265         }
266
267         # Clear the cache for subscribed users, so they'll update at next request
268         # XXX: someone clever could prepend instead of clearing the cache
269
270         $notice->blowCaches();
271
272         return $notice;
273     }
274
275     /** save all urls in the notice to the db
276      *
277      * follow redirects and save all available file information
278      * (mimetype, date, size, oembed, etc.)
279      *
280      * @return void
281      */
282     function saveUrls() {
283         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
284     }
285
286     function saveUrl($data) {
287         list($url, $notice_id) = $data;
288         File::processNew($url, $notice_id);
289     }
290
291     static function checkDupes($profile_id, $content) {
292         $profile = Profile::staticGet($profile_id);
293         if (!$profile) {
294             return false;
295         }
296         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
297         if ($notice) {
298             $last = 0;
299             while ($notice->fetch()) {
300                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
301                     return true;
302                 } else if ($notice->content == $content) {
303                     return false;
304                 }
305             }
306         }
307         # If we get here, oldest item in cache window is not
308         # old enough for dupe limit; do direct check against DB
309         $notice = new Notice();
310         $notice->profile_id = $profile_id;
311         $notice->content = $content;
312         if (common_config('db','type') == 'pgsql')
313           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
314         else
315           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
316
317         $cnt = $notice->count();
318         return ($cnt == 0);
319     }
320
321     static function checkEditThrottle($profile_id) {
322         $profile = Profile::staticGet($profile_id);
323         if (!$profile) {
324             return false;
325         }
326         # Get the Nth notice
327         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
328         if ($notice && $notice->fetch()) {
329             # If the Nth notice was posted less than timespan seconds ago
330             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
331                 # Then we throttle
332                 return false;
333             }
334         }
335         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
336         return true;
337     }
338
339     function getUploadedAttachment() {
340         $post = clone $this;
341         $query = 'select file.url as up, file.id as i from file join file_to_post on file.id = file_id where post_id=' . $post->escape($post->id) . ' and url like "%/notice/%/file"';
342         $post->query($query);
343         $post->fetch();
344         if (empty($post->up) || empty($post->i)) {
345             $ret = false;
346         } else {
347             $ret = array($post->up, $post->i);
348         }
349         $post->free();
350         return $ret;
351     }
352
353     function hasAttachments() {
354         $post = clone $this;
355         $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);
356         $post->query($query);
357         $post->fetch();
358         $n_attachments = intval($post->n_attachments);
359         $post->free();
360         return $n_attachments;
361     }
362
363     function attachments() {
364         // XXX: cache this
365         $att = array();
366         $f2p = new File_to_post;
367         $f2p->post_id = $this->id;
368         if ($f2p->find()) {
369             while ($f2p->fetch()) {
370                 $f = File::staticGet($f2p->file_id);
371                 $att[] = clone($f);
372             }
373         }
374         return $att;
375     }
376
377     function blowCaches($blowLast=false)
378     {
379         $this->blowSubsCache($blowLast);
380         $this->blowNoticeCache($blowLast);
381         $this->blowRepliesCache($blowLast);
382         $this->blowPublicCache($blowLast);
383         $this->blowTagCache($blowLast);
384         $this->blowGroupCache($blowLast);
385         $this->blowConversationCache($blowLast);
386         $profile = Profile::staticGet($this->profile_id);
387         $profile->blowNoticeCount();
388     }
389
390     function blowConversationCache($blowLast=false)
391     {
392         $cache = common_memcache();
393         if ($cache) {
394             $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
395             $cache->delete($ck);
396             if ($blowLast) {
397                 $cache->delete($ck.';last');
398             }
399         }
400     }
401
402     function blowGroupCache($blowLast=false)
403     {
404         $cache = common_memcache();
405         if ($cache) {
406             $group_inbox = new Group_inbox();
407             $group_inbox->notice_id = $this->id;
408             if ($group_inbox->find()) {
409                 while ($group_inbox->fetch()) {
410                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
411                     if ($blowLast) {
412                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
413                     }
414                     $member = new Group_member();
415                     $member->group_id = $group_inbox->group_id;
416                     if ($member->find()) {
417                         while ($member->fetch()) {
418                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
419                             if ($blowLast) {
420                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
421                             }
422                         }
423                     }
424                 }
425             }
426             $group_inbox->free();
427             unset($group_inbox);
428         }
429     }
430
431     function blowTagCache($blowLast=false)
432     {
433         $cache = common_memcache();
434         if ($cache) {
435             $tag = new Notice_tag();
436             $tag->notice_id = $this->id;
437             if ($tag->find()) {
438                 while ($tag->fetch()) {
439                     $tag->blowCache($blowLast);
440                     $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
441
442                     $cache->delete($ck);
443                     if ($blowLast) {
444                         $cache->delete($ck . ';last');
445                     }
446                 }
447             }
448             $tag->free();
449             unset($tag);
450         }
451     }
452
453     function blowSubsCache($blowLast=false)
454     {
455         $cache = common_memcache();
456         if ($cache) {
457             $user = new User();
458
459             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
460             $user->query('SELECT id ' .
461
462                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
463                          'WHERE subscription.subscribed = ' . $this->profile_id);
464
465             while ($user->fetch()) {
466                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
467                 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
468                 if ($blowLast) {
469                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
470                     $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
471                 }
472             }
473             $user->free();
474             unset($user);
475         }
476     }
477
478     function blowNoticeCache($blowLast=false)
479     {
480         if ($this->is_local) {
481             $cache = common_memcache();
482             if (!empty($cache)) {
483                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
484                 if ($blowLast) {
485                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
486                 }
487             }
488         }
489     }
490
491     function blowRepliesCache($blowLast=false)
492     {
493         $cache = common_memcache();
494         if ($cache) {
495             $reply = new Reply();
496             $reply->notice_id = $this->id;
497             if ($reply->find()) {
498                 while ($reply->fetch()) {
499                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
500                     if ($blowLast) {
501                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
502                     }
503                 }
504             }
505             $reply->free();
506             unset($reply);
507         }
508     }
509
510     function blowPublicCache($blowLast=false)
511     {
512         if ($this->is_local == 1) {
513             $cache = common_memcache();
514             if ($cache) {
515                 $cache->delete(common_cache_key('public'));
516                 if ($blowLast) {
517                     $cache->delete(common_cache_key('public').';last');
518                 }
519             }
520         }
521     }
522
523     function blowFavesCache($blowLast=false)
524     {
525         $cache = common_memcache();
526         if ($cache) {
527             $fave = new Fave();
528             $fave->notice_id = $this->id;
529             if ($fave->find()) {
530                 while ($fave->fetch()) {
531                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
532                     $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
533                     if ($blowLast) {
534                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
535                         $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
536                     }
537                 }
538             }
539             $fave->free();
540             unset($fave);
541         }
542     }
543
544     # XXX: too many args; we need to move to named params or even a separate
545     # class for notice streams
546
547     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
548
549         if (common_config('memcached', 'enabled')) {
550
551             # Skip the cache if this is a since, since_id or max_id qry
552             if ($since_id > 0 || $max_id > 0 || $since) {
553                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
554             } else {
555                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
556             }
557         }
558
559         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
560     }
561
562     static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
563
564         $needAnd = false;
565         $needWhere = true;
566
567         if (preg_match('/\bWHERE\b/i', $qry)) {
568             $needWhere = false;
569             $needAnd = true;
570         }
571
572         if ($since_id > 0) {
573
574             if ($needWhere) {
575                 $qry .= ' WHERE ';
576                 $needWhere = false;
577             } else {
578                 $qry .= ' AND ';
579             }
580
581             $qry .= ' notice.id > ' . $since_id;
582         }
583
584         if ($max_id > 0) {
585
586             if ($needWhere) {
587                 $qry .= ' WHERE ';
588                 $needWhere = false;
589             } else {
590                 $qry .= ' AND ';
591             }
592
593             $qry .= ' notice.id <= ' . $max_id;
594         }
595
596         if ($since) {
597
598             if ($needWhere) {
599                 $qry .= ' WHERE ';
600                 $needWhere = false;
601             } else {
602                 $qry .= ' AND ';
603             }
604
605             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
606         }
607
608         # Allow ORDER override
609
610         if ($order) {
611             $qry .= $order;
612         } else {
613             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
614         }
615
616         if (common_config('db','type') == 'pgsql') {
617             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
618         } else {
619             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
620         }
621
622         $notice = new Notice();
623
624         $notice->query($qry);
625
626         return $notice;
627     }
628
629     # XXX: this is pretty long and should probably be broken up into
630     # some helper functions
631
632     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
633
634         # If outside our cache window, just go to the DB
635
636         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
637             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
638         }
639
640         # Get the cache; if we can't, just go to the DB
641
642         $cache = common_memcache();
643
644         if (!$cache) {
645             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
646         }
647
648         # Get the notices out of the cache
649
650         $notices = $cache->get(common_cache_key($cachekey));
651
652         # On a cache hit, return a DB-object-like wrapper
653
654         if ($notices !== false) {
655             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
656             return $wrapper;
657         }
658
659         # If the cache was invalidated because of new data being
660         # added, we can try and just get the new stuff. We keep an additional
661         # copy of the data at the key + ';last'
662
663         # No cache hit. Try to get the *last* cached version
664
665         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
666
667         if ($last_notices) {
668
669             # Reverse-chron order, so last ID is last.
670
671             $last_id = $last_notices[0]->id;
672
673             # XXX: this assumes monotonically increasing IDs; a fair
674             # bet with our DB.
675
676             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
677                                                   $last_id, null, $order, null);
678
679             if ($new_notice) {
680                 $new_notices = array();
681                 while ($new_notice->fetch()) {
682                     $new_notices[] = clone($new_notice);
683                 }
684                 $new_notice->free();
685                 $notices = array_slice(array_merge($new_notices, $last_notices),
686                                        0, NOTICE_CACHE_WINDOW);
687
688                 # Store the array in the cache for next time
689
690                 $result = $cache->set(common_cache_key($cachekey), $notices);
691                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
692
693                 # return a wrapper of the array for use now
694
695                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
696             }
697         }
698
699         # Otherwise, get the full cache window out of the DB
700
701         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
702
703         # If there are no hits, just return the value
704
705         if (!$notice) {
706             return $notice;
707         }
708
709         # Pack results into an array
710
711         $notices = array();
712
713         while ($notice->fetch()) {
714             $notices[] = clone($notice);
715         }
716
717         $notice->free();
718
719         # Store the array in the cache for next time
720
721         $result = $cache->set(common_cache_key($cachekey), $notices);
722         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
723
724         # return a wrapper of the array for use now
725
726         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
727
728         return $wrapper;
729     }
730
731     function getStreamByIds($ids)
732     {
733         $cache = common_memcache();
734
735         if (!empty($cache)) {
736             $notices = array();
737             foreach ($ids as $id) {
738                 $n = Notice::staticGet('id', $id);
739                 if (!empty($n)) {
740                     $notices[] = $n;
741                 }
742             }
743             return new ArrayWrapper($notices);
744         } else {
745             $notice = new Notice();
746             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
747             $notice->orderBy('id DESC');
748
749             $notice->find();
750             return $notice;
751         }
752     }
753
754     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
755     {
756         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
757                               array(),
758                               'public',
759                               $offset, $limit, $since_id, $max_id, $since);
760
761         return Notice::getStreamByIds($ids);
762     }
763
764     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
765     {
766         $notice = new Notice();
767
768         $notice->selectAdd(); // clears it
769         $notice->selectAdd('id');
770
771         $notice->orderBy('id DESC');
772
773         if (!is_null($offset)) {
774             $notice->limit($offset, $limit);
775         }
776
777         if (common_config('public', 'localonly')) {
778             $notice->whereAdd('is_local = 1');
779         } else {
780             # -1 == blacklisted
781             $notice->whereAdd('is_local != -1');
782         }
783
784         if ($since_id != 0) {
785             $notice->whereAdd('id > ' . $since_id);
786         }
787
788         if ($max_id != 0) {
789             $notice->whereAdd('id <= ' . $max_id);
790         }
791
792         if (!is_null($since)) {
793             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
794         }
795
796         $ids = array();
797
798         if ($notice->find()) {
799             while ($notice->fetch()) {
800                 $ids[] = $notice->id;
801             }
802         }
803
804         $notice->free();
805         $notice = NULL;
806
807         return $ids;
808     }
809
810     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
811     {
812         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
813                               array($id),
814                               'notice:conversation_ids:'.$id,
815                               $offset, $limit, $since_id, $max_id, $since);
816
817         return Notice::getStreamByIds($ids);
818     }
819
820     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
821     {
822         $notice = new Notice();
823
824         $notice->selectAdd(); // clears it
825         $notice->selectAdd('id');
826
827         $notice->conversation = $id;
828
829         $notice->orderBy('id DESC');
830
831         if (!is_null($offset)) {
832             $notice->limit($offset, $limit);
833         }
834
835         if ($since_id != 0) {
836             $notice->whereAdd('id > ' . $since_id);
837         }
838
839         if ($max_id != 0) {
840             $notice->whereAdd('id <= ' . $max_id);
841         }
842
843         if (!is_null($since)) {
844             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
845         }
846
847         $ids = array();
848
849         if ($notice->find()) {
850             while ($notice->fetch()) {
851                 $ids[] = $notice->id;
852             }
853         }
854
855         $notice->free();
856         $notice = NULL;
857
858         return $ids;
859     }
860
861     function addToInboxes()
862     {
863         $enabled = common_config('inboxes', 'enabled');
864
865         if ($enabled === true || $enabled === 'transitional') {
866
867             // XXX: loads constants
868
869             $inbox = new Notice_inbox();
870
871             $users = $this->getSubscribedUsers();
872
873             // FIXME: kind of ignoring 'transitional'...
874             // we'll probably stop supporting inboxless mode
875             // in 0.9.x
876
877             $ni = array();
878
879             foreach ($users as $id) {
880                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
881             }
882
883             $groups = $this->saveGroups();
884
885             foreach ($groups as $group) {
886                 $users = $group->getUserMembers();
887                 foreach ($users as $id) {
888                     if (!array_key_exists($id, $ni)) {
889                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
890                     }
891                 }
892             }
893
894             $cnt = 0;
895
896             $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
897             $qry = $qryhdr;
898
899             foreach ($ni as $id => $source) {
900                 if ($cnt > 0) {
901                     $qry .= ', ';
902                 }
903                 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
904                 $cnt++;
905                 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
906                     Notice_inbox::gc($id);
907                 }
908                 if ($cnt >= MAX_BOXCARS) {
909                     $inbox = new Notice_inbox();
910                     $inbox->query($qry);
911                     $qry = $qryhdr;
912                     $cnt = 0;
913                 }
914             }
915
916             if ($cnt > 0) {
917                 $inbox = new Notice_inbox();
918                 $inbox->query($qry);
919             }
920         }
921
922         return;
923     }
924
925     function getSubscribedUsers()
926     {
927         $user = new User();
928
929         if(common_config('db','quote_identifiers'))
930           $user_table = '"user"';
931         else $user_table = 'user';
932
933         $qry =
934           'SELECT id ' .
935           'FROM '. $user_table .' JOIN subscription '.
936           'ON '. $user_table .'.id = subscription.subscriber ' .
937           'WHERE subscription.subscribed = %d ';
938
939         $user->query(sprintf($qry, $this->profile_id));
940
941         $ids = array();
942
943         while ($user->fetch()) {
944             $ids[] = $user->id;
945         }
946
947         $user->free();
948
949         return $ids;
950     }
951
952     function saveGroups()
953     {
954         $groups = array();
955
956         $enabled = common_config('inboxes', 'enabled');
957         if ($enabled !== true && $enabled !== 'transitional') {
958             return $groups;
959         }
960
961         /* extract all !group */
962         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
963                                 strtolower($this->content),
964                                 $match);
965         if (!$count) {
966             return $groups;
967         }
968
969         $profile = $this->getProfile();
970
971         /* Add them to the database */
972
973         foreach (array_unique($match[1]) as $nickname) {
974             /* XXX: remote groups. */
975             $group = User_group::getForNickname($nickname);
976
977             if (empty($group)) {
978                 continue;
979             }
980
981             // we automatically add a tag for every group name, too
982
983             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
984                                              'notice_id' => $this->id));
985
986             if (is_null($tag)) {
987                 $this->saveTag($nickname);
988             }
989
990             if ($profile->isMember($group)) {
991
992                 $result = $this->addToGroupInbox($group);
993
994                 if (!$result) {
995                     common_log_db_error($gi, 'INSERT', __FILE__);
996                 }
997
998                 $groups[] = clone($group);
999             }
1000         }
1001
1002         return $groups;
1003     }
1004
1005     function addToGroupInbox($group)
1006     {
1007         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1008                                          'notice_id' => $this->id));
1009
1010         if (empty($gi)) {
1011
1012             $gi = new Group_inbox();
1013
1014             $gi->group_id  = $group->id;
1015             $gi->notice_id = $this->id;
1016             $gi->created   = $this->created;
1017
1018             return $gi->insert();
1019         }
1020
1021         return true;
1022     }
1023
1024     function saveReplies()
1025     {
1026         // Alternative reply format
1027         $tname = false;
1028         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1029             $tname = $match[1];
1030         }
1031         // extract all @messages
1032         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1033
1034         $names = array();
1035
1036         if ($cnt || $tname) {
1037             // XXX: is there another way to make an array copy?
1038             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1039         }
1040
1041         $sender = Profile::staticGet($this->profile_id);
1042
1043         $replied = array();
1044
1045         // store replied only for first @ (what user/notice what the reply directed,
1046         // we assume first @ is it)
1047
1048         for ($i=0; $i<count($names); $i++) {
1049             $nickname = $names[$i];
1050             $recipient = common_relative_profile($sender, $nickname, $this->created);
1051             if (!$recipient) {
1052                 continue;
1053             }
1054             // Don't save replies from blocked profile to local user
1055             $recipient_user = User::staticGet('id', $recipient->id);
1056             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1057                 continue;
1058             }
1059             $reply = new Reply();
1060             $reply->notice_id = $this->id;
1061             $reply->profile_id = $recipient->id;
1062             $id = $reply->insert();
1063             if (!$id) {
1064                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1065                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1066                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1067                 return;
1068             } else {
1069                 $replied[$recipient->id] = 1;
1070             }
1071         }
1072
1073         // Hash format replies, too
1074         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1075         if ($cnt) {
1076             foreach ($match[1] as $tag) {
1077                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1078                 foreach ($tagged as $t) {
1079                     if (!$replied[$t->id]) {
1080                         // Don't save replies from blocked profile to local user
1081                         $t_user = User::staticGet('id', $t->id);
1082                         if ($t_user && $t_user->hasBlocked($sender)) {
1083                             continue;
1084                         }
1085                         $reply = new Reply();
1086                         $reply->notice_id = $this->id;
1087                         $reply->profile_id = $t->id;
1088                         $id = $reply->insert();
1089                         if (!$id) {
1090                             common_log_db_error($reply, 'INSERT', __FILE__);
1091                             return;
1092                         } else {
1093                             $replied[$recipient->id] = 1;
1094                         }
1095                     }
1096                 }
1097             }
1098         }
1099
1100         foreach (array_keys($replied) as $recipient) {
1101             $user = User::staticGet('id', $recipient);
1102             if ($user) {
1103                 mail_notify_attn($user, $this);
1104             }
1105         }
1106     }
1107
1108     function asAtomEntry($namespace=false, $source=false)
1109     {
1110         $profile = $this->getProfile();
1111
1112         $xs = new XMLStringer(true);
1113
1114         if ($namespace) {
1115             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1116                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1117         } else {
1118             $attrs = array();
1119         }
1120
1121         $xs->elementStart('entry', $attrs);
1122
1123         if ($source) {
1124             $xs->elementStart('source');
1125             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1126             $xs->element('link', array('href' => $profile->profileurl));
1127             $user = User::staticGet('id', $profile->id);
1128             if (!empty($user)) {
1129                 $atom_feed = common_local_url('api',
1130                                               array('apiaction' => 'statuses',
1131                                                     'method' => 'user_timeline',
1132                                                     'argument' => $profile->nickname.'.atom'));
1133                 $xs->element('link', array('rel' => 'self',
1134                                            'type' => 'application/atom+xml',
1135                                            'href' => $profile->profileurl));
1136                 $xs->element('link', array('rel' => 'license',
1137                                            'href' => common_config('license', 'url')));
1138             }
1139
1140             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1141         }
1142
1143         $xs->elementStart('author');
1144         $xs->element('name', null, $profile->nickname);
1145         $xs->element('uri', null, $profile->profileurl);
1146         $xs->elementEnd('author');
1147
1148         if ($source) {
1149             $xs->elementEnd('source');
1150         }
1151
1152         $xs->element('title', null, $this->content);
1153         $xs->element('summary', null, $this->content);
1154
1155         $xs->element('link', array('rel' => 'alternate',
1156                                    'href' => $this->bestUrl()));
1157
1158         $xs->element('id', null, $this->uri);
1159
1160         $xs->element('published', null, common_date_w3dtf($this->created));
1161         $xs->element('updated', null, common_date_w3dtf($this->modified));
1162
1163         if ($this->reply_to) {
1164             $reply_notice = Notice::staticGet('id', $this->reply_to);
1165             if (!empty($reply_notice)) {
1166                 $xs->element('link', array('rel' => 'related',
1167                                            'href' => $reply_notice->bestUrl()));
1168                 $xs->element('thr:in-reply-to',
1169                              array('ref' => $reply_notice->uri,
1170                                    'href' => $reply_notice->bestUrl()));
1171             }
1172         }
1173
1174         $xs->element('content', array('type' => 'html'), $this->rendered);
1175
1176         $tag = new Notice_tag();
1177         $tag->notice_id = $this->id;
1178         if ($tag->find()) {
1179             while ($tag->fetch()) {
1180                 $xs->element('category', array('term' => $tag->tag));
1181             }
1182         }
1183         $tag->free();
1184
1185         # Enclosures
1186         $attachments = $this->attachments();
1187         if($attachments){
1188             foreach($attachments as $attachment){
1189                 if ($attachment->isEnclosure()) {
1190                     $attributes = array('rel'=>'enclosure','href'=>$attachment->url,'type'=>$attachment->mimetype,'length'=>$attachment->size);
1191                     if($attachment->title){
1192                         $attributes['title']=$attachment->title;
1193                     }
1194                     $xs->element('link', $attributes, null);
1195                 }
1196             }
1197         }
1198
1199         $xs->elementEnd('entry');
1200
1201         return $xs->getString();
1202     }
1203
1204     function bestUrl()
1205     {
1206         if (!empty($this->url)) {
1207             return $this->url;
1208         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1209             return $this->uri;
1210         } else {
1211             return common_local_url('shownotice',
1212                                     array('notice' => $this->id));
1213         }
1214     }
1215
1216     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1217     {
1218         $cache = common_memcache();
1219
1220         if (empty($cache) ||
1221             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1222             is_null($limit) ||
1223             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1224             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1225                                                                       $max_id, $since)));
1226         }
1227
1228         $idkey = common_cache_key($cachekey);
1229
1230         $idstr = $cache->get($idkey);
1231
1232         if (!empty($idstr)) {
1233             // Cache hit! Woohoo!
1234             $window = explode(',', $idstr);
1235             $ids = array_slice($window, $offset, $limit);
1236             return $ids;
1237         }
1238
1239         $laststr = $cache->get($idkey.';last');
1240
1241         if (!empty($laststr)) {
1242             $window = explode(',', $laststr);
1243             $last_id = $window[0];
1244             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1245                                                                           $last_id, 0, null)));
1246
1247             $new_window = array_merge($new_ids, $window);
1248
1249             $new_windowstr = implode(',', $new_window);
1250
1251             $result = $cache->set($idkey, $new_windowstr);
1252             $result = $cache->set($idkey . ';last', $new_windowstr);
1253
1254             $ids = array_slice($new_window, $offset, $limit);
1255
1256             return $ids;
1257         }
1258
1259         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1260                                                                      0, 0, null)));
1261
1262         $windowstr = implode(',', $window);
1263
1264         $result = $cache->set($idkey, $windowstr);
1265         $result = $cache->set($idkey . ';last', $windowstr);
1266
1267         $ids = array_slice($window, $offset, $limit);
1268
1269         return $ids;
1270     }
1271
1272     /**
1273      * Determine which notice, if any, a new notice is in reply to.
1274      *
1275      * For conversation tracking, we try to see where this notice fits
1276      * in the tree. Rough algorithm is:
1277      *
1278      * if (reply_to is set and valid) {
1279      *     return reply_to;
1280      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1281      *     return ID of last notice by initial @name in content;
1282      * }
1283      *
1284      * Note that all @nickname instances will still be used to save "reply" records,
1285      * so the notice shows up in the mentioned users' "replies" tab.
1286      *
1287      * @param integer $reply_to   ID passed in by Web or API
1288      * @param integer $profile_id ID of author
1289      * @param string  $source     Source tag, like 'web' or 'gwibber'
1290      * @param string  $content    Final notice content
1291      *
1292      * @return integer ID of replied-to notice, or null for not a reply.
1293      */
1294
1295     static function getReplyTo($reply_to, $profile_id, $source, $content)
1296     {
1297         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1298
1299         // If $reply_to is specified, we check that it exists, and then
1300         // return it if it does
1301
1302         if (!empty($reply_to)) {
1303             $reply_notice = Notice::staticGet('id', $reply_to);
1304             if (!empty($reply_notice)) {
1305                 return $reply_to;
1306             }
1307         }
1308
1309         // If it's not a "low bandwidth" source (one where you can't set
1310         // a reply_to argument), we return. This is mostly web and API
1311         // clients.
1312
1313         if (!in_array($source, $lb)) {
1314             return null;
1315         }
1316
1317         // Is there an initial @ or T?
1318
1319         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1320             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1321             $nickname = common_canonical_nickname($match[1]);
1322         } else {
1323             return null;
1324         }
1325
1326         // Figure out who that is.
1327
1328         $sender = Profile::staticGet('id', $profile_id);
1329         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1330
1331         if (empty($recipient)) {
1332             return null;
1333         }
1334
1335         // Get their last notice
1336
1337         $last = $recipient->getCurrentNotice();
1338
1339         if (!empty($last)) {
1340             return $last->id;
1341         }
1342     }
1343 }