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