]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch 'testing' of gitorious.org:statusnet/mainline into 0.9.x
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  *
19  * @category Notices
20  * @package  StatusNet
21  * @author   Brenda Wallace <shiny@cpan.org>
22  * @author   Christopher Vollick <psycotica0@gmail.com>
23  * @author   CiaranG <ciaran@ciarang.com>
24  * @author   Craig Andrews <candrews@integralblue.com>
25  * @author   Evan Prodromou <evan@controlezvous.ca>
26  * @author   Gina Haeussge <osd@foosel.net>
27  * @author   Jeffery To <jeffery.to@gmail.com>
28  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
29  * @author   Robin Millette <millette@controlyourself.ca>
30  * @author   Sarven Capadisli <csarven@controlyourself.ca>
31  * @author   Tom Adams <tom@holizz.com>
32  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
33  */
34
35 if (!defined('STATUSNET') && !defined('LACONICA')) {
36     exit(1);
37 }
38
39 /**
40  * Table Definition for notice
41  */
42 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
43
44 /* We keep the first three 20-notice pages, plus one for pagination check,
45  * in the memcached cache. */
46
47 define('NOTICE_CACHE_WINDOW', 61);
48
49 define('MAX_BOXCARS', 128);
50
51 class Notice extends Memcached_DataObject
52 {
53     ###START_AUTOCODE
54     /* the code below is auto generated do not remove the above tag */
55
56     public $__table = 'notice';                          // table name
57     public $id;                              // int(4)  primary_key not_null
58     public $profile_id;                      // int(4)  multiple_key not_null
59     public $uri;                             // varchar(255)  unique_key
60     public $content;                         // text
61     public $rendered;                        // text
62     public $url;                             // varchar(255)
63     public $created;                         // datetime  multiple_key not_null default_0000-00-00%2000%3A00%3A00
64     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
65     public $reply_to;                        // int(4)
66     public $is_local;                        // 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         // For auditing purposes, save a record that the notice
98         // was deleted.
99
100         // @fixme we have some cases where things get re-run and so the
101         // insert fails.
102         $deleted = Deleted_notice::staticGet('id', $this->id);
103         if (!$deleted) {
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             $deleted->insert();
113         }
114
115         // Clear related records
116
117         $this->clearReplies();
118         $this->clearRepeats();
119         $this->clearFaves();
120         $this->clearTags();
121         $this->clearGroupInboxes();
122
123         // NOTE: we don't clear inboxes
124         // NOTE: we don't clear queue items
125
126         $result = parent::delete();
127
128         $this->blowOnDelete();
129         return $result;
130     }
131
132     /**
133      * Extract #hashtags from this notice's content and save them to the database.
134      */
135     function saveTags()
136     {
137         /* extract all #hastags */
138         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
139         if (!$count) {
140             return true;
141         }
142
143         /* Add them to the database */
144         return $this->saveKnownTags($match[1]);
145     }
146
147     /**
148      * Record the given set of hash tags in the db for this notice.
149      * Given tag strings will be normalized and checked for dupes.
150      */
151     function saveKnownTags($hashtags)
152     {
153         //turn each into their canonical tag
154         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
155         for($i=0; $i<count($hashtags); $i++) {
156             /* elide characters we don't want in the tag */
157             $hashtags[$i] = common_canonical_tag($hashtags[$i]);
158         }
159
160         foreach(array_unique($hashtags) as $hashtag) {
161             $this->saveTag($hashtag);
162             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
163         }
164         return true;
165     }
166
167     /**
168      * Record a single hash tag as associated with this notice.
169      * Tag format and uniqueness must be validated by caller.
170      */
171     function saveTag($hashtag)
172     {
173         $tag = new Notice_tag();
174         $tag->notice_id = $this->id;
175         $tag->tag = $hashtag;
176         $tag->created = $this->created;
177         $id = $tag->insert();
178
179         if (!$id) {
180             // TRANS: Server exception. %s are the error details.
181             throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
182                                               $last_error->message));
183             return;
184         }
185
186         // if it's saved, blow its cache
187         $tag->blowCache(false);
188     }
189
190     /**
191      * Save a new notice and push it out to subscribers' inboxes.
192      * Poster's permissions are checked before sending.
193      *
194      * @param int $profile_id Profile ID of the poster
195      * @param string $content source message text; links may be shortened
196      *                        per current user's preference
197      * @param string $source source key ('web', 'api', etc)
198      * @param array $options Associative array of optional properties:
199      *              string 'created' timestamp of notice; defaults to now
200      *              int 'is_local' source/gateway ID, one of:
201      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
202      *                  Notice::REMOTE_OMB      - Sent from a remote OMB service;
203      *                                            hide from public timeline but show in
204      *                                            local "and friends" timelines
205      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
206      *                  Notice::GATEWAY         - From another non-OMB service;
207      *                                            will not appear in public views
208      *              float 'lat' decimal latitude for geolocation
209      *              float 'lon' decimal longitude for geolocation
210      *              int 'location_id' geoname identifier
211      *              int 'location_ns' geoname namespace to interpret location_id
212      *              int 'reply_to'; notice ID this is a reply to
213      *              int 'repeat_of'; notice ID this is a repeat of
214      *              string 'uri' unique ID for notice; defaults to local notice URL
215      *              string 'url' permalink to notice; defaults to local notice URL
216      *              string 'rendered' rendered HTML version of content
217      *              array 'replies' list of profile URIs for reply delivery in
218      *                              place of extracting @-replies from content.
219      *              array 'groups' list of group IDs to deliver to, in place of
220      *                              extracting ! tags from content
221      *              array 'tags' list of hashtag strings to save with the notice
222      *                           in place of extracting # tags from content
223      *              array 'urls' list of attached/referred URLs to save with the
224      *                           notice in place of extracting links from content
225      * @fixme tag override
226      *
227      * @return Notice
228      * @throws ClientException
229      */
230     static function saveNew($profile_id, $content, $source, $options=null) {
231         $defaults = array('uri' => null,
232                           'url' => null,
233                           'reply_to' => null,
234                           'repeat_of' => null);
235
236         if (!empty($options)) {
237             $options = $options + $defaults;
238             extract($options);
239         }
240
241         if (!isset($is_local)) {
242             $is_local = Notice::LOCAL_PUBLIC;
243         }
244
245         $profile = Profile::staticGet($profile_id);
246
247         $final = common_shorten_links($content);
248
249         if (Notice::contentTooLong($final)) {
250             throw new ClientException(_('Problem saving notice. Too long.'));
251         }
252
253         if (empty($profile)) {
254             throw new ClientException(_('Problem saving notice. Unknown user.'));
255         }
256
257         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
258             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
259             throw new ClientException(_('Too many notices too fast; take a breather '.
260                                         'and post again in a few minutes.'));
261         }
262
263         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
264             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
265             throw new ClientException(_('Too many duplicate messages too quickly;'.
266                                         ' take a breather and post again in a few minutes.'));
267         }
268
269         if (!$profile->hasRight(Right::NEWNOTICE)) {
270             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
271             throw new ClientException(_('You are banned from posting notices on this site.'));
272         }
273
274         $notice = new Notice();
275         $notice->profile_id = $profile_id;
276
277         $autosource = common_config('public', 'autosource');
278
279         # Sandboxed are non-false, but not 1, either
280
281         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
282             ($source && $autosource && in_array($source, $autosource))) {
283             $notice->is_local = Notice::LOCAL_NONPUBLIC;
284         } else {
285             $notice->is_local = $is_local;
286         }
287
288         if (!empty($created)) {
289             $notice->created = $created;
290         } else {
291             $notice->created = common_sql_now();
292         }
293
294         $notice->content = $final;
295
296         $notice->source = $source;
297         $notice->uri = $uri;
298         $notice->url = $url;
299
300         // Handle repeat case
301
302         if (isset($repeat_of)) {
303             $notice->repeat_of = $repeat_of;
304         } else {
305             $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
306         }
307
308         if (!empty($notice->reply_to)) {
309             $reply = Notice::staticGet('id', $notice->reply_to);
310             $notice->conversation = $reply->conversation;
311         }
312
313         if (!empty($lat) && !empty($lon)) {
314             $notice->lat = $lat;
315             $notice->lon = $lon;
316         }
317
318         if (!empty($location_ns) && !empty($location_id)) {
319             $notice->location_id = $location_id;
320             $notice->location_ns = $location_ns;
321         }
322
323         if (!empty($rendered)) {
324             $notice->rendered = $rendered;
325         } else {
326             $notice->rendered = common_render_content($final, $notice);
327         }
328
329         if (Event::handle('StartNoticeSave', array(&$notice))) {
330
331             // XXX: some of these functions write to the DB
332
333             $id = $notice->insert();
334
335             if (!$id) {
336                 common_log_db_error($notice, 'INSERT', __FILE__);
337                 throw new ServerException(_('Problem saving notice.'));
338             }
339
340             // Update ID-dependent columns: URI, conversation
341
342             $orig = clone($notice);
343
344             $changed = false;
345
346             if (empty($uri)) {
347                 $notice->uri = common_notice_uri($notice);
348                 $changed = true;
349             }
350
351             // If it's not part of a conversation, it's
352             // the beginning of a new conversation.
353
354             if (empty($notice->conversation)) {
355                 $conv = Conversation::create();
356                 $notice->conversation = $conv->id;
357                 $changed = true;
358             }
359
360             if ($changed) {
361                 if (!$notice->update($orig)) {
362                     common_log_db_error($notice, 'UPDATE', __FILE__);
363                     throw new ServerException(_('Problem saving notice.'));
364                 }
365             }
366
367         }
368
369         # Clear the cache for subscribed users, so they'll update at next request
370         # XXX: someone clever could prepend instead of clearing the cache
371
372         $notice->blowOnInsert();
373
374         // Save per-notice metadata...
375
376         if (isset($replies)) {
377             $notice->saveKnownReplies($replies);
378         } else {
379             $notice->saveReplies();
380         }
381
382         if (isset($tags)) {
383             $notice->saveKnownTags($tags);
384         } else {
385             $notice->saveTags();
386         }
387
388         // Note: groups may save tags, so must be run after tags are saved
389         // to avoid errors on duplicates.
390         if (isset($groups)) {
391             $notice->saveKnownGroups($groups);
392         } else {
393             $notice->saveGroups();
394         }
395
396         if (isset($urls)) {
397             $notice->saveKnownUrls($urls);
398         } else {
399             $notice->saveUrls();
400         }
401
402         // Prepare inbox delivery, may be queued to background.
403         $notice->distribute();
404
405         return $notice;
406     }
407
408     function blowOnInsert($conversation = false)
409     {
410         self::blow('profile:notice_ids:%d', $this->profile_id);
411         self::blow('public');
412
413         // XXX: Before we were blowing the casche only if the notice id
414         // was not the root of the conversation.  What to do now?
415
416         self::blow('notice:conversation_ids:%d', $this->conversation);
417
418         if (!empty($this->repeat_of)) {
419             self::blow('notice:repeats:%d', $this->repeat_of);
420         }
421
422         $original = Notice::staticGet('id', $this->repeat_of);
423
424         if (!empty($original)) {
425             $originalUser = User::staticGet('id', $original->profile_id);
426             if (!empty($originalUser)) {
427                 self::blow('user:repeats_of_me:%d', $originalUser->id);
428             }
429         }
430
431         $profile = Profile::staticGet($this->profile_id);
432         if (!empty($profile)) {
433             $profile->blowNoticeCount();
434         }
435     }
436
437     /**
438      * Clear cache entries related to this notice at delete time.
439      * Necessary to avoid breaking paging on public, profile timelines.
440      */
441     function blowOnDelete()
442     {
443         $this->blowOnInsert();
444
445         self::blow('profile:notice_ids:%d;last', $this->profile_id);
446         self::blow('public;last');
447     }
448
449     /** save all urls in the notice to the db
450      *
451      * follow redirects and save all available file information
452      * (mimetype, date, size, oembed, etc.)
453      *
454      * @return void
455      */
456     function saveUrls() {
457         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
458     }
459
460     /**
461      * Save the given URLs as related links/attachments to the db
462      *
463      * follow redirects and save all available file information
464      * (mimetype, date, size, oembed, etc.)
465      *
466      * @return void
467      */
468     function saveKnownUrls($urls)
469     {
470         // @fixme validation?
471         foreach ($urls as $url) {
472             File::processNew($url, $this->id);
473         }
474     }
475
476     /**
477      * @private callback
478      */
479     function saveUrl($data) {
480         list($url, $notice_id) = $data;
481         File::processNew($url, $notice_id);
482     }
483
484     static function checkDupes($profile_id, $content) {
485         $profile = Profile::staticGet($profile_id);
486         if (empty($profile)) {
487             return false;
488         }
489         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
490         if (!empty($notice)) {
491             $last = 0;
492             while ($notice->fetch()) {
493                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
494                     return true;
495                 } else if ($notice->content == $content) {
496                     return false;
497                 }
498             }
499         }
500         # If we get here, oldest item in cache window is not
501         # old enough for dupe limit; do direct check against DB
502         $notice = new Notice();
503         $notice->profile_id = $profile_id;
504         $notice->content = $content;
505         if (common_config('db','type') == 'pgsql')
506           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
507         else
508           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
509
510         $cnt = $notice->count();
511         return ($cnt == 0);
512     }
513
514     static function checkEditThrottle($profile_id) {
515         $profile = Profile::staticGet($profile_id);
516         if (empty($profile)) {
517             return false;
518         }
519         # Get the Nth notice
520         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
521         if ($notice && $notice->fetch()) {
522             # If the Nth notice was posted less than timespan seconds ago
523             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
524                 # Then we throttle
525                 return false;
526             }
527         }
528         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
529         return true;
530     }
531
532     function getUploadedAttachment() {
533         $post = clone $this;
534         $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"';
535         $post->query($query);
536         $post->fetch();
537         if (empty($post->up) || empty($post->i)) {
538             $ret = false;
539         } else {
540             $ret = array($post->up, $post->i);
541         }
542         $post->free();
543         return $ret;
544     }
545
546     function hasAttachments() {
547         $post = clone $this;
548         $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);
549         $post->query($query);
550         $post->fetch();
551         $n_attachments = intval($post->n_attachments);
552         $post->free();
553         return $n_attachments;
554     }
555
556     function attachments() {
557         // XXX: cache this
558         $att = array();
559         $f2p = new File_to_post;
560         $f2p->post_id = $this->id;
561         if ($f2p->find()) {
562             while ($f2p->fetch()) {
563                 $f = File::staticGet($f2p->file_id);
564                 $att[] = clone($f);
565             }
566         }
567         return $att;
568     }
569
570     function getStreamByIds($ids)
571     {
572         $cache = common_memcache();
573
574         if (!empty($cache)) {
575             $notices = array();
576             foreach ($ids as $id) {
577                 $n = Notice::staticGet('id', $id);
578                 if (!empty($n)) {
579                     $notices[] = $n;
580                 }
581             }
582             return new ArrayWrapper($notices);
583         } else {
584             $notice = new Notice();
585             if (empty($ids)) {
586                 //if no IDs requested, just return the notice object
587                 return $notice;
588             }
589             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
590
591             $notice->find();
592
593             $temp = array();
594
595             while ($notice->fetch()) {
596                 $temp[$notice->id] = clone($notice);
597             }
598
599             $wrapped = array();
600
601             foreach ($ids as $id) {
602                 if (array_key_exists($id, $temp)) {
603                     $wrapped[] = $temp[$id];
604                 }
605             }
606
607             return new ArrayWrapper($wrapped);
608         }
609     }
610
611     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
612     {
613         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
614                               array(),
615                               'public',
616                               $offset, $limit, $since_id, $max_id);
617         return Notice::getStreamByIds($ids);
618     }
619
620     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
621     {
622         $notice = new Notice();
623
624         $notice->selectAdd(); // clears it
625         $notice->selectAdd('id');
626
627         $notice->orderBy('id DESC');
628
629         if (!is_null($offset)) {
630             $notice->limit($offset, $limit);
631         }
632
633         if (common_config('public', 'localonly')) {
634             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
635         } else {
636             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
637             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
638             $notice->whereAdd('is_local !='. Notice::GATEWAY);
639         }
640
641         if ($since_id != 0) {
642             $notice->whereAdd('id > ' . $since_id);
643         }
644
645         if ($max_id != 0) {
646             $notice->whereAdd('id <= ' . $max_id);
647         }
648
649         $ids = array();
650
651         if ($notice->find()) {
652             while ($notice->fetch()) {
653                 $ids[] = $notice->id;
654             }
655         }
656
657         $notice->free();
658         $notice = NULL;
659
660         return $ids;
661     }
662
663     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
664     {
665         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
666                               array($id),
667                               'notice:conversation_ids:'.$id,
668                               $offset, $limit, $since_id, $max_id);
669
670         return Notice::getStreamByIds($ids);
671     }
672
673     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
674     {
675         $notice = new Notice();
676
677         $notice->selectAdd(); // clears it
678         $notice->selectAdd('id');
679
680         $notice->conversation = $id;
681
682         $notice->orderBy('id DESC');
683
684         if (!is_null($offset)) {
685             $notice->limit($offset, $limit);
686         }
687
688         if ($since_id != 0) {
689             $notice->whereAdd('id > ' . $since_id);
690         }
691
692         if ($max_id != 0) {
693             $notice->whereAdd('id <= ' . $max_id);
694         }
695
696         $ids = array();
697
698         if ($notice->find()) {
699             while ($notice->fetch()) {
700                 $ids[] = $notice->id;
701             }
702         }
703
704         $notice->free();
705         $notice = NULL;
706
707         return $ids;
708     }
709
710     /**
711      * Is this notice part of an active conversation?
712      *
713      * @return boolean true if other messages exist in the same
714      *                 conversation, false if this is the only one
715      */
716     function hasConversation()
717     {
718         if (!empty($this->conversation)) {
719             $conversation = Notice::conversationStream(
720                 $this->conversation,
721                 1,
722                 1
723             );
724             if ($conversation->N > 0) {
725                 return true;
726             }
727         }
728         return false;
729     }
730
731     /**
732      * @param $groups array of Group *objects*
733      * @param $recipients array of profile *ids*
734      */
735     function whoGets($groups=null, $recipients=null)
736     {
737         $c = self::memcache();
738
739         if (!empty($c)) {
740             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
741             if ($ni !== false) {
742                 return $ni;
743             }
744         }
745
746         if (is_null($groups)) {
747             $groups = $this->getGroups();
748         }
749
750         if (is_null($recipients)) {
751             $recipients = $this->getReplies();
752         }
753
754         $users = $this->getSubscribedUsers();
755
756         // FIXME: kind of ignoring 'transitional'...
757         // we'll probably stop supporting inboxless mode
758         // in 0.9.x
759
760         $ni = array();
761
762         foreach ($users as $id) {
763             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
764         }
765
766         $profile = $this->getProfile();
767
768         foreach ($groups as $group) {
769             $users = $group->getUserMembers();
770             foreach ($users as $id) {
771                 if (!array_key_exists($id, $ni)) {
772                     $user = User::staticGet('id', $id);
773                     if (!$user->hasBlocked($profile)) {
774                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
775                     }
776                 }
777             }
778         }
779
780         foreach ($recipients as $recipient) {
781
782             if (!array_key_exists($recipient, $ni)) {
783                 $recipientUser = User::staticGet('id', $recipient);
784                 if (!empty($recipientUser)) {
785                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
786                 }
787             }
788         }
789
790         if (!empty($c)) {
791             // XXX: pack this data better
792             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
793         }
794
795         return $ni;
796     }
797
798     /**
799      * Adds this notice to the inboxes of each local user who should receive
800      * it, based on author subscriptions, group memberships, and @-replies.
801      *
802      * Warning: running a second time currently will make items appear
803      * multiple times in users' inboxes.
804      *
805      * @fixme make more robust against errors
806      * @fixme break up massive deliveries to smaller background tasks
807      *
808      * @param array $groups optional list of Group objects;
809      *              if left empty, will be loaded from group_inbox records
810      * @param array $recipient optional list of reply profile ids
811      *              if left empty, will be loaded from reply records
812      */
813     function addToInboxes($groups=null, $recipients=null)
814     {
815         $ni = $this->whoGets($groups, $recipients);
816
817         $ids = array_keys($ni);
818
819         // We remove the author (if they're a local user),
820         // since we'll have already done this in distribute()
821
822         $i = array_search($this->profile_id, $ids);
823
824         if ($i !== false) {
825             unset($ids[$i]);
826         }
827
828         // Bulk insert
829
830         Inbox::bulkInsert($this->id, $ids);
831
832         return;
833     }
834
835     function getSubscribedUsers()
836     {
837         $user = new User();
838
839         if(common_config('db','quote_identifiers'))
840           $user_table = '"user"';
841         else $user_table = 'user';
842
843         $qry =
844           'SELECT id ' .
845           'FROM '. $user_table .' JOIN subscription '.
846           'ON '. $user_table .'.id = subscription.subscriber ' .
847           'WHERE subscription.subscribed = %d ';
848
849         $user->query(sprintf($qry, $this->profile_id));
850
851         $ids = array();
852
853         while ($user->fetch()) {
854             $ids[] = $user->id;
855         }
856
857         $user->free();
858
859         return $ids;
860     }
861
862     /**
863      * Record this notice to the given group inboxes for delivery.
864      * Overrides the regular parsing of !group markup.
865      *
866      * @param string $group_ids
867      * @fixme might prefer URIs as identifiers, as for replies?
868      *        best with generalizations on user_group to support
869      *        remote groups better.
870      */
871     function saveKnownGroups($group_ids)
872     {
873         if (!is_array($group_ids)) {
874             throw new ServerException("Bad type provided to saveKnownGroups");
875         }
876
877         $groups = array();
878         foreach ($group_ids as $id) {
879             $group = User_group::staticGet('id', $id);
880             if ($group) {
881                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
882                 $result = $this->addToGroupInbox($group);
883                 if (!$result) {
884                     common_log_db_error($gi, 'INSERT', __FILE__);
885                 }
886
887                 // @fixme should we save the tags here or not?
888                 $groups[] = clone($group);
889             } else {
890                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
891             }
892         }
893
894         return $groups;
895     }
896
897     /**
898      * Parse !group delivery and record targets into group_inbox.
899      * @return array of Group objects
900      */
901     function saveGroups()
902     {
903         // Don't save groups for repeats
904
905         if (!empty($this->repeat_of)) {
906             return array();
907         }
908
909         $groups = array();
910
911         /* extract all !group */
912         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
913                                 strtolower($this->content),
914                                 $match);
915         if (!$count) {
916             return $groups;
917         }
918
919         $profile = $this->getProfile();
920
921         /* Add them to the database */
922
923         foreach (array_unique($match[1]) as $nickname) {
924             /* XXX: remote groups. */
925             $group = User_group::getForNickname($nickname, $profile);
926
927             if (empty($group)) {
928                 continue;
929             }
930
931             // we automatically add a tag for every group name, too
932
933             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
934                                              'notice_id' => $this->id));
935
936             if (is_null($tag)) {
937                 $this->saveTag($nickname);
938             }
939
940             if ($profile->isMember($group)) {
941
942                 $result = $this->addToGroupInbox($group);
943
944                 if (!$result) {
945                     common_log_db_error($gi, 'INSERT', __FILE__);
946                 }
947
948                 $groups[] = clone($group);
949             }
950         }
951
952         return $groups;
953     }
954
955     function addToGroupInbox($group)
956     {
957         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
958                                          'notice_id' => $this->id));
959
960         if (empty($gi)) {
961
962             $gi = new Group_inbox();
963
964             $gi->group_id  = $group->id;
965             $gi->notice_id = $this->id;
966             $gi->created   = $this->created;
967
968             $result = $gi->insert();
969
970             if (!$result) {
971                 common_log_db_error($gi, 'INSERT', __FILE__);
972                 throw new ServerException(_('Problem saving group inbox.'));
973             }
974
975             self::blow('user_group:notice_ids:%d', $gi->group_id);
976         }
977
978         return true;
979     }
980
981     /**
982      * Save reply records indicating that this notice needs to be
983      * delivered to the local users with the given URIs.
984      *
985      * Since this is expected to be used when saving foreign-sourced
986      * messages, we won't deliver to any remote targets as that's the
987      * source service's responsibility.
988      *
989      * Mail notifications etc will be handled later.
990      *
991      * @param array of unique identifier URIs for recipients
992      */
993     function saveKnownReplies($uris)
994     {
995         if (empty($uris)) {
996             return;
997         }
998         $sender = Profile::staticGet($this->profile_id);
999
1000         foreach ($uris as $uri) {
1001
1002             $user = User::staticGet('uri', $uri);
1003
1004             if (!empty($user)) {
1005                 if ($user->hasBlocked($sender)) {
1006                     continue;
1007                 }
1008
1009                 $reply = new Reply();
1010
1011                 $reply->notice_id  = $this->id;
1012                 $reply->profile_id = $user->id;
1013
1014                 $id = $reply->insert();
1015             }
1016         }
1017
1018         return;
1019     }
1020
1021     /**
1022      * Pull @-replies from this message's content in StatusNet markup format
1023      * and save reply records indicating that this message needs to be
1024      * delivered to those users.
1025      *
1026      * Mail notifications to local profiles will be sent later.
1027      *
1028      * @return array of integer profile IDs
1029      */
1030
1031     function saveReplies()
1032     {
1033         // Don't save reply data for repeats
1034
1035         if (!empty($this->repeat_of)) {
1036             return array();
1037         }
1038
1039         $sender = Profile::staticGet($this->profile_id);
1040
1041         // @todo ideally this parser information would only
1042         // be calculated once.
1043
1044         $mentions = common_find_mentions($this->content, $this);
1045
1046         $replied = array();
1047
1048         // store replied only for first @ (what user/notice what the reply directed,
1049         // we assume first @ is it)
1050
1051         foreach ($mentions as $mention) {
1052
1053             foreach ($mention['mentioned'] as $mentioned) {
1054
1055                 // skip if they're already covered
1056
1057                 if (!empty($replied[$mentioned->id])) {
1058                     continue;
1059                 }
1060
1061                 // Don't save replies from blocked profile to local user
1062
1063                 $mentioned_user = User::staticGet('id', $mentioned->id);
1064                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1065                     continue;
1066                 }
1067
1068                 $reply = new Reply();
1069
1070                 $reply->notice_id  = $this->id;
1071                 $reply->profile_id = $mentioned->id;
1072
1073                 $id = $reply->insert();
1074
1075                 if (!$id) {
1076                     common_log_db_error($reply, 'INSERT', __FILE__);
1077                     throw new ServerException("Couldn't save reply for {$this->id}, {$mentioned->id}");
1078                 } else {
1079                     $replied[$mentioned->id] = 1;
1080                     self::blow('reply:stream:%d', $mentioned->id);
1081                 }
1082             }
1083         }
1084
1085         $recipientIds = array_keys($replied);
1086
1087         return $recipientIds;
1088     }
1089
1090     /**
1091      * Pull the complete list of @-reply targets for this notice.
1092      *
1093      * @return array of integer profile ids
1094      */
1095     function getReplies()
1096     {
1097         // XXX: cache me
1098
1099         $ids = array();
1100
1101         $reply = new Reply();
1102         $reply->selectAdd();
1103         $reply->selectAdd('profile_id');
1104         $reply->notice_id = $this->id;
1105
1106         if ($reply->find()) {
1107             while($reply->fetch()) {
1108                 $ids[] = $reply->profile_id;
1109             }
1110         }
1111
1112         $reply->free();
1113
1114         return $ids;
1115     }
1116
1117     /**
1118      * Send e-mail notifications to local @-reply targets.
1119      *
1120      * Replies must already have been saved; this is expected to be run
1121      * from the distrib queue handler.
1122      */
1123     function sendReplyNotifications()
1124     {
1125         // Don't send reply notifications for repeats
1126
1127         if (!empty($this->repeat_of)) {
1128             return array();
1129         }
1130
1131         $recipientIds = $this->getReplies();
1132
1133         foreach ($recipientIds as $recipientId) {
1134             $user = User::staticGet('id', $recipientId);
1135             if (!empty($user)) {
1136                 mail_notify_attn($user, $this);
1137             }
1138         }
1139     }
1140
1141     /**
1142      * Pull list of groups this notice needs to be delivered to,
1143      * as previously recorded by saveGroups() or saveKnownGroups().
1144      *
1145      * @return array of Group objects
1146      */
1147     function getGroups()
1148     {
1149         // Don't save groups for repeats
1150
1151         if (!empty($this->repeat_of)) {
1152             return array();
1153         }
1154
1155         // XXX: cache me
1156
1157         $groups = array();
1158
1159         $gi = new Group_inbox();
1160
1161         $gi->selectAdd();
1162         $gi->selectAdd('group_id');
1163
1164         $gi->notice_id = $this->id;
1165
1166         if ($gi->find()) {
1167             while ($gi->fetch()) {
1168                 $group = User_group::staticGet('id', $gi->group_id);
1169                 if ($group) {
1170                     $groups[] = $group;
1171                 }
1172             }
1173         }
1174
1175         $gi->free();
1176
1177         return $groups;
1178     }
1179
1180     function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
1181     {
1182         $profile = $this->getProfile();
1183
1184         $xs = new XMLStringer(true);
1185
1186         if ($namespace) {
1187             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1188                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1189                            'xmlns:georss' => 'http://www.georss.org/georss',
1190                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1191                            'xmlns:media' => 'http://purl.org/syndication/atommedia',
1192                            'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1193                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1194                            'xmlns:statusnet' => 'http://status.net/ont/');
1195         } else {
1196             $attrs = array();
1197         }
1198
1199         $xs->elementStart('entry', $attrs);
1200
1201         if ($source) {
1202             $xs->elementStart('source');
1203             $xs->element('id', null, $profile->profileurl);
1204             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1205             $xs->element('link', array('href' => $profile->profileurl));
1206             $user = User::staticGet('id', $profile->id);
1207             if (!empty($user)) {
1208                 $atom_feed = common_local_url('ApiTimelineUser',
1209                                               array('format' => 'atom',
1210                                                     'id' => $profile->nickname));
1211                 $xs->element('link', array('rel' => 'self',
1212                                            'type' => 'application/atom+xml',
1213                                            'href' => $profile->profileurl));
1214                 $xs->element('link', array('rel' => 'license',
1215                                            'href' => common_config('license', 'url')));
1216             }
1217
1218             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1219             $xs->element('updated', null, common_date_w3dtf($this->created));
1220         }
1221
1222         if ($source) {
1223             $xs->elementEnd('source');
1224         }
1225
1226         $xs->element('title', null, common_xml_safe_str($this->content));
1227
1228         if ($author) {
1229             $xs->raw($profile->asAtomAuthor());
1230             $xs->raw($profile->asActivityActor());
1231         }
1232
1233         $xs->element('link', array('rel' => 'alternate',
1234                                    'type' => 'text/html',
1235                                    'href' => $this->bestUrl()));
1236
1237         $xs->element('id', null, $this->uri);
1238
1239         $xs->element('published', null, common_date_w3dtf($this->created));
1240         $xs->element('updated', null, common_date_w3dtf($this->created));
1241
1242         $noticeInfoAttr = array(
1243             'local_id'   => $this->id,    // local notice ID (useful to clients for ordering)
1244             'source'     => $this->source, // the client name (source attribution)
1245         );
1246
1247         $ns = $this->getSource();
1248         if ($ns) {
1249             if (!empty($ns->url)) {
1250                 $noticeInfoAttr['source_link'] = $ns->url;
1251             }
1252         }
1253
1254         if (!empty($cur)) {
1255             $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1256         }
1257
1258         if (!empty($this->repeat_of)) {
1259             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1260         }
1261
1262         $xs->element('statusnet:notice_info', $noticeInfoAttr, null);
1263
1264         if ($this->reply_to) {
1265             $reply_notice = Notice::staticGet('id', $this->reply_to);
1266             if (!empty($reply_notice)) {
1267                 $xs->element('link', array('rel' => 'related',
1268                                            'href' => $reply_notice->bestUrl()));
1269                 $xs->element('thr:in-reply-to',
1270                              array('ref' => $reply_notice->uri,
1271                                    'href' => $reply_notice->bestUrl()));
1272             }
1273         }
1274
1275         if (!empty($this->conversation)) {
1276
1277             $conv = Conversation::staticGet('id', $this->conversation);
1278
1279             if (!empty($conv)) {
1280                 $xs->element(
1281                     'link', array(
1282                         'rel' => 'ostatus:conversation',
1283                         'href' => $conv->uri
1284                     )
1285                 );
1286             }
1287         }
1288
1289         $reply_ids = $this->getReplies();
1290
1291         foreach ($reply_ids as $id) {
1292             $profile = Profile::staticGet('id', $id);
1293            if (!empty($profile)) {
1294                 $xs->element(
1295                     'link', array(
1296                         'rel' => 'ostatus:attention',
1297                         'href' => $profile->getUri()
1298                     )
1299                 );
1300             }
1301         }
1302
1303         $groups = $this->getGroups();
1304
1305         foreach ($groups as $group) {
1306             $xs->element(
1307                 'link', array(
1308                     'rel' => 'ostatus:attention',
1309                     'href' => $group->permalink()
1310                 )
1311             );
1312         }
1313
1314         if (!empty($this->repeat_of)) {
1315             $repeat = Notice::staticGet('id', $this->repeat_of);
1316             if (!empty($repeat)) {
1317                 $xs->element(
1318                     'ostatus:forward',
1319                      array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1320                 );
1321             }
1322         }
1323
1324         $xs->element(
1325             'content',
1326             array('type' => 'html'),
1327             common_xml_safe_str($this->rendered)
1328         );
1329
1330         $tag = new Notice_tag();
1331         $tag->notice_id = $this->id;
1332         if ($tag->find()) {
1333             while ($tag->fetch()) {
1334                 $xs->element('category', array('term' => $tag->tag));
1335             }
1336         }
1337         $tag->free();
1338
1339         # Enclosures
1340         $attachments = $this->attachments();
1341         if($attachments){
1342             foreach($attachments as $attachment){
1343                 $enclosure=$attachment->getEnclosure();
1344                 if ($enclosure) {
1345                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1346                     if($enclosure->title){
1347                         $attributes['title']=$enclosure->title;
1348                     }
1349                     $xs->element('link', $attributes, null);
1350                 }
1351             }
1352         }
1353
1354         if (!empty($this->lat) && !empty($this->lon)) {
1355             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1356         }
1357
1358         $xs->elementEnd('entry');
1359
1360         return $xs->getString();
1361     }
1362
1363     /**
1364      * Returns an XML string fragment with a reference to a notice as an
1365      * Activity Streams noun object with the given element type.
1366      *
1367      * Assumes that 'activity' namespace has been previously defined.
1368      *
1369      * @param string $element one of 'subject', 'object', 'target'
1370      * @return string
1371      */
1372     function asActivityNoun($element)
1373     {
1374         $noun = ActivityObject::fromNotice($this);
1375         return $noun->asString('activity:' . $element);
1376     }
1377
1378     function bestUrl()
1379     {
1380         if (!empty($this->url)) {
1381             return $this->url;
1382         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1383             return $this->uri;
1384         } else {
1385             return common_local_url('shownotice',
1386                                     array('notice' => $this->id));
1387         }
1388     }
1389
1390     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1391     {
1392         $cache = common_memcache();
1393
1394         if (empty($cache) ||
1395             $since_id != 0 || $max_id != 0 ||
1396             is_null($limit) ||
1397             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1398             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1399                                                                       $max_id)));
1400         }
1401
1402         $idkey = common_cache_key($cachekey);
1403
1404         $idstr = $cache->get($idkey);
1405
1406         if ($idstr !== false) {
1407             // Cache hit! Woohoo!
1408             $window = explode(',', $idstr);
1409             $ids = array_slice($window, $offset, $limit);
1410             return $ids;
1411         }
1412
1413         $laststr = $cache->get($idkey.';last');
1414
1415         if ($laststr !== false) {
1416             $window = explode(',', $laststr);
1417             $last_id = $window[0];
1418             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1419                                                                           $last_id, 0, null)));
1420
1421             $new_window = array_merge($new_ids, $window);
1422
1423             $new_windowstr = implode(',', $new_window);
1424
1425             $result = $cache->set($idkey, $new_windowstr);
1426             $result = $cache->set($idkey . ';last', $new_windowstr);
1427
1428             $ids = array_slice($new_window, $offset, $limit);
1429
1430             return $ids;
1431         }
1432
1433         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1434                                                                      0, 0, null)));
1435
1436         $windowstr = implode(',', $window);
1437
1438         $result = $cache->set($idkey, $windowstr);
1439         $result = $cache->set($idkey . ';last', $windowstr);
1440
1441         $ids = array_slice($window, $offset, $limit);
1442
1443         return $ids;
1444     }
1445
1446     /**
1447      * Determine which notice, if any, a new notice is in reply to.
1448      *
1449      * For conversation tracking, we try to see where this notice fits
1450      * in the tree. Rough algorithm is:
1451      *
1452      * if (reply_to is set and valid) {
1453      *     return reply_to;
1454      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1455      *     return ID of last notice by initial @name in content;
1456      * }
1457      *
1458      * Note that all @nickname instances will still be used to save "reply" records,
1459      * so the notice shows up in the mentioned users' "replies" tab.
1460      *
1461      * @param integer $reply_to   ID passed in by Web or API
1462      * @param integer $profile_id ID of author
1463      * @param string  $source     Source tag, like 'web' or 'gwibber'
1464      * @param string  $content    Final notice content
1465      *
1466      * @return integer ID of replied-to notice, or null for not a reply.
1467      */
1468
1469     static function getReplyTo($reply_to, $profile_id, $source, $content)
1470     {
1471         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1472
1473         // If $reply_to is specified, we check that it exists, and then
1474         // return it if it does
1475
1476         if (!empty($reply_to)) {
1477             $reply_notice = Notice::staticGet('id', $reply_to);
1478             if (!empty($reply_notice)) {
1479                 return $reply_to;
1480             }
1481         }
1482
1483         // If it's not a "low bandwidth" source (one where you can't set
1484         // a reply_to argument), we return. This is mostly web and API
1485         // clients.
1486
1487         if (!in_array($source, $lb)) {
1488             return null;
1489         }
1490
1491         // Is there an initial @ or T?
1492
1493         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1494             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1495             $nickname = common_canonical_nickname($match[1]);
1496         } else {
1497             return null;
1498         }
1499
1500         // Figure out who that is.
1501
1502         $sender = Profile::staticGet('id', $profile_id);
1503         if (empty($sender)) {
1504             return null;
1505         }
1506
1507         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1508
1509         if (empty($recipient)) {
1510             return null;
1511         }
1512
1513         // Get their last notice
1514
1515         $last = $recipient->getCurrentNotice();
1516
1517         if (!empty($last)) {
1518             return $last->id;
1519         }
1520     }
1521
1522     static function maxContent()
1523     {
1524         $contentlimit = common_config('notice', 'contentlimit');
1525         // null => use global limit (distinct from 0!)
1526         if (is_null($contentlimit)) {
1527             $contentlimit = common_config('site', 'textlimit');
1528         }
1529         return $contentlimit;
1530     }
1531
1532     static function contentTooLong($content)
1533     {
1534         $contentlimit = self::maxContent();
1535         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1536     }
1537
1538     function getLocation()
1539     {
1540         $location = null;
1541
1542         if (!empty($this->location_id) && !empty($this->location_ns)) {
1543             $location = Location::fromId($this->location_id, $this->location_ns);
1544         }
1545
1546         if (is_null($location)) { // no ID, or Location::fromId() failed
1547             if (!empty($this->lat) && !empty($this->lon)) {
1548                 $location = Location::fromLatLon($this->lat, $this->lon);
1549             }
1550         }
1551
1552         return $location;
1553     }
1554
1555     function repeat($repeater_id, $source)
1556     {
1557         $author = Profile::staticGet('id', $this->profile_id);
1558
1559         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1560         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1561         $content = sprintf(_('RT @%1$s %2$s'),
1562                            $author->nickname,
1563                            $this->content);
1564
1565         $maxlen = common_config('site', 'textlimit');
1566         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1567             // Web interface and current Twitter API clients will
1568             // pull the original notice's text, but some older
1569             // clients and RSS/Atom feeds will see this trimmed text.
1570             //
1571             // Unfortunately this is likely to lose tags or URLs
1572             // at the end of long notices.
1573             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1574         }
1575
1576         return self::saveNew($repeater_id, $content, $source,
1577                              array('repeat_of' => $this->id));
1578     }
1579
1580     // These are supposed to be in chron order!
1581
1582     function repeatStream($limit=100)
1583     {
1584         $cache = common_memcache();
1585
1586         if (empty($cache)) {
1587             $ids = $this->_repeatStreamDirect($limit);
1588         } else {
1589             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1590             if ($idstr !== false) {
1591                 $ids = explode(',', $idstr);
1592             } else {
1593                 $ids = $this->_repeatStreamDirect(100);
1594                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1595             }
1596             if ($limit < 100) {
1597                 // We do a max of 100, so slice down to limit
1598                 $ids = array_slice($ids, 0, $limit);
1599             }
1600         }
1601
1602         return Notice::getStreamByIds($ids);
1603     }
1604
1605     function _repeatStreamDirect($limit)
1606     {
1607         $notice = new Notice();
1608
1609         $notice->selectAdd(); // clears it
1610         $notice->selectAdd('id');
1611
1612         $notice->repeat_of = $this->id;
1613
1614         $notice->orderBy('created'); // NB: asc!
1615
1616         if (!is_null($offset)) {
1617             $notice->limit($offset, $limit);
1618         }
1619
1620         $ids = array();
1621
1622         if ($notice->find()) {
1623             while ($notice->fetch()) {
1624                 $ids[] = $notice->id;
1625             }
1626         }
1627
1628         $notice->free();
1629         $notice = NULL;
1630
1631         return $ids;
1632     }
1633
1634     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1635     {
1636         $options = array();
1637
1638         if (!empty($location_id) && !empty($location_ns)) {
1639
1640             $options['location_id'] = $location_id;
1641             $options['location_ns'] = $location_ns;
1642
1643             $location = Location::fromId($location_id, $location_ns);
1644
1645             if (!empty($location)) {
1646                 $options['lat'] = $location->lat;
1647                 $options['lon'] = $location->lon;
1648             }
1649
1650         } else if (!empty($lat) && !empty($lon)) {
1651
1652             $options['lat'] = $lat;
1653             $options['lon'] = $lon;
1654
1655             $location = Location::fromLatLon($lat, $lon);
1656
1657             if (!empty($location)) {
1658                 $options['location_id'] = $location->location_id;
1659                 $options['location_ns'] = $location->location_ns;
1660             }
1661         } else if (!empty($profile)) {
1662
1663             if (isset($profile->lat) && isset($profile->lon)) {
1664                 $options['lat'] = $profile->lat;
1665                 $options['lon'] = $profile->lon;
1666             }
1667
1668             if (isset($profile->location_id) && isset($profile->location_ns)) {
1669                 $options['location_id'] = $profile->location_id;
1670                 $options['location_ns'] = $profile->location_ns;
1671             }
1672         }
1673
1674         return $options;
1675     }
1676
1677     function clearReplies()
1678     {
1679         $replyNotice = new Notice();
1680         $replyNotice->reply_to = $this->id;
1681
1682         //Null any notices that are replies to this notice
1683
1684         if ($replyNotice->find()) {
1685             while ($replyNotice->fetch()) {
1686                 $orig = clone($replyNotice);
1687                 $replyNotice->reply_to = null;
1688                 $replyNotice->update($orig);
1689             }
1690         }
1691
1692         // Reply records
1693
1694         $reply = new Reply();
1695         $reply->notice_id = $this->id;
1696
1697         if ($reply->find()) {
1698             while($reply->fetch()) {
1699                 self::blow('reply:stream:%d', $reply->profile_id);
1700                 $reply->delete();
1701             }
1702         }
1703
1704         $reply->free();
1705     }
1706
1707     function clearRepeats()
1708     {
1709         $repeatNotice = new Notice();
1710         $repeatNotice->repeat_of = $this->id;
1711
1712         //Null any notices that are repeats of this notice
1713
1714         if ($repeatNotice->find()) {
1715             while ($repeatNotice->fetch()) {
1716                 $orig = clone($repeatNotice);
1717                 $repeatNotice->repeat_of = null;
1718                 $repeatNotice->update($orig);
1719             }
1720         }
1721     }
1722
1723     function clearFaves()
1724     {
1725         $fave = new Fave();
1726         $fave->notice_id = $this->id;
1727
1728         if ($fave->find()) {
1729             while ($fave->fetch()) {
1730                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1731                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1732                 self::blow('fave:ids_by_user:%d', $fave->user_id);
1733                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1734                 $fave->delete();
1735             }
1736         }
1737
1738         $fave->free();
1739     }
1740
1741     function clearTags()
1742     {
1743         $tag = new Notice_tag();
1744         $tag->notice_id = $this->id;
1745
1746         if ($tag->find()) {
1747             while ($tag->fetch()) {
1748                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1749                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1750                 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1751                 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1752                 $tag->delete();
1753             }
1754         }
1755
1756         $tag->free();
1757     }
1758
1759     function clearGroupInboxes()
1760     {
1761         $gi = new Group_inbox();
1762
1763         $gi->notice_id = $this->id;
1764
1765         if ($gi->find()) {
1766             while ($gi->fetch()) {
1767                 self::blow('user_group:notice_ids:%d', $gi->group_id);
1768                 $gi->delete();
1769             }
1770         }
1771
1772         $gi->free();
1773     }
1774
1775     function distribute()
1776     {
1777         // We always insert for the author so they don't
1778         // have to wait
1779
1780         $user = User::staticGet('id', $this->profile_id);
1781         if (!empty($user)) {
1782             Inbox::insertNotice($user->id, $this->id);
1783         }
1784
1785         if (common_config('queue', 'inboxes')) {
1786             // If there's a failure, we want to _force_
1787             // distribution at this point.
1788             try {
1789                 $qm = QueueManager::get();
1790                 $qm->enqueue($this, 'distrib');
1791             } catch (Exception $e) {
1792                 // If the exception isn't transient, this
1793                 // may throw more exceptions as DQH does
1794                 // its own enqueueing. So, we ignore them!
1795                 try {
1796                     $handler = new DistribQueueHandler();
1797                     $handler->handle($this);
1798                 } catch (Exception $e) {
1799                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1800                 }
1801                 // Re-throw so somebody smarter can handle it.
1802                 throw $e;
1803             }
1804         } else {
1805             $handler = new DistribQueueHandler();
1806             $handler->handle($this);
1807         }
1808     }
1809
1810     function insert()
1811     {
1812         $result = parent::insert();
1813
1814         if ($result) {
1815             // Profile::hasRepeated() abuses pkeyGet(), so we
1816             // have to clear manually
1817             if (!empty($this->repeat_of)) {
1818                 $c = self::memcache();
1819                 if (!empty($c)) {
1820                     $ck = self::multicacheKey('Notice',
1821                                               array('profile_id' => $this->profile_id,
1822                                                     'repeat_of' => $this->repeat_of));
1823                     $c->delete($ck);
1824                 }
1825             }
1826         }
1827
1828         return $result;
1829     }
1830
1831     /**
1832      * Get the source of the notice
1833      *
1834      * @return Notice_source $ns A notice source object. 'code' is the only attribute
1835      *                           guaranteed to be populated.
1836      */
1837     function getSource()
1838     {
1839         $ns = new Notice_source();
1840         if (!empty($this->source)) {
1841             switch ($this->source) {
1842             case 'web':
1843             case 'xmpp':
1844             case 'mail':
1845             case 'omb':
1846             case 'system':
1847             case 'api':
1848                 $ns->code = $this->source;
1849                 break;
1850             default:
1851                 $ns = Notice_source::staticGet($this->source);
1852                 if (!$ns) {
1853                     $ns = new Notice_source();
1854                     $ns->code = $this->source;
1855                     $app = Oauth_application::staticGet('name', $this->source);
1856                     if ($app) {
1857                         $ns->name = $app->name;
1858                         $ns->url  = $app->source_url;
1859                     }
1860                 }
1861                 break;
1862             }
1863         }
1864         return $ns;
1865     }
1866
1867 }