]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
change Laconica and Control Yourself to StatusNet in PHP files
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /*
3  * StatusNet - a distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, 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('MAX_BOXCARS', 128);
33
34 class Notice extends Memcached_DataObject
35 {
36     ###START_AUTOCODE
37     /* the code below is auto generated do not remove the above tag */
38
39     public $__table = 'notice';                          // table name
40     public $id;                              // int(4)  primary_key not_null
41     public $profile_id;                      // int(4)   not_null
42     public $uri;                             // varchar(255)  unique_key
43     public $content;                         // varchar(140)
44     public $rendered;                        // text()
45     public $url;                             // varchar(255)
46     public $created;                         // datetime()   not_null
47     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
48     public $reply_to;                        // int(4)
49     public $is_local;                        // tinyint(1)
50     public $source;                          // varchar(32)
51     public $conversation;                    // int(4)
52
53     /* Static get */
54     function staticGet($k,$v=NULL) {
55         return Memcached_DataObject::staticGet('Notice',$k,$v);
56     }
57
58     /* the code above is auto generated do not remove the tag below */
59     ###END_AUTOCODE
60
61     /* Notice types */ 
62     const LOCAL_PUBLIC    =  1;
63     const REMOTE_OMB      =  0;
64     const LOCAL_NONPUBLIC = -1;
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=Notice::LOCAL_PUBLIC, $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 = Notice::LOCAL_NONPUBLIC;
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 == Notice::LOCAL_PUBLIC) {
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 = ' . Notice::LOCAL_PUBLIC);
779         } else {
780             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
781             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
782             $notice->whereAdd('is_local !='. Notice::GATEWAY);
783         }
784
785         if ($since_id != 0) {
786             $notice->whereAdd('id > ' . $since_id);
787         }
788
789         if ($max_id != 0) {
790             $notice->whereAdd('id <= ' . $max_id);
791         }
792
793         if (!is_null($since)) {
794             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
795         }
796
797         $ids = array();
798
799         if ($notice->find()) {
800             while ($notice->fetch()) {
801                 $ids[] = $notice->id;
802             }
803         }
804
805         $notice->free();
806         $notice = NULL;
807
808         return $ids;
809     }
810
811     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
812     {
813         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
814                               array($id),
815                               'notice:conversation_ids:'.$id,
816                               $offset, $limit, $since_id, $max_id, $since);
817
818         return Notice::getStreamByIds($ids);
819     }
820
821     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
822     {
823         $notice = new Notice();
824
825         $notice->selectAdd(); // clears it
826         $notice->selectAdd('id');
827
828         $notice->conversation = $id;
829
830         $notice->orderBy('id DESC');
831
832         if (!is_null($offset)) {
833             $notice->limit($offset, $limit);
834         }
835
836         if ($since_id != 0) {
837             $notice->whereAdd('id > ' . $since_id);
838         }
839
840         if ($max_id != 0) {
841             $notice->whereAdd('id <= ' . $max_id);
842         }
843
844         if (!is_null($since)) {
845             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
846         }
847
848         $ids = array();
849
850         if ($notice->find()) {
851             while ($notice->fetch()) {
852                 $ids[] = $notice->id;
853             }
854         }
855
856         $notice->free();
857         $notice = NULL;
858
859         return $ids;
860     }
861
862     function addToInboxes()
863     {
864         $enabled = common_config('inboxes', 'enabled');
865
866         if ($enabled === true || $enabled === 'transitional') {
867
868             // XXX: loads constants
869
870             $inbox = new Notice_inbox();
871
872             $users = $this->getSubscribedUsers();
873
874             // FIXME: kind of ignoring 'transitional'...
875             // we'll probably stop supporting inboxless mode
876             // in 0.9.x
877
878             $ni = array();
879
880             foreach ($users as $id) {
881                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
882             }
883
884             $groups = $this->saveGroups();
885
886             foreach ($groups as $group) {
887                 $users = $group->getUserMembers();
888                 foreach ($users as $id) {
889                     if (!array_key_exists($id, $ni)) {
890                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
891                     }
892                 }
893             }
894
895             $cnt = 0;
896
897             $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
898             $qry = $qryhdr;
899
900             foreach ($ni as $id => $source) {
901                 if ($cnt > 0) {
902                     $qry .= ', ';
903                 }
904                 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
905                 $cnt++;
906                 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
907                     Notice_inbox::gc($id);
908                 }
909                 if ($cnt >= MAX_BOXCARS) {
910                     $inbox = new Notice_inbox();
911                     $inbox->query($qry);
912                     $qry = $qryhdr;
913                     $cnt = 0;
914                 }
915             }
916
917             if ($cnt > 0) {
918                 $inbox = new Notice_inbox();
919                 $inbox->query($qry);
920             }
921         }
922
923         return;
924     }
925
926     function getSubscribedUsers()
927     {
928         $user = new User();
929
930         if(common_config('db','quote_identifiers'))
931           $user_table = '"user"';
932         else $user_table = 'user';
933
934         $qry =
935           'SELECT id ' .
936           'FROM '. $user_table .' JOIN subscription '.
937           'ON '. $user_table .'.id = subscription.subscriber ' .
938           'WHERE subscription.subscribed = %d ';
939
940         $user->query(sprintf($qry, $this->profile_id));
941
942         $ids = array();
943
944         while ($user->fetch()) {
945             $ids[] = $user->id;
946         }
947
948         $user->free();
949
950         return $ids;
951     }
952
953     function saveGroups()
954     {
955         $groups = array();
956
957         $enabled = common_config('inboxes', 'enabled');
958         if ($enabled !== true && $enabled !== 'transitional') {
959             return $groups;
960         }
961
962         /* extract all !group */
963         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
964                                 strtolower($this->content),
965                                 $match);
966         if (!$count) {
967             return $groups;
968         }
969
970         $profile = $this->getProfile();
971
972         /* Add them to the database */
973
974         foreach (array_unique($match[1]) as $nickname) {
975             /* XXX: remote groups. */
976             $group = User_group::getForNickname($nickname);
977
978             if (empty($group)) {
979                 continue;
980             }
981
982             // we automatically add a tag for every group name, too
983
984             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
985                                              'notice_id' => $this->id));
986
987             if (is_null($tag)) {
988                 $this->saveTag($nickname);
989             }
990
991             if ($profile->isMember($group)) {
992
993                 $result = $this->addToGroupInbox($group);
994
995                 if (!$result) {
996                     common_log_db_error($gi, 'INSERT', __FILE__);
997                 }
998
999                 $groups[] = clone($group);
1000             }
1001         }
1002
1003         return $groups;
1004     }
1005
1006     function addToGroupInbox($group)
1007     {
1008         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1009                                          'notice_id' => $this->id));
1010
1011         if (empty($gi)) {
1012
1013             $gi = new Group_inbox();
1014
1015             $gi->group_id  = $group->id;
1016             $gi->notice_id = $this->id;
1017             $gi->created   = $this->created;
1018
1019             return $gi->insert();
1020         }
1021
1022         return true;
1023     }
1024
1025     function saveReplies()
1026     {
1027         // Alternative reply format
1028         $tname = false;
1029         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1030             $tname = $match[1];
1031         }
1032         // extract all @messages
1033         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1034
1035         $names = array();
1036
1037         if ($cnt || $tname) {
1038             // XXX: is there another way to make an array copy?
1039             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1040         }
1041
1042         $sender = Profile::staticGet($this->profile_id);
1043
1044         $replied = array();
1045
1046         // store replied only for first @ (what user/notice what the reply directed,
1047         // we assume first @ is it)
1048
1049         for ($i=0; $i<count($names); $i++) {
1050             $nickname = $names[$i];
1051             $recipient = common_relative_profile($sender, $nickname, $this->created);
1052             if (!$recipient) {
1053                 continue;
1054             }
1055             // Don't save replies from blocked profile to local user
1056             $recipient_user = User::staticGet('id', $recipient->id);
1057             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1058                 continue;
1059             }
1060             $reply = new Reply();
1061             $reply->notice_id = $this->id;
1062             $reply->profile_id = $recipient->id;
1063             $id = $reply->insert();
1064             if (!$id) {
1065                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1066                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1067                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1068                 return;
1069             } else {
1070                 $replied[$recipient->id] = 1;
1071             }
1072         }
1073
1074         // Hash format replies, too
1075         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1076         if ($cnt) {
1077             foreach ($match[1] as $tag) {
1078                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1079                 foreach ($tagged as $t) {
1080                     if (!$replied[$t->id]) {
1081                         // Don't save replies from blocked profile to local user
1082                         $t_user = User::staticGet('id', $t->id);
1083                         if ($t_user && $t_user->hasBlocked($sender)) {
1084                             continue;
1085                         }
1086                         $reply = new Reply();
1087                         $reply->notice_id = $this->id;
1088                         $reply->profile_id = $t->id;
1089                         $id = $reply->insert();
1090                         if (!$id) {
1091                             common_log_db_error($reply, 'INSERT', __FILE__);
1092                             return;
1093                         } else {
1094                             $replied[$recipient->id] = 1;
1095                         }
1096                     }
1097                 }
1098             }
1099         }
1100
1101         foreach (array_keys($replied) as $recipient) {
1102             $user = User::staticGet('id', $recipient);
1103             if ($user) {
1104                 mail_notify_attn($user, $this);
1105             }
1106         }
1107     }
1108
1109     function asAtomEntry($namespace=false, $source=false)
1110     {
1111         $profile = $this->getProfile();
1112
1113         $xs = new XMLStringer(true);
1114
1115         if ($namespace) {
1116             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1117                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1118         } else {
1119             $attrs = array();
1120         }
1121
1122         $xs->elementStart('entry', $attrs);
1123
1124         if ($source) {
1125             $xs->elementStart('source');
1126             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1127             $xs->element('link', array('href' => $profile->profileurl));
1128             $user = User::staticGet('id', $profile->id);
1129             if (!empty($user)) {
1130                 $atom_feed = common_local_url('api',
1131                                               array('apiaction' => 'statuses',
1132                                                     'method' => 'user_timeline',
1133                                                     'argument' => $profile->nickname.'.atom'));
1134                 $xs->element('link', array('rel' => 'self',
1135                                            'type' => 'application/atom+xml',
1136                                            'href' => $profile->profileurl));
1137                 $xs->element('link', array('rel' => 'license',
1138                                            'href' => common_config('license', 'url')));
1139             }
1140
1141             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1142         }
1143
1144         $xs->elementStart('author');
1145         $xs->element('name', null, $profile->nickname);
1146         $xs->element('uri', null, $profile->profileurl);
1147         $xs->elementEnd('author');
1148
1149         if ($source) {
1150             $xs->elementEnd('source');
1151         }
1152
1153         $xs->element('title', null, $this->content);
1154         $xs->element('summary', null, $this->content);
1155
1156         $xs->element('link', array('rel' => 'alternate',
1157                                    'href' => $this->bestUrl()));
1158
1159         $xs->element('id', null, $this->uri);
1160
1161         $xs->element('published', null, common_date_w3dtf($this->created));
1162         $xs->element('updated', null, common_date_w3dtf($this->modified));
1163
1164         if ($this->reply_to) {
1165             $reply_notice = Notice::staticGet('id', $this->reply_to);
1166             if (!empty($reply_notice)) {
1167                 $xs->element('link', array('rel' => 'related',
1168                                            'href' => $reply_notice->bestUrl()));
1169                 $xs->element('thr:in-reply-to',
1170                              array('ref' => $reply_notice->uri,
1171                                    'href' => $reply_notice->bestUrl()));
1172             }
1173         }
1174
1175         $xs->element('content', array('type' => 'html'), $this->rendered);
1176
1177         $tag = new Notice_tag();
1178         $tag->notice_id = $this->id;
1179         if ($tag->find()) {
1180             while ($tag->fetch()) {
1181                 $xs->element('category', array('term' => $tag->tag));
1182             }
1183         }
1184         $tag->free();
1185
1186         # Enclosures
1187         $attachments = $this->attachments();
1188         if($attachments){
1189             foreach($attachments as $attachment){
1190                 if ($attachment->isEnclosure()) {
1191                     $attributes = array('rel'=>'enclosure','href'=>$attachment->url,'type'=>$attachment->mimetype,'length'=>$attachment->size);
1192                     if($attachment->title){
1193                         $attributes['title']=$attachment->title;
1194                     }
1195                     $xs->element('link', $attributes, null);
1196                 }
1197             }
1198         }
1199
1200         $xs->elementEnd('entry');
1201
1202         return $xs->getString();
1203     }
1204
1205     function bestUrl()
1206     {
1207         if (!empty($this->url)) {
1208             return $this->url;
1209         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1210             return $this->uri;
1211         } else {
1212             return common_local_url('shownotice',
1213                                     array('notice' => $this->id));
1214         }
1215     }
1216
1217     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1218     {
1219         $cache = common_memcache();
1220
1221         if (empty($cache) ||
1222             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1223             is_null($limit) ||
1224             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1225             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1226                                                                       $max_id, $since)));
1227         }
1228
1229         $idkey = common_cache_key($cachekey);
1230
1231         $idstr = $cache->get($idkey);
1232
1233         if (!empty($idstr)) {
1234             // Cache hit! Woohoo!
1235             $window = explode(',', $idstr);
1236             $ids = array_slice($window, $offset, $limit);
1237             return $ids;
1238         }
1239
1240         $laststr = $cache->get($idkey.';last');
1241
1242         if (!empty($laststr)) {
1243             $window = explode(',', $laststr);
1244             $last_id = $window[0];
1245             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1246                                                                           $last_id, 0, null)));
1247
1248             $new_window = array_merge($new_ids, $window);
1249
1250             $new_windowstr = implode(',', $new_window);
1251
1252             $result = $cache->set($idkey, $new_windowstr);
1253             $result = $cache->set($idkey . ';last', $new_windowstr);
1254
1255             $ids = array_slice($new_window, $offset, $limit);
1256
1257             return $ids;
1258         }
1259
1260         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1261                                                                      0, 0, null)));
1262
1263         $windowstr = implode(',', $window);
1264
1265         $result = $cache->set($idkey, $windowstr);
1266         $result = $cache->set($idkey . ';last', $windowstr);
1267
1268         $ids = array_slice($window, $offset, $limit);
1269
1270         return $ids;
1271     }
1272
1273     /**
1274      * Determine which notice, if any, a new notice is in reply to.
1275      *
1276      * For conversation tracking, we try to see where this notice fits
1277      * in the tree. Rough algorithm is:
1278      *
1279      * if (reply_to is set and valid) {
1280      *     return reply_to;
1281      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1282      *     return ID of last notice by initial @name in content;
1283      * }
1284      *
1285      * Note that all @nickname instances will still be used to save "reply" records,
1286      * so the notice shows up in the mentioned users' "replies" tab.
1287      *
1288      * @param integer $reply_to   ID passed in by Web or API
1289      * @param integer $profile_id ID of author
1290      * @param string  $source     Source tag, like 'web' or 'gwibber'
1291      * @param string  $content    Final notice content
1292      *
1293      * @return integer ID of replied-to notice, or null for not a reply.
1294      */
1295
1296     static function getReplyTo($reply_to, $profile_id, $source, $content)
1297     {
1298         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1299
1300         // If $reply_to is specified, we check that it exists, and then
1301         // return it if it does
1302
1303         if (!empty($reply_to)) {
1304             $reply_notice = Notice::staticGet('id', $reply_to);
1305             if (!empty($reply_notice)) {
1306                 return $reply_to;
1307             }
1308         }
1309
1310         // If it's not a "low bandwidth" source (one where you can't set
1311         // a reply_to argument), we return. This is mostly web and API
1312         // clients.
1313
1314         if (!in_array($source, $lb)) {
1315             return null;
1316         }
1317
1318         // Is there an initial @ or T?
1319
1320         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1321             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1322             $nickname = common_canonical_nickname($match[1]);
1323         } else {
1324             return null;
1325         }
1326
1327         // Figure out who that is.
1328
1329         $sender = Profile::staticGet('id', $profile_id);
1330         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1331
1332         if (empty($recipient)) {
1333             return null;
1334         }
1335
1336         // Get their last notice
1337
1338         $last = $recipient->getCurrentNotice();
1339
1340         if (!empty($last)) {
1341             return $last->id;
1342         }
1343     }
1344 }