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