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