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