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