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