]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Ostatus_profile.php
try different ways to get a profile from a feed
[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 XML string fragment with profile information as an
142      * Activity Streams noun object with the given element type.
143      *
144      * Assumes that 'activity' namespace has been previously defined.
145      *
146      * @param string $element one of 'actor', 'subject', 'object', 'target'
147      * @return string
148      */
149     function asActivityNoun($element)
150     {
151         $xs = new XMLStringer(true);
152         $avatarHref = Avatar::defaultImage(AVATAR_PROFILE_SIZE);
153         $avatarType = 'image/png';
154         if ($this->isGroup()) {
155             $type = 'http://activitystrea.ms/schema/1.0/group';
156             $self = $this->localGroup();
157
158             // @fixme put a standard getAvatar() interface on groups too
159             if ($self->homepage_logo) {
160                 $avatarHref = $self->homepage_logo;
161                 $map = array('png' => 'image/png',
162                              'jpg' => 'image/jpeg',
163                              'jpeg' => 'image/jpeg',
164                              'gif' => 'image/gif');
165                 $extension = pathinfo(parse_url($avatarHref, PHP_URL_PATH), PATHINFO_EXTENSION);
166                 if (isset($map[$extension])) {
167                     $avatarType = $map[$extension];
168                 }
169             }
170         } else {
171             $type = 'http://activitystrea.ms/schema/1.0/person';
172             $self = $this->localProfile();
173             $avatar = $self->getAvatar(AVATAR_PROFILE_SIZE);
174             if ($avatar) {
175                   $avatarHref = $avatar->url;
176                   $avatarType = $avatar->mediatype;
177             }
178         }
179         $xs->elementStart('activity:' . $element);
180         $xs->element(
181             'activity:object-type',
182             null,
183             $type
184         );
185         $xs->element(
186             'id',
187             null,
188             $this->uri); // ?
189         $xs->element('title', null, $self->getBestName());
190
191         $xs->element(
192             'link', array(
193                 'type' => $avatarType,
194                 'href' => $avatarHref
195             ),
196             ''
197         );
198
199         $xs->elementEnd('activity:' . $element);
200
201         return $xs->getString();
202     }
203
204     /**
205      * Damn dirty hack!
206      */
207     function isGroup()
208     {
209         return (strpos($this->feeduri, '/groups/') !== false);
210     }
211
212     /**
213      * Subscribe a local user to this remote user.
214      * PuSH subscription will be started if necessary, and we'll
215      * send a Salmon notification to the remote server if available
216      * notifying them of the sub.
217      *
218      * @param User $user
219      * @return boolean success
220      * @throws FeedException
221      */
222     public function subscribeLocalToRemote(User $user)
223     {
224         if ($this->isGroup()) {
225             throw new ServerException("Can't subscribe to a remote group");
226         }
227
228         if ($this->subscribe()) {
229             if ($user->subscribeTo($this->localProfile())) {
230                 $this->notify($user->getProfile(), ActivityVerb::FOLLOW, $this);
231                 return true;
232             }
233         }
234         return false;
235     }
236
237     /**
238      * Mark this remote profile as subscribing to the given local user,
239      * and send appropriate notifications to the user.
240      *
241      * This will generally be in response to a subscription notification
242      * from a foreign site to our local Salmon response channel.
243      *
244      * @param User $user
245      * @return boolean success
246      */
247     public function subscribeRemoteToLocal(User $user)
248     {
249         if ($this->isGroup()) {
250             throw new ServerException("Remote groups can't subscribe to local users");
251         }
252
253         // @fixme use regular channels for subbing, once they accept remote profiles
254         $sub = new Subscription();
255         $sub->subscriber = $this->profile_id;
256         $sub->subscribed = $user->id;
257         $sub->created = common_sql_now(); // current time
258
259         if ($sub->insert()) {
260             // @fixme use subs_notify() if refactored to take profiles?
261             mail_subscribe_notify_profile($user, $this->localProfile());
262             return true;
263         }
264         return false;
265     }
266
267     /**
268      * Send a subscription request to the hub for this feed.
269      * The hub will later send us a confirmation POST to /main/push/callback.
270      *
271      * @return bool true on success, false on failure
272      * @throws ServerException if feed state is not valid
273      */
274     public function subscribe()
275     {
276         $feedsub = FeedSub::ensureFeed($this->feeduri);
277         if ($feedsub->sub_state == 'active' || $feedsub->sub_state == 'subscribe') {
278             return true;
279         } else if ($feedsub->sub_state == '' || $feedsub->sub_state == 'inactive') {
280             return $feedsub->subscribe();
281         } else if ('unsubscribe') {
282             throw new FeedSubException("Unsub is pending, can't subscribe...");
283         }
284     }
285
286     /**
287      * Send a PuSH unsubscription request to the hub for this feed.
288      * The hub will later send us a confirmation POST to /main/push/callback.
289      *
290      * @return bool true on success, false on failure
291      * @throws ServerException if feed state is not valid
292      */
293     public function unsubscribe() {
294         $feedsub = FeedSub::staticGet('uri', $this->feeduri);
295         if ($feedsub->sub_state == 'active') {
296             return $feedsub->unsubscribe();
297         } else if ($feedsub->sub_state == '' || $feedsub->sub_state == 'inactive' || $feedsub->sub_state == 'unsubscribe') {
298             return true;
299         } else if ($feedsub->sub_state == 'subscribe') {
300             throw new FeedSubException("Feed is awaiting subscription, can't unsub...");
301         }
302     }
303
304     /**
305      * Send an Activity Streams notification to the remote Salmon endpoint,
306      * if so configured.
307      *
308      * @param Profile $actor  Actor who did the activity
309      * @param string  $verb   Activity::SUBSCRIBE or Activity::JOIN
310      * @param Object  $object object of the action; must define asActivityNoun($tag)
311      */
312     public function notify($actor, $verb, $object=null)
313     {
314         if (!($actor instanceof Profile)) {
315             $type = gettype($actor);
316             if ($type == 'object') {
317                 $type = get_class($actor);
318             }
319             throw new ServerException("Invalid actor passed to " . __METHOD__ . ": " . $type);
320         }
321         if ($object == null) {
322             $object = $this;
323         }
324         if ($this->salmonuri) {
325
326             $text = 'update';
327             $id = TagURI::mint('%s:%s:%s',
328                                $verb,
329                                $actor->getURI(),
330                                common_date_iso8601(date()));
331
332             // @fixme consolidate all these NS settings somewhere
333             $attributes = array('xmlns' => Activity::ATOM,
334                                 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
335                                 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
336                                 'xmlns:georss' => 'http://www.georss.org/georss',
337                                 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
338
339             $entry = new XMLStringer();
340             $entry->elementStart('entry', $attributes);
341             $entry->element('id', null, $id);
342             $entry->element('title', null, $text);
343             $entry->element('summary', null, $text);
344             $entry->element('published', null, common_date_w3dtf(common_sql_now()));
345
346             $entry->element('activity:verb', null, $verb);
347             $entry->raw($actor->asAtomAuthor());
348             $entry->raw($actor->asActivityActor());
349             $entry->raw($object->asActivityNoun('object'));
350             $entry->elementEnd('entry');
351
352             $xml = $entry->getString();
353             common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
354
355             $salmon = new Salmon(); // ?
356             $salmon->post($this->salmonuri, $xml);
357         }
358     }
359
360     public function notifyActivity($activity)
361     {
362         if ($this->salmonuri) {
363
364             $xml = $activity->asString();
365
366             $salmon = new Salmon(); // ?
367
368             $salmon->post($this->salmonuri, $xml);
369         }
370
371         return;
372     }
373
374     function getBestName()
375     {
376         if ($this->isGroup()) {
377             return $this->localGroup()->getBestName();
378         } else {
379             return $this->localProfile()->getBestName();
380         }
381     }
382
383     function atomFeed($actor)
384     {
385         $feed = new Atom10Feed();
386         // @fixme should these be set up somewhere else?
387         $feed->addNamespace('activity', 'http://activitystrea.ms/spec/1.0/');
388         $feed->addNamespace('thr', 'http://purl.org/syndication/thread/1.0');
389         $feed->addNamespace('georss', 'http://www.georss.org/georss');
390         $feed->addNamespace('ostatus', 'http://ostatus.org/schema/1.0');
391
392         $taguribase = common_config('integration', 'taguri');
393         $feed->setId("tag:{$taguribase}:UserTimeline:{$actor->id}"); // ???
394
395         $feed->setTitle($actor->getBestName() . ' timeline'); // @fixme
396         $feed->setUpdated(time());
397         $feed->setPublished(time());
398
399         $feed->addLink(common_local_url('ApiTimelineUser',
400                                         array('id' => $actor->id,
401                                               'type' => 'atom')),
402                        array('rel' => 'self',
403                              'type' => 'application/atom+xml'));
404
405         $feed->addLink(common_local_url('userbyid',
406                                         array('id' => $actor->id)),
407                        array('rel' => 'alternate',
408                              'type' => 'text/html'));
409
410         return $feed;
411     }
412
413     /**
414      * Read and post notices for updates from the feed.
415      * Currently assumes that all items in the feed are new,
416      * coming from a PuSH hub.
417      *
418      * @param DOMDocument $feed
419      */
420     public function processFeed($feed)
421     {
422         $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
423         if ($entries->length == 0) {
424             common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
425             return;
426         }
427
428         for ($i = 0; $i < $entries->length; $i++) {
429             $entry = $entries->item($i);
430             $this->processEntry($entry, $feed);
431         }
432     }
433
434     /**
435      * Process a posted entry from this feed source.
436      *
437      * @param DOMElement $entry
438      * @param DOMElement $feed for context
439      */
440     protected function processEntry($entry, $feed)
441     {
442         $activity = new Activity($entry, $feed);
443
444         $debug = var_export($activity, true);
445         common_log(LOG_DEBUG, $debug);
446
447         if ($activity->verb == ActivityVerb::POST) {
448             $this->processPost($activity);
449         } else {
450             common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
451         }
452     }
453
454     /**
455      * Process an incoming post activity from this remote feed.
456      * @param Activity $activity
457      */
458     protected function processPost($activity)
459     {
460         if ($this->isGroup()) {
461             // @fixme validate these profiles in some way!
462             $oprofile = self::ensureActorProfile($activity);
463         } else {
464             $actorUri = self::getActorProfileURI($activity);
465             if ($actorUri == $this->uri) {
466                 // @fixme check if profile info has changed and update it
467             } else {
468                 // @fixme drop or reject the messages once we've got the canonical profile URI recorded sanely
469                 common_log(LOG_INFO, "OStatus: Warning: non-group post with unexpected author: $actorUri expected $this->uri");
470                 //return;
471             }
472             $oprofile = $this;
473         }
474
475         $sourceUri = $activity->object->id;
476
477         $dupe = Notice::staticGet('uri', $sourceUri);
478
479         if ($dupe) {
480             common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
481             return;
482         }
483
484         $sourceUrl = null;
485
486         if ($activity->object->link) {
487             $sourceUrl = $activity->object->link;
488         } else if (preg_match('!^https?://!', $activity->object->id)) {
489             $sourceUrl = $activity->object->id;
490         }
491
492         // @fixme sanitize and save HTML content if available
493
494         $content = $activity->object->title;
495
496         $params = array('is_local' => Notice::REMOTE_OMB,
497                         'url' => $sourceUrl,
498                         'uri' => $sourceUri);
499
500         $location = $activity->context->location;
501
502         if ($location) {
503             $params['lat'] = $location->lat;
504             $params['lon'] = $location->lon;
505             if ($location->location_id) {
506                 $params['location_ns'] = $location->location_ns;
507                 $params['location_id'] = $location->location_id;
508             }
509         }
510
511         // @fixme save detailed ostatus source info
512         // @fixme ensure that groups get handled correctly
513
514         $saved = Notice::saveNew($oprofile->localProfile()->id,
515                                  $content,
516                                  'ostatus',
517                                  $params);
518     }
519
520     /**
521      * @param string $profile_url
522      * @return Ostatus_profile
523      * @throws FeedSubException
524      */
525     public static function ensureProfile($profile_uri)
526     {
527         // Get the canonical feed URI and check it
528         $discover = new FeedDiscovery();
529         $feeduri = $discover->discoverFromURL($profile_uri);
530
531         //$feedsub = FeedSub::ensureFeed($feeduri, $discover->feed);
532         $huburi = $discover->getAtomLink('hub');
533         $salmonuri = $discover->getAtomLink('salmon');
534
535         if (!$huburi) {
536             // We can only deal with folks with a PuSH hub
537             throw new FeedSubNoHubException();
538         }
539
540         // Try to get a profile from the feed activity:subject
541
542         $feedEl = $discover->feed->documentElement;
543
544         $subject = ActivityUtils::child($feedEl, Activity::SUBJECT, Activity::SPEC);
545
546         if (!empty($subject)) {
547             $subjObject = new ActivityObject($subject);
548             return self::ensureActivityObjectProfile($subjObject, $feeduri, $salmonuri);
549         }
550
551         // Otherwise, try the feed author
552
553         $author = ActivityUtils::child($feedEl, Activity::AUTHOR, Activity::ATOM);
554
555         if (!empty($author)) {
556             $authorObject = new ActivityObject($author);
557             return self::ensureActivityObjectProfile($authorObject, $feeduri, $salmonuri);
558         }
559
560         // Sheesh. Not a very nice feed! Let's try fingerpoken in the
561         // entries.
562
563         $entries = $discover->feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
564
565         if (!empty($entries) && $entries->length > 0) {
566
567             $entry = $entries->item(0);
568
569             $actor = ActivityUtils::child($entry, Activity::ACTOR, Activity::SPEC);
570
571             if (!empty($actor)) {
572                 $actorObject = new ActivityObject($actor);
573                 return self::ensureActivityObjectProfile($actorObject, $feeduri, $salmonuri);
574
575             }
576
577             $author = ActivityUtils::child($entry, Activity::AUTHOR, Activity::ATOM);
578
579             if (!empty($author)) {
580                 $authorObject = new ActivityObject($author);
581                 return self::ensureActivityObjectProfile($authorObject, $feeduri, $salmonuri);
582             }
583         }
584
585         // XXX: make some educated guesses here
586
587         throw new FeedSubException("Can't find enough profile information to make a feed.");
588     }
589
590     /**
591      *
592      * Download and update given avatar image
593      * @param string $url
594      * @throws Exception in various failure cases
595      */
596     protected function updateAvatar($url)
597     {
598         // @fixme this should be better encapsulated
599         // ripped from oauthstore.php (for old OMB client)
600         $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
601         copy($url, $temp_filename);
602
603         if ($this->isGroup()) {
604             $id = $this->group_id;
605         } else {
606             $id = $this->profile_id;
607         }
608         // @fixme should we be using different ids?
609         $imagefile = new ImageFile($id, $temp_filename);
610         $filename = Avatar::filename($id,
611                                      image_type_to_extension($imagefile->type),
612                                      null,
613                                      common_timestamp());
614         rename($temp_filename, Avatar::path($filename));
615         if ($this->isGroup()) {
616             $group = $this->localGroup();
617             $group->setOriginal($filename);
618         } else {
619             $profile = $this->localProfile();
620             $profile->setOriginal($filename);
621         }
622     }
623
624     protected static function getActivityObjectAvatar($object)
625     {
626         // XXX: go poke around in the feed
627         return $object->avatar;
628     }
629
630     /**
631      * Get an appropriate avatar image source URL, if available.
632      *
633      * @param ActivityObject $actor
634      * @param DOMElement $feed
635      * @return string
636      */
637
638     protected static function getAvatar($actor, $feed)
639     {
640         $url = '';
641         $icon = '';
642         if ($actor->avatar) {
643             $url = trim($actor->avatar);
644         }
645         if (!$url) {
646             // Check <atom:logo> and <atom:icon> on the feed
647             $els = $feed->childNodes();
648             if ($els && $els->length) {
649                 for ($i = 0; $i < $els->length; $i++) {
650                     $el = $els->item($i);
651                     if ($el->namespaceURI == Activity::ATOM) {
652                         if (empty($url) && $el->localName == 'logo') {
653                             $url = trim($el->textContent);
654                             break;
655                         }
656                         if (empty($icon) && $el->localName == 'icon') {
657                             // Use as a fallback
658                             $icon = trim($el->textContent);
659                         }
660                     }
661                 }
662             }
663             if ($icon && !$url) {
664                 $url = $icon;
665             }
666         }
667         if ($url) {
668             $opts = array('allowed_schemes' => array('http', 'https'));
669             if (Validate::uri($url, $opts)) {
670                 return $url;
671             }
672         }
673         return common_path('plugins/OStatus/images/96px-Feed-icon.svg.png');
674     }
675
676     /**
677      * Fetch, or build if necessary, an Ostatus_profile for the actor
678      * in a given Activity Streams activity.
679      *
680      * @param Activity $activity
681      * @param string $feeduri if we already know the canonical feed URI!
682      * @param string $salmonuri if we already know the salmon return channel URI
683      * @return Ostatus_profile
684      */
685
686     public static function ensureActorProfile($activity, $feeduri=null, $salmonuri=null)
687     {
688         return self::ensureActivityObjectProfile($activity->actor, $feeduri, $salmonuri);
689     }
690
691     public static function ensureActivityObjectProfile($object, $feeduri=null, $salmonuri=null)
692     {
693         $profile = self::getActivityObjectProfile($object);
694         if (!$profile) {
695             $profile = self::createActivityObjectProfile($object, $feeduri, $salmonuri);
696         }
697         return $profile;
698     }
699
700     /**
701      * @param Activity $activity
702      * @return mixed matching Ostatus_profile or false if none known
703      */
704     protected static function getActorProfile($activity)
705     {
706         return self::getActivityObjectProfile($activity->actor);
707     }
708
709     protected static function getActivityObjectProfile($object)
710     {
711         $uri = self::getActivityObjectProfileURI($object);
712         return Ostatus_profile::staticGet('homeuri', $uri);
713     }
714
715     protected static function getActorProfileURI($activity)
716     {
717         return self::getActivityObjectProfileURI($activity->actor);
718     }
719
720     /**
721      * @param Activity $activity
722      * @return string
723      * @throws ServerException
724      */
725     protected static function getActivityObjectProfileURI($object)
726     {
727         $opts = array('allowed_schemes' => array('http', 'https'));
728         if ($object->id && Validate::uri($object->id, $opts)) {
729             return $object->id;
730         }
731         if ($object->link && Validate::uri($object->link, $opts)) {
732             return $object->link;
733         }
734         throw new ServerException("No author ID URI found");
735     }
736
737     /**
738      * @fixme validate stuff somewhere
739      */
740
741     protected static function createActorProfile($activity, $feeduri=null, $salmonuri=null)
742     {
743         $actor = $activity->actor;
744
745         self::createActivityObjectProfile($actor, $feeduri, $salmonuri);
746     }
747
748     protected static function createActivityObjectProfile($object, $feeduri=null, $salmonuri=null)
749     {
750         $homeuri = self::getActivityObjectProfileURI($object);
751         $nickname = self::getActivityObjectNickname($object);
752         $avatar = self::getActivityObjectAvatar($object);
753
754         if (!$homeuri) {
755             common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
756             throw new ServerException("No profile URI");
757         }
758
759         if (!$feeduri || !$salmonuri) {
760             // Get the canonical feed URI and check it
761             $discover = new FeedDiscovery();
762             $feeduri = $discover->discoverFromURL($homeuri);
763
764             $huburi = $discover->getAtomLink('hub');
765             $salmonuri = $discover->getAtomLink('salmon');
766
767             if (!$huburi) {
768                 // We can only deal with folks with a PuSH hub
769                 throw new FeedSubNoHubException();
770             }
771         }
772
773         $profile = new Profile();
774         $profile->nickname   = $nickname;
775         $profile->fullname   = $object->title;
776         $profile->profileurl = $object->link;
777         $profile->created    = common_sql_now();
778
779         // @fixme bio
780         // @fixme tags/categories
781         // @fixme location?
782         // @todo tags from categories
783         // @todo lat/lon/location?
784
785         $ok = $profile->insert();
786
787         if (!$ok) {
788             throw new ServerException("Can't save local profile");
789         }
790
791         // @fixme either need to do feed discovery here
792         // or need to split out some of the feed stuff
793         // so we can leave it empty until later.
794
795         $oprofile = new Ostatus_profile();
796
797         $oprofile->uri        = $homeuri;
798         $oprofile->feeduri    = $feeduri;
799         $oprofile->salmonuri  = $salmonuri;
800         $oprofile->profile_id = $profile->id;
801
802         $oprofile->created    = common_sql_now();
803         $oprofile->modified   = common_sql_now();
804
805         $ok = $oprofile->insert();
806
807         if ($ok) {
808             $oprofile->updateAvatar($avatar);
809             return $oprofile;
810         } else {
811             throw new ServerException("Can't save OStatus profile");
812         }
813     }
814
815     protected static function getActivityObjectNickname($object)
816     {
817         // XXX: check whatever PoCo calls a nickname first
818
819         $nickname = self::nicknameFromURI($object->id);
820
821         if (empty($nickname)) {
822             $nickname = common_nicknamize($object->title);
823         }
824
825         return $nickname;
826     }
827
828     protected static function nicknameFromURI($uri)
829     {
830         preg_match('/(\w+):/', $uri, $matches);
831
832         $protocol = $matches[1];
833
834         switch ($protocol) {
835         case 'acct':
836         case 'mailto':
837             if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
838                 return common_canonical_nickname($matches[1]);
839             }
840             return null;
841         case 'http':
842             return common_url_to_nickname($uri);
843             break;
844         default:
845             return null;
846         }
847     }
848 }