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