]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
clear repeat_of flag when a notice is deleted
[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         }
488     }
489
490     function blowConversationCache($blowLast=false)
491     {
492         $cache = common_memcache();
493         if ($cache) {
494             $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
495             $cache->delete($ck);
496             if ($blowLast) {
497                 $cache->delete($ck.';last');
498             }
499         }
500     }
501
502     function blowGroupCache($blowLast=false)
503     {
504         $cache = common_memcache();
505         if ($cache) {
506             $group_inbox = new Group_inbox();
507             $group_inbox->notice_id = $this->id;
508             if ($group_inbox->find()) {
509                 while ($group_inbox->fetch()) {
510                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
511                     if ($blowLast) {
512                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
513                     }
514                     $member = new Group_member();
515                     $member->group_id = $group_inbox->group_id;
516                     if ($member->find()) {
517                         while ($member->fetch()) {
518                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
519                             if ($blowLast) {
520                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
521                             }
522                         }
523                     }
524                 }
525             }
526             $group_inbox->free();
527             unset($group_inbox);
528         }
529     }
530
531     function blowTagCache($blowLast=false)
532     {
533         $cache = common_memcache();
534         if ($cache) {
535             $tag = new Notice_tag();
536             $tag->notice_id = $this->id;
537             if ($tag->find()) {
538                 while ($tag->fetch()) {
539                     $tag->blowCache($blowLast);
540                     $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
541
542                     $cache->delete($ck);
543                     if ($blowLast) {
544                         $cache->delete($ck . ';last');
545                     }
546                 }
547             }
548             $tag->free();
549             unset($tag);
550         }
551     }
552
553     function blowSubsCache($blowLast=false)
554     {
555         $cache = common_memcache();
556         if ($cache) {
557             $user = new User();
558
559             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
560             $user->query('SELECT id ' .
561
562                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
563                          'WHERE subscription.subscribed = ' . $this->profile_id);
564
565             while ($user->fetch()) {
566                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
567                 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
568                 if ($blowLast) {
569                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
570                     $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
571                 }
572             }
573             $user->free();
574             unset($user);
575         }
576     }
577
578     function blowNoticeCache($blowLast=false)
579     {
580         if ($this->is_local) {
581             $cache = common_memcache();
582             if (!empty($cache)) {
583                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
584                 if ($blowLast) {
585                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
586                 }
587             }
588         }
589     }
590
591     function blowRepliesCache($blowLast=false)
592     {
593         $cache = common_memcache();
594         if ($cache) {
595             $reply = new Reply();
596             $reply->notice_id = $this->id;
597             if ($reply->find()) {
598                 while ($reply->fetch()) {
599                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
600                     if ($blowLast) {
601                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
602                     }
603                 }
604             }
605             $reply->free();
606             unset($reply);
607         }
608     }
609
610     function blowPublicCache($blowLast=false)
611     {
612         if ($this->is_local == Notice::LOCAL_PUBLIC) {
613             $cache = common_memcache();
614             if ($cache) {
615                 $cache->delete(common_cache_key('public'));
616                 if ($blowLast) {
617                     $cache->delete(common_cache_key('public').';last');
618                 }
619             }
620         }
621     }
622
623     function blowFavesCache($blowLast=false)
624     {
625         $cache = common_memcache();
626         if ($cache) {
627             $fave = new Fave();
628             $fave->notice_id = $this->id;
629             if ($fave->find()) {
630                 while ($fave->fetch()) {
631                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
632                     $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
633                     if ($blowLast) {
634                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
635                         $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
636                     }
637                 }
638             }
639             $fave->free();
640             unset($fave);
641         }
642     }
643
644     # XXX: too many args; we need to move to named params or even a separate
645     # class for notice streams
646
647     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
648
649         if (common_config('memcached', 'enabled')) {
650
651             # Skip the cache if this is a since, since_id or max_id qry
652             if ($since_id > 0 || $max_id > 0 || $since) {
653                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
654             } else {
655                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
656             }
657         }
658
659         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
660     }
661
662     static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
663
664         $needAnd = false;
665         $needWhere = true;
666
667         if (preg_match('/\bWHERE\b/i', $qry)) {
668             $needWhere = false;
669             $needAnd = true;
670         }
671
672         if ($since_id > 0) {
673
674             if ($needWhere) {
675                 $qry .= ' WHERE ';
676                 $needWhere = false;
677             } else {
678                 $qry .= ' AND ';
679             }
680
681             $qry .= ' notice.id > ' . $since_id;
682         }
683
684         if ($max_id > 0) {
685
686             if ($needWhere) {
687                 $qry .= ' WHERE ';
688                 $needWhere = false;
689             } else {
690                 $qry .= ' AND ';
691             }
692
693             $qry .= ' notice.id <= ' . $max_id;
694         }
695
696         if ($since) {
697
698             if ($needWhere) {
699                 $qry .= ' WHERE ';
700                 $needWhere = false;
701             } else {
702                 $qry .= ' AND ';
703             }
704
705             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
706         }
707
708         # Allow ORDER override
709
710         if ($order) {
711             $qry .= $order;
712         } else {
713             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
714         }
715
716         if (common_config('db','type') == 'pgsql') {
717             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
718         } else {
719             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
720         }
721
722         $notice = new Notice();
723
724         $notice->query($qry);
725
726         return $notice;
727     }
728
729     # XXX: this is pretty long and should probably be broken up into
730     # some helper functions
731
732     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
733
734         # If outside our cache window, just go to the DB
735
736         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
737             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
738         }
739
740         # Get the cache; if we can't, just go to the DB
741
742         $cache = common_memcache();
743
744         if (empty($cache)) {
745             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
746         }
747
748         # Get the notices out of the cache
749
750         $notices = $cache->get(common_cache_key($cachekey));
751
752         # On a cache hit, return a DB-object-like wrapper
753
754         if ($notices !== false) {
755             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
756             return $wrapper;
757         }
758
759         # If the cache was invalidated because of new data being
760         # added, we can try and just get the new stuff. We keep an additional
761         # copy of the data at the key + ';last'
762
763         # No cache hit. Try to get the *last* cached version
764
765         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
766
767         if ($last_notices) {
768
769             # Reverse-chron order, so last ID is last.
770
771             $last_id = $last_notices[0]->id;
772
773             # XXX: this assumes monotonically increasing IDs; a fair
774             # bet with our DB.
775
776             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
777                                                   $last_id, null, $order, null);
778
779             if ($new_notice) {
780                 $new_notices = array();
781                 while ($new_notice->fetch()) {
782                     $new_notices[] = clone($new_notice);
783                 }
784                 $new_notice->free();
785                 $notices = array_slice(array_merge($new_notices, $last_notices),
786                                        0, NOTICE_CACHE_WINDOW);
787
788                 # Store the array in the cache for next time
789
790                 $result = $cache->set(common_cache_key($cachekey), $notices);
791                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
792
793                 # return a wrapper of the array for use now
794
795                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
796             }
797         }
798
799         # Otherwise, get the full cache window out of the DB
800
801         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
802
803         # If there are no hits, just return the value
804
805         if (empty($notice)) {
806             return $notice;
807         }
808
809         # Pack results into an array
810
811         $notices = array();
812
813         while ($notice->fetch()) {
814             $notices[] = clone($notice);
815         }
816
817         $notice->free();
818
819         # Store the array in the cache for next time
820
821         $result = $cache->set(common_cache_key($cachekey), $notices);
822         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
823
824         # return a wrapper of the array for use now
825
826         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
827
828         return $wrapper;
829     }
830
831     function getStreamByIds($ids)
832     {
833         $cache = common_memcache();
834
835         if (!empty($cache)) {
836             $notices = array();
837             foreach ($ids as $id) {
838                 $n = Notice::staticGet('id', $id);
839                 if (!empty($n)) {
840                     $notices[] = $n;
841                 }
842             }
843             return new ArrayWrapper($notices);
844         } else {
845             $notice = new Notice();
846             if (empty($ids)) {
847                 //if no IDs requested, just return the notice object
848                 return $notice;
849             }
850             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
851
852             $notice->find();
853
854             $temp = array();
855
856             while ($notice->fetch()) {
857                 $temp[$notice->id] = clone($notice);
858             }
859
860             $wrapped = array();
861
862             foreach ($ids as $id) {
863                 if (array_key_exists($id, $temp)) {
864                     $wrapped[] = $temp[$id];
865                 }
866             }
867
868             return new ArrayWrapper($wrapped);
869         }
870     }
871
872     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
873     {
874         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
875                               array(),
876                               'public',
877                               $offset, $limit, $since_id, $max_id, $since);
878
879         return Notice::getStreamByIds($ids);
880     }
881
882     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
883     {
884         $notice = new Notice();
885
886         $notice->selectAdd(); // clears it
887         $notice->selectAdd('id');
888
889         $notice->orderBy('id DESC');
890
891         if (!is_null($offset)) {
892             $notice->limit($offset, $limit);
893         }
894
895         if (common_config('public', 'localonly')) {
896             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
897         } else {
898             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
899             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
900             $notice->whereAdd('is_local !='. Notice::GATEWAY);
901         }
902
903         if ($since_id != 0) {
904             $notice->whereAdd('id > ' . $since_id);
905         }
906
907         if ($max_id != 0) {
908             $notice->whereAdd('id <= ' . $max_id);
909         }
910
911         if (!is_null($since)) {
912             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
913         }
914
915         $ids = array();
916
917         if ($notice->find()) {
918             while ($notice->fetch()) {
919                 $ids[] = $notice->id;
920             }
921         }
922
923         $notice->free();
924         $notice = NULL;
925
926         return $ids;
927     }
928
929     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
930     {
931         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
932                               array($id),
933                               'notice:conversation_ids:'.$id,
934                               $offset, $limit, $since_id, $max_id, $since);
935
936         return Notice::getStreamByIds($ids);
937     }
938
939     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
940     {
941         $notice = new Notice();
942
943         $notice->selectAdd(); // clears it
944         $notice->selectAdd('id');
945
946         $notice->conversation = $id;
947
948         $notice->orderBy('id DESC');
949
950         if (!is_null($offset)) {
951             $notice->limit($offset, $limit);
952         }
953
954         if ($since_id != 0) {
955             $notice->whereAdd('id > ' . $since_id);
956         }
957
958         if ($max_id != 0) {
959             $notice->whereAdd('id <= ' . $max_id);
960         }
961
962         if (!is_null($since)) {
963             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
964         }
965
966         $ids = array();
967
968         if ($notice->find()) {
969             while ($notice->fetch()) {
970                 $ids[] = $notice->id;
971             }
972         }
973
974         $notice->free();
975         $notice = NULL;
976
977         return $ids;
978     }
979
980     function addToInboxes()
981     {
982         // XXX: loads constants
983
984         $inbox = new Notice_inbox();
985
986         $users = $this->getSubscribedUsers();
987
988         // FIXME: kind of ignoring 'transitional'...
989         // we'll probably stop supporting inboxless mode
990         // in 0.9.x
991
992         $ni = array();
993
994         foreach ($users as $id) {
995             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
996         }
997
998         $groups = $this->saveGroups();
999         $profile = $this->getProfile();
1000
1001         foreach ($groups as $group) {
1002             $users = $group->getUserMembers();
1003             foreach ($users as $id) {
1004                 if (!array_key_exists($id, $ni)) {
1005                     $user = User::staticGet('id', $id);
1006                     if (!$user->hasBlocked($profile)) {
1007                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1008                     }
1009                 }
1010             }
1011         }
1012
1013         $recipients = $this->saveReplies();
1014
1015         foreach ($recipients as $recipient) {
1016
1017             if (!array_key_exists($recipient, $ni)) {
1018                 $recipientUser = User::staticGet('id', $recipient);
1019                 if (!empty($recipientUser)) {
1020                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1021                 }
1022             }
1023         }
1024
1025         Notice_inbox::bulkInsert($this->id, $this->created, $ni);
1026
1027         return;
1028     }
1029
1030     function getSubscribedUsers()
1031     {
1032         $user = new User();
1033
1034         if(common_config('db','quote_identifiers'))
1035           $user_table = '"user"';
1036         else $user_table = 'user';
1037
1038         $qry =
1039           'SELECT id ' .
1040           'FROM '. $user_table .' JOIN subscription '.
1041           'ON '. $user_table .'.id = subscription.subscriber ' .
1042           'WHERE subscription.subscribed = %d ';
1043
1044         $user->query(sprintf($qry, $this->profile_id));
1045
1046         $ids = array();
1047
1048         while ($user->fetch()) {
1049             $ids[] = $user->id;
1050         }
1051
1052         $user->free();
1053
1054         return $ids;
1055     }
1056
1057     function saveGroups()
1058     {
1059         $groups = array();
1060
1061         /* extract all !group */
1062         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
1063                                 strtolower($this->content),
1064                                 $match);
1065         if (!$count) {
1066             return $groups;
1067         }
1068
1069         $profile = $this->getProfile();
1070
1071         /* Add them to the database */
1072
1073         foreach (array_unique($match[1]) as $nickname) {
1074             /* XXX: remote groups. */
1075             $group = User_group::getForNickname($nickname);
1076
1077             if (empty($group)) {
1078                 continue;
1079             }
1080
1081             // we automatically add a tag for every group name, too
1082
1083             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
1084                                              'notice_id' => $this->id));
1085
1086             if (is_null($tag)) {
1087                 $this->saveTag($nickname);
1088             }
1089
1090             if ($profile->isMember($group)) {
1091
1092                 $result = $this->addToGroupInbox($group);
1093
1094                 if (!$result) {
1095                     common_log_db_error($gi, 'INSERT', __FILE__);
1096                 }
1097
1098                 $groups[] = clone($group);
1099             }
1100         }
1101
1102         return $groups;
1103     }
1104
1105     function addToGroupInbox($group)
1106     {
1107         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1108                                          'notice_id' => $this->id));
1109
1110         if (empty($gi)) {
1111
1112             $gi = new Group_inbox();
1113
1114             $gi->group_id  = $group->id;
1115             $gi->notice_id = $this->id;
1116             $gi->created   = $this->created;
1117
1118             return $gi->insert();
1119         }
1120
1121         return true;
1122     }
1123
1124     function saveReplies()
1125     {
1126         // Alternative reply format
1127         $tname = false;
1128         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1129             $tname = $match[1];
1130         }
1131         // extract all @messages
1132         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1133
1134         $names = array();
1135
1136         if ($cnt || $tname) {
1137             // XXX: is there another way to make an array copy?
1138             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1139         }
1140
1141         $sender = Profile::staticGet($this->profile_id);
1142
1143         $replied = array();
1144
1145         // store replied only for first @ (what user/notice what the reply directed,
1146         // we assume first @ is it)
1147
1148         for ($i=0; $i<count($names); $i++) {
1149             $nickname = $names[$i];
1150             $recipient = common_relative_profile($sender, $nickname, $this->created);
1151             if (empty($recipient)) {
1152                 continue;
1153             }
1154             // Don't save replies from blocked profile to local user
1155             $recipient_user = User::staticGet('id', $recipient->id);
1156             if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
1157                 continue;
1158             }
1159             $reply = new Reply();
1160             $reply->notice_id = $this->id;
1161             $reply->profile_id = $recipient->id;
1162             $id = $reply->insert();
1163             if (!$id) {
1164                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1165                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1166                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1167                 return array();
1168             } else {
1169                 $replied[$recipient->id] = 1;
1170             }
1171         }
1172
1173         // Hash format replies, too
1174         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1175         if ($cnt) {
1176             foreach ($match[1] as $tag) {
1177                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1178                 foreach ($tagged as $t) {
1179                     if (!$replied[$t->id]) {
1180                         // Don't save replies from blocked profile to local user
1181                         $t_user = User::staticGet('id', $t->id);
1182                         if ($t_user && $t_user->hasBlocked($sender)) {
1183                             continue;
1184                         }
1185                         $reply = new Reply();
1186                         $reply->notice_id = $this->id;
1187                         $reply->profile_id = $t->id;
1188                         $id = $reply->insert();
1189                         if (!$id) {
1190                             common_log_db_error($reply, 'INSERT', __FILE__);
1191                             return array();
1192                         } else {
1193                             $replied[$recipient->id] = 1;
1194                         }
1195                     }
1196                 }
1197             }
1198         }
1199
1200         $recipientIds = array_keys($replied);
1201
1202         foreach ($recipientIds as $recipient) {
1203             $user = User::staticGet('id', $recipient);
1204             if ($user) {
1205                 mail_notify_attn($user, $this);
1206             }
1207         }
1208
1209         return $recipientIds;
1210     }
1211
1212     function asAtomEntry($namespace=false, $source=false)
1213     {
1214         $profile = $this->getProfile();
1215
1216         $xs = new XMLStringer(true);
1217
1218         if ($namespace) {
1219             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1220                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1221         } else {
1222             $attrs = array();
1223         }
1224
1225         $xs->elementStart('entry', $attrs);
1226
1227         if ($source) {
1228             $xs->elementStart('source');
1229             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1230             $xs->element('link', array('href' => $profile->profileurl));
1231             $user = User::staticGet('id', $profile->id);
1232             if (!empty($user)) {
1233                 $atom_feed = common_local_url('ApiTimelineUser',
1234                                               array('format' => 'atom',
1235                                                     'id' => $profile->nickname));
1236                 $xs->element('link', array('rel' => 'self',
1237                                            'type' => 'application/atom+xml',
1238                                            'href' => $profile->profileurl));
1239                 $xs->element('link', array('rel' => 'license',
1240                                            'href' => common_config('license', 'url')));
1241             }
1242
1243             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1244         }
1245
1246         $xs->elementStart('author');
1247         $xs->element('name', null, $profile->nickname);
1248         $xs->element('uri', null, $profile->profileurl);
1249         $xs->elementEnd('author');
1250
1251         if ($source) {
1252             $xs->elementEnd('source');
1253         }
1254
1255         $xs->element('title', null, $this->content);
1256         $xs->element('summary', null, $this->content);
1257
1258         $xs->element('link', array('rel' => 'alternate',
1259                                    'href' => $this->bestUrl()));
1260
1261         $xs->element('id', null, $this->uri);
1262
1263         $xs->element('published', null, common_date_w3dtf($this->created));
1264         $xs->element('updated', null, common_date_w3dtf($this->modified));
1265
1266         if ($this->reply_to) {
1267             $reply_notice = Notice::staticGet('id', $this->reply_to);
1268             if (!empty($reply_notice)) {
1269                 $xs->element('link', array('rel' => 'related',
1270                                            'href' => $reply_notice->bestUrl()));
1271                 $xs->element('thr:in-reply-to',
1272                              array('ref' => $reply_notice->uri,
1273                                    'href' => $reply_notice->bestUrl()));
1274             }
1275         }
1276
1277         $xs->element('content', array('type' => 'html'), $this->rendered);
1278
1279         $tag = new Notice_tag();
1280         $tag->notice_id = $this->id;
1281         if ($tag->find()) {
1282             while ($tag->fetch()) {
1283                 $xs->element('category', array('term' => $tag->tag));
1284             }
1285         }
1286         $tag->free();
1287
1288         # Enclosures
1289         $attachments = $this->attachments();
1290         if($attachments){
1291             foreach($attachments as $attachment){
1292                 $enclosure=$attachment->getEnclosure();
1293                 if ($enclosure) {
1294                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1295                     if($enclosure->title){
1296                         $attributes['title']=$enclosure->title;
1297                     }
1298                     $xs->element('link', $attributes, null);
1299                 }
1300             }
1301         }
1302
1303         if (!empty($this->lat) && !empty($this->lon)) {
1304             $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1305             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1306             $xs->elementEnd('geo');
1307         }
1308
1309         $xs->elementEnd('entry');
1310
1311         return $xs->getString();
1312     }
1313
1314     function bestUrl()
1315     {
1316         if (!empty($this->url)) {
1317             return $this->url;
1318         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1319             return $this->uri;
1320         } else {
1321             return common_local_url('shownotice',
1322                                     array('notice' => $this->id));
1323         }
1324     }
1325
1326     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1327     {
1328         $cache = common_memcache();
1329
1330         if (empty($cache) ||
1331             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1332             is_null($limit) ||
1333             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1334             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1335                                                                       $max_id, $since)));
1336         }
1337
1338         $idkey = common_cache_key($cachekey);
1339
1340         $idstr = $cache->get($idkey);
1341
1342         if (!empty($idstr)) {
1343             // Cache hit! Woohoo!
1344             $window = explode(',', $idstr);
1345             $ids = array_slice($window, $offset, $limit);
1346             return $ids;
1347         }
1348
1349         $laststr = $cache->get($idkey.';last');
1350
1351         if (!empty($laststr)) {
1352             $window = explode(',', $laststr);
1353             $last_id = $window[0];
1354             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1355                                                                           $last_id, 0, null)));
1356
1357             $new_window = array_merge($new_ids, $window);
1358
1359             $new_windowstr = implode(',', $new_window);
1360
1361             $result = $cache->set($idkey, $new_windowstr);
1362             $result = $cache->set($idkey . ';last', $new_windowstr);
1363
1364             $ids = array_slice($new_window, $offset, $limit);
1365
1366             return $ids;
1367         }
1368
1369         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1370                                                                      0, 0, null)));
1371
1372         $windowstr = implode(',', $window);
1373
1374         $result = $cache->set($idkey, $windowstr);
1375         $result = $cache->set($idkey . ';last', $windowstr);
1376
1377         $ids = array_slice($window, $offset, $limit);
1378
1379         return $ids;
1380     }
1381
1382     /**
1383      * Determine which notice, if any, a new notice is in reply to.
1384      *
1385      * For conversation tracking, we try to see where this notice fits
1386      * in the tree. Rough algorithm is:
1387      *
1388      * if (reply_to is set and valid) {
1389      *     return reply_to;
1390      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1391      *     return ID of last notice by initial @name in content;
1392      * }
1393      *
1394      * Note that all @nickname instances will still be used to save "reply" records,
1395      * so the notice shows up in the mentioned users' "replies" tab.
1396      *
1397      * @param integer $reply_to   ID passed in by Web or API
1398      * @param integer $profile_id ID of author
1399      * @param string  $source     Source tag, like 'web' or 'gwibber'
1400      * @param string  $content    Final notice content
1401      *
1402      * @return integer ID of replied-to notice, or null for not a reply.
1403      */
1404
1405     static function getReplyTo($reply_to, $profile_id, $source, $content)
1406     {
1407         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1408
1409         // If $reply_to is specified, we check that it exists, and then
1410         // return it if it does
1411
1412         if (!empty($reply_to)) {
1413             $reply_notice = Notice::staticGet('id', $reply_to);
1414             if (!empty($reply_notice)) {
1415                 return $reply_to;
1416             }
1417         }
1418
1419         // If it's not a "low bandwidth" source (one where you can't set
1420         // a reply_to argument), we return. This is mostly web and API
1421         // clients.
1422
1423         if (!in_array($source, $lb)) {
1424             return null;
1425         }
1426
1427         // Is there an initial @ or T?
1428
1429         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1430             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1431             $nickname = common_canonical_nickname($match[1]);
1432         } else {
1433             return null;
1434         }
1435
1436         // Figure out who that is.
1437
1438         $sender = Profile::staticGet('id', $profile_id);
1439         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1440
1441         if (empty($recipient)) {
1442             return null;
1443         }
1444
1445         // Get their last notice
1446
1447         $last = $recipient->getCurrentNotice();
1448
1449         if (!empty($last)) {
1450             return $last->id;
1451         }
1452     }
1453
1454     static function maxContent()
1455     {
1456         $contentlimit = common_config('notice', 'contentlimit');
1457         // null => use global limit (distinct from 0!)
1458         if (is_null($contentlimit)) {
1459             $contentlimit = common_config('site', 'textlimit');
1460         }
1461         return $contentlimit;
1462     }
1463
1464     static function contentTooLong($content)
1465     {
1466         $contentlimit = self::maxContent();
1467         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1468     }
1469
1470     function getLocation()
1471     {
1472         $location = null;
1473
1474         if (!empty($this->location_id) && !empty($this->location_ns)) {
1475             $location = Location::fromId($this->location_id, $this->location_ns);
1476         }
1477
1478         if (is_null($location)) { // no ID, or Location::fromId() failed
1479             if (!empty($this->lat) && !empty($this->lon)) {
1480                 $location = Location::fromLatLon($this->lat, $this->lon);
1481             }
1482         }
1483
1484         return $location;
1485     }
1486
1487     function repeat($repeater_id, $source)
1488     {
1489         $author = Profile::staticGet('id', $this->profile_id);
1490
1491         // FIXME: truncate on long repeats...?
1492
1493         $content = sprintf(_('RT @%1$s %2$s'),
1494                            $author->nickname,
1495                            $this->content);
1496
1497         return self::saveNew($repeater_id, $content, $source,
1498                              array('repeat_of' => $this->id));
1499     }
1500
1501     // These are supposed to be in chron order!
1502
1503     function repeatStream($limit=100)
1504     {
1505         $cache = common_memcache();
1506
1507         if (empty($cache)) {
1508             $ids = $this->_repeatStreamDirect($limit);
1509         } else {
1510             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1511             if (!empty($idstr)) {
1512                 $ids = explode(',', $idstr);
1513             } else {
1514                 $ids = $this->_repeatStreamDirect(100);
1515                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1516             }
1517             if ($limit < 100) {
1518                 // We do a max of 100, so slice down to limit
1519                 $ids = array_slice($ids, 0, $limit);
1520             }
1521         }
1522
1523         return Notice::getStreamByIds($ids);
1524     }
1525
1526     function _repeatStreamDirect($limit)
1527     {
1528         $notice = new Notice();
1529
1530         $notice->selectAdd(); // clears it
1531         $notice->selectAdd('id');
1532
1533         $notice->repeat_of = $this->id;
1534
1535         $notice->orderBy('created'); // NB: asc!
1536
1537         if (!is_null($offset)) {
1538             $notice->limit($offset, $limit);
1539         }
1540
1541         $ids = array();
1542
1543         if ($notice->find()) {
1544             while ($notice->fetch()) {
1545                 $ids[] = $notice->id;
1546             }
1547         }
1548
1549         $notice->free();
1550         $notice = NULL;
1551
1552         return $ids;
1553     }
1554 }