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