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