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