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