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