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