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