]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Ostatus_profile.php
Merge remote-tracking branch 'upstream/master' into social-master
[quix0rs-gnu-social.git] / plugins / OStatus / classes / Ostatus_profile.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009-2010, 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
20 if (!defined('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * @package OStatusPlugin
24  * @author Brion Vibber <brion@status.net>
25  * @maintainer Mikael Nordfeldth <mmn@hethane.se>
26  */
27 class Ostatus_profile extends Managed_DataObject
28 {
29     public $__table = 'ostatus_profile';
30
31     public $uri;
32
33     public $profile_id;
34     public $group_id;
35     public $peopletag_id;
36
37     public $feeduri;
38     public $salmonuri;
39     public $avatar; // remote URL of the last avatar we saved
40
41     public $created;
42     public $modified;
43
44     /**
45      * Return table definition for Schema setup and DB_DataObject usage.
46      *
47      * @return array array of column definitions
48      */
49     static function schemaDef()
50     {
51         return array(
52             'fields' => array(
53                 'uri' => array('type' => 'varchar', 'length' => 191, 'not null' => true),
54                 'profile_id' => array('type' => 'integer'),
55                 'group_id' => array('type' => 'integer'),
56                 'peopletag_id' => array('type' => 'integer'),
57                 'feeduri' => array('type' => 'varchar', 'length' => 191),
58                 'salmonuri' => array('type' => 'varchar', 'length' => 191),
59                 'avatar' => array('type' => 'text'),
60                 'created' => array('type' => 'datetime', 'not null' => true),
61                 'modified' => array('type' => 'datetime', 'not null' => true),
62             ),
63             'primary key' => array('uri'),
64             'unique keys' => array(
65                 'ostatus_profile_profile_id_key' => array('profile_id'),
66                 'ostatus_profile_group_id_key' => array('group_id'),
67                 'ostatus_profile_peopletag_id_key' => array('peopletag_id'),
68                 'ostatus_profile_feeduri_key' => array('feeduri'),
69             ),
70             'foreign keys' => array(
71                 'ostatus_profile_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
72                 'ostatus_profile_group_id_fkey' => array('user_group', array('group_id' => 'id')),
73                 'ostatus_profile_peopletag_id_fkey' => array('profile_list', array('peopletag_id' => 'id')),
74             ),
75         );
76     }
77
78     public function getUri()
79     {
80         return $this->uri;
81     }
82
83     public function fromProfile(Profile $profile)
84     {
85         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
86         if (!$oprofile instanceof Ostatus_profile) {
87             throw new Exception('No Ostatus_profile for Profile ID: '.$profile->id);
88         }
89     }
90
91     /**
92      * Fetch the locally stored profile for this feed
93      * @return Profile
94      * @throws NoProfileException if it was not found
95      */
96     public function localProfile()
97     {
98         if ($this->isGroup()) {
99             return $this->localGroup()->getProfile();
100         }
101
102         $profile = Profile::getKV('id', $this->profile_id);
103         if (!$profile instanceof Profile) {
104             throw new NoProfileException($this->profile_id);
105         }
106         return $profile;
107     }
108
109     /**
110      * Fetch the StatusNet-side profile for this feed
111      * @return Profile
112      */
113     public function localGroup()
114     {
115         $group = User_group::getKV('id', $this->group_id);
116
117         if (!$group instanceof User_group) {
118             throw new NoSuchGroupException(array('id'=>$this->group_id));
119         }
120
121         return $group;
122     }
123
124     /**
125      * Fetch the StatusNet-side peopletag for this feed
126      * @return Profile
127      */
128     public function localPeopletag()
129     {
130         if ($this->peopletag_id) {
131             return Profile_list::getKV('id', $this->peopletag_id);
132         }
133         return null;
134     }
135
136     /**
137      * Returns an ActivityObject describing this remote user or group profile.
138      * Can then be used to generate Atom chunks.
139      *
140      * @return ActivityObject
141      */
142     function asActivityObject()
143     {
144         if ($this->isGroup()) {
145             return ActivityObject::fromGroup($this->localGroup());
146         } else if ($this->isPeopletag()) {
147             return ActivityObject::fromPeopletag($this->localPeopletag());
148         } else {
149             return $this->localProfile()->asActivityObject();
150         }
151     }
152
153     /**
154      * Returns an XML string fragment with profile information as an
155      * Activity Streams noun object with the given element type.
156      *
157      * Assumes that 'activity' namespace has been previously defined.
158      *
159      * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
160      *
161      * @param string $element one of 'actor', 'subject', 'object', 'target'
162      * @return string
163      */
164     function asActivityNoun($element)
165     {
166         if ($this->isGroup()) {
167             $noun = ActivityObject::fromGroup($this->localGroup());
168             return $noun->asString('activity:' . $element);
169         } else if ($this->isPeopletag()) {
170             $noun = ActivityObject::fromPeopletag($this->localPeopletag());
171             return $noun->asString('activity:' . $element);
172         } else {
173             $noun = $this->localProfile()->asActivityObject();
174             return $noun->asString('activity:' . $element);
175         }
176     }
177
178     /**
179      * @return boolean true if this is a remote group
180      */
181     function isGroup()
182     {
183         if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
184             return false;
185         } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
186             return true;
187         } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
188             // TRANS: Server exception. %s is a URI
189             throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
190         } else {
191             // TRANS: Server exception. %s is a URI
192             throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
193         }
194     }
195
196     /**
197      * @return boolean true if this is a remote peopletag
198      */
199     function isPeopletag()
200     {
201         if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
202             return false;
203         } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
204             return true;
205         } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
206             // TRANS: Server exception. %s is a URI
207             throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
208         } else {
209             // TRANS: Server exception. %s is a URI
210             throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
211         }
212     }
213
214     /**
215      * Send a subscription request to the hub for this feed.
216      * The hub will later send us a confirmation POST to /main/push/callback.
217      *
218      * @return void
219      * @throws ServerException if feed state is not valid or subscription fails.
220      */
221     public function subscribe()
222     {
223         $feedsub = FeedSub::ensureFeed($this->feeduri);
224         if ($feedsub->sub_state == 'active') {
225             // Active subscription, we don't need to do anything.
226             return;
227         }
228
229         // Inactive or we got left in an inconsistent state.
230         // Run a subscription request to make sure we're current!
231         return $feedsub->subscribe();
232     }
233
234     /**
235      * Check if this remote profile has any active local subscriptions, and
236      * if not drop the PuSH subscription feed.
237      *
238      * @return boolean true if subscription is removed, false if there are still subscribers to the feed
239      * @throws Exception of various kinds on failure.
240      */
241     public function unsubscribe() {
242         return $this->garbageCollect();
243     }
244
245     /**
246      * Check if this remote profile has any active local subscriptions, and
247      * if not drop the PuSH subscription feed.
248      *
249      * @return boolean true if subscription is removed, false if there are still subscribers to the feed
250      * @throws Exception of various kinds on failure.
251      */
252     public function garbageCollect()
253     {
254         $feedsub = FeedSub::getKV('uri', $this->feeduri);
255         if ($feedsub instanceof FeedSub) {
256             return $feedsub->garbageCollect();
257         }
258         // Since there's no FeedSub we can assume it's already garbage collected
259         return true;
260     }
261
262     /**
263      * Check if this remote profile has any active local subscriptions, so the
264      * PuSH subscription layer can decide if it can drop the feed.
265      *
266      * This gets called via the FeedSubSubscriberCount event when running
267      * FeedSub::garbageCollect().
268      *
269      * @return int
270      * @throws NoProfileException if there is no local profile for the object
271      */
272     public function subscriberCount()
273     {
274         if ($this->isGroup()) {
275             $members = $this->localGroup()->getMembers(0, 1);
276             $count = $members->N;
277         } else if ($this->isPeopletag()) {
278             $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
279             $count = $subscribers->N;
280         } else {
281             $profile = $this->localProfile();
282             if ($profile->hasLocalTags()) {
283                 $count = 1;
284             } else {
285                 $count = $profile->subscriberCount();
286             }
287         }
288         common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
289
290         // Other plugins may be piggybacking on OStatus without having
291         // an active group or user-to-user subscription we know about.
292         Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
293         common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
294
295         return $count;
296     }
297
298     /**
299      * Send an Activity Streams notification to the remote Salmon endpoint,
300      * if so configured.
301      *
302      * @param Profile $actor  Actor who did the activity
303      * @param string  $verb   Activity::SUBSCRIBE or Activity::JOIN
304      * @param Object  $object object of the action; must define asActivityNoun($tag)
305      */
306     public function notify(Profile $actor, $verb, $object=null, $target=null)
307     {
308         if ($object == null) {
309             $object = $this;
310         }
311         if (empty($this->salmonuri)) {
312             return false;
313         }
314         $text = 'update';
315         $id = TagURI::mint('%s:%s:%s',
316                            $verb,
317                            $actor->getURI(),
318                            common_date_iso8601(time()));
319
320         // @todo FIXME: Consolidate all these NS settings somewhere.
321         $attributes = array('xmlns' => Activity::ATOM,
322                             'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
323                             'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
324                             'xmlns:georss' => 'http://www.georss.org/georss',
325                             'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
326                             'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
327                             'xmlns:media' => 'http://purl.org/syndication/atommedia');
328
329         $entry = new XMLStringer();
330         $entry->elementStart('entry', $attributes);
331         $entry->element('id', null, $id);
332         $entry->element('title', null, $text);
333         $entry->element('summary', null, $text);
334         $entry->element('published', null, common_date_w3dtf(common_sql_now()));
335
336         $entry->element('activity:verb', null, $verb);
337         $entry->raw($actor->asAtomAuthor());
338         $entry->raw($actor->asActivityActor());
339         $entry->raw($object->asActivityNoun('object'));
340         if ($target != null) {
341             $entry->raw($target->asActivityNoun('target'));
342         }
343         $entry->elementEnd('entry');
344
345         $xml = $entry->getString();
346         common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
347
348         Salmon::post($this->salmonuri, $xml, $actor->getUser());
349     }
350
351     /**
352      * Send a Salmon notification ping immediately, and confirm that we got
353      * an acceptable response from the remote site.
354      *
355      * @param mixed $entry XML string, Notice, or Activity
356      * @param Profile $actor
357      * @return boolean success
358      */
359     public function notifyActivity($entry, Profile $actor)
360     {
361         if ($this->salmonuri) {
362             return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor->getUser());
363         }
364         common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
365
366         return false;
367     }
368
369     /**
370      * Queue a Salmon notification for later. If queues are disabled we'll
371      * send immediately but won't get the return value.
372      *
373      * @param mixed $entry XML string, Notice, or Activity
374      * @param Profile $actor Acting profile
375      * @return boolean success
376      */
377     public function notifyDeferred($entry, Profile $actor)
378     {
379         if ($this->salmonuri) {
380             $data = array('salmonuri' => $this->salmonuri,
381                           'entry' => $this->notifyPrepXml($entry),
382                           'actor' => $actor->id);
383
384             $qm = QueueManager::get();
385             return $qm->enqueue($data, 'salmon');
386         }
387
388         return false;
389     }
390
391     protected function notifyPrepXml($entry)
392     {
393         $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
394         if (is_string($entry)) {
395             return $entry;
396         } else if ($entry instanceof Activity) {
397             return $preamble . $entry->asString(true);
398         } else if ($entry instanceof Notice) {
399             return $preamble . $entry->asAtomEntry(true, true);
400         } else {
401             // TRANS: Server exception.
402             throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
403         }
404     }
405
406     function getBestName()
407     {
408         if ($this->isGroup()) {
409             return $this->localGroup()->getBestName();
410         } else if ($this->isPeopletag()) {
411             return $this->localPeopletag()->getBestName();
412         } else {
413             return $this->localProfile()->getBestName();
414         }
415     }
416
417     /**
418      * Read and post notices for updates from the feed.
419      * Currently assumes that all items in the feed are new,
420      * coming from a PuSH hub.
421      *
422      * @param DOMDocument $doc
423      * @param string $source identifier ("push")
424      */
425     public function processFeed(DOMDocument $doc, $source)
426     {
427         $feed = $doc->documentElement;
428
429         if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
430             $this->processAtomFeed($feed, $source);
431         } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
432             $this->processRssFeed($feed, $source);
433         } else {
434             // TRANS: Exception.
435             throw new Exception(_m('Unknown feed format.'));
436         }
437     }
438
439     public function processAtomFeed(DOMElement $feed, $source)
440     {
441         $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
442         if ($entries->length == 0) {
443             common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
444             return;
445         }
446
447         for ($i = 0; $i < $entries->length; $i++) {
448             $entry = $entries->item($i);
449             $this->processEntry($entry, $feed, $source);
450         }
451     }
452
453     public function processRssFeed(DOMElement $rss, $source)
454     {
455         $channels = $rss->getElementsByTagName('channel');
456
457         if ($channels->length == 0) {
458             // TRANS: Exception.
459             throw new Exception(_m('RSS feed without a channel.'));
460         } else if ($channels->length > 1) {
461             common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
462         }
463
464         $channel = $channels->item(0);
465
466         $items = $channel->getElementsByTagName('item');
467
468         for ($i = 0; $i < $items->length; $i++) {
469             $item = $items->item($i);
470             $this->processEntry($item, $channel, $source);
471         }
472     }
473
474     /**
475      * Process a posted entry from this feed source.
476      *
477      * @param DOMElement $entry
478      * @param DOMElement $feed for context
479      * @param string $source identifier ("push" or "salmon")
480      *
481      * @return Notice Notice representing the new (or existing) activity
482      */
483     public function processEntry(DOMElement $entry, DOMElement $feed, $source)
484     {
485         $activity = new Activity($entry, $feed);
486         return $this->processActivity($activity, $source);
487     }
488
489     // TODO: Make this throw an exception
490     public function processActivity(Activity $activity, $source)
491     {
492         $notice = null;
493
494         // The "WithProfile" events were added later.
495
496         if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
497             Event::handle('StartHandleFeedEntry', array($activity))) {
498
499             switch ($activity->verb) {
500             case ActivityVerb::POST:
501                 // @todo process all activity objects
502                 switch ($activity->objects[0]->type) {
503                 case ActivityObject::ARTICLE:
504                 case ActivityObject::BLOGENTRY:
505                 case ActivityObject::NOTE:
506                 case ActivityObject::STATUS:
507                 case ActivityObject::COMMENT:
508                 case null:
509                     $notice = $this->processPost($activity, $source);
510                     break;
511                 default:
512                     // TRANS: Client exception.
513                     throw new ClientException(_m('Cannot handle that kind of post.'));
514                 }
515                 break;
516             default:
517                 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
518             }
519
520             Event::handle('EndHandleFeedEntry', array($activity));
521             Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
522         }
523
524         return $notice;
525     }
526
527     /**
528      * Process an incoming post activity from this remote feed.
529      * @param Activity $activity
530      * @param string $method 'push' or 'salmon'
531      * @return mixed saved Notice or false
532      * @todo FIXME: Break up this function, it's getting nasty long
533      */
534     public function processPost(Activity $activity, $method)
535     {
536         $notice = null;
537
538         $profile = ActivityUtils::checkAuthorship($activity, $this->localProfile());
539
540         // It's not always an ActivityObject::NOTE, but... let's just say it is.
541
542         $note = $activity->objects[0];
543
544         // The id URI will be used as a unique identifier for the notice,
545         // protecting against duplicate saves. It isn't required to be a URL;
546         // tag: URIs for instance are found in Google Buzz feeds.
547         $sourceUri = $note->id;
548         $dupe = Notice::getKV('uri', $sourceUri);
549         if ($dupe instanceof Notice) {
550             common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
551             return $dupe;
552         }
553
554         // We'll also want to save a web link to the original notice, if provided.
555         $sourceUrl = null;
556         if ($note->link) {
557             $sourceUrl = $note->link;
558         } else if ($activity->link) {
559             $sourceUrl = $activity->link;
560         } else if (preg_match('!^https?://!', $note->id)) {
561             $sourceUrl = $note->id;
562         }
563
564         // Use summary as fallback for content
565
566         if (!empty($note->content)) {
567             $sourceContent = $note->content;
568         } else if (!empty($note->summary)) {
569             $sourceContent = $note->summary;
570         } else if (!empty($note->title)) {
571             $sourceContent = $note->title;
572         } else {
573             // @todo FIXME: Fetch from $sourceUrl?
574             // TRANS: Client exception. %s is a source URI.
575             throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
576         }
577
578         // Get (safe!) HTML and text versions of the content
579
580         $rendered = common_purify($sourceContent);
581         $content = common_strip_html($rendered);
582
583         $shortened = common_shorten_links($content);
584
585         // If it's too long, try using the summary, and make the
586         // HTML an attachment.
587
588         $attachment = null;
589
590         if (Notice::contentTooLong($shortened)) {
591             $attachment = $this->saveHTMLFile($note->title, $rendered);
592             $summary = common_strip_html($note->summary);
593             if (empty($summary)) {
594                 $summary = $content;
595             }
596             $shortSummary = common_shorten_links($summary);
597             if (Notice::contentTooLong($shortSummary)) {
598                 $url = common_shorten_url($sourceUrl);
599                 $shortSummary = substr($shortSummary,
600                                        0,
601                                        Notice::maxContent() - (mb_strlen($url) + 2));
602                 $content = $shortSummary . ' ' . $url;
603
604                 // We mark up the attachment link specially for the HTML output
605                 // so we can fold-out the full version inline.
606
607                 // @todo FIXME i18n: This tooltip will be saved with the site's default language
608                 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
609                 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
610                 $showMoreText = _m('Show more');
611                 $attachUrl = common_local_url('attachment',
612                                               array('attachment' => $attachment->id));
613                 $rendered = common_render_text($shortSummary) .
614                             '<a href="' . htmlspecialchars($attachUrl) .'"'.
615                             ' class="attachment more"' .
616                             ' title="'. htmlspecialchars($showMoreText) . '">' .
617                             '&#8230;' .
618                             '</a>';
619             }
620         }
621
622         $options = array('is_local' => Notice::REMOTE,
623                         'url' => $sourceUrl,
624                         'uri' => $sourceUri,
625                         'rendered' => $rendered,
626                         'replies' => array(),
627                         'groups' => array(),
628                         'peopletags' => array(),
629                         'tags' => array(),
630                         'urls' => array());
631
632         // Check for optional attributes...
633
634         if (!empty($activity->time)) {
635             $options['created'] = common_sql_date($activity->time);
636         }
637
638         if ($activity->context) {
639             // TODO: context->attention
640             list($options['groups'], $options['replies'])
641                 = self::filterAttention($profile, $activity->context->attention);
642
643             // Maintain direct reply associations
644             // @todo FIXME: What about conversation ID?
645             if (!empty($activity->context->replyToID)) {
646                 $orig = Notice::getKV('uri', $activity->context->replyToID);
647                 if ($orig instanceof Notice) {
648                     $options['reply_to'] = $orig->id;
649                 }
650             }
651             if (!empty($activity->context->conversation)) {
652                 // we store the URI here, Notice class can look it up later
653                 $options['conversation'] = $activity->context->conversation;
654             }
655
656             $location = $activity->context->location;
657             if ($location) {
658                 $options['lat'] = $location->lat;
659                 $options['lon'] = $location->lon;
660                 if ($location->location_id) {
661                     $options['location_ns'] = $location->location_ns;
662                     $options['location_id'] = $location->location_id;
663                 }
664             }
665         }
666
667         if ($this->isPeopletag()) {
668             $options['peopletags'][] = $this->localPeopletag();
669         }
670
671         // Atom categories <-> hashtags
672         foreach ($activity->categories as $cat) {
673             if ($cat->term) {
674                 $term = common_canonical_tag($cat->term);
675                 if ($term) {
676                     $options['tags'][] = $term;
677                 }
678             }
679         }
680
681         // Atom enclosures -> attachment URLs
682         foreach ($activity->enclosures as $href) {
683             // @todo FIXME: Save these locally or....?
684             $options['urls'][] = $href;
685         }
686
687         try {
688             $saved = Notice::saveNew($profile->id,
689                                      $content,
690                                      'ostatus',
691                                      $options);
692             if ($saved instanceof Notice) {
693                 Ostatus_source::saveNew($saved, $this, $method);
694                 if ($attachment instanceof File) {
695                     File_to_post::processNew($attachment, $saved);
696                 }
697             }
698         } catch (Exception $e) {
699             common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
700             throw $e;
701         }
702         common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
703         return $saved;
704     }
705
706     /**
707      * Filters a list of recipient ID URIs to just those for local delivery.
708      * @param Profile local profile of sender
709      * @param array in/out &$attention_uris set of URIs, will be pruned on output
710      * @return array of group IDs
711      */
712     static public function filterAttention(Profile $sender, array $attention)
713     {
714         common_debug("Original reply recipients: " . implode(', ', array_keys($attention)));
715         $groups = array();
716         $replies = array();
717         foreach ($attention as $recipient=>$type) {
718             // Is the recipient a local user?
719             $user = User::getKV('uri', $recipient);
720             if ($user instanceof User) {
721                 // @todo FIXME: Sender verification, spam etc?
722                 $replies[] = $recipient;
723                 continue;
724             }
725
726             // Is the recipient a local group?
727             // TODO: $group = User_group::getKV('uri', $recipient);
728             $id = OStatusPlugin::localGroupFromUrl($recipient);
729             if ($id) {
730                 $group = User_group::getKV('id', $id);
731                 if ($group instanceof User_group) {
732                     // Deliver to all members of this local group if allowed.
733                     if ($sender->isMember($group)) {
734                         $groups[] = $group->id;
735                     } else {
736                         common_debug(sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
737                     }
738                     continue;
739                 } else {
740                     common_debug("Skipping reply to bogus group $recipient");
741                 }
742             }
743
744             // Is the recipient a remote user or group?
745             try {
746                 $oprofile = self::ensureProfileURI($recipient);
747                 if ($oprofile->isGroup()) {
748                     // Deliver to local members of this remote group.
749                     // @todo FIXME: Sender verification?
750                     $groups[] = $oprofile->group_id;
751                 } else {
752                     // may be canonicalized or something
753                     $replies[] = $oprofile->getUri();
754                 }
755                 continue;
756             } catch (Exception $e) {
757                 // Neither a recognizable local nor remote user!
758                 common_debug("Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
759             }
760
761         }
762         common_debug("Local reply recipients: " . implode(', ', $replies));
763         common_debug("Local group recipients: " . implode(', ', $groups));
764         return array($groups, $replies);
765     }
766
767     /**
768      * Look up and if necessary create an Ostatus_profile for the remote entity
769      * with the given profile page URL. This should never return null -- you
770      * will either get an object or an exception will be thrown.
771      *
772      * @param string $profile_url
773      * @return Ostatus_profile
774      * @throws Exception on various error conditions
775      * @throws OStatusShadowException if this reference would obscure a local user/group
776      */
777     public static function ensureProfileURL($profile_url, array $hints=array())
778     {
779         $oprofile = self::getFromProfileURL($profile_url);
780
781         if ($oprofile instanceof Ostatus_profile) {
782             return $oprofile;
783         }
784
785         $hints['profileurl'] = $profile_url;
786
787         // Fetch the URL
788         // XXX: HTTP caching
789
790         $client = new HTTPClient();
791         $client->setHeader('Accept', 'text/html,application/xhtml+xml');
792         $response = $client->get($profile_url);
793
794         if (!$response->isOk()) {
795             // TRANS: Exception. %s is a profile URL.
796             throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
797         }
798
799         // Check if we have a non-canonical URL
800
801         $finalUrl = $response->getUrl();
802
803         if ($finalUrl != $profile_url) {
804
805             $hints['profileurl'] = $finalUrl;
806
807             $oprofile = self::getFromProfileURL($finalUrl);
808
809             if ($oprofile instanceof Ostatus_profile) {
810                 return $oprofile;
811             }
812         }
813
814         // Try to get some hCard data
815
816         $body = $response->getBody();
817
818         $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
819
820         if (!empty($hcardHints)) {
821             $hints = array_merge($hints, $hcardHints);
822         }
823
824         // Check if they've got an LRDD header
825
826         $lrdd = LinkHeader::getLink($response, 'lrdd');
827         try {
828             $xrd = new XML_XRD();
829             $xrd->loadFile($lrdd);
830             $xrdHints = DiscoveryHints::fromXRD($xrd);
831             $hints = array_merge($hints, $xrdHints);
832         } catch (Exception $e) {
833             // No hints available from XRD
834         }
835
836         // If discovery found a feedurl (probably from LRDD), use it.
837
838         if (array_key_exists('feedurl', $hints)) {
839             return self::ensureFeedURL($hints['feedurl'], $hints);
840         }
841
842         // Get the feed URL from HTML
843
844         $discover = new FeedDiscovery();
845
846         $feedurl = $discover->discoverFromHTML($finalUrl, $body);
847
848         if (!empty($feedurl)) {
849             $hints['feedurl'] = $feedurl;
850             return self::ensureFeedURL($feedurl, $hints);
851         }
852
853         // TRANS: Exception. %s is a URL.
854         throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
855     }
856
857     /**
858      * Look up the Ostatus_profile, if present, for a remote entity with the
859      * given profile page URL. Will return null for both unknown and invalid
860      * remote profiles.
861      *
862      * @return mixed Ostatus_profile or null
863      * @throws OStatusShadowException for local profiles
864      */
865     static function getFromProfileURL($profile_url)
866     {
867         $profile = Profile::getKV('profileurl', $profile_url);
868         if (!$profile instanceof Profile) {
869             return null;
870         }
871
872         try {
873             $oprofile = self::getFromProfile($profile);
874             // We found the profile, return it!
875             return $oprofile;
876         } catch (NoResultException $e) {
877             // Could not find an OStatus profile, is it instead a local user?
878             $user = User::getKV('id', $profile->id);
879             if ($user instanceof User) {
880                 // @todo i18n FIXME: use sprintf and add i18n (?)
881                 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
882             }
883         }
884
885         // Continue discovery; it's a remote profile
886         // for OMB or some other protocol, may also
887         // support OStatus
888
889         return null;
890     }
891
892     static function getFromProfile(Profile $profile)
893     {
894         $oprofile = new Ostatus_profile();
895         $oprofile->profile_id = $profile->id;
896         if (!$oprofile->find(true)) {
897             throw new NoResultException($oprofile);
898         }
899         return $oprofile;
900     }
901
902     /**
903      * Look up and if necessary create an Ostatus_profile for remote entity
904      * with the given update feed. This should never return null -- you will
905      * either get an object or an exception will be thrown.
906      *
907      * @return Ostatus_profile
908      * @throws Exception
909      */
910     public static function ensureFeedURL($feed_url, array $hints=array())
911     {
912         $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
913         if ($oprofile instanceof Ostatus_profile) {
914             return $oprofile;
915         }
916
917         $discover = new FeedDiscovery();
918
919         $feeduri = $discover->discoverFromFeedURL($feed_url);
920         $hints['feedurl'] = $feeduri;
921
922         $huburi = $discover->getHubLink();
923         $hints['hub'] = $huburi;
924
925         // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
926         $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
927                         ?: $discover->getAtomLink(Salmon::NS_REPLIES);
928         $hints['salmon'] = $salmonuri;
929
930         if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
931             // We can only deal with folks with a PuSH hub
932             // unless we have something similar available locally.
933             throw new FeedSubNoHubException();
934         }
935
936         $feedEl = $discover->root;
937
938         if ($feedEl->tagName == 'feed') {
939             return self::ensureAtomFeed($feedEl, $hints);
940         } else if ($feedEl->tagName == 'channel') {
941             return self::ensureRssChannel($feedEl, $hints);
942         } else {
943             throw new FeedSubBadXmlException($feeduri);
944         }
945     }
946
947     /**
948      * Look up and, if necessary, create an Ostatus_profile for the remote
949      * profile with the given Atom feed - actually loaded from the feed.
950      * This should never return null -- you will either get an object or
951      * an exception will be thrown.
952      *
953      * @param DOMElement $feedEl root element of a loaded Atom feed
954      * @param array $hints additional discovery information passed from higher levels
955      * @todo FIXME: Should this be marked public?
956      * @return Ostatus_profile
957      * @throws Exception
958      */
959     public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
960     {
961         $author = ActivityUtils::getFeedAuthor($feedEl);
962
963         if (empty($author)) {
964             // XXX: make some educated guesses here
965             // TRANS: Feed sub exception.
966             throw new FeedSubException(_m('Cannot find enough profile '.
967                                           'information to make a feed.'));
968         }
969
970         return self::ensureActivityObjectProfile($author, $hints);
971     }
972
973     /**
974      * Look up and, if necessary, create an Ostatus_profile for the remote
975      * profile with the given RSS feed - actually loaded from the feed.
976      * This should never return null -- you will either get an object or
977      * an exception will be thrown.
978      *
979      * @param DOMElement $feedEl root element of a loaded RSS feed
980      * @param array $hints additional discovery information passed from higher levels
981      * @todo FIXME: Should this be marked public?
982      * @return Ostatus_profile
983      * @throws Exception
984      */
985     public static function ensureRssChannel(DOMElement $feedEl, array $hints)
986     {
987         // Special-case for Posterous. They have some nice metadata in their
988         // posterous:author elements. We should use them instead of the channel.
989
990         $items = $feedEl->getElementsByTagName('item');
991
992         if ($items->length > 0) {
993             $item = $items->item(0);
994             $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
995             if (!empty($authorEl)) {
996                 $obj = ActivityObject::fromPosterousAuthor($authorEl);
997                 // Posterous has multiple authors per feed, and multiple feeds
998                 // per author. We check if this is the "main" feed for this author.
999                 if (array_key_exists('profileurl', $hints) &&
1000                     !empty($obj->poco) &&
1001                     common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1002                     return self::ensureActivityObjectProfile($obj, $hints);
1003                 }
1004             }
1005         }
1006
1007         $obj = ActivityUtils::getFeedAuthor($feedEl);
1008
1009         // @todo FIXME: We should check whether this feed has elements
1010         // with different <author> or <dc:creator> elements, and... I dunno.
1011         // Do something about that.
1012
1013         if(empty($obj)) { $obj = ActivityObject::fromRssChannel($feedEl); }
1014
1015         return self::ensureActivityObjectProfile($obj, $hints);
1016     }
1017
1018     /**
1019      * Download and update given avatar image
1020      *
1021      * @param string $url
1022      * @return Avatar    The Avatar we have on disk. (seldom used)
1023      * @throws Exception in various failure cases
1024      */
1025     public function updateAvatar($url, $force=false)
1026     {
1027         try {
1028             // If avatar URL differs: update. If URLs were identical but we're forced: update.
1029             if ($url == $this->avatar && !$force) {
1030                 // If there's no locally stored avatar, throw an exception and continue fetching below.
1031                 $avatar = Avatar::getUploaded($this->localProfile()) instanceof Avatar;
1032                 return $avatar;
1033             }
1034         } catch (NoAvatarException $e) {
1035             // No avatar available, let's fetch it.
1036         }
1037
1038         if (!common_valid_http_url($url)) {
1039             // TRANS: Server exception. %s is a URL.
1040             throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1041         }
1042
1043         $self = $this->localProfile();
1044
1045         // @todo FIXME: This should be better encapsulated
1046         // ripped from oauthstore.php (for old OMB client)
1047         $temp_filename = tempnam(common_get_temp_dir(), 'listener_avatar');
1048         try {
1049             $imgData = HTTPClient::quickGet($url);
1050             // Make sure it's at least an image file. ImageFile can do the rest.
1051             if (false === getimagesizefromstring($imgData)) {
1052                 throw new UnsupportedMediaException(_('Downloaded group avatar was not an image.'));
1053             }
1054             file_put_contents($temp_filename, $imgData);
1055             unset($imgData);    // No need to carry this in memory.
1056
1057             if ($this->isGroup()) {
1058                 $id = $this->group_id;
1059             } else {
1060                 $id = $this->profile_id;
1061             }
1062             $imagefile = new ImageFile(null, $temp_filename);
1063             $filename = Avatar::filename($id,
1064                                          image_type_to_extension($imagefile->type),
1065                                          null,
1066                                          common_timestamp());
1067             rename($temp_filename, Avatar::path($filename));
1068         } catch (Exception $e) {
1069             unlink($temp_filename);
1070             throw $e;
1071         }
1072         // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1073         // keep from accidentally saving images from command-line (queues)
1074         // that can't be read from web server, which causes hard-to-notice
1075         // problems later on:
1076         //
1077         // http://status.net/open-source/issues/2663
1078         chmod(Avatar::path($filename), 0644);
1079
1080         $self->setOriginal($filename);
1081
1082         $orig = clone($this);
1083         $this->avatar = $url;
1084         $this->update($orig);
1085
1086         return Avatar::getUploaded($self);
1087     }
1088
1089     /**
1090      * Pull avatar URL from ActivityObject or profile hints
1091      *
1092      * @param ActivityObject $object
1093      * @param array $hints
1094      * @return mixed URL string or false
1095      */
1096     public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
1097     {
1098         if ($object->avatarLinks) {
1099             $best = false;
1100             // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1101             foreach ($object->avatarLinks as $avatar) {
1102                 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1103                     // Exact match!
1104                     $best = $avatar;
1105                     break;
1106                 }
1107                 if (!$best || $avatar->width > $best->width) {
1108                     $best = $avatar;
1109                 }
1110             }
1111             return $best->url;
1112         } else if (array_key_exists('avatar', $hints)) {
1113             return $hints['avatar'];
1114         }
1115         return false;
1116     }
1117
1118     /**
1119      * Get an appropriate avatar image source URL, if available.
1120      *
1121      * @param ActivityObject $actor
1122      * @param DOMElement $feed
1123      * @return string
1124      */
1125     protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
1126     {
1127         $url = '';
1128         $icon = '';
1129         if ($actor->avatar) {
1130             $url = trim($actor->avatar);
1131         }
1132         if (!$url) {
1133             // Check <atom:logo> and <atom:icon> on the feed
1134             $els = $feed->childNodes();
1135             if ($els && $els->length) {
1136                 for ($i = 0; $i < $els->length; $i++) {
1137                     $el = $els->item($i);
1138                     if ($el->namespaceURI == Activity::ATOM) {
1139                         if (empty($url) && $el->localName == 'logo') {
1140                             $url = trim($el->textContent);
1141                             break;
1142                         }
1143                         if (empty($icon) && $el->localName == 'icon') {
1144                             // Use as a fallback
1145                             $icon = trim($el->textContent);
1146                         }
1147                     }
1148                 }
1149             }
1150             if ($icon && !$url) {
1151                 $url = $icon;
1152             }
1153         }
1154         if ($url) {
1155             $opts = array('allowed_schemes' => array('http', 'https'));
1156             if (common_valid_http_url($url)) {
1157                 return $url;
1158             }
1159         }
1160
1161         return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1162     }
1163
1164     /**
1165      * Fetch, or build if necessary, an Ostatus_profile for the actor
1166      * in a given Activity Streams activity.
1167      * This should never return null -- you will either get an object or
1168      * an exception will be thrown.
1169      *
1170      * @param Activity $activity
1171      * @param string $feeduri if we already know the canonical feed URI!
1172      * @param string $salmonuri if we already know the salmon return channel URI
1173      * @return Ostatus_profile
1174      * @throws Exception
1175      */
1176     public static function ensureActorProfile(Activity $activity, array $hints=array())
1177     {
1178         return self::ensureActivityObjectProfile($activity->actor, $hints);
1179     }
1180
1181     /**
1182      * Fetch, or build if necessary, an Ostatus_profile for the profile
1183      * in a given Activity Streams object (can be subject, actor, or object).
1184      * This should never return null -- you will either get an object or
1185      * an exception will be thrown.
1186      *
1187      * @param ActivityObject $object
1188      * @param array $hints additional discovery information passed from higher levels
1189      * @return Ostatus_profile
1190      * @throws Exception
1191      */
1192     public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
1193     {
1194         $profile = self::getActivityObjectProfile($object);
1195         if ($profile instanceof Ostatus_profile) {
1196             $profile->updateFromActivityObject($object, $hints);
1197         } else {
1198             $profile = self::createActivityObjectProfile($object, $hints);
1199         }
1200         return $profile;
1201     }
1202
1203     /**
1204      * @param Activity $activity
1205      * @return mixed matching Ostatus_profile or false if none known
1206      * @throws ServerException if feed info invalid
1207      */
1208     public static function getActorProfile(Activity $activity)
1209     {
1210         return self::getActivityObjectProfile($activity->actor);
1211     }
1212
1213     /**
1214      * @param ActivityObject $activity
1215      * @return mixed matching Ostatus_profile or false if none known
1216      * @throws ServerException if feed info invalid
1217      */
1218     protected static function getActivityObjectProfile(ActivityObject $object)
1219     {
1220         $uri = self::getActivityObjectProfileURI($object);
1221         return Ostatus_profile::getKV('uri', $uri);
1222     }
1223
1224     /**
1225      * Get the identifier URI for the remote entity described
1226      * by this ActivityObject. This URI is *not* guaranteed to be
1227      * a resolvable HTTP/HTTPS URL.
1228      *
1229      * @param ActivityObject $object
1230      * @return string
1231      * @throws ServerException if feed info invalid
1232      */
1233     protected static function getActivityObjectProfileURI(ActivityObject $object)
1234     {
1235         if ($object->id) {
1236             if (ActivityUtils::validateUri($object->id)) {
1237                 return $object->id;
1238             }
1239         }
1240
1241         // If the id is missing or invalid (we've seen feeds mistakenly listing
1242         // things like local usernames in that field) then we'll use the profile
1243         // page link, if valid.
1244         if ($object->link && common_valid_http_url($object->link)) {
1245             return $object->link;
1246         }
1247         // TRANS: Server exception.
1248         throw new ServerException(_m('No author ID URI found.'));
1249     }
1250
1251     /**
1252      * @todo FIXME: Validate stuff somewhere.
1253      */
1254
1255     /**
1256      * Create local ostatus_profile and profile/user_group entries for
1257      * the provided remote user or group.
1258      * This should never return null -- you will either get an object or
1259      * an exception will be thrown.
1260      *
1261      * @param ActivityObject $object
1262      * @param array $hints
1263      *
1264      * @return Ostatus_profile
1265      */
1266     protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
1267     {
1268         $homeuri = $object->id;
1269         $discover = false;
1270
1271         if (!$homeuri) {
1272             common_debug(__METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1273             // TRANS: Exception.
1274             throw new Exception(_m('No profile URI.'));
1275         }
1276
1277         $user = User::getKV('uri', $homeuri);
1278         if ($user instanceof User) {
1279             // TRANS: Exception.
1280             throw new Exception(_m('Local user cannot be referenced as remote.'));
1281         }
1282
1283         if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1284             // TRANS: Exception.
1285             throw new Exception(_m('Local group cannot be referenced as remote.'));
1286         }
1287
1288         $ptag = Profile_list::getKV('uri', $homeuri);
1289         if ($ptag instanceof Profile_list) {
1290             $local_user = User::getKV('id', $ptag->tagger);
1291             if ($local_user instanceof User) {
1292                 // TRANS: Exception.
1293                 throw new Exception(_m('Local list cannot be referenced as remote.'));
1294             }
1295         }
1296
1297         if (array_key_exists('feedurl', $hints)) {
1298             $feeduri = $hints['feedurl'];
1299         } else {
1300             $discover = new FeedDiscovery();
1301             $feeduri = $discover->discoverFromURL($homeuri);
1302         }
1303
1304         if (array_key_exists('salmon', $hints)) {
1305             $salmonuri = $hints['salmon'];
1306         } else {
1307             if (!$discover) {
1308                 $discover = new FeedDiscovery();
1309                 $discover->discoverFromFeedURL($hints['feedurl']);
1310             }
1311             // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1312             $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1313                             ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1314         }
1315
1316         if (array_key_exists('hub', $hints)) {
1317             $huburi = $hints['hub'];
1318         } else {
1319             if (!$discover) {
1320                 $discover = new FeedDiscovery();
1321                 $discover->discoverFromFeedURL($hints['feedurl']);
1322             }
1323             $huburi = $discover->getHubLink();
1324         }
1325
1326         if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
1327             // We can only deal with folks with a PuSH hub
1328             throw new FeedSubNoHubException();
1329         }
1330
1331         $oprofile = new Ostatus_profile();
1332
1333         $oprofile->uri        = $homeuri;
1334         $oprofile->feeduri    = $feeduri;
1335         $oprofile->salmonuri  = $salmonuri;
1336
1337         $oprofile->created    = common_sql_now();
1338         $oprofile->modified   = common_sql_now();
1339
1340         if ($object->type == ActivityObject::PERSON) {
1341             $profile = new Profile();
1342             $profile->created = common_sql_now();
1343             self::updateProfile($profile, $object, $hints);
1344
1345             $oprofile->profile_id = $profile->insert();
1346             if ($oprofile->profile_id === false) {
1347                 // TRANS: Server exception.
1348                 throw new ServerException(_m('Cannot save local profile.'));
1349             }
1350         } else if ($object->type == ActivityObject::GROUP) {
1351             $profile = new Profile();
1352             $profile->query('BEGIN');
1353
1354             $group = new User_group();
1355             $group->uri = $homeuri;
1356             $group->created = common_sql_now();
1357             self::updateGroup($group, $object, $hints);
1358
1359             // TODO: We should do this directly in User_group->insert()!
1360             // currently it's duplicated in User_group->update()
1361             // AND User_group->register()!!!
1362             $fields = array(/*group field => profile field*/
1363                         'nickname'      => 'nickname',
1364                         'fullname'      => 'fullname',
1365                         'mainpage'      => 'profileurl',
1366                         'homepage'      => 'homepage',
1367                         'description'   => 'bio',
1368                         'location'      => 'location',
1369                         'created'       => 'created',
1370                         'modified'      => 'modified',
1371                         );
1372             foreach ($fields as $gf=>$pf) {
1373                 $profile->$pf = $group->$gf;
1374             }
1375             $profile_id = $profile->insert();
1376             if ($profile_id === false) {
1377                 $profile->query('ROLLBACK');
1378                 throw new ServerException(_('Profile insertion failed.'));
1379             }
1380
1381             $group->profile_id = $profile_id;
1382
1383             $oprofile->group_id = $group->insert();
1384             if ($oprofile->group_id === false) {
1385                 $profile->query('ROLLBACK');
1386                 // TRANS: Server exception.
1387                 throw new ServerException(_m('Cannot save local profile.'));
1388             }
1389
1390             $profile->query('COMMIT');
1391         } else if ($object->type == ActivityObject::_LIST) {
1392             $ptag = new Profile_list();
1393             $ptag->uri = $homeuri;
1394             $ptag->created = common_sql_now();
1395             self::updatePeopletag($ptag, $object, $hints);
1396
1397             $oprofile->peopletag_id = $ptag->insert();
1398             if ($oprofile->peopletag_id === false) {
1399                 // TRANS: Server exception.
1400                 throw new ServerException(_m('Cannot save local list.'));
1401             }
1402         }
1403
1404         $ok = $oprofile->insert();
1405
1406         if ($ok === false) {
1407             // TRANS: Server exception.
1408             throw new ServerException(_m('Cannot save OStatus profile.'));
1409         }
1410
1411         $avatar = self::getActivityObjectAvatar($object, $hints);
1412
1413         if ($avatar) {
1414             try {
1415                 $oprofile->updateAvatar($avatar);
1416             } catch (Exception $ex) {
1417                 // Profile is saved, but Avatar is messed up. We're
1418                 // just going to continue.
1419                 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1420             }
1421         }
1422
1423         return $oprofile;
1424     }
1425
1426     /**
1427      * Save any updated profile information to our local copy.
1428      * @param ActivityObject $object
1429      * @param array $hints
1430      */
1431     public function updateFromActivityObject(ActivityObject $object, array $hints=array())
1432     {
1433         if ($this->isGroup()) {
1434             $group = $this->localGroup();
1435             self::updateGroup($group, $object, $hints);
1436         } else if ($this->isPeopletag()) {
1437             $ptag = $this->localPeopletag();
1438             self::updatePeopletag($ptag, $object, $hints);
1439         } else {
1440             $profile = $this->localProfile();
1441             self::updateProfile($profile, $object, $hints);
1442         }
1443
1444         $avatar = self::getActivityObjectAvatar($object, $hints);
1445         if ($avatar && !isset($ptag)) {
1446             try {
1447                 $this->updateAvatar($avatar);
1448             } catch (Exception $ex) {
1449                 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1450             }
1451         }
1452     }
1453
1454     public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
1455     {
1456         $orig = clone($profile);
1457
1458         // Existing nickname is better than nothing.
1459
1460         if (!array_key_exists('nickname', $hints)) {
1461             $hints['nickname'] = $profile->nickname;
1462         }
1463
1464         $nickname = self::getActivityObjectNickname($object, $hints);
1465
1466         if (!empty($nickname)) {
1467             $profile->nickname = $nickname;
1468         }
1469
1470         if (!empty($object->title)) {
1471             $profile->fullname = $object->title;
1472         } else if (array_key_exists('fullname', $hints)) {
1473             $profile->fullname = $hints['fullname'];
1474         }
1475
1476         if (!empty($object->link)) {
1477             $profile->profileurl = $object->link;
1478         } else if (array_key_exists('profileurl', $hints)) {
1479             $profile->profileurl = $hints['profileurl'];
1480         } else if (common_valid_http_url($object->id)) {
1481             $profile->profileurl = $object->id;
1482         }
1483
1484         $bio = self::getActivityObjectBio($object, $hints);
1485
1486         if (!empty($bio)) {
1487             $profile->bio = $bio;
1488         }
1489
1490         $location = self::getActivityObjectLocation($object, $hints);
1491
1492         if (!empty($location)) {
1493             $profile->location = $location;
1494         }
1495
1496         $homepage = self::getActivityObjectHomepage($object, $hints);
1497
1498         if (!empty($homepage)) {
1499             $profile->homepage = $homepage;
1500         }
1501
1502         if (!empty($object->geopoint)) {
1503             $location = ActivityContext::locationFromPoint($object->geopoint);
1504             if (!empty($location)) {
1505                 $profile->lat = $location->lat;
1506                 $profile->lon = $location->lon;
1507             }
1508         }
1509
1510         // @todo FIXME: tags/categories
1511         // @todo tags from categories
1512
1513         if ($profile->id) {
1514             common_debug("Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1515             $profile->update($orig);
1516         }
1517     }
1518
1519     protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
1520     {
1521         $orig = clone($group);
1522
1523         $group->nickname = self::getActivityObjectNickname($object, $hints);
1524         $group->fullname = $object->title;
1525
1526         if (!empty($object->link)) {
1527             $group->mainpage = $object->link;
1528         } else if (array_key_exists('profileurl', $hints)) {
1529             $group->mainpage = $hints['profileurl'];
1530         }
1531
1532         // @todo tags from categories
1533         $group->description = self::getActivityObjectBio($object, $hints);
1534         $group->location = self::getActivityObjectLocation($object, $hints);
1535         $group->homepage = self::getActivityObjectHomepage($object, $hints);
1536
1537         if ($group->id) {   // If no id, we haven't called insert() yet, so don't run update()
1538             common_debug("Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1539             $group->update($orig);
1540         }
1541     }
1542
1543     protected static function updatePeopletag(Peopletag $tag, ActivityObject $object, array $hints=array()) {
1544         $orig = clone($tag);
1545
1546         $tag->tag = $object->title;
1547
1548         if (!empty($object->link)) {
1549             $tag->mainpage = $object->link;
1550         } else if (array_key_exists('profileurl', $hints)) {
1551             $tag->mainpage = $hints['profileurl'];
1552         }
1553
1554         $tag->description = $object->summary;
1555         $tagger = self::ensureActivityObjectProfile($object->owner);
1556         $tag->tagger = $tagger->profile_id;
1557
1558         if ($tag->id) {
1559             common_debug("Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1560             $tag->update($orig);
1561         }
1562     }
1563
1564     protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
1565     {
1566         $homepage = null;
1567         $poco     = $object->poco;
1568
1569         if (!empty($poco)) {
1570             $url = $poco->getPrimaryURL();
1571             if ($url && $url->type == 'homepage') {
1572                 $homepage = $url->value;
1573             }
1574         }
1575
1576         // @todo Try for a another PoCo URL?
1577
1578         return $homepage;
1579     }
1580
1581     protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
1582     {
1583         $location = null;
1584
1585         if (!empty($object->poco) &&
1586             isset($object->poco->address->formatted)) {
1587             $location = $object->poco->address->formatted;
1588         } else if (array_key_exists('location', $hints)) {
1589             $location = $hints['location'];
1590         }
1591
1592         if (!empty($location)) {
1593             if (mb_strlen($location) > 191) {   // not 255 because utf8mb4 takes more space
1594                 $location = mb_substr($note, 0, 191 - 3) . ' â€¦ ';
1595             }
1596         }
1597
1598         // @todo Try to find location some othe way? Via goerss point?
1599
1600         return $location;
1601     }
1602
1603     protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
1604     {
1605         $bio  = null;
1606
1607         if (!empty($object->poco)) {
1608             $note = $object->poco->note;
1609         } else if (array_key_exists('bio', $hints)) {
1610             $note = $hints['bio'];
1611         }
1612
1613         if (!empty($note)) {
1614             if (Profile::bioTooLong($note)) {
1615                 // XXX: truncate ok?
1616                 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' â€¦ ';
1617             } else {
1618                 $bio = $note;
1619             }
1620         }
1621
1622         // @todo Try to get bio info some other way?
1623
1624         return $bio;
1625     }
1626
1627     public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
1628     {
1629         if ($object->poco) {
1630             if (!empty($object->poco->preferredUsername)) {
1631                 return common_nicknamize($object->poco->preferredUsername);
1632             }
1633         }
1634
1635         if (!empty($object->nickname)) {
1636             return common_nicknamize($object->nickname);
1637         }
1638
1639         if (array_key_exists('nickname', $hints)) {
1640             return $hints['nickname'];
1641         }
1642
1643         // Try the profile url (like foo.example.com or example.com/user/foo)
1644         if (!empty($object->link)) {
1645             $profileUrl = $object->link;
1646         } else if (!empty($hints['profileurl'])) {
1647             $profileUrl = $hints['profileurl'];
1648         }
1649
1650         if (!empty($profileUrl)) {
1651             $nickname = self::nicknameFromURI($profileUrl);
1652         }
1653
1654         // Try the URI (may be a tag:, http:, acct:, ...
1655
1656         if (empty($nickname)) {
1657             $nickname = self::nicknameFromURI($object->id);
1658         }
1659
1660         // Try a Webfinger if one was passed (way) down
1661
1662         if (empty($nickname)) {
1663             if (array_key_exists('webfinger', $hints)) {
1664                 $nickname = self::nicknameFromURI($hints['webfinger']);
1665             }
1666         }
1667
1668         // Try the name
1669
1670         if (empty($nickname)) {
1671             $nickname = common_nicknamize($object->title);
1672         }
1673
1674         return $nickname;
1675     }
1676
1677     protected static function nicknameFromURI($uri)
1678     {
1679         if (preg_match('/(\w+):/', $uri, $matches)) {
1680             $protocol = $matches[1];
1681         } else {
1682             return null;
1683         }
1684
1685         switch ($protocol) {
1686         case 'acct':
1687         case 'mailto':
1688             if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1689                 return common_canonical_nickname($matches[1]);
1690             }
1691             return null;
1692         case 'http':
1693             return common_url_to_nickname($uri);
1694             break;
1695         default:
1696             return null;
1697         }
1698     }
1699
1700     /**
1701      * Look up, and if necessary create, an Ostatus_profile for the remote
1702      * entity with the given webfinger address.
1703      * This should never return null -- you will either get an object or
1704      * an exception will be thrown.
1705      *
1706      * @param string $addr webfinger address
1707      * @return Ostatus_profile
1708      * @throws Exception on error conditions
1709      * @throws OStatusShadowException if this reference would obscure a local user/group
1710      */
1711     public static function ensureWebfinger($addr)
1712     {
1713         // First, try the cache
1714
1715         $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1716
1717         if ($uri !== false) {
1718             if (is_null($uri)) {
1719                 // Negative cache entry
1720                 // TRANS: Exception.
1721                 throw new Exception(_m('Not a valid webfinger address.'));
1722             }
1723             $oprofile = Ostatus_profile::getKV('uri', $uri);
1724             if ($oprofile instanceof Ostatus_profile) {
1725                 return $oprofile;
1726             }
1727         }
1728
1729         // Try looking it up
1730         $oprofile = Ostatus_profile::getKV('uri', Discovery::normalize($addr));
1731
1732         if ($oprofile instanceof Ostatus_profile) {
1733             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1734             return $oprofile;
1735         }
1736
1737         // Now, try some discovery
1738
1739         $disco = new Discovery();
1740
1741         try {
1742             $xrd = $disco->lookup($addr);
1743         } catch (Exception $e) {
1744             // Save negative cache entry so we don't waste time looking it up again.
1745             // @todo FIXME: Distinguish temporary failures?
1746             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1747             // TRANS: Exception.
1748             throw new Exception(_m('Not a valid webfinger address.'));
1749         }
1750
1751         $hints = array_merge(array('webfinger' => $addr),
1752                              DiscoveryHints::fromXRD($xrd));
1753
1754         // If there's an Hcard, let's grab its info
1755         if (array_key_exists('hcard', $hints)) {
1756             if (!array_key_exists('profileurl', $hints) ||
1757                 $hints['hcard'] != $hints['profileurl']) {
1758                 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1759                 $hints = array_merge($hcardHints, $hints);
1760             }
1761         }
1762
1763         // If we got a feed URL, try that
1764         $feedUrl = null;
1765         if (array_key_exists('feedurl', $hints)) {
1766             $feedUrl = $hints['feedurl'];
1767             try {
1768                 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1769                 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1770                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1771                 return $oprofile;
1772             } catch (Exception $e) {
1773                 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1774                 // keep looking
1775             }
1776         }
1777
1778         // If we got a profile page, try that!
1779         $profileUrl = null;
1780         if (array_key_exists('profileurl', $hints)) {
1781             $profileUrl = $hints['profileurl'];
1782             try {
1783                 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1784                 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1785                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1786                 return $oprofile;
1787             } catch (OStatusShadowException $e) {
1788                 // We've ended up with a remote reference to a local user or group.
1789                 // @todo FIXME: Ideally we should be able to say who it was so we can
1790                 // go back and refer to it the regular way
1791                 throw $e;
1792             } catch (Exception $e) {
1793                 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1794                 // keep looking
1795                 //
1796                 // @todo FIXME: This means an error discovering from profile page
1797                 // may give us a corrupt entry using the webfinger URI, which
1798                 // will obscure the correct page-keyed profile later on.
1799             }
1800         }
1801
1802         // XXX: try hcard
1803         // XXX: try FOAF
1804
1805         if (array_key_exists('salmon', $hints)) {
1806             $salmonEndpoint = $hints['salmon'];
1807
1808             // An account URL, a salmon endpoint, and a dream? Not much to go
1809             // on, but let's give it a try
1810
1811             $uri = 'acct:'.$addr;
1812
1813             $profile = new Profile();
1814
1815             $profile->nickname = self::nicknameFromUri($uri);
1816             $profile->created  = common_sql_now();
1817
1818             if (!is_null($profileUrl)) {
1819                 $profile->profileurl = $profileUrl;
1820             }
1821
1822             $profile_id = $profile->insert();
1823
1824             if ($profile_id === false) {
1825                 common_log_db_error($profile, 'INSERT', __FILE__);
1826                 // TRANS: Exception. %s is a webfinger address.
1827                 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1828             }
1829
1830             $oprofile = new Ostatus_profile();
1831
1832             $oprofile->uri        = $uri;
1833             $oprofile->salmonuri  = $salmonEndpoint;
1834             $oprofile->profile_id = $profile_id;
1835             $oprofile->created    = common_sql_now();
1836
1837             if (!is_null($feedUrl)) {
1838                 $oprofile->feeduri = $feedUrl;
1839             }
1840
1841             $result = $oprofile->insert();
1842
1843             if ($result === false) {
1844                 $profile->delete();
1845                 common_log_db_error($oprofile, 'INSERT', __FILE__);
1846                 // TRANS: Exception. %s is a webfinger address.
1847                 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1848             }
1849
1850             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1851             return $oprofile;
1852         }
1853
1854         // TRANS: Exception. %s is a webfinger address.
1855         throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1856     }
1857
1858     /**
1859      * Store the full-length scrubbed HTML of a remote notice to an attachment
1860      * file on our server. We'll link to this at the end of the cropped version.
1861      *
1862      * @param string $title plaintext for HTML page's title
1863      * @param string $rendered HTML fragment for HTML page's body
1864      * @return File
1865      */
1866     function saveHTMLFile($title, $rendered)
1867     {
1868         $final = sprintf("<!DOCTYPE html>\n" .
1869                          '<html><head>' .
1870                          '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1871                          '<title>%s</title>' .
1872                          '</head>' .
1873                          '<body>%s</body></html>',
1874                          htmlspecialchars($title),
1875                          $rendered);
1876
1877         $filename = File::filename($this->localProfile(),
1878                                    'ostatus', // ignored?
1879                                    'text/html');
1880
1881         $filepath = File::path($filename);
1882         $fileurl = File::url($filename);
1883
1884         file_put_contents($filepath, $final);
1885
1886         $file = new File;
1887
1888         $file->filename = $filename;
1889         $file->urlhash  = File::hashurl($fileurl);
1890         $file->url      = $fileurl;
1891         $file->size     = filesize($filepath);
1892         $file->date     = time();
1893         $file->mimetype = 'text/html';
1894
1895         $file_id = $file->insert();
1896
1897         if ($file_id === false) {
1898             common_log_db_error($file, "INSERT", __FILE__);
1899             // TRANS: Server exception.
1900             throw new ServerException(_m('Could not store HTML content of long post as file.'));
1901         }
1902
1903         return $file;
1904     }
1905
1906     static function ensureProfileURI($uri)
1907     {
1908         $oprofile = null;
1909
1910         // First, try to query it
1911
1912         $oprofile = Ostatus_profile::getKV('uri', $uri);
1913
1914         if ($oprofile instanceof Ostatus_profile) {
1915             return $oprofile;
1916         }
1917
1918         // If unfound, do discovery stuff
1919         if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1920             $protocol = $match[1];
1921             switch ($protocol) {
1922             case 'http':
1923             case 'https':
1924                 $oprofile = self::ensureProfileURL($uri);
1925                 break;
1926             case 'acct':
1927             case 'mailto':
1928                 $rest = $match[2];
1929                 $oprofile = self::ensureWebfinger($rest);
1930                 break;
1931             default:
1932                 // TRANS: Server exception.
1933                 // TRANS: %1$s is a protocol, %2$s is a URI.
1934                 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1935                                                   $protocol,
1936                                                   $uri));
1937             }
1938         } else {
1939             // TRANS: Server exception. %s is a URI.
1940             throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1941         }
1942
1943         return $oprofile;
1944     }
1945
1946     public function checkAuthorship(Activity $activity)
1947     {
1948         if ($this->isGroup() || $this->isPeopletag()) {
1949             // A group or propletag feed will contain posts from multiple authors.
1950             $oprofile = self::ensureActorProfile($activity);
1951             if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1952                 // Groups can't post notices in StatusNet.
1953                 common_log(LOG_WARNING,
1954                     "OStatus: skipping post with group listed ".
1955                     "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
1956                 throw new ServerException('Activity author is a non-actor');
1957             }
1958         } else {
1959             $actor = $activity->actor;
1960
1961             if (!$actor instanceof Profile) {
1962                 // OK here! assume the default
1963             } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
1964                 $this->updateFromActivityObject($actor);
1965             } else if ($actor->id) {
1966                 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1967                 // This isn't what we expect from mainline OStatus person feeds!
1968                 // Group feeds go down another path, with different validation...
1969                 // Most likely this is a plain ol' blog feed of some kind which
1970                 // doesn't match our expectations. We'll take the entry, but ignore
1971                 // the <author> info.
1972                 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
1973             } else {
1974                 // Plain <author> without ActivityStreams actor info.
1975                 // We'll just ignore this info for now and save the update under the feed's identity.
1976             }
1977
1978             $oprofile = $this;
1979         }
1980
1981         return $oprofile->localProfile();
1982     }
1983
1984     public function updateUriKeys($profile_uri, array $hints=array())
1985     {
1986         $orig = clone($this);
1987
1988         common_debug('URIFIX These identities both say they are each other: "'.$orig->uri.'" and "'.$profile_uri.'"');
1989         $this->uri = $profile_uri;
1990
1991         if (array_key_exists('feedurl', $hints)) {
1992             if (!empty($this->feeduri)) {
1993                 common_debug('URIFIX Changing FeedSub ['.$feedsub->id.'] feeduri "'.$feedsub->uri.'" to "'.$hints['feedurl']);
1994                 $feedsub = FeedSub::getKV('uri', $this->feeduri);
1995                 $feedorig = clone($feedsub);
1996                 $feedsub->uri = $hints['feedurl'];
1997                 $feedsub->updateWithKeys($feedorig);
1998             } else {
1999                 common_debug('URIFIX Old Ostatus_profile did not have feedurl set, ensuring feed: '.$hints['feedurl']);
2000                 FeedSub::ensureFeed($hints['feedurl']);
2001             }
2002             $this->feeduri = $hints['feedurl'];
2003         }
2004         if (array_key_exists('salmon', $hints)) {
2005             common_debug('URIFIX Changing Ostatus_profile salmonuri from "'.$this->salmonuri.'" to "'.$hints['salmon'].'"');
2006             $this->salmonuri = $hints['salmon'];
2007         }
2008
2009         common_debug('URIFIX Updating Ostatus_profile URI for '.$orig->uri.' to '.$this->uri);
2010         $this->updateWithKeys($orig, 'uri');    // 'uri' is the primary key column
2011
2012         common_debug('URIFIX Subscribing/renewing feedsub for Ostatus_profile '.$this->uri);
2013         $this->subscribe();
2014     }
2015 }
2016
2017 /**
2018  * Exception indicating we've got a remote reference to a local user,
2019  * not a remote user!
2020  *
2021  * If we can ue a local profile after all, it's available as $e->profile.
2022  */
2023 class OStatusShadowException extends Exception
2024 {
2025     public $profile;
2026
2027     /**
2028      * @param Profile $profile
2029      * @param string $message
2030      */
2031     function __construct($profile, $message) {
2032         $this->profile = $profile;
2033         parent::__construct($message);
2034     }
2035 }