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