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