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