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