]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Ostatus_profile.php
OStatus: do PuSH subscription setup from subscribe/join event hooks, so resubscribing...
[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 /**
21  * @package OStatusPlugin
22  * @maintainer Brion Vibber <brion@status.net>
23  */
24
25 class Ostatus_profile extends Memcached_DataObject
26 {
27     public $__table = 'ostatus_profile';
28
29     public $uri;
30
31     public $profile_id;
32     public $group_id;
33
34     public $feeduri;
35     public $salmonuri;
36
37     public $created;
38     public $modified;
39
40     public /*static*/ function staticGet($k, $v=null)
41     {
42         return parent::staticGet(__CLASS__, $k, $v);
43     }
44
45     /**
46      * return table definition for DB_DataObject
47      *
48      * DB_DataObject needs to know something about the table to manipulate
49      * instances. This method provides all the DB_DataObject needs to know.
50      *
51      * @return array array of column definitions
52      */
53
54     function table()
55     {
56         return array('uri' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
57                      'profile_id' => DB_DATAOBJECT_INT,
58                      'group_id' => DB_DATAOBJECT_INT,
59                      'feeduri' => DB_DATAOBJECT_STR,
60                      'salmonuri' =>  DB_DATAOBJECT_STR,
61                      'created' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL,
62                      'modified' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL);
63     }
64
65     static function schemaDef()
66     {
67         return array(new ColumnDef('uri', 'varchar',
68                                    255, false, 'PRI'),
69                      new ColumnDef('profile_id', 'integer',
70                                    null, true, 'UNI'),
71                      new ColumnDef('group_id', 'integer',
72                                    null, true, 'UNI'),
73                      new ColumnDef('feeduri', 'varchar',
74                                    255, true, 'UNI'),
75                      new ColumnDef('salmonuri', 'text',
76                                    null, true),
77                      new ColumnDef('created', 'datetime',
78                                    null, false),
79                      new ColumnDef('modified', 'datetime',
80                                    null, false));
81     }
82
83     /**
84      * return key definitions for DB_DataObject
85      *
86      * DB_DataObject needs to know about keys that the table has; this function
87      * defines them.
88      *
89      * @return array key definitions
90      */
91
92     function keys()
93     {
94         return array_keys($this->keyTypes());
95     }
96
97     /**
98      * return key definitions for Memcached_DataObject
99      *
100      * Our caching system uses the same key definitions, but uses a different
101      * method to get them.
102      *
103      * @return array key definitions
104      */
105
106     function keyTypes()
107     {
108         return array('uri' => 'K', 'profile_id' => 'U', 'group_id' => 'U', 'feeduri' => 'U');
109     }
110
111     function sequenceKey()
112     {
113         return array(false, false, false);
114     }
115
116     /**
117      * Fetch the StatusNet-side profile for this feed
118      * @return Profile
119      */
120     public function localProfile()
121     {
122         if ($this->profile_id) {
123             return Profile::staticGet('id', $this->profile_id);
124         }
125         return null;
126     }
127
128     /**
129      * Fetch the StatusNet-side profile for this feed
130      * @return Profile
131      */
132     public function localGroup()
133     {
134         if ($this->group_id) {
135             return User_group::staticGet('id', $this->group_id);
136         }
137         return null;
138     }
139
140     /**
141      * Returns an ActivityObject describing this remote user or group profile.
142      * Can then be used to generate Atom chunks.
143      *
144      * @return ActivityObject
145      */
146     function asActivityObject()
147     {
148         if ($this->isGroup()) {
149             $object = new ActivityObject();
150             $object->type = 'http://activitystrea.ms/schema/1.0/group';
151             $object->id = $this->uri;
152             $self = $this->localGroup();
153
154             // @fixme put a standard getAvatar() interface on groups too
155             if ($self->homepage_logo) {
156                 $object->avatar = $self->homepage_logo;
157                 $map = array('png' => 'image/png',
158                              'jpg' => 'image/jpeg',
159                              'jpeg' => 'image/jpeg',
160                              'gif' => 'image/gif');
161                 $extension = pathinfo(parse_url($avatarHref, PHP_URL_PATH), PATHINFO_EXTENSION);
162                 if (isset($map[$extension])) {
163                     // @fixme this ain't used/saved yet
164                     $object->avatarType = $map[$extension];
165                 }
166             }
167
168             $object->link = $this->uri; // @fixme accurate?
169             return $object;
170         } else {
171             return ActivityObject::fromProfile($this->localProfile());
172         }
173     }
174
175     /**
176      * Returns an XML string fragment with profile information as an
177      * Activity Streams noun object with the given element type.
178      *
179      * Assumes that 'activity' namespace has been previously defined.
180      *
181      * @fixme replace with wrappers on asActivityObject when it's got everything.
182      *
183      * @param string $element one of 'actor', 'subject', 'object', 'target'
184      * @return string
185      */
186     function asActivityNoun($element)
187     {
188         $xs = new XMLStringer(true);
189         $avatarHref = Avatar::defaultImage(AVATAR_PROFILE_SIZE);
190         $avatarType = 'image/png';
191         if ($this->isGroup()) {
192             $type = 'http://activitystrea.ms/schema/1.0/group';
193             $self = $this->localGroup();
194
195             // @fixme put a standard getAvatar() interface on groups too
196             if ($self->homepage_logo) {
197                 $avatarHref = $self->homepage_logo;
198                 $map = array('png' => 'image/png',
199                              'jpg' => 'image/jpeg',
200                              'jpeg' => 'image/jpeg',
201                              'gif' => 'image/gif');
202                 $extension = pathinfo(parse_url($avatarHref, PHP_URL_PATH), PATHINFO_EXTENSION);
203                 if (isset($map[$extension])) {
204                     $avatarType = $map[$extension];
205                 }
206             }
207         } else {
208             $type = 'http://activitystrea.ms/schema/1.0/person';
209             $self = $this->localProfile();
210             $avatar = $self->getAvatar(AVATAR_PROFILE_SIZE);
211             if ($avatar) {
212                   $avatarHref = $avatar->url;
213                   $avatarType = $avatar->mediatype;
214             }
215         }
216         $xs->elementStart('activity:' . $element);
217         $xs->element(
218             'activity:object-type',
219             null,
220             $type
221         );
222         $xs->element(
223             'id',
224             null,
225             $this->uri); // ?
226         $xs->element('title', null, $self->getBestName());
227
228         $xs->element(
229             'link', array(
230                 'type' => $avatarType,
231                 'href' => $avatarHref
232             ),
233             ''
234         );
235
236         $xs->elementEnd('activity:' . $element);
237
238         return $xs->getString();
239     }
240
241     /**
242      * @return boolean true if this is a remote group
243      */
244     function isGroup()
245     {
246         if ($this->profile_id && !$this->group_id) {
247             return false;
248         } else if ($this->group_id && !$this->profile_id) {
249             return true;
250         } else if ($this->group_id && $this->profile_id) {
251             throw new ServerException("Invalid ostatus_profile state: both group and profile IDs set for $this->uri");
252         } else {
253             throw new ServerException("Invalid ostatus_profile state: both group and profile IDs empty for $this->uri");
254         }
255     }
256
257     /**
258      * Subscribe a local user to this remote user.
259      * PuSH subscription will be started if necessary, and we'll
260      * send a Salmon notification to the remote server if available
261      * notifying them of the sub.
262      *
263      * @param User $user
264      * @return boolean success
265      * @throws FeedException
266      */
267     public function subscribeLocalToRemote(User $user)
268     {
269         if ($this->isGroup()) {
270             throw new ServerException("Can't subscribe to a remote group");
271         }
272
273         if ($this->subscribe()) {
274             if ($user->subscribeTo($this->localProfile())) {
275                 $this->notify($user->getProfile(), ActivityVerb::FOLLOW, $this);
276                 return true;
277             }
278         }
279         return false;
280     }
281
282     /**
283      * Mark this remote profile as subscribing to the given local user,
284      * and send appropriate notifications to the user.
285      *
286      * This will generally be in response to a subscription notification
287      * from a foreign site to our local Salmon response channel.
288      *
289      * @param User $user
290      * @return boolean success
291      */
292     public function subscribeRemoteToLocal(User $user)
293     {
294         if ($this->isGroup()) {
295             throw new ServerException("Remote groups can't subscribe to local users");
296         }
297
298         // @fixme use regular channels for subbing, once they accept remote profiles
299         $sub = new Subscription();
300         $sub->subscriber = $this->profile_id;
301         $sub->subscribed = $user->id;
302         $sub->created = common_sql_now(); // current time
303
304         if ($sub->insert()) {
305             // @fixme use subs_notify() if refactored to take profiles?
306             mail_subscribe_notify_profile($user, $this->localProfile());
307             return true;
308         }
309         return false;
310     }
311
312     /**
313      * Send a subscription request to the hub for this feed.
314      * The hub will later send us a confirmation POST to /main/push/callback.
315      *
316      * @return bool true on success, false on failure
317      * @throws ServerException if feed state is not valid
318      */
319     public function subscribe()
320     {
321         $feedsub = FeedSub::ensureFeed($this->feeduri);
322         if ($feedsub->sub_state == 'active' || $feedsub->sub_state == 'subscribe') {
323             return true;
324         } else if ($feedsub->sub_state == '' || $feedsub->sub_state == 'inactive') {
325             return $feedsub->subscribe();
326         } else if ('unsubscribe') {
327             throw new FeedSubException("Unsub is pending, can't subscribe...");
328         }
329     }
330
331     /**
332      * Send a PuSH unsubscription request to the hub for this feed.
333      * The hub will later send us a confirmation POST to /main/push/callback.
334      *
335      * @return bool true on success, false on failure
336      * @throws ServerException if feed state is not valid
337      */
338     public function unsubscribe() {
339         $feedsub = FeedSub::staticGet('uri', $this->feeduri);
340         if ($feedsub->sub_state == 'active') {
341             return $feedsub->unsubscribe();
342         } else if ($feedsub->sub_state == '' || $feedsub->sub_state == 'inactive' || $feedsub->sub_state == 'unsubscribe') {
343             return true;
344         } else if ($feedsub->sub_state == 'subscribe') {
345             throw new FeedSubException("Feed is awaiting subscription, can't unsub...");
346         }
347     }
348
349     /**
350      * Check if this remote profile has any active local subscriptions, and
351      * if not drop the PuSH subscription feed.
352      *
353      * @return boolean
354      */
355     public function garbageCollect()
356     {
357         if ($this->isGroup()) {
358             $members = $this->localGroup()->getMembers(0, 1);
359             $count = $members->N;
360         } else {
361             $count = $this->localProfile()->subscriberCount();
362         }
363         if ($count == 0) {
364             common_log(LOG_INFO, "Unsubscribing from now-unused remote feed $oprofile->feeduri");
365             $this->unsubscribe();
366             return true;
367         } else {
368             return false;
369         }
370     }
371
372     /**
373      * Send an Activity Streams notification to the remote Salmon endpoint,
374      * if so configured.
375      *
376      * @param Profile $actor  Actor who did the activity
377      * @param string  $verb   Activity::SUBSCRIBE or Activity::JOIN
378      * @param Object  $object object of the action; must define asActivityNoun($tag)
379      */
380     public function notify($actor, $verb, $object=null)
381     {
382         if (!($actor instanceof Profile)) {
383             $type = gettype($actor);
384             if ($type == 'object') {
385                 $type = get_class($actor);
386             }
387             throw new ServerException("Invalid actor passed to " . __METHOD__ . ": " . $type);
388         }
389         if ($object == null) {
390             $object = $this;
391         }
392         if ($this->salmonuri) {
393
394             $text = 'update';
395             $id = TagURI::mint('%s:%s:%s',
396                                $verb,
397                                $actor->getURI(),
398                                common_date_iso8601(time()));
399
400             // @fixme consolidate all these NS settings somewhere
401             $attributes = array('xmlns' => Activity::ATOM,
402                                 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
403                                 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
404                                 'xmlns:georss' => 'http://www.georss.org/georss',
405                                 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
406                                 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0');
407
408             $entry = new XMLStringer();
409             $entry->elementStart('entry', $attributes);
410             $entry->element('id', null, $id);
411             $entry->element('title', null, $text);
412             $entry->element('summary', null, $text);
413             $entry->element('published', null, common_date_w3dtf(common_sql_now()));
414
415             $entry->element('activity:verb', null, $verb);
416             $entry->raw($actor->asAtomAuthor());
417             $entry->raw($actor->asActivityActor());
418             $entry->raw($object->asActivityNoun('object'));
419             $entry->elementEnd('entry');
420
421             $xml = $entry->getString();
422             common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
423
424             $salmon = new Salmon(); // ?
425             return $salmon->post($this->salmonuri, $xml);
426         }
427         return false;
428     }
429
430     public function notifyActivity($activity)
431     {
432         if ($this->salmonuri) {
433
434             $xml = '<?xml version="1.0" encoding="UTF-8" ?' . '>' .
435                           $activity->asString(true);
436
437             $salmon = new Salmon(); // ?
438
439             return $salmon->post($this->salmonuri, $xml);
440         }
441
442         return false;
443     }
444
445     function getBestName()
446     {
447         if ($this->isGroup()) {
448             return $this->localGroup()->getBestName();
449         } else {
450             return $this->localProfile()->getBestName();
451         }
452     }
453
454     function atomFeed($actor)
455     {
456         $feed = new Atom10Feed();
457         // @fixme should these be set up somewhere else?
458         $feed->addNamespace('activity', 'http://activitystrea.ms/spec/1.0/');
459         $feed->addNamespace('thr', 'http://purl.org/syndication/thread/1.0');
460         $feed->addNamespace('georss', 'http://www.georss.org/georss');
461         $feed->addNamespace('ostatus', 'http://ostatus.org/schema/1.0');
462
463         $taguribase = common_config('integration', 'taguri');
464         $feed->setId("tag:{$taguribase}:UserTimeline:{$actor->id}"); // ???
465
466         $feed->setTitle($actor->getBestName() . ' timeline'); // @fixme
467         $feed->setUpdated(time());
468         $feed->setPublished(time());
469
470         $feed->addLink(common_local_url('ApiTimelineUser',
471                                         array('id' => $actor->id,
472                                               'type' => 'atom')),
473                        array('rel' => 'self',
474                              'type' => 'application/atom+xml'));
475
476         $feed->addLink(common_local_url('userbyid',
477                                         array('id' => $actor->id)),
478                        array('rel' => 'alternate',
479                              'type' => 'text/html'));
480
481         return $feed;
482     }
483
484     /**
485      * Read and post notices for updates from the feed.
486      * Currently assumes that all items in the feed are new,
487      * coming from a PuSH hub.
488      *
489      * @param DOMDocument $feed
490      */
491     public function processFeed($feed)
492     {
493         $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
494         if ($entries->length == 0) {
495             common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
496             return;
497         }
498
499         for ($i = 0; $i < $entries->length; $i++) {
500             $entry = $entries->item($i);
501             $this->processEntry($entry, $feed);
502         }
503     }
504
505     /**
506      * Process a posted entry from this feed source.
507      *
508      * @param DOMElement $entry
509      * @param DOMElement $feed for context
510      */
511     protected function processEntry($entry, $feed)
512     {
513         $activity = new Activity($entry, $feed);
514
515         $debug = var_export($activity, true);
516         common_log(LOG_DEBUG, $debug);
517
518         if ($activity->verb == ActivityVerb::POST) {
519             $this->processPost($activity);
520         } else {
521             common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
522         }
523     }
524
525     /**
526      * Process an incoming post activity from this remote feed.
527      * @param Activity $activity
528      * @fixme break up this function, it's getting nasty long
529      */
530     protected function processPost($activity)
531     {
532         if ($this->isGroup()) {
533             // @fixme validate these profiles in some way!
534             $oprofile = self::ensureActorProfile($activity);
535         } else {
536             $actorUri = self::getActorProfileURI($activity);
537             if ($actorUri == $this->uri) {
538                 // @fixme check if profile info has changed and update it
539             } else {
540                 // @fixme drop or reject the messages once we've got the canonical profile URI recorded sanely
541                 common_log(LOG_INFO, "OStatus: Warning: non-group post with unexpected author: $actorUri expected $this->uri");
542                 //return;
543             }
544             $oprofile = $this;
545         }
546         $sourceUri = $activity->object->id;
547
548         $dupe = Notice::staticGet('uri', $sourceUri);
549
550         if ($dupe) {
551             common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
552             return;
553         }
554
555         $sourceUrl = null;
556
557         if ($activity->object->link) {
558             $sourceUrl = $activity->object->link;
559         } else if (preg_match('!^https?://!', $activity->object->id)) {
560             $sourceUrl = $activity->object->id;
561         }
562
563         // @fixme sanitize and save HTML content if available
564
565         $content = $activity->object->title;
566
567         $params = array('is_local' => Notice::REMOTE_OMB,
568                         'url' => $sourceUrl,
569                         'uri' => $sourceUri);
570
571         $location = $activity->context->location;
572
573         if ($location) {
574             $params['lat'] = $location->lat;
575             $params['lon'] = $location->lon;
576             if ($location->location_id) {
577                 $params['location_ns'] = $location->location_ns;
578                 $params['location_id'] = $location->location_id;
579             }
580         }
581
582         $profile = $oprofile->localProfile();
583         $params['groups'] = array();
584         $params['replies'] = array();
585         if ($activity->context) {
586             foreach ($activity->context->attention as $recipient) {
587                 $roprofile = Ostatus_profile::staticGet('uri', $recipient);
588                 if ($roprofile) {
589                     if ($roprofile->isGroup()) {
590                         // Deliver to local recipients of this remote group.
591                         // @fixme sender verification?
592                         $params['groups'][] = $roprofile->group_id;
593                         continue;
594                     } else {
595                         // Delivery to remote users is the source service's job.
596                         continue;
597                     }
598                 }
599     
600                 $user = User::staticGet('uri', $recipient);
601                 if ($user) {
602                     // An @-reply directed to a local user.
603                     // @fixme sender verification, spam etc?
604                     $params['replies'][] = $recipient;
605                     continue;
606                 }
607     
608                 // @fixme we need a uri on user_group
609                 // $group = User_group::staticGet('uri', $recipient);
610                 $template = common_local_url('groupbyid', array('id' => '31337'));
611                 $template = preg_quote($template, '/');
612                 $template = str_replace('31337', '(\d+)', $template);
613                 common_log(LOG_DEBUG, $template);
614                 if (preg_match("/$template/", $recipient, $matches)) {
615                     $id = $matches[1];
616                     $group = User_group::staticGet('id', $id);
617                     if ($group) {
618                         // Deliver to all members of this local group.
619                         // @fixme sender verification?
620                         if ($profile->isMember($group)) {
621                             common_log(LOG_DEBUG, "delivering to group $id $group->nickname");
622                             $params['groups'][] = $group->id;
623                         } else {
624                             common_log(LOG_DEBUG, "not delivering to group $id $group->nickname because sender $profile->nickname is not a member");
625                         }
626                         continue;
627                     } else {
628                         common_log(LOG_DEBUG, "not delivering to missing group $id");
629                     }
630                 } else {
631                     common_log(LOG_DEBUG, "not delivering to groups for $recipient");
632                 }
633             }
634         }
635
636         try {
637             $saved = Notice::saveNew($profile->id,
638                                      $content,
639                                      'ostatus',
640                                      $params);
641         } catch (Exception $e) {
642             common_log(LOG_ERR, "Failed saving notice entry for $sourceUri: " . $e->getMessage());
643             return;
644         }
645
646         // Record which feed this came through...
647         try {
648             Ostatus_source::saveNew($saved, $this, 'push');
649         } catch (Exception $e) {
650             common_log(LOG_ERR, "Failed saving ostatus_source entry for $saved->notice_id: " . $e->getMessage());
651         }
652     }
653
654     /**
655      * @param string $profile_url
656      * @return Ostatus_profile
657      * @throws FeedSubException
658      */
659     public static function ensureProfile($profile_uri, $hints=array())
660     {
661         // Get the canonical feed URI and check it
662         $discover = new FeedDiscovery();
663         $feeduri = $discover->discoverFromURL($profile_uri);
664
665         //$feedsub = FeedSub::ensureFeed($feeduri, $discover->feed);
666         $huburi = $discover->getAtomLink('hub');
667         $salmonuri = $discover->getAtomLink('salmon');
668
669         if (!$huburi) {
670             // We can only deal with folks with a PuSH hub
671             throw new FeedSubNoHubException();
672         }
673
674         // Try to get a profile from the feed activity:subject
675
676         $feedEl = $discover->feed->documentElement;
677
678         $subject = ActivityUtils::child($feedEl, Activity::SUBJECT, Activity::SPEC);
679
680         if (!empty($subject)) {
681             $subjObject = new ActivityObject($subject);
682             return self::ensureActivityObjectProfile($subjObject, $feeduri, $salmonuri, $hints);
683         }
684
685         // Otherwise, try the feed author
686
687         $author = ActivityUtils::child($feedEl, Activity::AUTHOR, Activity::ATOM);
688
689         if (!empty($author)) {
690             $authorObject = new ActivityObject($author);
691             return self::ensureActivityObjectProfile($authorObject, $feeduri, $salmonuri, $hints);
692         }
693
694         // Sheesh. Not a very nice feed! Let's try fingerpoken in the
695         // entries.
696
697         $entries = $discover->feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
698
699         if (!empty($entries) && $entries->length > 0) {
700
701             $entry = $entries->item(0);
702
703             $actor = ActivityUtils::child($entry, Activity::ACTOR, Activity::SPEC);
704
705             if (!empty($actor)) {
706                 $actorObject = new ActivityObject($actor);
707                 return self::ensureActivityObjectProfile($actorObject, $feeduri, $salmonuri, $hints);
708
709             }
710
711             $author = ActivityUtils::child($entry, Activity::AUTHOR, Activity::ATOM);
712
713             if (!empty($author)) {
714                 $authorObject = new ActivityObject($author);
715                 return self::ensureActivityObjectProfile($authorObject, $feeduri, $salmonuri, $hints);
716             }
717         }
718
719         // XXX: make some educated guesses here
720
721         throw new FeedSubException("Can't find enough profile information to make a feed.");
722     }
723
724     /**
725      *
726      * Download and update given avatar image
727      * @param string $url
728      * @throws Exception in various failure cases
729      */
730     protected function updateAvatar($url)
731     {
732         if ($this->isGroup()) {
733             $self = $this->localGroup();
734         } else {
735             $self = $this->localProfile();
736         }
737         if (!$self) {
738             throw new ServerException(sprintf(
739                 _m("Tried to update avatar for unsaved remote profile %s"),
740                 $this->uri));
741         }
742
743         // @fixme this should be better encapsulated
744         // ripped from oauthstore.php (for old OMB client)
745         $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
746         if (!copy($url, $temp_filename)) {
747             throw new ServerException(sprintf(_m("Unable to fetch avatar from %s"), $url));
748         }
749
750         if ($this->isGroup()) {
751             $id = $this->group_id;
752         } else {
753             $id = $this->profile_id;
754         }
755         // @fixme should we be using different ids?
756         $imagefile = new ImageFile($id, $temp_filename);
757         $filename = Avatar::filename($id,
758                                      image_type_to_extension($imagefile->type),
759                                      null,
760                                      common_timestamp());
761         rename($temp_filename, Avatar::path($filename));
762         $self->setOriginal($filename);
763     }
764
765     protected static function getActivityObjectAvatar($object)
766     {
767         // XXX: go poke around in the feed
768         return $object->avatar;
769     }
770
771     /**
772      * Get an appropriate avatar image source URL, if available.
773      *
774      * @param ActivityObject $actor
775      * @param DOMElement $feed
776      * @return string
777      */
778
779     protected static function getAvatar($actor, $feed)
780     {
781         $url = '';
782         $icon = '';
783         if ($actor->avatar) {
784             $url = trim($actor->avatar);
785         }
786         if (!$url) {
787             // Check <atom:logo> and <atom:icon> on the feed
788             $els = $feed->childNodes();
789             if ($els && $els->length) {
790                 for ($i = 0; $i < $els->length; $i++) {
791                     $el = $els->item($i);
792                     if ($el->namespaceURI == Activity::ATOM) {
793                         if (empty($url) && $el->localName == 'logo') {
794                             $url = trim($el->textContent);
795                             break;
796                         }
797                         if (empty($icon) && $el->localName == 'icon') {
798                             // Use as a fallback
799                             $icon = trim($el->textContent);
800                         }
801                     }
802                 }
803             }
804             if ($icon && !$url) {
805                 $url = $icon;
806             }
807         }
808         if ($url) {
809             $opts = array('allowed_schemes' => array('http', 'https'));
810             if (Validate::uri($url, $opts)) {
811                 return $url;
812             }
813         }
814         return common_path('plugins/OStatus/images/96px-Feed-icon.svg.png');
815     }
816
817     /**
818      * Fetch, or build if necessary, an Ostatus_profile for the actor
819      * in a given Activity Streams activity.
820      *
821      * @param Activity $activity
822      * @param string $feeduri if we already know the canonical feed URI!
823      * @param string $salmonuri if we already know the salmon return channel URI
824      * @return Ostatus_profile
825      */
826
827     public static function ensureActorProfile($activity, $feeduri=null, $salmonuri=null)
828     {
829         return self::ensureActivityObjectProfile($activity->actor, $feeduri, $salmonuri);
830     }
831
832     public static function ensureActivityObjectProfile($object, $feeduri=null, $salmonuri=null, $hints=array())
833     {
834         $profile = self::getActivityObjectProfile($object);
835         if (!$profile) {
836             $profile = self::createActivityObjectProfile($object, $feeduri, $salmonuri, $hints);
837         }
838         return $profile;
839     }
840
841     /**
842      * @param Activity $activity
843      * @return mixed matching Ostatus_profile or false if none known
844      */
845     protected static function getActorProfile($activity)
846     {
847         return self::getActivityObjectProfile($activity->actor);
848     }
849
850     protected static function getActivityObjectProfile($object)
851     {
852         $uri = self::getActivityObjectProfileURI($object);
853         return Ostatus_profile::staticGet('uri', $uri);
854     }
855
856     protected static function getActorProfileURI($activity)
857     {
858         return self::getActivityObjectProfileURI($activity->actor);
859     }
860
861     /**
862      * @param Activity $activity
863      * @return string
864      * @throws ServerException
865      */
866     protected static function getActivityObjectProfileURI($object)
867     {
868         $opts = array('allowed_schemes' => array('http', 'https'));
869         if ($object->id && Validate::uri($object->id, $opts)) {
870             return $object->id;
871         }
872         if ($object->link && Validate::uri($object->link, $opts)) {
873             return $object->link;
874         }
875         throw new ServerException("No author ID URI found");
876     }
877
878     /**
879      * @fixme validate stuff somewhere
880      */
881
882     protected static function createActorProfile($activity, $feeduri=null, $salmonuri=null)
883     {
884         $actor = $activity->actor;
885
886         self::createActivityObjectProfile($actor, $feeduri, $salmonuri);
887     }
888
889     /**
890      * Create local ostatus_profile and profile/user_group entries for
891      * the provided remote user or group.
892      *
893      * @param ActivityObject $object
894      * @param string $feeduri
895      * @param string $salmonuri
896      * @param array $hints
897      *
898      * @fixme fold $feeduri/$salmonuri into $hints
899      * @return Ostatus_profile
900      */
901     protected static function createActivityObjectProfile($object, $feeduri=null, $salmonuri=null, $hints=array())
902     {
903         $homeuri  = $object->id;
904         $nickname = self::getActivityObjectNickname($object, $hints);
905         $avatar   = self::getActivityObjectAvatar($object);
906
907         if (!$homeuri) {
908             common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
909             throw new ServerException("No profile URI");
910         }
911
912         if (empty($feeduri)) {
913             if (array_key_exists('feedurl', $hints)) {
914                 $feeduri = $hints['feedurl'];
915             }
916         }
917
918         if (empty($salmonuri)) {
919             if (array_key_exists('salmon', $hints)) {
920                 $salmonuri = $hints['salmon'];
921             }
922         }
923
924         if (!$feeduri || !$salmonuri) {
925             // Get the canonical feed URI and check it
926             $discover = new FeedDiscovery();
927             $feeduri = $discover->discoverFromURL($homeuri);
928
929             $huburi = $discover->getAtomLink('hub');
930             $salmonuri = $discover->getAtomLink('salmon');
931
932             if (!$huburi) {
933                 // We can only deal with folks with a PuSH hub
934                 throw new FeedSubNoHubException();
935             }
936         }
937
938         $oprofile = new Ostatus_profile();
939
940         $oprofile->uri        = $homeuri;
941         $oprofile->feeduri    = $feeduri;
942         $oprofile->salmonuri  = $salmonuri;
943
944         $oprofile->created    = common_sql_now();
945         $oprofile->modified   = common_sql_now();
946
947         if ($object->type == ActivityObject::PERSON) {
948             $profile = new Profile();
949             $profile->nickname   = $nickname;
950             $profile->fullname   = $object->title;
951             if (!empty($object->link)) {
952                 $profile->profileurl = $object->link;
953             } else if (array_key_exists('profileurl', $hints)) {
954                 $profile->profileurl = $hints['profileurl'];
955             }
956             $profile->created    = common_sql_now();
957     
958             // @fixme bio
959             // @fixme tags/categories
960             // @fixme location?
961             // @todo tags from categories
962             // @todo lat/lon/location?
963     
964             $oprofile->profile_id = $profile->insert();
965     
966             if (!$oprofile->profile_id) {
967                 throw new ServerException("Can't save local profile");
968             }
969         } else {
970             $group = new User_group();
971             $group->nickname = $nickname;
972             $group->fullname = $object->title;
973             // @fixme no canonical profileurl; using homepage instead for now
974             $group->homepage = $homeuri;
975             $group->created = common_sql_now();
976
977             // @fixme homepage
978             // @fixme bio
979             // @fixme tags/categories
980             // @fixme location?
981             // @todo tags from categories
982             // @todo lat/lon/location?
983
984             $oprofile->group_id = $group->insert();
985
986             if (!$oprofile->group_id) {
987                 throw new ServerException("Can't save local profile");
988             }
989         }
990
991         $ok = $oprofile->insert();
992
993         if ($ok) {
994             if ($avatar) {
995                 $oprofile->updateAvatar($avatar);
996             }
997             return $oprofile;
998         } else {
999             throw new ServerException("Can't save OStatus profile");
1000         }
1001     }
1002
1003     protected static function getActivityObjectNickname($object, $hints=array())
1004     {
1005         if (!empty($object->nickname)) {
1006             return common_nicknamize($object->nickname);
1007         }
1008
1009         // Try the definitive ID
1010
1011         $nickname = self::nicknameFromURI($object->id);
1012
1013         // Try a Webfinger if one was passed (way) down
1014
1015         if (empty($nickname)) {
1016             if (array_key_exists('webfinger', $hints)) {
1017                 $nickname = self::nicknameFromURI($hints['webfinger']);
1018             }
1019         }
1020
1021         // Try the name
1022
1023         if (empty($nickname)) {
1024             $nickname = common_nicknamize($object->title);
1025         }
1026
1027         return $nickname;
1028     }
1029
1030     protected static function nicknameFromURI($uri)
1031     {
1032         preg_match('/(\w+):/', $uri, $matches);
1033
1034         $protocol = $matches[1];
1035
1036         switch ($protocol) {
1037         case 'acct':
1038         case 'mailto':
1039             if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1040                 return common_canonical_nickname($matches[1]);
1041             }
1042             return null;
1043         case 'http':
1044             return common_url_to_nickname($uri);
1045             break;
1046         default:
1047             return null;
1048         }
1049     }
1050
1051     public static function ensureWebfinger($addr)
1052     {
1053         // First, look it up
1054
1055         $oprofile = Ostatus_profile::staticGet('uri', 'acct:'.$addr);
1056
1057         if (!empty($oprofile)) {
1058             return $oprofile;
1059         }
1060
1061         // Now, try some discovery
1062
1063         $wf = new Webfinger();
1064
1065         $result = $wf->lookup($addr);
1066
1067         if (!$result) {
1068             return null;
1069         }
1070
1071         foreach ($result->links as $link) {
1072             switch ($link['rel']) {
1073             case Webfinger::PROFILEPAGE:
1074                 $profileUrl = $link['href'];
1075                 break;
1076             case 'salmon':
1077                 $salmonEndpoint = $link['href'];
1078                 break;
1079             case Webfinger::UPDATESFROM:
1080                 $feedUrl = $link['href'];
1081                 break;
1082             default:
1083                 common_log(LOG_NOTICE, "Don't know what to do with rel = '{$link['rel']}'");
1084                 break;
1085             }
1086         }
1087
1088         $hints = array('webfinger' => $addr,
1089                        'profileurl' => $profileUrl,
1090                        'feedurl' => $feedUrl,
1091                        'salmon' => $salmonEndpoint);
1092
1093         // If we got a feed URL, try that
1094
1095         if (isset($feedUrl)) {
1096             try {
1097                 $oprofile = self::ensureProfile($feedUrl, $hints);
1098                 return $oprofile;
1099             } catch (Exception $e) {
1100                 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1101                 // keep looking
1102             }
1103         }
1104
1105         // If we got a profile page, try that!
1106
1107         if (isset($profileUrl)) {
1108             try {
1109                 $oprofile = self::ensureProfile($profileUrl, $hints);
1110                 return $oprofile;
1111             } catch (Exception $e) {
1112                 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1113                 // keep looking
1114             }
1115         }
1116
1117         // XXX: try hcard
1118         // XXX: try FOAF
1119
1120         if (isset($salmonEndpoint)) {
1121
1122             // An account URL, a salmon endpoint, and a dream? Not much to go
1123             // on, but let's give it a try
1124
1125             $uri = 'acct:'.$addr;
1126
1127             $profile = new Profile();
1128
1129             $profile->nickname = self::nicknameFromUri($uri);
1130             $profile->created  = common_sql_now();
1131
1132             if (isset($profileUrl)) {
1133                 $profile->profileurl = $profileUrl;
1134             }
1135
1136             $profile_id = $profile->insert();
1137
1138             if (!$profile_id) {
1139                 common_log_db_error($profile, 'INSERT', __FILE__);
1140                 throw new Exception("Couldn't save profile for '$addr'");
1141             }
1142
1143             $oprofile = new Ostatus_profile();
1144
1145             $oprofile->uri        = $uri;
1146             $oprofile->salmonuri  = $salmonEndpoint;
1147             $oprofile->profile_id = $profile_id;
1148             $oprofile->created    = common_sql_now();
1149
1150             if (isset($feedUrl)) {
1151                 $profile->feeduri = $feedUrl;
1152             }
1153
1154             $result = $oprofile->insert();
1155
1156             if (!$result) {
1157                 common_log_db_error($oprofile, 'INSERT', __FILE__);
1158                 throw new Exception("Couldn't save ostatus_profile for '$addr'");
1159             }
1160
1161             return $oprofile;
1162         }
1163
1164         return null;
1165     }
1166 }