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