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