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