]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Ostatus_profile.php
Merge branch '1.0.x' of gitorious.org:statusnet/mainline 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         throw new ServerException(_m('No author ID URI found.'));
1213     }
1214
1215     /**
1216      * @fixme validate stuff somewhere
1217      */
1218
1219     /**
1220      * Create local ostatus_profile and profile/user_group entries for
1221      * the provided remote user or group.
1222      * This should never return null -- you will either get an object or
1223      * an exception will be thrown.
1224      *
1225      * @param ActivityObject $object
1226      * @param array $hints
1227      *
1228      * @return Ostatus_profile
1229      */
1230     protected static function createActivityObjectProfile($object, $hints=array())
1231     {
1232         $homeuri = $object->id;
1233         $discover = false;
1234
1235         if (!$homeuri) {
1236             common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1237             throw new Exception(_m('No profile URI.'));
1238         }
1239
1240         $user = User::staticGet('uri', $homeuri);
1241         if ($user) {
1242             // TRANS: Exception.
1243             throw new Exception(_m('Local user cannot be referenced as remote.'));
1244         }
1245
1246         if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1247             // TRANS: Exception.
1248             throw new Exception(_m('Local group cannot be referenced as remote.'));
1249         }
1250
1251         $ptag = Profile_list::staticGet('uri', $homeuri);
1252         if ($ptag) {
1253             $local_user = User::staticGet('id', $ptag->tagger);
1254             if (!empty($local_user)) {
1255                 throw new Exception(_m('Local list cannot be referenced as remote.'));
1256             }
1257         }
1258
1259         if (array_key_exists('feedurl', $hints)) {
1260             $feeduri = $hints['feedurl'];
1261         } else {
1262             $discover = new FeedDiscovery();
1263             $feeduri = $discover->discoverFromURL($homeuri);
1264         }
1265
1266         if (array_key_exists('salmon', $hints)) {
1267             $salmonuri = $hints['salmon'];
1268         } else {
1269             if (!$discover) {
1270                 $discover = new FeedDiscovery();
1271                 $discover->discoverFromFeedURL($hints['feedurl']);
1272             }
1273             $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1274         }
1275
1276         if (array_key_exists('hub', $hints)) {
1277             $huburi = $hints['hub'];
1278         } else {
1279             if (!$discover) {
1280                 $discover = new FeedDiscovery();
1281                 $discover->discoverFromFeedURL($hints['feedurl']);
1282             }
1283             $huburi = $discover->getHubLink();
1284         }
1285
1286         if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1287             // We can only deal with folks with a PuSH hub
1288             throw new FeedSubNoHubException();
1289         }
1290
1291         $oprofile = new Ostatus_profile();
1292
1293         $oprofile->uri        = $homeuri;
1294         $oprofile->feeduri    = $feeduri;
1295         $oprofile->salmonuri  = $salmonuri;
1296
1297         $oprofile->created    = common_sql_now();
1298         $oprofile->modified   = common_sql_now();
1299
1300         if ($object->type == ActivityObject::PERSON) {
1301             $profile = new Profile();
1302             $profile->created = common_sql_now();
1303             self::updateProfile($profile, $object, $hints);
1304
1305             $oprofile->profile_id = $profile->insert();
1306             if (!$oprofile->profile_id) {
1307             // TRANS: Server exception.
1308                 throw new ServerException(_m('Cannot save local profile.'));
1309             }
1310         } else if ($object->type == ActivityObject::GROUP) {
1311             $group = new User_group();
1312             $group->uri = $homeuri;
1313             $group->created = common_sql_now();
1314             self::updateGroup($group, $object, $hints);
1315
1316             $oprofile->group_id = $group->insert();
1317             if (!$oprofile->group_id) {
1318                 // TRANS: Server exception.
1319                 throw new ServerException(_m('Cannot save local profile.'));
1320             }
1321         } else if ($object->type == ActivityObject::_LIST) {
1322             $ptag = new Profile_list();
1323             $ptag->uri = $homeuri;
1324             $ptag->created = common_sql_now();
1325             self::updatePeopletag($ptag, $object, $hints);
1326
1327             $oprofile->peopletag_id = $ptag->insert();
1328             if (!$oprofile->peopletag_id) {
1329                 throw new ServerException(_m('Cannot save local list.'));
1330             }
1331         }
1332
1333         $ok = $oprofile->insert();
1334
1335         if (!$ok) {
1336             // TRANS: Server exception.
1337             throw new ServerException(_m('Cannot save OStatus profile.'));
1338         }
1339
1340         $avatar = self::getActivityObjectAvatar($object, $hints);
1341
1342         if ($avatar) {
1343             try {
1344                 $oprofile->updateAvatar($avatar);
1345             } catch (Exception $ex) {
1346                 // Profile is saved, but Avatar is messed up. We're
1347                 // just going to continue.
1348                 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1349             }
1350         }
1351
1352         return $oprofile;
1353     }
1354
1355     /**
1356      * Save any updated profile information to our local copy.
1357      * @param ActivityObject $object
1358      * @param array $hints
1359      */
1360     public function updateFromActivityObject($object, $hints=array())
1361     {
1362         if ($this->isGroup()) {
1363             $group = $this->localGroup();
1364             self::updateGroup($group, $object, $hints);
1365         } else if ($this->isPeopletag()) {
1366             $ptag = $this->localPeopletag();
1367             self::updatePeopletag($ptag, $object, $hints);
1368         } else {
1369             $profile = $this->localProfile();
1370             self::updateProfile($profile, $object, $hints);
1371         }
1372
1373         $avatar = self::getActivityObjectAvatar($object, $hints);
1374         if ($avatar && !isset($ptag)) {
1375             try {
1376                 $this->updateAvatar($avatar);
1377             } catch (Exception $ex) {
1378                 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1379             }
1380         }
1381     }
1382
1383     public static function updateProfile($profile, $object, $hints=array())
1384     {
1385         $orig = clone($profile);
1386
1387         // Existing nickname is better than nothing.
1388
1389         if (!array_key_exists('nickname', $hints)) {
1390             $hints['nickname'] = $profile->nickname;
1391         }
1392
1393         $nickname = self::getActivityObjectNickname($object, $hints);
1394
1395         if (!empty($nickname)) {
1396             $profile->nickname = $nickname;
1397         }
1398
1399         if (!empty($object->title)) {
1400             $profile->fullname = $object->title;
1401         } else if (array_key_exists('fullname', $hints)) {
1402             $profile->fullname = $hints['fullname'];
1403         }
1404
1405         if (!empty($object->link)) {
1406             $profile->profileurl = $object->link;
1407         } else if (array_key_exists('profileurl', $hints)) {
1408             $profile->profileurl = $hints['profileurl'];
1409         } else if (Validate::uri($object->id, array('allowed_schemes' => array('http', 'https')))) {
1410             $profile->profileurl = $object->id;
1411         }
1412
1413         $bio = self::getActivityObjectBio($object, $hints);
1414
1415         if (!empty($bio)) {
1416             $profile->bio = $bio;
1417         }
1418
1419         $location = self::getActivityObjectLocation($object, $hints);
1420
1421         if (!empty($location)) {
1422             $profile->location = $location;
1423         }
1424
1425         $homepage = self::getActivityObjectHomepage($object, $hints);
1426
1427         if (!empty($homepage)) {
1428             $profile->homepage = $homepage;
1429         }
1430
1431         if (!empty($object->geopoint)) {
1432             $location = ActivityContext::locationFromPoint($object->geopoint);
1433             if (!empty($location)) {
1434                 $profile->lat = $location->lat;
1435                 $profile->lon = $location->lon;
1436             }
1437         }
1438
1439         // @fixme tags/categories
1440         // @todo tags from categories
1441
1442         if ($profile->id) {
1443             common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1444             $profile->update($orig);
1445         }
1446     }
1447
1448     protected static function updateGroup($group, $object, $hints=array())
1449     {
1450         $orig = clone($group);
1451
1452         $group->nickname = self::getActivityObjectNickname($object, $hints);
1453         $group->fullname = $object->title;
1454
1455         if (!empty($object->link)) {
1456             $group->mainpage = $object->link;
1457         } else if (array_key_exists('profileurl', $hints)) {
1458             $group->mainpage = $hints['profileurl'];
1459         }
1460
1461         // @todo tags from categories
1462         $group->description = self::getActivityObjectBio($object, $hints);
1463         $group->location = self::getActivityObjectLocation($object, $hints);
1464         $group->homepage = self::getActivityObjectHomepage($object, $hints);
1465
1466         if ($group->id) {
1467             common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1468             $group->update($orig);
1469         }
1470     }
1471
1472     protected static function updatePeopletag($tag, $object, $hints=array()) {
1473         $orig = clone($tag);
1474
1475         $tag->tag = $object->title;
1476
1477         if (!empty($object->link)) {
1478             $tag->mainpage = $object->link;
1479         } else if (array_key_exists('profileurl', $hints)) {
1480             $tag->mainpage = $hints['profileurl'];
1481         }
1482
1483         $tag->description = $object->summary;
1484         $tagger = self::ensureActivityObjectProfile($object->owner);
1485         $tag->tagger = $tagger->profile_id;
1486
1487         if ($tag->id) {
1488             common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1489             $tag->update($orig);
1490         }
1491     }
1492
1493     protected static function getActivityObjectHomepage($object, $hints=array())
1494     {
1495         $homepage = null;
1496         $poco     = $object->poco;
1497
1498         if (!empty($poco)) {
1499             $url = $poco->getPrimaryURL();
1500             if ($url && $url->type == 'homepage') {
1501                 $homepage = $url->value;
1502             }
1503         }
1504
1505         // @todo Try for a another PoCo URL?
1506
1507         return $homepage;
1508     }
1509
1510     protected static function getActivityObjectLocation($object, $hints=array())
1511     {
1512         $location = null;
1513
1514         if (!empty($object->poco) &&
1515             isset($object->poco->address->formatted)) {
1516             $location = $object->poco->address->formatted;
1517         } else if (array_key_exists('location', $hints)) {
1518             $location = $hints['location'];
1519         }
1520
1521         if (!empty($location)) {
1522             if (mb_strlen($location) > 255) {
1523                 $location = mb_substr($note, 0, 255 - 3) . ' â€¦ ';
1524             }
1525         }
1526
1527         // @todo Try to find location some othe way? Via goerss point?
1528
1529         return $location;
1530     }
1531
1532     protected static function getActivityObjectBio($object, $hints=array())
1533     {
1534         $bio  = null;
1535
1536         if (!empty($object->poco)) {
1537             $note = $object->poco->note;
1538         } else if (array_key_exists('bio', $hints)) {
1539             $note = $hints['bio'];
1540         }
1541
1542         if (!empty($note)) {
1543             if (Profile::bioTooLong($note)) {
1544                 // XXX: truncate ok?
1545                 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' â€¦ ';
1546             } else {
1547                 $bio = $note;
1548             }
1549         }
1550
1551         // @todo Try to get bio info some other way?
1552
1553         return $bio;
1554     }
1555
1556     public static function getActivityObjectNickname($object, $hints=array())
1557     {
1558         if ($object->poco) {
1559             if (!empty($object->poco->preferredUsername)) {
1560                 return common_nicknamize($object->poco->preferredUsername);
1561             }
1562         }
1563
1564         if (!empty($object->nickname)) {
1565             return common_nicknamize($object->nickname);
1566         }
1567
1568         if (array_key_exists('nickname', $hints)) {
1569             return $hints['nickname'];
1570         }
1571
1572         // Try the profile url (like foo.example.com or example.com/user/foo)
1573         if (!empty($object->link)) {
1574             $profileUrl = $object->link;
1575         } else if (!empty($hints['profileurl'])) {
1576             $profileUrl = $hints['profileurl'];
1577         }
1578
1579         if (!empty($profileUrl)) {
1580             $nickname = self::nicknameFromURI($profileUrl);
1581         }
1582
1583         // Try the URI (may be a tag:, http:, acct:, ...
1584
1585         if (empty($nickname)) {
1586             $nickname = self::nicknameFromURI($object->id);
1587         }
1588
1589         // Try a Webfinger if one was passed (way) down
1590
1591         if (empty($nickname)) {
1592             if (array_key_exists('webfinger', $hints)) {
1593                 $nickname = self::nicknameFromURI($hints['webfinger']);
1594             }
1595         }
1596
1597         // Try the name
1598
1599         if (empty($nickname)) {
1600             $nickname = common_nicknamize($object->title);
1601         }
1602
1603         return $nickname;
1604     }
1605
1606     protected static function nicknameFromURI($uri)
1607     {
1608         if (preg_match('/(\w+):/', $uri, $matches)) {
1609             $protocol = $matches[1];
1610         } else {
1611             return null;
1612         }
1613
1614         switch ($protocol) {
1615         case 'acct':
1616         case 'mailto':
1617             if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1618                 return common_canonical_nickname($matches[1]);
1619             }
1620             return null;
1621         case 'http':
1622             return common_url_to_nickname($uri);
1623             break;
1624         default:
1625             return null;
1626         }
1627     }
1628
1629     /**
1630      * Look up, and if necessary create, an Ostatus_profile for the remote
1631      * entity with the given webfinger address.
1632      * This should never return null -- you will either get an object or
1633      * an exception will be thrown.
1634      *
1635      * @param string $addr webfinger address
1636      * @return Ostatus_profile
1637      * @throws Exception on error conditions
1638      * @throws OStatusShadowException if this reference would obscure a local user/group
1639      */
1640     public static function ensureWebfinger($addr)
1641     {
1642         // First, try the cache
1643
1644         $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1645
1646         if ($uri !== false) {
1647             if (is_null($uri)) {
1648                 // Negative cache entry
1649                 // TRANS: Exception.
1650                 throw new Exception(_m('Not a valid webfinger address.'));
1651             }
1652             $oprofile = Ostatus_profile::staticGet('uri', $uri);
1653             if (!empty($oprofile)) {
1654                 return $oprofile;
1655             }
1656         }
1657
1658         // Try looking it up
1659         $oprofile = Ostatus_profile::staticGet('uri', 'acct:'.$addr);
1660
1661         if (!empty($oprofile)) {
1662             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1663             return $oprofile;
1664         }
1665
1666         // Now, try some discovery
1667
1668         $disco = new Discovery();
1669
1670         try {
1671             $xrd = $disco->lookup($addr);
1672         } catch (Exception $e) {
1673             // Save negative cache entry so we don't waste time looking it up again.
1674             // @fixme distinguish temporary failures?
1675             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1676                 // TRANS: Exception.
1677             throw new Exception(_m('Not a valid webfinger address.'));
1678         }
1679
1680         $hints = array('webfinger' => $addr);
1681
1682         $dhints = DiscoveryHints::fromXRD($xrd);
1683
1684         $hints = array_merge($hints, $dhints);
1685
1686         // If there's an Hcard, let's grab its info
1687         if (array_key_exists('hcard', $hints)) {
1688             if (!array_key_exists('profileurl', $hints) ||
1689                 $hints['hcard'] != $hints['profileurl']) {
1690                 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1691                 $hints = array_merge($hcardHints, $hints);
1692             }
1693         }
1694
1695         // If we got a feed URL, try that
1696         if (array_key_exists('feedurl', $hints)) {
1697             try {
1698                 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1699                 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1700                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1701                 return $oprofile;
1702             } catch (Exception $e) {
1703                 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1704                 // keep looking
1705             }
1706         }
1707
1708         // If we got a profile page, try that!
1709         if (array_key_exists('profileurl', $hints)) {
1710             try {
1711                 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1712                 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1713                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1714                 return $oprofile;
1715             } catch (OStatusShadowException $e) {
1716                 // We've ended up with a remote reference to a local user or group.
1717                 // @fixme ideally we should be able to say who it was so we can
1718                 // go back and refer to it the regular way
1719                 throw $e;
1720             } catch (Exception $e) {
1721                 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1722                 // keep looking
1723                 //
1724                 // @fixme this means an error discovering from profile page
1725                 // may give us a corrupt entry using the webfinger URI, which
1726                 // will obscure the correct page-keyed profile later on.
1727             }
1728         }
1729
1730         // XXX: try hcard
1731         // XXX: try FOAF
1732
1733         if (array_key_exists('salmon', $hints)) {
1734
1735             $salmonEndpoint = $hints['salmon'];
1736
1737             // An account URL, a salmon endpoint, and a dream? Not much to go
1738             // on, but let's give it a try
1739
1740             $uri = 'acct:'.$addr;
1741
1742             $profile = new Profile();
1743
1744             $profile->nickname = self::nicknameFromUri($uri);
1745             $profile->created  = common_sql_now();
1746
1747             if (isset($profileUrl)) {
1748                 $profile->profileurl = $profileUrl;
1749             }
1750
1751             $profile_id = $profile->insert();
1752
1753             if (!$profile_id) {
1754                 common_log_db_error($profile, 'INSERT', __FILE__);
1755                 // TRANS: Exception. %s is a webfinger address.
1756                 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1757             }
1758
1759             $oprofile = new Ostatus_profile();
1760
1761             $oprofile->uri        = $uri;
1762             $oprofile->salmonuri  = $salmonEndpoint;
1763             $oprofile->profile_id = $profile_id;
1764             $oprofile->created    = common_sql_now();
1765
1766             if (isset($feedUrl)) {
1767                 $profile->feeduri = $feedUrl;
1768             }
1769
1770             $result = $oprofile->insert();
1771
1772             if (!$result) {
1773                 common_log_db_error($oprofile, 'INSERT', __FILE__);
1774                 // TRANS: Exception. %s is a webfinger address.
1775                 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1776             }
1777
1778             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1779             return $oprofile;
1780         }
1781
1782         // TRANS: Exception. %s is a webfinger address.
1783         throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1784     }
1785
1786     /**
1787      * Store the full-length scrubbed HTML of a remote notice to an attachment
1788      * file on our server. We'll link to this at the end of the cropped version.
1789      *
1790      * @param string $title plaintext for HTML page's title
1791      * @param string $rendered HTML fragment for HTML page's body
1792      * @return File
1793      */
1794     function saveHTMLFile($title, $rendered)
1795     {
1796         $final = sprintf("<!DOCTYPE html>\n" .
1797                          '<html><head>' .
1798                          '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1799                          '<title>%s</title>' .
1800                          '</head>' .
1801                          '<body>%s</body></html>',
1802                          htmlspecialchars($title),
1803                          $rendered);
1804
1805         $filename = File::filename($this->localProfile(),
1806                                    'ostatus', // ignored?
1807                                    'text/html');
1808
1809         $filepath = File::path($filename);
1810
1811         file_put_contents($filepath, $final);
1812
1813         $file = new File;
1814
1815         $file->filename = $filename;
1816         $file->url      = File::url($filename);
1817         $file->size     = filesize($filepath);
1818         $file->date     = time();
1819         $file->mimetype = 'text/html';
1820
1821         $file_id = $file->insert();
1822
1823         if ($file_id === false) {
1824             common_log_db_error($file, "INSERT", __FILE__);
1825             // TRANS: Server exception.
1826             throw new ServerException(_m('Could not store HTML content of long post as file.'));
1827         }
1828
1829         return $file;
1830     }
1831
1832     static function ensureProfileURI($uri)
1833     {
1834         $oprofile = null;
1835
1836         // First, try to query it
1837
1838         $oprofile = Ostatus_profile::staticGet('uri', $uri);
1839
1840         // If unfound, do discovery stuff
1841
1842         if (empty($oprofile)) {
1843             if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1844                 $protocol = $match[1];
1845                 switch ($protocol) {
1846                 case 'http':
1847                 case 'https':
1848                     $oprofile = Ostatus_profile::ensureProfileURL($uri);
1849                     break;
1850                 case 'acct':
1851                 case 'mailto':
1852                     $rest = $match[2];
1853                     $oprofile = Ostatus_profile::ensureWebfinger($rest);
1854                     break;
1855                 default:
1856                     // TRANS: Server exception.
1857                     // TRANS: %1$s is a protocol, %2$s is a URI.
1858                     throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1859                                                       $protocol,
1860                                                       $uri));
1861                     break;
1862                 }
1863             } else {
1864                 // TRANS: Server exception. %s is a URI.
1865                 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1866             }
1867         }
1868
1869         return $oprofile;
1870     }
1871
1872     function checkAuthorship($activity)
1873     {
1874         if ($this->isGroup() || $this->isPeopletag()) {
1875             // A group or propletag feed will contain posts from multiple authors.
1876             $oprofile = self::ensureActorProfile($activity);
1877             if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1878                 // Groups can't post notices in StatusNet.
1879                 common_log(LOG_WARNING,
1880                     "OStatus: skipping post with group listed ".
1881                     "as author: $oprofile->uri in feed from $this->uri");
1882                 return false;
1883             }
1884         } else {
1885             $actor = $activity->actor;
1886
1887             if (empty($actor)) {
1888                 // OK here! assume the default
1889             } else if ($actor->id == $this->uri || $actor->link == $this->uri) {
1890                 $this->updateFromActivityObject($actor);
1891             } else if ($actor->id) {
1892                 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1893                 // This isn't what we expect from mainline OStatus person feeds!
1894                 // Group feeds go down another path, with different validation...
1895                 // Most likely this is a plain ol' blog feed of some kind which
1896                 // doesn't match our expectations. We'll take the entry, but ignore
1897                 // the <author> info.
1898                 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for {$this->uri}");
1899             } else {
1900                 // Plain <author> without ActivityStreams actor info.
1901                 // We'll just ignore this info for now and save the update under the feed's identity.
1902             }
1903
1904             $oprofile = $this;
1905         }
1906
1907         return $oprofile;
1908     }
1909 }
1910
1911 /**
1912  * Exception indicating we've got a remote reference to a local user,
1913  * not a remote user!
1914  *
1915  * If we can ue a local profile after all, it's available as $e->profile.
1916  */
1917 class OStatusShadowException extends Exception
1918 {
1919     public $profile;
1920
1921     /**
1922      * @param Profile $profile
1923      * @param string $message
1924      */
1925     function __construct($profile, $message) {
1926         $this->profile = $profile;
1927         parent::__construct($message);
1928     }
1929 }