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