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