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