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