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