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