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