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