]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Some work on ActivityModeration with notice deletion
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008-2011 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  * @author   Mikael Nordfeldth <mmn@hethane.se>
33  * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
35  */
36
37 if (!defined('GNUSOCIAL')) { exit(1); }
38
39 /**
40  * Table Definition for notice
41  */
42
43 /* We keep 200 notices, the max number of notices available per API request,
44  * in the memcached cache. */
45
46 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
47
48 define('MAX_BOXCARS', 128);
49
50 class Notice extends Managed_DataObject
51 {
52     ###START_AUTOCODE
53     /* the code below is auto generated do not remove the above tag */
54
55     public $__table = 'notice';                          // table name
56     public $id;                              // int(4)  primary_key not_null
57     public $profile_id;                      // int(4)  multiple_key not_null
58     public $uri;                             // varchar(191)  unique_key   not 255 because utf8mb4 takes more space
59     public $content;                         // text
60     public $rendered;                        // text
61     public $url;                             // varchar(191)   not 255 because utf8mb4 takes more space
62     public $created;                         // datetime  multiple_key not_null default_0000-00-00%2000%3A00%3A00
63     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
64     public $reply_to;                        // int(4)
65     public $is_local;                        // int(4)
66     public $source;                          // varchar(32)
67     public $conversation;                    // int(4)
68     public $repeat_of;                       // int(4)
69     public $verb;                            // varchar(191)   not 255 because utf8mb4 takes more space
70     public $object_type;                     // varchar(191)   not 255 because utf8mb4 takes more space
71     public $scope;                           // int(4)
72
73     /* the code above is auto generated do not remove the tag below */
74     ###END_AUTOCODE
75
76     public static function schemaDef()
77     {
78         $def = array(
79             'fields' => array(
80                 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
81                 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
82                 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
83                 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8mb4_general_ci'),
84                 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
85                 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
86                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
87                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
88                 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
89                 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
90                 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
91                 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
92                 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
93                 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
94                 'verb' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
95                 'scope' => array('type' => 'int',
96                                  'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
97             ),
98             'primary key' => array('id'),
99             'unique keys' => array(
100                 'notice_uri_key' => array('uri'),
101             ),
102             'foreign keys' => array(
103                 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
104                 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
105                 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
106                 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
107             ),
108             'indexes' => array(
109                 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
110                 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
111                 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
112                 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
113                 'notice_replyto_idx' => array('reply_to')
114             )
115         );
116
117         if (common_config('search', 'type') == 'fulltext') {
118             $def['fulltext indexes'] = array('content' => array('content'));
119         }
120
121         return $def;
122     }
123
124     /* Notice types */
125     const LOCAL_PUBLIC    =  1;
126     const REMOTE          =  0;
127     const LOCAL_NONPUBLIC = -1;
128     const GATEWAY         = -2;
129
130     const PUBLIC_SCOPE    = 0; // Useful fake constant
131     const SITE_SCOPE      = 1;
132     const ADDRESSEE_SCOPE = 2;
133     const GROUP_SCOPE     = 4;
134     const FOLLOWER_SCOPE  = 8;
135
136     protected $_profile = array();
137
138     /**
139      * Will always return a profile, if anything fails it will
140      * (through _setProfile) throw a NoProfileException.
141      */
142     public function getProfile()
143     {
144         if (!isset($this->_profile[$this->profile_id])) {
145             // We could've sent getKV directly to _setProfile, but occasionally we get
146             // a "false" (instead of null), likely because it indicates a cache miss.
147             $profile = Profile::getKV('id', $this->profile_id);
148             $this->_setProfile($profile instanceof Profile ? $profile : null);
149         }
150         return $this->_profile[$this->profile_id];
151     }
152
153     public function _setProfile(Profile $profile=null)
154     {
155         if (!$profile instanceof Profile) {
156             throw new NoProfileException($this->profile_id);
157         }
158         $this->_profile[$this->profile_id] = $profile;
159     }
160
161     public function deleteAs(Profile $actor)
162     {
163         if ($this->getProfile()->sameAs($actor) || $actor->hasRight(Right::DELETEOTHERSNOTICE)) {
164             return $this->delete();
165         }
166         throw new AuthorizationException(_('You are not allowed to delete other user\'s notices'));
167     }
168
169     public function delete($useWhere=false)
170     {
171         if (Event::handle('NoticeDeleteRelated', array($this))) {
172
173             // Clear related records
174
175             $this->clearReplies();
176             $this->clearLocation();
177             $this->clearRepeats();
178             $this->clearTags();
179             $this->clearGroupInboxes();
180             $this->clearFiles();
181             $this->clearAttentions();
182
183             // NOTE: we don't clear queue items
184         }
185
186         $result = parent::delete($useWhere);
187
188         $this->blowOnDelete();
189         return $result;
190     }
191
192     public function getUri()
193     {
194         return $this->uri;
195     }
196
197     /*
198      * Get a Notice object by URI. Will call external plugins for help
199      * using the event StartGetNoticeFromURI.
200      *
201      * @param string $uri A unique identifier for a resource (notice in this case)
202      */
203     static function fromUri($uri)
204     {
205         $notice = null;
206
207         if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
208             $notice = Notice::getKV('uri', $uri);
209             Event::handle('EndGetNoticeFromUri', array($uri, $notice));
210         }
211
212         if (!$notice instanceof Notice) {
213             throw new UnknownUriException($uri);
214         }
215
216         return $notice;
217     }
218
219     /*
220      * @param $root boolean If true, link to just the conversation root.
221      *
222      * @return URL to conversation
223      */
224     public function getConversationUrl($anchor=true)
225     {
226         return Conversation::getUrlFromNotice($this, $anchor);
227     }
228
229     /*
230      * Get the local representation URL of this notice.
231      */
232     public function getLocalUrl()
233     {
234         return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
235     }
236
237     public function getTitle()
238     {
239         $title = null;
240         if (Event::handle('GetNoticeTitle', array($this, &$title))) {
241             // TRANS: Title of a notice posted without a title value.
242             // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
243             $title = sprintf(_('%1$s\'s status on %2$s'),
244                              $this->getProfile()->getFancyName(),
245                              common_exact_date($this->created));
246         }
247         return $title;
248     }
249
250     public function getContent()
251     {
252         return $this->content;
253     }
254
255     /*
256      * Get the original representation URL of this notice.
257      *
258      * @param boolean $fallback     Whether to fall back to generate a local URL or throw InvalidUrlException
259      */
260     public function getUrl($fallback=false)
261     {
262         // The risk is we start having empty urls and non-http uris...
263         // and we can't really handle any other protocol right now.
264         switch (true) {
265         case common_valid_http_url($this->url): // should we allow non-http/https URLs?
266             return $this->url;
267         case !$this->isLocal() && common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
268             return $this->uri;
269         case $this->isLocal() || $fallback:
270             // let's generate a valid link to our locally available notice on demand
271             return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
272         default:
273             common_debug('No URL available for notice: id='.$this->id);
274             throw new InvalidUrlException($this->url);
275         }
276     }
277
278     public function get_object_type($canonical=false) {
279         return $canonical
280                 ? ActivityObject::canonicalType($this->object_type)
281                 : $this->object_type;
282     }
283
284     public static function getByUri($uri)
285     {
286         $notice = new Notice();
287         $notice->uri = $uri;
288         if (!$notice->find(true)) {
289             throw new NoResultException($notice);
290         }
291         return $notice;
292     }
293
294     /**
295      * Extract #hashtags from this notice's content and save them to the database.
296      */
297     function saveTags()
298     {
299         /* extract all #hastags */
300         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
301         if (!$count) {
302             return true;
303         }
304
305         /* Add them to the database */
306         return $this->saveKnownTags($match[1]);
307     }
308
309     /**
310      * Record the given set of hash tags in the db for this notice.
311      * Given tag strings will be normalized and checked for dupes.
312      */
313     function saveKnownTags($hashtags)
314     {
315         //turn each into their canonical tag
316         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
317         for($i=0; $i<count($hashtags); $i++) {
318             /* elide characters we don't want in the tag */
319             $hashtags[$i] = common_canonical_tag($hashtags[$i]);
320         }
321
322         foreach(array_unique($hashtags) as $hashtag) {
323             $this->saveTag($hashtag);
324             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
325         }
326         return true;
327     }
328
329     /**
330      * Record a single hash tag as associated with this notice.
331      * Tag format and uniqueness must be validated by caller.
332      */
333     function saveTag($hashtag)
334     {
335         $tag = new Notice_tag();
336         $tag->notice_id = $this->id;
337         $tag->tag = $hashtag;
338         $tag->created = $this->created;
339         $id = $tag->insert();
340
341         if (!$id) {
342             // TRANS: Server exception. %s are the error details.
343             throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
344                                               $last_error->message));
345             return;
346         }
347
348         // if it's saved, blow its cache
349         $tag->blowCache(false);
350     }
351
352     /**
353      * Save a new notice and push it out to subscribers' inboxes.
354      * Poster's permissions are checked before sending.
355      *
356      * @param int $profile_id Profile ID of the poster
357      * @param string $content source message text; links may be shortened
358      *                        per current user's preference
359      * @param string $source source key ('web', 'api', etc)
360      * @param array $options Associative array of optional properties:
361      *              string 'created' timestamp of notice; defaults to now
362      *              int 'is_local' source/gateway ID, one of:
363      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
364      *                  Notice::REMOTE          - Sent from a remote service;
365      *                                            hide from public timeline but show in
366      *                                            local "and friends" timelines
367      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
368      *                  Notice::GATEWAY         - From another non-OStatus service;
369      *                                            will not appear in public views
370      *              float 'lat' decimal latitude for geolocation
371      *              float 'lon' decimal longitude for geolocation
372      *              int 'location_id' geoname identifier
373      *              int 'location_ns' geoname namespace to interpret location_id
374      *              int 'reply_to'; notice ID this is a reply to
375      *              int 'repeat_of'; notice ID this is a repeat of
376      *              string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
377      *              string 'url' permalink to notice; defaults to local notice URL
378      *              string 'rendered' rendered HTML version of content
379      *              array 'replies' list of profile URIs for reply delivery in
380      *                              place of extracting @-replies from content.
381      *              array 'groups' list of group IDs to deliver to, in place of
382      *                              extracting ! tags from content
383      *              array 'tags' list of hashtag strings to save with the notice
384      *                           in place of extracting # tags from content
385      *              array 'urls' list of attached/referred URLs to save with the
386      *                           notice in place of extracting links from content
387      *              boolean 'distribute' whether to distribute the notice, default true
388      *              string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
389      *              string 'verb' URL of the associated verb (default ActivityVerb::POST)
390      *              int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
391      *
392      * @fixme tag override
393      *
394      * @return Notice
395      * @throws ClientException
396      */
397     static function saveNew($profile_id, $content, $source, array $options=null) {
398         $defaults = array('uri' => null,
399                           'url' => null,
400                           'conversation' => null,   // URI of conversation
401                           'reply_to' => null,       // This will override convo URI if the parent is known
402                           'repeat_of' => null,      // This will override convo URI if the repeated notice is known
403                           'scope' => null,
404                           'distribute' => true,
405                           'object_type' => null,
406                           'verb' => null);
407
408         if (!empty($options) && is_array($options)) {
409             $options = array_merge($defaults, $options);
410             extract($options);
411         } else {
412             extract($defaults);
413         }
414
415         if (!isset($is_local)) {
416             $is_local = Notice::LOCAL_PUBLIC;
417         }
418
419         $profile = Profile::getKV('id', $profile_id);
420         if (!$profile instanceof Profile) {
421             // TRANS: Client exception thrown when trying to save a notice for an unknown user.
422             throw new ClientException(_('Problem saving notice. Unknown user.'));
423         }
424
425         $user = User::getKV('id', $profile_id);
426         if ($user instanceof User) {
427             // Use the local user's shortening preferences, if applicable.
428             $final = $user->shortenLinks($content);
429         } else {
430             $final = common_shorten_links($content);
431         }
432
433         if (Notice::contentTooLong($final)) {
434             // TRANS: Client exception thrown if a notice contains too many characters.
435             throw new ClientException(_('Problem saving notice. Too long.'));
436         }
437
438         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
439             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
440             // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
441             throw new ClientException(_('Too many notices too fast; take a breather '.
442                                         'and post again in a few minutes.'));
443         }
444
445         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
446             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
447             // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
448             throw new ClientException(_('Too many duplicate messages too quickly;'.
449                                         ' take a breather and post again in a few minutes.'));
450         }
451
452         if (!$profile->hasRight(Right::NEWNOTICE)) {
453             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
454
455             // TRANS: Client exception thrown when a user tries to post while being banned.
456             throw new ClientException(_('You are banned from posting notices on this site.'), 403);
457         }
458
459         $notice = new Notice();
460         $notice->profile_id = $profile_id;
461
462         $autosource = common_config('public', 'autosource');
463
464         // Sandboxed are non-false, but not 1, either
465
466         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
467             ($source && $autosource && in_array($source, $autosource))) {
468             $notice->is_local = Notice::LOCAL_NONPUBLIC;
469         } else {
470             $notice->is_local = $is_local;
471         }
472
473         if (!empty($created)) {
474             $notice->created = $created;
475         } else {
476             $notice->created = common_sql_now();
477         }
478
479         if (!$notice->isLocal()) {
480             // Only do these checks for non-local notices. Local notices will generate these values later.
481             if (!common_valid_http_url($url)) {
482                 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
483             }
484             if (empty($uri)) {
485                 throw new ServerException('No URI for remote notice. Cannot accept that.');
486             }
487         }
488
489         $notice->content = $final;
490
491         $notice->source = $source;
492         $notice->uri = $uri;
493         $notice->url = $url;
494
495         // Get the groups here so we can figure out replies and such
496         if (!isset($groups)) {
497             $groups = User_group::idsFromText($notice->content, $profile);
498         }
499
500         $reply = null;
501
502         // Handle repeat case
503
504         if (!empty($options['repeat_of'])) {
505
506             // Check for a private one
507
508             $repeat = Notice::getByID($options['repeat_of']);
509
510             if ($profile->sameAs($repeat->getProfile())) {
511                 // TRANS: Client error displayed when trying to repeat an own notice.
512                 throw new ClientException(_('You cannot repeat your own notice.'));
513             }
514
515             if ($repeat->scope != Notice::SITE_SCOPE &&
516                 $repeat->scope != Notice::PUBLIC_SCOPE) {
517                 // TRANS: Client error displayed when trying to repeat a non-public notice.
518                 throw new ClientException(_('Cannot repeat a private notice.'), 403);
519             }
520
521             if (!$repeat->inScope($profile)) {
522                 // The generic checks above should cover this, but let's be sure!
523                 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
524                 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
525             }
526
527             if ($profile->hasRepeated($repeat)) {
528                 // TRANS: Client error displayed when trying to repeat an already repeated notice.
529                 throw new ClientException(_('You already repeated that notice.'));
530             }
531
532             $notice->repeat_of = $repeat->id;
533             $notice->conversation = $repeat->conversation;
534         } else {
535             $reply = null;
536
537             // If $reply_to is specified, we check that it exists, and then
538             // return it if it does
539             if (!empty($reply_to)) {
540                 $reply = Notice::getKV('id', $reply_to);
541             } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
542                 // If the source lacks capability of sending the "reply_to"
543                 // metadata, let's try to find an inline replyto-reference.
544                 $reply = self::getInlineReplyTo($profile, $final);
545             }
546
547             if ($reply instanceof Notice) {
548                 if (!$reply->inScope($profile)) {
549                     // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
550                     // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
551                     throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
552                                                       $profile->nickname, $reply->id), 403);
553                 }
554
555                 // If it's a repeat, the reply_to should be to the original
556                 if ($reply->isRepeat()) {
557                     $notice->reply_to = $reply->repeat_of;
558                 } else {
559                     $notice->reply_to = $reply->id;
560                 }
561                 // But the conversation ought to be the same :)
562                 $notice->conversation = $reply->conversation;
563
564                 // If the original is private to a group, and notice has
565                 // no group specified, make it to the same group(s)
566
567                 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
568                     $groups = array();
569                     $replyGroups = $reply->getGroups();
570                     foreach ($replyGroups as $group) {
571                         if ($profile->isMember($group)) {
572                             $groups[] = $group->id;
573                         }
574                     }
575                 }
576
577                 // Scope set below
578             }
579
580             // If we don't know the reply, we might know the conversation!
581             // This will happen if a known remote user replies to an
582             // unknown remote user - within a known conversation.
583             if (empty($notice->conversation) and !empty($options['conversation'])) {
584                 $conv = Conversation::getKV('uri', $options['conversation']);
585                 if ($conv instanceof Conversation) {
586                     common_debug('Conversation stitched together from (probably) a reply to unknown remote user. Activity creation time ('.$notice->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
587                     $notice->conversation = $conv->id;
588                 } else {
589                     // Conversation URI was not found, so we must create it. But we can't create it
590                     // until we have a Notice ID because of the database layout...
591                     // $options['conversation'] will be used later after the $notice->insert();
592                     common_debug('Conversation URI not found, so we have to create it after inserting this Notice: '.$options['conversation']);
593                 }
594             } else {
595                 // If we're not using the attached conversation URI let's remove it
596                 // so we don't mistake ourselves later, when creating our own Conversation.
597                 // This implies that the notice knows which conversation it belongs to.
598                 $options['conversation'] = null;
599             }
600         }
601
602         $notloc = new Notice_location();
603         if (!empty($lat) && !empty($lon)) {
604             $notloc->lat = $lat;
605             $notloc->lon = $lon;
606         }
607
608         if (!empty($location_ns) && !empty($location_id)) {
609             $notloc->location_id = $location_id;
610             $notloc->location_ns = $location_ns;
611         }
612
613         if (!empty($rendered)) {
614             $notice->rendered = $rendered;
615         } else {
616             $notice->rendered = common_render_content($final, $notice);
617         }
618
619         if (empty($verb)) {
620             if ($notice->isRepeat()) {
621                 $notice->verb        = ActivityVerb::SHARE;
622                 $notice->object_type = ActivityObject::ACTIVITY;
623             } else {
624                 $notice->verb        = ActivityVerb::POST;
625             }
626         } else {
627             $notice->verb = $verb;
628         }
629
630         if (empty($object_type)) {
631             $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
632         } else {
633             $notice->object_type = $object_type;
634         }
635
636         if (is_null($scope) && $reply instanceof Notice) {
637             $notice->scope = $reply->scope;
638         } else {
639             $notice->scope = $scope;
640         }
641
642         $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
643
644         if (Event::handle('StartNoticeSave', array(&$notice))) {
645
646             // XXX: some of these functions write to the DB
647
648             try {
649                 $notice->insert();  // throws exception on failure, if successful we have an ->id
650
651                 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
652                     $notloc->notice_id = $notice->getID();
653                     $notloc->insert();  // store the notice location if it had any information
654                 }
655
656                 // If it's not part of a conversation, it's
657                 // the beginning of a new conversation.
658                 if (empty($notice->conversation)) {
659                     $orig = clone($notice);
660                     // $act->context->conversation will be null if it was not provided
661
662                     $conv = Conversation::create($notice, $options['conversation']);
663                     $notice->conversation = $conv->id;
664                     $notice->update($orig);
665                 }
666             } catch (Exception $e) {
667                 // Let's test if we managed initial insert, which would imply
668                 // failing on some update-part (check 'insert()'). Delete if
669                 // something had been stored to the database.
670                 if (!empty($notice->id)) {
671                     $notice->delete();
672                 }
673                 throw $e;
674             }
675         }
676
677         // Clear the cache for subscribed users, so they'll update at next request
678         // XXX: someone clever could prepend instead of clearing the cache
679
680         // Save per-notice metadata...
681
682         if (isset($replies)) {
683             $notice->saveKnownReplies($replies);
684         } else {
685             $notice->saveReplies();
686         }
687
688         if (isset($tags)) {
689             $notice->saveKnownTags($tags);
690         } else {
691             $notice->saveTags();
692         }
693
694         // Note: groups may save tags, so must be run after tags are saved
695         // to avoid errors on duplicates.
696         // Note: groups should always be set.
697
698         $notice->saveKnownGroups($groups);
699
700         if (isset($urls)) {
701             $notice->saveKnownUrls($urls);
702         } else {
703             $notice->saveUrls();
704         }
705
706         if ($distribute) {
707             // Prepare inbox delivery, may be queued to background.
708             $notice->distribute();
709         }
710
711         return $notice;
712     }
713
714     static function saveActivity(Activity $act, Profile $actor, array $options=array())
715     {
716         // First check if we're going to let this Activity through from the specific actor
717         if (!$actor->hasRight(Right::NEWNOTICE)) {
718             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
719
720             // TRANS: Client exception thrown when a user tries to post while being banned.
721             throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
722         }
723         if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
724             common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
725             // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
726             throw new ClientException(_m('Too many notices too fast; take a breather '.
727                                         'and post again in a few minutes.'));
728         }
729
730         // Get ActivityObject properties
731         if (!empty($act->id)) {
732             // implied object
733             $options['uri'] = $act->id;
734             $options['url'] = $act->link;
735         } else {
736             $actobj = count($act->objects)==1 ? $act->objects[0] : null;
737             if (!is_null($actobj) && !empty($actobj->id)) {
738                 $options['uri'] = $actobj->id;
739                 if ($actobj->link) {
740                     $options['url'] = $actobj->link;
741                 } elseif (preg_match('!^https?://!', $actobj->id)) {
742                     $options['url'] = $actobj->id;
743                 }
744             }
745         }
746
747         $defaults = array(
748                           'groups'   => array(),
749                           'is_local' => self::LOCAL_PUBLIC,
750                           'mentions' => array(),
751                           'reply_to' => null,
752                           'repeat_of' => null,
753                           'scope' => null,
754                           'source' => 'unknown',
755                           'tags' => array(),
756                           'uri' => null,
757                           'url' => null,
758                           'urls' => array(),
759                           'distribute' => true);
760
761         // options will have default values when nothing has been supplied
762         $options = array_merge($defaults, $options);
763         foreach (array_keys($defaults) as $key) {
764             // Only convert the keynames we specify ourselves from 'defaults' array into variables
765             $$key = $options[$key];
766         }
767         extract($options, EXTR_SKIP);
768
769         $stored = new Notice();
770         if (!empty($uri)) {
771             $stored->uri = $uri;
772             if ($stored->find()) {
773                 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
774                 throw new Exception('Notice URI already exists');
775             }
776         }
777
778         $stored->profile_id = $actor->id;
779         $stored->source = $source;
780         $stored->uri = $uri;
781         $stored->url = $url;
782         $stored->verb = $act->verb;
783
784         // Use the local user's shortening preferences, if applicable.
785         $stored->rendered = $actor->isLocal()
786                                 ? $actor->shortenLinks($act->content)
787                                 : $act->content;
788         $stored->content = common_strip_html($stored->rendered);
789
790         $autosource = common_config('public', 'autosource');
791
792         // Sandboxed are non-false, but not 1, either
793         if (!$actor->hasRight(Right::PUBLICNOTICE) ||
794             ($source && $autosource && in_array($source, $autosource))) {
795             $stored->is_local = Notice::LOCAL_NONPUBLIC;
796         }
797
798         // Maybe a missing act-time should be fatal if the actor is not local?
799         if (!empty($act->time)) {
800             $stored->created = common_sql_date($act->time);
801         } else {
802             $stored->created = common_sql_now();
803         }
804
805         $reply = null;
806         if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
807             $reply = self::getKV('uri', $act->context->replyToID);
808         }
809         if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
810             $reply = self::getKV('uri', $act->target->id);
811         }
812
813         if ($reply instanceof Notice) {
814             if (!$reply->inScope($actor)) {
815                 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
816                 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
817                 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
818             }
819
820             $stored->reply_to     = $reply->id;
821             $stored->conversation = $reply->conversation;
822
823             // If the original is private to a group, and notice has no group specified,
824             // make it to the same group(s)
825             if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
826                 $groups = array();
827                 $replyGroups = $reply->getGroups();
828                 foreach ($replyGroups as $group) {
829                     if ($actor->isMember($group)) {
830                         $groups[] = $group->id;
831                     }
832                 }
833             }
834
835             if (is_null($scope)) {
836                 $scope = $reply->scope;
837             }
838         } else {
839             // If we don't know the reply, we might know the conversation!
840             // This will happen if a known remote user replies to an
841             // unknown remote user - within a known conversation.
842             if (empty($stored->conversation) and !empty($act->context->conversation)) {
843                 $conv = Conversation::getKV('uri', $act->context->conversation);
844                 if ($conv instanceof Conversation) {
845                     common_debug('Conversation stitched together from (probably) a reply activity to unknown remote user. Activity creation time ('.$stored->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
846                     $stored->conversation = $conv->getID();
847                 } else {
848                     // Conversation URI was not found, so we must create it. But we can't create it
849                     // until we have a Notice ID because of the database layout...
850                     // $options['conversation'] will be used later after the $stored->insert();
851                     common_debug('Conversation URI from activity context not found, so we have to create it after inserting this Notice: '.$act->context->conversation);
852                 }
853             }
854         }
855
856         $notloc = null;
857         if ($act->context instanceof ActivityContext) {
858             if ($act->context->location instanceof Location) {
859                 $notloc = Notice_location::fromLocation($act->context->location);
860             }
861         } else {
862             $act->context = new ActivityContext();
863         }
864
865         $stored->scope = self::figureOutScope($actor, $groups, $scope);
866
867         foreach ($act->categories as $cat) {
868             if ($cat->term) {
869                 $term = common_canonical_tag($cat->term);
870                 if (!empty($term)) {
871                     $tags[] = $term;
872                 }
873             }
874         }
875
876         foreach ($act->enclosures as $href) {
877             // @todo FIXME: Save these locally or....?
878             $urls[] = $href;
879         }
880
881         if (Event::handle('StartNoticeSave', array(&$stored))) {
882             // XXX: some of these functions write to the DB
883
884             try {
885                 $stored->insert();    // throws exception on error
886
887                 if ($notloc instanceof Notice_location) {
888                     $notloc->notice_id = $stored->getID();
889                     $notloc->insert();
890                 }
891
892                 $orig = clone($stored); // for updating later in this try clause
893
894                 $object = null;
895                 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
896                 if (empty($object)) {
897                     throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->uri . ': '.$act->asString());
898                 }
899
900                 // If it's not part of a conversation, it's the beginning
901                 // of a new one (or belongs to a previously unknown URI).
902                 if (empty($stored->conversation)) {
903                     // $act->context->conversation will be null if it was not provided
904                     common_debug('Creating a new conversation for stored notice ID='.$stored->getID().' with URI: '.$act->context->conversation);
905                     $conv = Conversation::create($stored, $act->context->conversation);
906                     $stored->conversation = $conv->getID();
907                 }
908
909                 $stored->update($orig);
910             } catch (Exception $e) {
911                 if (empty($stored->id)) {
912                     common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
913                 } else {
914                     common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
915                     $stored->delete();
916                 }
917                 throw $e;
918             }
919         }
920         if (!$stored instanceof Notice) {
921             throw new ServerException('StartNoticeSave did not give back a Notice');
922         }
923
924         // Save per-notice metadata...
925         $mentions = array();
926         $groups   = array();
927
928         // This event lets plugins filter out non-local recipients (attentions we don't care about)
929         // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
930         Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
931
932         if (!empty($mentions)) {
933             $stored->saveKnownReplies($mentions);
934         } else {
935             $stored->saveReplies();
936         }
937
938         if (!empty($tags)) {
939             $stored->saveKnownTags($tags);
940         } else {
941             $stored->saveTags();
942         }
943
944         // Note: groups may save tags, so must be run after tags are saved
945         // to avoid errors on duplicates.
946         // Note: groups should always be set.
947
948         $stored->saveKnownGroups($groups);
949
950         if (!empty($urls)) {
951             $stored->saveKnownUrls($urls);
952         } else {
953             $stored->saveUrls();
954         }
955
956         if ($distribute) {
957             // Prepare inbox delivery, may be queued to background.
958             $stored->distribute();
959         }
960
961         return $stored;
962     }
963
964     static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
965         if (is_null($scope)) {
966             $scope = self::defaultScope();
967         }
968
969         // For private streams
970         try {
971             $user = $actor->getUser();
972             // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
973             if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
974                 $scope |= Notice::FOLLOWER_SCOPE;
975             }
976         } catch (NoSuchUserException $e) {
977             // TODO: Not a local user, so we don't know about scope preferences... yet!
978         }
979
980         // Force the scope for private groups
981         foreach ($groups as $group_id) {
982             try {
983                 $group = User_group::getByID($group_id);
984                 if ($group->force_scope) {
985                     $scope |= Notice::GROUP_SCOPE;
986                     break;
987                 }
988             } catch (Exception $e) {
989                 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
990             }
991         }
992
993         return $scope;
994     }
995
996     function blowOnInsert($conversation = false)
997     {
998         $this->blowStream('profile:notice_ids:%d', $this->profile_id);
999
1000         if ($this->isPublic()) {
1001             $this->blowStream('public');
1002             $this->blowStream('networkpublic');
1003         }
1004
1005         self::blow('notice:list-ids:conversation:%s', $this->conversation);
1006         self::blow('conversation:notice_count:%d', $this->conversation);
1007
1008         if ($this->isRepeat()) {
1009             // XXX: we should probably only use one of these
1010             $this->blowStream('notice:repeats:%d', $this->repeat_of);
1011             self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1012         }
1013
1014         $original = Notice::getKV('id', $this->repeat_of);
1015
1016         if ($original instanceof Notice) {
1017             $originalUser = User::getKV('id', $original->profile_id);
1018             if ($originalUser instanceof User) {
1019                 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1020             }
1021         }
1022
1023         $profile = Profile::getKV($this->profile_id);
1024
1025         if ($profile instanceof Profile) {
1026             $profile->blowNoticeCount();
1027         }
1028
1029         $ptags = $this->getProfileTags();
1030         foreach ($ptags as $ptag) {
1031             $ptag->blowNoticeStreamCache();
1032         }
1033     }
1034
1035     /**
1036      * Clear cache entries related to this notice at delete time.
1037      * Necessary to avoid breaking paging on public, profile timelines.
1038      */
1039     function blowOnDelete()
1040     {
1041         $this->blowOnInsert();
1042
1043         self::blow('profile:notice_ids:%d;last', $this->profile_id);
1044
1045         if ($this->isPublic()) {
1046             self::blow('public;last');
1047             self::blow('networkpublic;last');
1048         }
1049
1050         self::blow('fave:by_notice', $this->id);
1051
1052         if ($this->conversation) {
1053             // In case we're the first, will need to calc a new root.
1054             self::blow('notice:conversation_root:%d', $this->conversation);
1055         }
1056
1057         $ptags = $this->getProfileTags();
1058         foreach ($ptags as $ptag) {
1059             $ptag->blowNoticeStreamCache(true);
1060         }
1061     }
1062
1063     function blowStream()
1064     {
1065         $c = self::memcache();
1066
1067         if (empty($c)) {
1068             return false;
1069         }
1070
1071         $args = func_get_args();
1072         $format = array_shift($args);
1073         $keyPart = vsprintf($format, $args);
1074         $cacheKey = Cache::key($keyPart);
1075         $c->delete($cacheKey);
1076
1077         // delete the "last" stream, too, if this notice is
1078         // older than the top of that stream
1079
1080         $lastKey = $cacheKey.';last';
1081
1082         $lastStr = $c->get($lastKey);
1083
1084         if ($lastStr !== false) {
1085             $window     = explode(',', $lastStr);
1086             $lastID     = $window[0];
1087             $lastNotice = Notice::getKV('id', $lastID);
1088             if (!$lastNotice instanceof Notice // just weird
1089                 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1090                 $c->delete($lastKey);
1091             }
1092         }
1093     }
1094
1095     /** save all urls in the notice to the db
1096      *
1097      * follow redirects and save all available file information
1098      * (mimetype, date, size, oembed, etc.)
1099      *
1100      * @return void
1101      */
1102     function saveUrls() {
1103         if (common_config('attachments', 'process_links')) {
1104             common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1105         }
1106     }
1107
1108     /**
1109      * Save the given URLs as related links/attachments to the db
1110      *
1111      * follow redirects and save all available file information
1112      * (mimetype, date, size, oembed, etc.)
1113      *
1114      * @return void
1115      */
1116     function saveKnownUrls($urls)
1117     {
1118         if (common_config('attachments', 'process_links')) {
1119             // @fixme validation?
1120             foreach (array_unique($urls) as $url) {
1121                 $this->saveUrl($url, $this);
1122             }
1123         }
1124     }
1125
1126     /**
1127      * @private callback
1128      */
1129     function saveUrl($url, Notice $notice) {
1130         try {
1131             File::processNew($url, $notice);
1132         } catch (ServerException $e) {
1133             // Could not save URL. Log it?
1134         }
1135     }
1136
1137     static function checkDupes($profile_id, $content) {
1138         $profile = Profile::getKV($profile_id);
1139         if (!$profile instanceof Profile) {
1140             return false;
1141         }
1142         $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1143         if (!empty($notice)) {
1144             $last = 0;
1145             while ($notice->fetch()) {
1146                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1147                     return true;
1148                 } else if ($notice->content == $content) {
1149                     return false;
1150                 }
1151             }
1152         }
1153         // If we get here, oldest item in cache window is not
1154         // old enough for dupe limit; do direct check against DB
1155         $notice = new Notice();
1156         $notice->profile_id = $profile_id;
1157         $notice->content = $content;
1158         $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1159         $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1160
1161         $cnt = $notice->count();
1162         return ($cnt == 0);
1163     }
1164
1165     static function checkEditThrottle($profile_id) {
1166         $profile = Profile::getKV($profile_id);
1167         if (!$profile instanceof Profile) {
1168             return false;
1169         }
1170         // Get the Nth notice
1171         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1172         if ($notice && $notice->fetch()) {
1173             // If the Nth notice was posted less than timespan seconds ago
1174             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1175                 // Then we throttle
1176                 return false;
1177             }
1178         }
1179         // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1180         return true;
1181     }
1182
1183         protected $_attachments = array();
1184
1185     function attachments() {
1186                 if (isset($this->_attachments[$this->id])) {
1187             return $this->_attachments[$this->id];
1188         }
1189
1190         $f2ps = File_to_post::listGet('post_id', array($this->id));
1191                 $ids = array();
1192                 foreach ($f2ps[$this->id] as $f2p) {
1193             $ids[] = $f2p->file_id;
1194         }
1195
1196                 $files = File::multiGet('id', $ids);
1197                 $this->_attachments[$this->id] = $files->fetchAll();
1198         return $this->_attachments[$this->id];
1199     }
1200
1201         function _setAttachments($attachments)
1202         {
1203             $this->_attachments[$this->id] = $attachments;
1204         }
1205
1206     static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1207     {
1208         $stream = new PublicNoticeStream();
1209         return $stream->getNotices($offset, $limit, $since_id, $max_id);
1210     }
1211
1212     static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
1213     {
1214         $stream = new ConversationNoticeStream($id);
1215         return $stream->getNotices($offset, $limit, $since_id, $max_id);
1216     }
1217
1218     /**
1219      * Is this notice part of an active conversation?
1220      *
1221      * @return boolean true if other messages exist in the same
1222      *                 conversation, false if this is the only one
1223      */
1224     function hasConversation()
1225     {
1226         if (empty($this->conversation)) {
1227             // this notice is not part of a conversation apparently
1228             // FIXME: all notices should have a conversation value, right?
1229             return false;
1230         }
1231
1232         $stream = new ConversationNoticeStream($this->conversation);
1233         $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
1234
1235         // if our "offset 1, limit 1" query got a result, return true else false
1236         return $notice->N > 0;
1237     }
1238
1239     /**
1240      * Grab the earliest notice from this conversation.
1241      *
1242      * @return Notice or null
1243      */
1244     function conversationRoot($profile=-1)
1245     {
1246         // XXX: can this happen?
1247
1248         if (empty($this->conversation)) {
1249             return null;
1250         }
1251
1252         // Get the current profile if not specified
1253
1254         if (is_int($profile) && $profile == -1) {
1255             $profile = Profile::current();
1256         }
1257
1258         // If this notice is out of scope, no root for you!
1259
1260         if (!$this->inScope($profile)) {
1261             return null;
1262         }
1263
1264         // If this isn't a reply to anything, then it's its own
1265         // root if it's the earliest notice in the conversation:
1266
1267         if (empty($this->reply_to)) {
1268             $root = new Notice;
1269             $root->conversation = $this->conversation;
1270             $root->orderBy('notice.created ASC');
1271             $root->find(true);  // true means "fetch first result"
1272             $root->free();
1273             return $root;
1274         }
1275
1276         if (is_null($profile)) {
1277             $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1278         } else {
1279             $keypart = sprintf('notice:conversation_root:%d:%d',
1280                                $this->id,
1281                                $profile->id);
1282         }
1283
1284         $root = self::cacheGet($keypart);
1285
1286         if ($root !== false && $root->inScope($profile)) {
1287             return $root;
1288         }
1289
1290         $last = $this;
1291         while (true) {
1292             try {
1293                 $parent = $last->getParent();
1294                 if ($parent->inScope($profile)) {
1295                     $last = $parent;
1296                     continue;
1297                 }
1298             } catch (NoParentNoticeException $e) {
1299                 // Latest notice has no parent
1300             } catch (NoResultException $e) {
1301                 // Notice was not found, so we can't go further up in the tree.
1302                 // FIXME: Maybe we should do this in a more stable way where deleted
1303                 // notices won't break conversation chains?
1304             }
1305             // No parent, or parent out of scope
1306             $root = $last;
1307             break;
1308         }
1309
1310         self::cacheSet($keypart, $root);
1311
1312         return $root;
1313     }
1314
1315     /**
1316      * Pull up a full list of local recipients who will be getting
1317      * this notice in their inbox. Results will be cached, so don't
1318      * change the input data wily-nilly!
1319      *
1320      * @param array $groups optional list of Group objects;
1321      *              if left empty, will be loaded from group_inbox records
1322      * @param array $recipient optional list of reply profile ids
1323      *              if left empty, will be loaded from reply records
1324      * @return array associating recipient user IDs with an inbox source constant
1325      */
1326     function whoGets(array $groups=null, array $recipients=null)
1327     {
1328         $c = self::memcache();
1329
1330         if (!empty($c)) {
1331             $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1332             if ($ni !== false) {
1333                 return $ni;
1334             }
1335         }
1336
1337         if (is_null($recipients)) {
1338             $recipients = $this->getReplies();
1339         }
1340
1341         $ni = array();
1342
1343         // Give plugins a chance to add folks in at start...
1344         if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1345
1346             $users = $this->getSubscribedUsers();
1347             foreach ($users as $id) {
1348                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1349             }
1350
1351             if (is_null($groups)) {
1352                 $groups = $this->getGroups();
1353             }
1354             foreach ($groups as $group) {
1355                 $users = $group->getUserMembers();
1356                 foreach ($users as $id) {
1357                     if (!array_key_exists($id, $ni)) {
1358                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1359                     }
1360                 }
1361             }
1362
1363             $ptAtts = $this->getAttentionsFromProfileTags();
1364             foreach ($ptAtts as $key=>$val) {
1365                 if (!array_key_exists($key, $ni)) {
1366                     $ni[$key] = $val;
1367                 }
1368             }
1369
1370             foreach ($recipients as $recipient) {
1371                 if (!array_key_exists($recipient, $ni)) {
1372                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1373                 }
1374             }
1375
1376             // Exclude any deleted, non-local, or blocking recipients.
1377             $profile = $this->getProfile();
1378             $originalProfile = null;
1379             if ($this->isRepeat()) {
1380                 // Check blocks against the original notice's poster as well.
1381                 $original = Notice::getKV('id', $this->repeat_of);
1382                 if ($original instanceof Notice) {
1383                     $originalProfile = $original->getProfile();
1384                 }
1385             }
1386
1387             foreach ($ni as $id => $source) {
1388                 try {
1389                     $user = User::getKV('id', $id);
1390                     if (!$user instanceof User ||
1391                         $user->hasBlocked($profile) ||
1392                         ($originalProfile && $user->hasBlocked($originalProfile))) {
1393                         unset($ni[$id]);
1394                     }
1395                 } catch (UserNoProfileException $e) {
1396                     // User doesn't have a profile; invalid; skip them.
1397                     unset($ni[$id]);
1398                 }
1399             }
1400
1401             // Give plugins a chance to filter out...
1402             Event::handle('EndNoticeWhoGets', array($this, &$ni));
1403         }
1404
1405         if (!empty($c)) {
1406             // XXX: pack this data better
1407             $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1408         }
1409
1410         return $ni;
1411     }
1412
1413     function getSubscribedUsers()
1414     {
1415         $user = new User();
1416
1417         if(common_config('db','quote_identifiers'))
1418           $user_table = '"user"';
1419         else $user_table = 'user';
1420
1421         $qry =
1422           'SELECT id ' .
1423           'FROM '. $user_table .' JOIN subscription '.
1424           'ON '. $user_table .'.id = subscription.subscriber ' .
1425           'WHERE subscription.subscribed = %d ';
1426
1427         $user->query(sprintf($qry, $this->profile_id));
1428
1429         $ids = array();
1430
1431         while ($user->fetch()) {
1432             $ids[] = $user->id;
1433         }
1434
1435         $user->free();
1436
1437         return $ids;
1438     }
1439
1440     function getProfileTags()
1441     {
1442         $profile = $this->getProfile();
1443         $list    = $profile->getOtherTags($profile);
1444         $ptags   = array();
1445
1446         while($list->fetch()) {
1447             $ptags[] = clone($list);
1448         }
1449
1450         return $ptags;
1451     }
1452
1453     public function getAttentionsFromProfileTags()
1454     {
1455         $ni = array();
1456         $ptags = $this->getProfileTags();
1457         foreach ($ptags as $ptag) {
1458             $users = $ptag->getUserSubscribers();
1459             foreach ($users as $id) {
1460                 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1461             }
1462         }
1463         return $ni;
1464     }
1465
1466     /**
1467      * Record this notice to the given group inboxes for delivery.
1468      * Overrides the regular parsing of !group markup.
1469      *
1470      * @param string $group_ids
1471      * @fixme might prefer URIs as identifiers, as for replies?
1472      *        best with generalizations on user_group to support
1473      *        remote groups better.
1474      */
1475     function saveKnownGroups($group_ids)
1476     {
1477         if (!is_array($group_ids)) {
1478             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1479             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1480         }
1481
1482         $groups = array();
1483         foreach (array_unique($group_ids) as $id) {
1484             $group = User_group::getKV('id', $id);
1485             if ($group instanceof User_group) {
1486                 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1487                 $result = $this->addToGroupInbox($group);
1488                 if (!$result) {
1489                     common_log_db_error($gi, 'INSERT', __FILE__);
1490                 }
1491
1492                 if (common_config('group', 'addtag')) {
1493                     // we automatically add a tag for every group name, too
1494
1495                     $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1496                                                      'notice_id' => $this->id));
1497
1498                     if (is_null($tag)) {
1499                         $this->saveTag($group->nickname);
1500                     }
1501                 }
1502
1503                 $groups[] = clone($group);
1504             } else {
1505                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1506             }
1507         }
1508
1509         return $groups;
1510     }
1511
1512     function addToGroupInbox(User_group $group)
1513     {
1514         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1515                                          'notice_id' => $this->id));
1516
1517         if (!$gi instanceof Group_inbox) {
1518
1519             $gi = new Group_inbox();
1520
1521             $gi->group_id  = $group->id;
1522             $gi->notice_id = $this->id;
1523             $gi->created   = $this->created;
1524
1525             $result = $gi->insert();
1526
1527             if (!$result) {
1528                 common_log_db_error($gi, 'INSERT', __FILE__);
1529                 // TRANS: Server exception thrown when an update for a group inbox fails.
1530                 throw new ServerException(_('Problem saving group inbox.'));
1531             }
1532
1533             self::blow('user_group:notice_ids:%d', $gi->group_id);
1534         }
1535
1536         return true;
1537     }
1538
1539     /**
1540      * Save reply records indicating that this notice needs to be
1541      * delivered to the local users with the given URIs.
1542      *
1543      * Since this is expected to be used when saving foreign-sourced
1544      * messages, we won't deliver to any remote targets as that's the
1545      * source service's responsibility.
1546      *
1547      * Mail notifications etc will be handled later.
1548      *
1549      * @param array  $uris   Array of unique identifier URIs for recipients
1550      */
1551     function saveKnownReplies(array $uris)
1552     {
1553         if (empty($uris)) {
1554             return;
1555         }
1556
1557         $sender = Profile::getKV($this->profile_id);
1558
1559         foreach (array_unique($uris) as $uri) {
1560             try {
1561                 $profile = Profile::fromUri($uri);
1562             } catch (UnknownUriException $e) {
1563                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1564                 continue;
1565             }
1566
1567             if ($profile->hasBlocked($sender)) {
1568                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1569                 continue;
1570             }
1571
1572             $this->saveReply($profile->id);
1573             self::blow('reply:stream:%d', $profile->id);
1574         }
1575
1576         return;
1577     }
1578
1579     /**
1580      * Pull @-replies from this message's content in StatusNet markup format
1581      * and save reply records indicating that this message needs to be
1582      * delivered to those users.
1583      *
1584      * Mail notifications to local profiles will be sent later.
1585      *
1586      * @return array of integer profile IDs
1587      */
1588
1589     function saveReplies()
1590     {
1591         // Don't save reply data for repeats
1592
1593         if ($this->isRepeat()) {
1594             return array();
1595         }
1596
1597         $sender = $this->getProfile();
1598
1599         $replied = array();
1600
1601         // If it's a reply, save for the replied-to author
1602         try {
1603             $parent = $this->getParent();
1604             $parentauthor = $parent->getProfile();
1605             $this->saveReply($parentauthor->id);
1606             $replied[$parentauthor->id] = 1;
1607             self::blow('reply:stream:%d', $parentauthor->id);
1608         } catch (NoParentNoticeException $e) {
1609             // Not a reply, since it has no parent!
1610         } catch (NoResultException $e) {
1611             // Parent notice was probably deleted
1612         }
1613
1614         // @todo ideally this parser information would only
1615         // be calculated once.
1616
1617         $mentions = common_find_mentions($this->content, $this);
1618
1619         // store replied only for first @ (what user/notice what the reply directed,
1620         // we assume first @ is it)
1621
1622         foreach ($mentions as $mention) {
1623
1624             foreach ($mention['mentioned'] as $mentioned) {
1625
1626                 // skip if they're already covered
1627                 if (array_key_exists($mentioned->id, $replied)) {
1628                     continue;
1629                 }
1630
1631                 // Don't save replies from blocked profile to local user
1632
1633                 $mentioned_user = User::getKV('id', $mentioned->id);
1634                 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1635                     continue;
1636                 }
1637
1638                 $this->saveReply($mentioned->id);
1639                 $replied[$mentioned->id] = 1;
1640                 self::blow('reply:stream:%d', $mentioned->id);
1641             }
1642         }
1643
1644         $recipientIds = array_keys($replied);
1645
1646         return $recipientIds;
1647     }
1648
1649     function saveReply($profileId)
1650     {
1651         $reply = new Reply();
1652
1653         $reply->notice_id  = $this->id;
1654         $reply->profile_id = $profileId;
1655         $reply->modified   = $this->created;
1656
1657         $reply->insert();
1658
1659         return $reply;
1660     }
1661
1662     protected $_replies = array();
1663
1664     /**
1665      * Pull the complete list of @-mentioned profile IDs for this notice.
1666      *
1667      * @return array of integer profile ids
1668      */
1669     function getReplies()
1670     {
1671         if (!isset($this->_replies[$this->getID()])) {
1672             $mentions = Reply::multiGet('notice_id', array($this->getID()));
1673             $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1674         }
1675         return $this->_replies[$this->getID()];
1676     }
1677
1678     function _setReplies($replies)
1679     {
1680         $this->_replies[$this->getID()] = $replies;
1681     }
1682
1683     /**
1684      * Pull the complete list of @-reply targets for this notice.
1685      *
1686      * @return array of Profiles
1687      */
1688     function getReplyProfiles()
1689     {
1690         $ids = $this->getReplies();
1691
1692         $profiles = Profile::multiGet('id', $ids);
1693
1694         return $profiles->fetchAll();
1695     }
1696
1697     /**
1698      * Send e-mail notifications to local @-reply targets.
1699      *
1700      * Replies must already have been saved; this is expected to be run
1701      * from the distrib queue handler.
1702      */
1703     function sendReplyNotifications()
1704     {
1705         // Don't send reply notifications for repeats
1706
1707         if ($this->isRepeat()) {
1708             return array();
1709         }
1710
1711         $recipientIds = $this->getReplies();
1712         if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1713             require_once INSTALLDIR.'/lib/mail.php';
1714
1715             foreach ($recipientIds as $recipientId) {
1716                 $user = User::getKV('id', $recipientId);
1717                 if ($user instanceof User) {
1718                     mail_notify_attn($user, $this);
1719                 }
1720             }
1721             Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1722         }
1723     }
1724
1725     /**
1726      * Pull list of groups this notice needs to be delivered to,
1727      * as previously recorded by saveKnownGroups().
1728      *
1729      * @return array of Group objects
1730      */
1731
1732     protected $_groups = array();
1733
1734     function getGroups()
1735     {
1736         // Don't save groups for repeats
1737
1738         if (!empty($this->repeat_of)) {
1739             return array();
1740         }
1741
1742         if (isset($this->_groups[$this->id])) {
1743             return $this->_groups[$this->id];
1744         }
1745
1746         $gis = Group_inbox::listGet('notice_id', array($this->id));
1747
1748         $ids = array();
1749
1750                 foreach ($gis[$this->id] as $gi) {
1751                     $ids[] = $gi->group_id;
1752                 }
1753
1754                 $groups = User_group::multiGet('id', $ids);
1755                 $this->_groups[$this->id] = $groups->fetchAll();
1756                 return $this->_groups[$this->id];
1757     }
1758
1759     function _setGroups($groups)
1760     {
1761         $this->_groups[$this->id] = $groups;
1762     }
1763
1764     /**
1765      * Convert a notice into an activity for export.
1766      *
1767      * @param Profile $scoped   The currently logged in/scoped profile
1768      *
1769      * @return Activity activity object representing this Notice.
1770      */
1771
1772     function asActivity(Profile $scoped=null)
1773     {
1774         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1775
1776         if ($act instanceof Activity) {
1777             return $act;
1778         }
1779         $act = new Activity();
1780
1781         if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1782
1783             $act->id      = $this->uri;
1784             $act->time    = strtotime($this->created);
1785             try {
1786                 $act->link    = $this->getUrl();
1787             } catch (InvalidUrlException $e) {
1788                 // The notice is probably a share or similar, which don't
1789                 // have a representational URL of their own.
1790             }
1791             $act->content = common_xml_safe_str($this->rendered);
1792
1793             $profile = $this->getProfile();
1794
1795             $act->actor            = $profile->asActivityObject();
1796             $act->actor->extra[]   = $profile->profileInfo($scoped);
1797
1798             $act->verb = $this->verb;
1799
1800             if (!$this->repeat_of) {
1801                 $act->objects[] = $this->asActivityObject();
1802             }
1803
1804             // XXX: should this be handled by default processing for object entry?
1805
1806             // Categories
1807
1808             $tags = $this->getTags();
1809
1810             foreach ($tags as $tag) {
1811                 $cat       = new AtomCategory();
1812                 $cat->term = $tag;
1813
1814                 $act->categories[] = $cat;
1815             }
1816
1817             // Enclosures
1818             // XXX: use Atom Media and/or File activity objects instead
1819
1820             $attachments = $this->attachments();
1821
1822             foreach ($attachments as $attachment) {
1823                 // Include local attachments in Activity
1824                 if (!empty($attachment->filename)) {
1825                     $act->enclosures[] = $attachment->getEnclosure();
1826                 }
1827             }
1828
1829             $ctx = new ActivityContext();
1830
1831             try {
1832                 $reply = $this->getParent();
1833                 $ctx->replyToID  = $reply->getUri();
1834                 $ctx->replyToUrl = $reply->getUrl(true);    // true for fallback to local URL, less messy
1835             } catch (NoParentNoticeException $e) {
1836                 // This is not a reply to something
1837             } catch (NoResultException $e) {
1838                 // Parent notice was probably deleted
1839             }
1840
1841             try {
1842                 $ctx->location = Notice_location::locFromStored($this);
1843             } catch (ServerException $e) {
1844                 $ctx->location = null;
1845             }
1846
1847             $conv = null;
1848
1849             if (!empty($this->conversation)) {
1850                 $conv = Conversation::getKV('id', $this->conversation);
1851                 if ($conv instanceof Conversation) {
1852                     $ctx->conversation = $conv->uri;
1853                 }
1854             }
1855
1856             $reply_ids = $this->getReplies();
1857
1858             foreach ($reply_ids as $id) {
1859                 $rprofile = Profile::getKV('id', $id);
1860                 if ($rprofile instanceof Profile) {
1861                     $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1862                 }
1863             }
1864
1865             $groups = $this->getGroups();
1866
1867             foreach ($groups as $group) {
1868                 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1869             }
1870
1871             switch ($this->scope) {
1872             case Notice::PUBLIC_SCOPE:
1873                 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1874                 break;
1875             case Notice::FOLLOWER_SCOPE:
1876                 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1877                 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1878                 break;
1879             }
1880
1881             $act->context = $ctx;
1882
1883             $source = $this->getSource();
1884
1885             if ($source instanceof Notice_source) {
1886                 $act->generator = ActivityObject::fromNoticeSource($source);
1887             }
1888
1889             // Source
1890
1891             $atom_feed = $profile->getAtomFeed();
1892
1893             if (!empty($atom_feed)) {
1894
1895                 $act->source = new ActivitySource();
1896
1897                 // XXX: we should store the actual feed ID
1898
1899                 $act->source->id = $atom_feed;
1900
1901                 // XXX: we should store the actual feed title
1902
1903                 $act->source->title = $profile->getBestName();
1904
1905                 $act->source->links['alternate'] = $profile->profileurl;
1906                 $act->source->links['self']      = $atom_feed;
1907
1908                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1909
1910                 $notice = $profile->getCurrentNotice();
1911
1912                 if ($notice instanceof Notice) {
1913                     $act->source->updated = self::utcDate($notice->created);
1914                 }
1915
1916                 $user = User::getKV('id', $profile->id);
1917
1918                 if ($user instanceof User) {
1919                     $act->source->links['license'] = common_config('license', 'url');
1920                 }
1921             }
1922
1923             if ($this->isLocal()) {
1924                 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1925                                                                            'format' => 'atom'));
1926                 $act->editLink = $act->selfLink;
1927             }
1928
1929             Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1930         }
1931
1932         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1933
1934         return $act;
1935     }
1936
1937     // This has gotten way too long. Needs to be sliced up into functional bits
1938     // or ideally exported to a utility class.
1939
1940     function asAtomEntry($namespace=false,
1941                          $source=false,
1942                          $author=true,
1943                          Profile $scoped=null)
1944     {
1945         $act = $this->asActivity($scoped);
1946         $act->extra[] = $this->noticeInfo($scoped);
1947         return $act->asString($namespace, $author, $source);
1948     }
1949
1950     /**
1951      * Extra notice info for atom entries
1952      *
1953      * Clients use some extra notice info in the atom stream.
1954      * This gives it to them.
1955      *
1956      * @param Profile $scoped   The currently logged in/scoped profile
1957      *
1958      * @return array representation of <statusnet:notice_info> element
1959      */
1960
1961     function noticeInfo(Profile $scoped=null)
1962     {
1963         // local notice ID (useful to clients for ordering)
1964
1965         $noticeInfoAttr = array('local_id' => $this->id);
1966
1967         // notice source
1968
1969         $ns = $this->getSource();
1970
1971         if ($ns instanceof Notice_source) {
1972             $noticeInfoAttr['source'] =  $ns->code;
1973             if (!empty($ns->url)) {
1974                 $noticeInfoAttr['source_link'] = $ns->url;
1975                 if (!empty($ns->name)) {
1976                     $noticeInfoAttr['source'] =  '<a href="'
1977                         . htmlspecialchars($ns->url)
1978                         . '" rel="nofollow">'
1979                         . htmlspecialchars($ns->name)
1980                         . '</a>';
1981                 }
1982             }
1983         }
1984
1985         // favorite and repeated
1986
1987         if ($scoped instanceof Profile) {
1988             $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
1989         }
1990
1991         if (!empty($this->repeat_of)) {
1992             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1993         }
1994
1995         Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
1996
1997         return array('statusnet:notice_info', $noticeInfoAttr, null);
1998     }
1999
2000     /**
2001      * Returns an XML string fragment with a reference to a notice as an
2002      * Activity Streams noun object with the given element type.
2003      *
2004      * Assumes that 'activity' namespace has been previously defined.
2005      *
2006      * @param string $element one of 'subject', 'object', 'target'
2007      * @return string
2008      */
2009
2010     function asActivityNoun($element)
2011     {
2012         $noun = $this->asActivityObject();
2013         return $noun->asString('activity:' . $element);
2014     }
2015
2016     public function asActivityObject()
2017     {
2018         $object = new ActivityObject();
2019
2020         if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2021             $object->type    = $this->object_type ?: ActivityObject::NOTE;
2022             $object->id      = $this->getUri();
2023             $object->title   = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2024             $object->content = $this->rendered;
2025             $object->link    = $this->getUrl();
2026
2027             $object->extra[] = array('status_net', array('notice_id' => $this->id));
2028
2029             Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2030         }
2031
2032         return $object;
2033     }
2034
2035     /**
2036      * Determine which notice, if any, a new notice is in reply to.
2037      *
2038      * For conversation tracking, we try to see where this notice fits
2039      * in the tree. Beware that this may very well give false positives
2040      * and add replies to wrong threads (if there have been newer posts
2041      * by the same user as we're replying to).
2042      *
2043      * @param Profile $sender     Author profile
2044      * @param string  $content    Final notice content
2045      *
2046      * @return integer ID of replied-to notice, or null for not a reply.
2047      */
2048
2049     static function getInlineReplyTo(Profile $sender, $content)
2050     {
2051         // Is there an initial @ or T?
2052         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2053                 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2054             $nickname = common_canonical_nickname($match[1]);
2055         } else {
2056             return null;
2057         }
2058
2059         // Figure out who that is.
2060         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2061
2062         if ($recipient instanceof Profile) {
2063             // Get their last notice
2064             $last = $recipient->getCurrentNotice();
2065             if ($last instanceof Notice) {
2066                 return $last;
2067             }
2068             // Maybe in the future we want to handle something else below
2069             // so don't return getCurrentNotice() immediately.
2070         }
2071
2072         return null;
2073     }
2074
2075     static function maxContent()
2076     {
2077         $contentlimit = common_config('notice', 'contentlimit');
2078         // null => use global limit (distinct from 0!)
2079         if (is_null($contentlimit)) {
2080             $contentlimit = common_config('site', 'textlimit');
2081         }
2082         return $contentlimit;
2083     }
2084
2085     static function contentTooLong($content)
2086     {
2087         $contentlimit = self::maxContent();
2088         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2089     }
2090
2091     /**
2092      * Convenience function for posting a repeat of an existing message.
2093      *
2094      * @param Profile $repeater Profile which is doing the repeat
2095      * @param string $source: posting source key, eg 'web', 'api', etc
2096      * @return Notice
2097      *
2098      * @throws Exception on failure or permission problems
2099      */
2100     function repeat(Profile $repeater, $source)
2101     {
2102         $author = $this->getProfile();
2103
2104         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2105         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2106         $content = sprintf(_('RT @%1$s %2$s'),
2107                            $author->getNickname(),
2108                            $this->content);
2109
2110         $maxlen = self::maxContent();
2111         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2112             // Web interface and current Twitter API clients will
2113             // pull the original notice's text, but some older
2114             // clients and RSS/Atom feeds will see this trimmed text.
2115             //
2116             // Unfortunately this is likely to lose tags or URLs
2117             // at the end of long notices.
2118             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2119         }
2120
2121
2122         // Scope is same as this one's
2123         return self::saveNew($repeater->id,
2124                              $content,
2125                              $source,
2126                              array('repeat_of' => $this->id,
2127                                    'scope' => $this->scope));
2128     }
2129
2130     // These are supposed to be in chron order!
2131
2132     function repeatStream($limit=100)
2133     {
2134         $cache = Cache::instance();
2135
2136         if (empty($cache)) {
2137             $ids = $this->_repeatStreamDirect($limit);
2138         } else {
2139             $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2140             if ($idstr !== false) {
2141                 if (empty($idstr)) {
2142                         $ids = array();
2143                 } else {
2144                         $ids = explode(',', $idstr);
2145                 }
2146             } else {
2147                 $ids = $this->_repeatStreamDirect(100);
2148                 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2149             }
2150             if ($limit < 100) {
2151                 // We do a max of 100, so slice down to limit
2152                 $ids = array_slice($ids, 0, $limit);
2153             }
2154         }
2155
2156         return NoticeStream::getStreamByIds($ids);
2157     }
2158
2159     function _repeatStreamDirect($limit)
2160     {
2161         $notice = new Notice();
2162
2163         $notice->selectAdd(); // clears it
2164         $notice->selectAdd('id');
2165
2166         $notice->repeat_of = $this->id;
2167
2168         $notice->orderBy('created, id'); // NB: asc!
2169
2170         if (!is_null($limit)) {
2171             $notice->limit(0, $limit);
2172         }
2173
2174         return $notice->fetchAll('id');
2175     }
2176
2177     static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2178     {
2179         $options = array();
2180
2181         if (!empty($location_id) && !empty($location_ns)) {
2182             $options['location_id'] = $location_id;
2183             $options['location_ns'] = $location_ns;
2184
2185             $location = Location::fromId($location_id, $location_ns);
2186
2187             if ($location instanceof Location) {
2188                 $options['lat'] = $location->lat;
2189                 $options['lon'] = $location->lon;
2190             }
2191
2192         } else if (!empty($lat) && !empty($lon)) {
2193             $options['lat'] = $lat;
2194             $options['lon'] = $lon;
2195
2196             $location = Location::fromLatLon($lat, $lon);
2197
2198             if ($location instanceof Location) {
2199                 $options['location_id'] = $location->location_id;
2200                 $options['location_ns'] = $location->location_ns;
2201             }
2202         } else if (!empty($profile)) {
2203             if (isset($profile->lat) && isset($profile->lon)) {
2204                 $options['lat'] = $profile->lat;
2205                 $options['lon'] = $profile->lon;
2206             }
2207
2208             if (isset($profile->location_id) && isset($profile->location_ns)) {
2209                 $options['location_id'] = $profile->location_id;
2210                 $options['location_ns'] = $profile->location_ns;
2211             }
2212         }
2213
2214         return $options;
2215     }
2216
2217     function clearAttentions()
2218     {
2219         $att = new Attention();
2220         $att->notice_id = $this->getID();
2221
2222         if ($att->find()) {
2223             while ($att->fetch()) {
2224                 // Can't do delete() on the object directly since it won't remove all of it
2225                 $other = clone($att);
2226                 $other->delete();
2227             }
2228         }
2229     }
2230
2231     function clearReplies()
2232     {
2233         $replyNotice = new Notice();
2234         $replyNotice->reply_to = $this->id;
2235
2236         //Null any notices that are replies to this notice
2237
2238         if ($replyNotice->find()) {
2239             while ($replyNotice->fetch()) {
2240                 $orig = clone($replyNotice);
2241                 $replyNotice->reply_to = null;
2242                 $replyNotice->update($orig);
2243             }
2244         }
2245
2246         // Reply records
2247
2248         $reply = new Reply();
2249         $reply->notice_id = $this->id;
2250
2251         if ($reply->find()) {
2252             while($reply->fetch()) {
2253                 self::blow('reply:stream:%d', $reply->profile_id);
2254                 $reply->delete();
2255             }
2256         }
2257
2258         $reply->free();
2259     }
2260
2261     function clearLocation()
2262     {
2263         $loc = new Notice_location();
2264         $loc->notice_id = $this->id;
2265
2266         if ($loc->find()) {
2267             $loc->delete();
2268         }
2269     }
2270
2271     function clearFiles()
2272     {
2273         $f2p = new File_to_post();
2274
2275         $f2p->post_id = $this->id;
2276
2277         if ($f2p->find()) {
2278             while ($f2p->fetch()) {
2279                 $f2p->delete();
2280             }
2281         }
2282         // FIXME: decide whether to delete File objects
2283         // ...and related (actual) files
2284     }
2285
2286     function clearRepeats()
2287     {
2288         $repeatNotice = new Notice();
2289         $repeatNotice->repeat_of = $this->id;
2290
2291         //Null any notices that are repeats of this notice
2292
2293         if ($repeatNotice->find()) {
2294             while ($repeatNotice->fetch()) {
2295                 $orig = clone($repeatNotice);
2296                 $repeatNotice->repeat_of = null;
2297                 $repeatNotice->update($orig);
2298             }
2299         }
2300     }
2301
2302     function clearTags()
2303     {
2304         $tag = new Notice_tag();
2305         $tag->notice_id = $this->id;
2306
2307         if ($tag->find()) {
2308             while ($tag->fetch()) {
2309                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2310                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2311                 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2312                 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2313                 $tag->delete();
2314             }
2315         }
2316
2317         $tag->free();
2318     }
2319
2320     function clearGroupInboxes()
2321     {
2322         $gi = new Group_inbox();
2323
2324         $gi->notice_id = $this->id;
2325
2326         if ($gi->find()) {
2327             while ($gi->fetch()) {
2328                 self::blow('user_group:notice_ids:%d', $gi->group_id);
2329                 $gi->delete();
2330             }
2331         }
2332
2333         $gi->free();
2334     }
2335
2336     function distribute()
2337     {
2338         // We always insert for the author so they don't
2339         // have to wait
2340         Event::handle('StartNoticeDistribute', array($this));
2341
2342         // If there's a failure, we want to _force_
2343         // distribution at this point.
2344         try {
2345             $qm = QueueManager::get();
2346             $qm->enqueue($this, 'distrib');
2347         } catch (Exception $e) {
2348             // If the exception isn't transient, this
2349             // may throw more exceptions as DQH does
2350             // its own enqueueing. So, we ignore them!
2351             try {
2352                 $handler = new DistribQueueHandler();
2353                 $handler->handle($this);
2354             } catch (Exception $e) {
2355                 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2356             }
2357             // Re-throw so somebody smarter can handle it.
2358             throw $e;
2359         }
2360     }
2361
2362     function insert()
2363     {
2364         $result = parent::insert();
2365
2366         if ($result === false) {
2367             common_log_db_error($this, 'INSERT', __FILE__);
2368             // TRANS: Server exception thrown when a stored object entry cannot be saved.
2369             throw new ServerException('Could not save Notice');
2370         }
2371
2372         // Profile::hasRepeated() abuses pkeyGet(), so we
2373         // have to clear manually
2374         if (!empty($this->repeat_of)) {
2375             $c = self::memcache();
2376             if (!empty($c)) {
2377                 $ck = self::multicacheKey('Notice',
2378                                           array('profile_id' => $this->profile_id,
2379                                                 'repeat_of' => $this->repeat_of));
2380                 $c->delete($ck);
2381             }
2382         }
2383
2384         // Update possibly ID-dependent columns: URI, conversation
2385         // (now that INSERT has added the notice's local id)
2386         $orig = clone($this);
2387         $changed = false;
2388
2389         // We can only get here if it's a local notice, since remote notices
2390         // should've bailed out earlier due to lacking a URI.
2391         if (empty($this->uri)) {
2392             $this->uri = sprintf('%s%s=%d:%s=%s',
2393                                 TagURI::mint(),
2394                                 'noticeId', $this->id,
2395                                 'objectType', $this->get_object_type(true));
2396             $changed = true;
2397         }
2398
2399         if ($changed && $this->update($orig) === false) {
2400             common_log_db_error($notice, 'UPDATE', __FILE__);
2401             // TRANS: Server exception thrown when a notice cannot be updated.
2402             throw new ServerException(_('Problem saving notice.'));
2403         }
2404
2405         $this->blowOnInsert();
2406
2407         return $result;
2408     }
2409
2410     /**
2411      * Get the source of the notice
2412      *
2413      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2414      *                           guaranteed to be populated.
2415      */
2416     function getSource()
2417     {
2418         if (empty($this->source)) {
2419             return false;
2420         }
2421
2422         $ns = new Notice_source();
2423         switch ($this->source) {
2424         case 'web':
2425         case 'xmpp':
2426         case 'mail':
2427         case 'omb':
2428         case 'system':
2429         case 'api':
2430             $ns->code = $this->source;
2431             break;
2432         default:
2433             $ns = Notice_source::getKV($this->source);
2434             if (!$ns) {
2435                 $ns = new Notice_source();
2436                 $ns->code = $this->source;
2437                 $app = Oauth_application::getKV('name', $this->source);
2438                 if ($app) {
2439                     $ns->name = $app->name;
2440                     $ns->url  = $app->source_url;
2441                 }
2442             }
2443             break;
2444         }
2445
2446         return $ns;
2447     }
2448
2449     /**
2450      * Determine whether the notice was locally created
2451      *
2452      * @return boolean locality
2453      */
2454
2455     public function isLocal()
2456     {
2457         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2458                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2459     }
2460
2461     public function isRepeat()
2462     {
2463         return !empty($this->repeat_of);
2464     }
2465
2466     /**
2467      * Get the list of hash tags saved with this notice.
2468      *
2469      * @return array of strings
2470      */
2471     public function getTags()
2472     {
2473         $tags = array();
2474
2475         $keypart = sprintf('notice:tags:%d', $this->id);
2476
2477         $tagstr = self::cacheGet($keypart);
2478
2479         if ($tagstr !== false) {
2480             $tags = explode(',', $tagstr);
2481         } else {
2482             $tag = new Notice_tag();
2483             $tag->notice_id = $this->id;
2484             if ($tag->find()) {
2485                 while ($tag->fetch()) {
2486                     $tags[] = $tag->tag;
2487                 }
2488             }
2489             self::cacheSet($keypart, implode(',', $tags));
2490         }
2491
2492         return $tags;
2493     }
2494
2495     static private function utcDate($dt)
2496     {
2497         $dateStr = date('d F Y H:i:s', strtotime($dt));
2498         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2499         return $d->format(DATE_W3C);
2500     }
2501
2502     /**
2503      * Look up the creation timestamp for a given notice ID, even
2504      * if it's been deleted.
2505      *
2506      * @param int $id
2507      * @return mixed string recorded creation timestamp, or false if can't be found
2508      */
2509     public static function getAsTimestamp($id)
2510     {
2511         if (!$id) {
2512             return false;
2513         }
2514
2515         $notice = Notice::getKV('id', $id);
2516         if ($notice) {
2517             return $notice->created;
2518         }
2519
2520         $deleted = Deleted_notice::getKV('id', $id);
2521         if ($deleted) {
2522             return $deleted->created;
2523         }
2524
2525         return false;
2526     }
2527
2528     /**
2529      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2530      * parameter, matching notices posted after the given one (exclusive).
2531      *
2532      * If the referenced notice can't be found, will return false.
2533      *
2534      * @param int $id
2535      * @param string $idField
2536      * @param string $createdField
2537      * @return mixed string or false if no match
2538      */
2539     public static function whereSinceId($id, $idField='id', $createdField='created')
2540     {
2541         $since = Notice::getAsTimestamp($id);
2542         if ($since) {
2543             return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2544         }
2545         return false;
2546     }
2547
2548     /**
2549      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2550      * parameter, matching notices posted after the given one (exclusive), and
2551      * if necessary add it to the data object's query.
2552      *
2553      * @param DB_DataObject $obj
2554      * @param int $id
2555      * @param string $idField
2556      * @param string $createdField
2557      * @return mixed string or false if no match
2558      */
2559     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2560     {
2561         $since = self::whereSinceId($id, $idField, $createdField);
2562         if ($since) {
2563             $obj->whereAdd($since);
2564         }
2565     }
2566
2567     /**
2568      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2569      * parameter, matching notices posted before the given one (inclusive).
2570      *
2571      * If the referenced notice can't be found, will return false.
2572      *
2573      * @param int $id
2574      * @param string $idField
2575      * @param string $createdField
2576      * @return mixed string or false if no match
2577      */
2578     public static function whereMaxId($id, $idField='id', $createdField='created')
2579     {
2580         $max = Notice::getAsTimestamp($id);
2581         if ($max) {
2582             return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2583         }
2584         return false;
2585     }
2586
2587     /**
2588      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2589      * parameter, matching notices posted before the given one (inclusive), and
2590      * if necessary add it to the data object's query.
2591      *
2592      * @param DB_DataObject $obj
2593      * @param int $id
2594      * @param string $idField
2595      * @param string $createdField
2596      * @return mixed string or false if no match
2597      */
2598     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2599     {
2600         $max = self::whereMaxId($id, $idField, $createdField);
2601         if ($max) {
2602             $obj->whereAdd($max);
2603         }
2604     }
2605
2606     function isPublic()
2607     {
2608         return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2609                 ($this->is_local != Notice::GATEWAY));
2610     }
2611
2612     /**
2613      * Check that the given profile is allowed to read, respond to, or otherwise
2614      * act on this notice.
2615      *
2616      * The $scope member is a bitmask of scopes, representing a logical AND of the
2617      * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2618      * "only visible to people who are mentioned in the notice AND are users on this site."
2619      * Users on the site who are not mentioned in the notice will not be able to see the
2620      * notice.
2621      *
2622      * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2623      *
2624      * @return boolean whether the profile is in the notice's scope
2625      */
2626     function inScope($profile)
2627     {
2628         if (is_null($profile)) {
2629             $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2630         } else {
2631             $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2632         }
2633
2634         $result = self::cacheGet($keypart);
2635
2636         if ($result === false) {
2637             $bResult = false;
2638             if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2639                 $bResult = $this->_inScope($profile);
2640                 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2641             }
2642             $result = ($bResult) ? 1 : 0;
2643             self::cacheSet($keypart, $result, 0, 300);
2644         }
2645
2646         return ($result == 1) ? true : false;
2647     }
2648
2649     protected function _inScope($profile)
2650     {
2651         if (!is_null($this->scope)) {
2652             $scope = $this->scope;
2653         } else {
2654             $scope = self::defaultScope();
2655         }
2656
2657         if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2658             return !$this->isHiddenSpam($profile);
2659         }
2660
2661         // If there's scope, anon cannot be in scope
2662         if (empty($profile)) {
2663             return false;
2664         }
2665
2666         // Author is always in scope
2667         if ($this->profile_id == $profile->id) {
2668             return true;
2669         }
2670
2671         // Only for users on this site
2672         if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2673             return false;
2674         }
2675
2676         // Only for users mentioned in the notice
2677         if ($scope & Notice::ADDRESSEE_SCOPE) {
2678
2679             $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2680                                          'profile_id' => $profile->id));
2681
2682             if (!$reply instanceof Reply) {
2683                 return false;
2684             }
2685         }
2686
2687         // Only for members of the given group
2688         if ($scope & Notice::GROUP_SCOPE) {
2689
2690             // XXX: just query for the single membership
2691
2692             $groups = $this->getGroups();
2693
2694             $foundOne = false;
2695
2696             foreach ($groups as $group) {
2697                 if ($profile->isMember($group)) {
2698                     $foundOne = true;
2699                     break;
2700                 }
2701             }
2702
2703             if (!$foundOne) {
2704                 return false;
2705             }
2706         }
2707
2708         if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2709
2710             if (!Subscription::exists($profile, $this->getProfile())) {
2711                 return false;
2712             }
2713         }
2714
2715         return !$this->isHiddenSpam($profile);
2716     }
2717
2718     function isHiddenSpam($profile) {
2719
2720         // Hide posts by silenced users from everyone but moderators.
2721
2722         if (common_config('notice', 'hidespam')) {
2723
2724             try {
2725                 $author = $this->getProfile();
2726             } catch(Exception $e) {
2727                 // If we can't get an author, keep it hidden.
2728                 // XXX: technically not spam, but, whatever.
2729                 return true;
2730             }
2731
2732             if ($author->hasRole(Profile_role::SILENCED)) {
2733                 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2734                     return true;
2735                 }
2736             }
2737         }
2738
2739         return false;
2740     }
2741
2742     public function getParent()
2743     {
2744         if (empty($this->reply_to)) {
2745             throw new NoParentNoticeException($this);
2746         }
2747         return self::getByID($this->reply_to);
2748     }
2749
2750     /**
2751      * Magic function called at serialize() time.
2752      *
2753      * We use this to drop a couple process-specific references
2754      * from DB_DataObject which can cause trouble in future
2755      * processes.
2756      *
2757      * @return array of variable names to include in serialization.
2758      */
2759
2760     function __sleep()
2761     {
2762         $vars = parent::__sleep();
2763         $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2764         return array_diff($vars, $skip);
2765     }
2766
2767     static function defaultScope()
2768     {
2769         $scope = common_config('notice', 'defaultscope');
2770         if (is_null($scope)) {
2771                 if (common_config('site', 'private')) {
2772                         $scope = 1;
2773                 } else {
2774                         $scope = 0;
2775                 }
2776         }
2777         return $scope;
2778     }
2779
2780         static function fillProfiles($notices)
2781         {
2782                 $map = self::getProfiles($notices);
2783                 foreach ($notices as $entry=>$notice) {
2784             try {
2785                         if (array_key_exists($notice->profile_id, $map)) {
2786                                 $notice->_setProfile($map[$notice->profile_id]);
2787                         }
2788             } catch (NoProfileException $e) {
2789                 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2790                 unset($notices[$entry]);
2791             }
2792                 }
2793
2794                 return array_values($map);
2795         }
2796
2797         static function getProfiles(&$notices)
2798         {
2799                 $ids = array();
2800                 foreach ($notices as $notice) {
2801                         $ids[] = $notice->profile_id;
2802                 }
2803                 $ids = array_unique($ids);
2804                 return Profile::pivotGet('id', $ids);
2805         }
2806
2807         static function fillGroups(&$notices)
2808         {
2809         $ids = self::_idsOf($notices);
2810         $gis = Group_inbox::listGet('notice_id', $ids);
2811         $gids = array();
2812
2813                 foreach ($gis as $id => $gi) {
2814                     foreach ($gi as $g)
2815                     {
2816                         $gids[] = $g->group_id;
2817                     }
2818                 }
2819
2820                 $gids = array_unique($gids);
2821                 $group = User_group::pivotGet('id', $gids);
2822                 foreach ($notices as $notice)
2823                 {
2824                         $grps = array();
2825                         $gi = $gis[$notice->id];
2826                         foreach ($gi as $g) {
2827                             $grps[] = $group[$g->group_id];
2828                         }
2829                     $notice->_setGroups($grps);
2830                 }
2831         }
2832
2833     static function _idsOf(array &$notices)
2834     {
2835                 $ids = array();
2836                 foreach ($notices as $notice) {
2837                         $ids[$notice->id] = true;
2838                 }
2839                 return array_keys($ids);
2840     }
2841
2842     static function fillAttachments(&$notices)
2843     {
2844         $ids = self::_idsOf($notices);
2845         $f2pMap = File_to_post::listGet('post_id', $ids);
2846                 $fileIds = array();
2847                 foreach ($f2pMap as $noticeId => $f2ps) {
2848             foreach ($f2ps as $f2p) {
2849                 $fileIds[] = $f2p->file_id;
2850             }
2851         }
2852
2853         $fileIds = array_unique($fileIds);
2854                 $fileMap = File::pivotGet('id', $fileIds);
2855                 foreach ($notices as $notice)
2856                 {
2857                         $files = array();
2858                         $f2ps = $f2pMap[$notice->id];
2859                         foreach ($f2ps as $f2p) {
2860                             $files[] = $fileMap[$f2p->file_id];
2861                         }
2862                     $notice->_setAttachments($files);
2863                 }
2864     }
2865
2866     static function fillReplies(&$notices)
2867     {
2868         $ids = self::_idsOf($notices);
2869         $replyMap = Reply::listGet('notice_id', $ids);
2870         foreach ($notices as $notice) {
2871             $replies = $replyMap[$notice->id];
2872             $ids = array();
2873             foreach ($replies as $reply) {
2874                 $ids[] = $reply->profile_id;
2875             }
2876             $notice->_setReplies($ids);
2877         }
2878     }
2879
2880     static public function beforeSchemaUpdate()
2881     {
2882         $table = strtolower(get_called_class());
2883         $schema = Schema::get();
2884         $schemadef = $schema->getTableDef($table);
2885
2886         // 2015-09-04 We move Notice location data to Notice_location
2887         // First we see if we have to do this at all
2888         if (!isset($schemadef['fields']['lat'])
2889                 && !isset($schemadef['fields']['lon'])
2890                 && !isset($schemadef['fields']['location_id'])
2891                 && !isset($schemadef['fields']['location_ns'])) {
2892             // We have already removed the location fields, so no need to migrate.
2893             return;
2894         }
2895         // Then we make sure the Notice_location table is created!
2896         $schema->ensureTable('notice_location', Notice_location::schemaDef());
2897
2898         // Then we continue on our road to migration!
2899         echo "\nFound old $table table, moving location data to 'notice_location' table... (this will probably take a LONG time, but can be aborted and continued)";
2900
2901         $notice = new Notice();
2902         $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
2903                              'WHERE lat IS NOT NULL ' .
2904                                 'OR lon IS NOT NULL ' .
2905                                 'OR location_id IS NOT NULL ' .
2906                                 'OR location_ns IS NOT NULL',
2907                              $schema->quoteIdentifier($table)));
2908         print "\nFound {$notice->N} notices with location data, inserting";
2909         while ($notice->fetch()) {
2910             $notloc = Notice_location::getKV('notice_id', $notice->id);
2911             if ($notloc instanceof Notice_location) {
2912                 print "-";
2913                 continue;
2914             }
2915             $notloc = new Notice_location();
2916             $notloc->notice_id = $notice->id;
2917             $notloc->lat= $notice->lat;
2918             $notloc->lon= $notice->lon;
2919             $notloc->location_id= $notice->location_id;
2920             $notloc->location_ns= $notice->location_ns;
2921             $notloc->insert();
2922             print ".";
2923         }
2924         print "\n";
2925     }
2926 }