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