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