3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2009-2010, StatusNet, Inc.
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.
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.
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/>.
21 * @package OStatusPlugin
22 * @maintainer Brion Vibber <brion@status.net>
25 class Ostatus_profile extends Memcached_DataObject
27 public $__table = 'ostatus_profile';
40 public /*static*/ function staticGet($k, $v=null)
42 return parent::staticGet(__CLASS__, $k, $v);
46 * return table definition for DB_DataObject
48 * DB_DataObject needs to know something about the table to manipulate
49 * instances. This method provides all the DB_DataObject needs to know.
51 * @return array array of column definitions
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);
65 static function schemaDef()
67 return array(new ColumnDef('uri', 'varchar',
69 new ColumnDef('profile_id', 'integer',
71 new ColumnDef('group_id', 'integer',
73 new ColumnDef('feeduri', 'varchar',
75 new ColumnDef('salmonuri', 'text',
77 new ColumnDef('created', 'datetime',
79 new ColumnDef('modified', 'datetime',
84 * return key definitions for DB_DataObject
86 * DB_DataObject needs to know about keys that the table has; this function
89 * @return array key definitions
94 return array_keys($this->keyTypes());
98 * return key definitions for Memcached_DataObject
100 * Our caching system uses the same key definitions, but uses a different
101 * method to get them.
103 * @return array key definitions
108 return array('uri' => 'K', 'profile_id' => 'U', 'group_id' => 'U', 'feeduri' => 'U');
111 function sequenceKey()
113 return array(false, false, false);
117 * Fetch the StatusNet-side profile for this feed
120 public function localProfile()
122 if ($this->profile_id) {
123 return Profile::staticGet('id', $this->profile_id);
129 * Fetch the StatusNet-side profile for this feed
132 public function localGroup()
134 if ($this->group_id) {
135 return User_group::staticGet('id', $this->group_id);
141 * Returns an ActivityObject describing this remote user or group profile.
142 * Can then be used to generate Atom chunks.
144 * @return ActivityObject
146 function asActivityObject()
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();
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];
168 $object->link = $this->uri; // @fixme accurate?
171 return ActivityObject::fromProfile($this->localProfile());
176 * Returns an XML string fragment with profile information as an
177 * Activity Streams noun object with the given element type.
179 * Assumes that 'activity' namespace has been previously defined.
181 * @fixme replace with wrappers on asActivityObject when it's got everything.
183 * @param string $element one of 'actor', 'subject', 'object', 'target'
186 function asActivityNoun($element)
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();
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];
208 $type = 'http://activitystrea.ms/schema/1.0/person';
209 $self = $this->localProfile();
210 $avatar = $self->getAvatar(AVATAR_PROFILE_SIZE);
212 $avatarHref = $avatar->url;
213 $avatarType = $avatar->mediatype;
216 $xs->elementStart('activity:' . $element);
218 'activity:object-type',
226 $xs->element('title', null, $self->getBestName());
230 'type' => $avatarType,
231 'href' => $avatarHref
236 $xs->elementEnd('activity:' . $element);
238 return $xs->getString();
242 * @return boolean true if this is a remote group
246 if ($this->profile_id && !$this->group_id) {
248 } else if ($this->group_id && !$this->profile_id) {
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");
253 throw new ServerException("Invalid ostatus_profile state: both group and profile IDs empty for $this->uri");
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.
264 * @return boolean success
265 * @throws FeedException
267 public function subscribeLocalToRemote(User $user)
269 if ($this->isGroup()) {
270 throw new ServerException("Can't subscribe to a remote group");
273 if ($this->subscribe()) {
274 if ($user->subscribeTo($this->localProfile())) {
275 $this->notify($user->getProfile(), ActivityVerb::FOLLOW, $this);
283 * Mark this remote profile as subscribing to the given local user,
284 * and send appropriate notifications to the user.
286 * This will generally be in response to a subscription notification
287 * from a foreign site to our local Salmon response channel.
290 * @return boolean success
292 public function subscribeRemoteToLocal(User $user)
294 if ($this->isGroup()) {
295 throw new ServerException("Remote groups can't subscribe to local users");
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
304 if ($sub->insert()) {
305 // @fixme use subs_notify() if refactored to take profiles?
306 mail_subscribe_notify_profile($user, $this->localProfile());
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.
316 * @return bool true on success, false on failure
317 * @throws ServerException if feed state is not valid
319 public function subscribe()
321 $feedsub = FeedSub::ensureFeed($this->feeduri);
322 if ($feedsub->sub_state == 'active' || $feedsub->sub_state == 'subscribe') {
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...");
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.
335 * @return bool true on success, false on failure
336 * @throws ServerException if feed state is not valid
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') {
344 } else if ($feedsub->sub_state == 'subscribe') {
345 throw new FeedSubException("Feed is awaiting subscription, can't unsub...");
350 * Check if this remote profile has any active local subscriptions, and
351 * if not drop the PuSH subscription feed.
355 public function garbageCollect()
357 if ($this->isGroup()) {
358 $members = $this->localGroup()->getMembers(0, 1);
359 $count = $members->N;
361 $count = $this->localProfile()->subscriberCount();
364 common_log(LOG_INFO, "Unsubscribing from now-unused remote feed $oprofile->feeduri");
365 $this->unsubscribe();
373 * Send an Activity Streams notification to the remote Salmon endpoint,
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)
380 public function notify($actor, $verb, $object=null)
382 if (!($actor instanceof Profile)) {
383 $type = gettype($actor);
384 if ($type == 'object') {
385 $type = get_class($actor);
387 throw new ServerException("Invalid actor passed to " . __METHOD__ . ": " . $type);
389 if ($object == null) {
392 if ($this->salmonuri) {
395 $id = TagURI::mint('%s:%s:%s',
398 common_date_iso8601(time()));
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');
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()));
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');
421 $xml = $entry->getString();
422 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
424 $salmon = new Salmon(); // ?
425 return $salmon->post($this->salmonuri, $xml);
430 public function notifyActivity($activity)
432 if ($this->salmonuri) {
434 $xml = '<?xml version="1.0" encoding="UTF-8" ?' . '>' .
435 $activity->asString(true);
437 $salmon = new Salmon(); // ?
439 return $salmon->post($this->salmonuri, $xml);
445 function getBestName()
447 if ($this->isGroup()) {
448 return $this->localGroup()->getBestName();
450 return $this->localProfile()->getBestName();
454 function atomFeed($actor)
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');
463 $taguribase = common_config('integration', 'taguri');
464 $feed->setId("tag:{$taguribase}:UserTimeline:{$actor->id}"); // ???
466 $feed->setTitle($actor->getBestName() . ' timeline'); // @fixme
467 $feed->setUpdated(time());
468 $feed->setPublished(time());
470 $feed->addLink(common_local_url('ApiTimelineUser',
471 array('id' => $actor->id,
473 array('rel' => 'self',
474 'type' => 'application/atom+xml'));
476 $feed->addLink(common_local_url('userbyid',
477 array('id' => $actor->id)),
478 array('rel' => 'alternate',
479 'type' => 'text/html'));
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.
489 * @param DOMDocument $feed
491 public function processFeed($feed)
493 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
494 if ($entries->length == 0) {
495 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
499 for ($i = 0; $i < $entries->length; $i++) {
500 $entry = $entries->item($i);
501 $this->processEntry($entry, $feed);
506 * Process a posted entry from this feed source.
508 * @param DOMElement $entry
509 * @param DOMElement $feed for context
511 protected function processEntry($entry, $feed)
513 $activity = new Activity($entry, $feed);
515 $debug = var_export($activity, true);
516 common_log(LOG_DEBUG, $debug);
518 if ($activity->verb == ActivityVerb::POST) {
519 $this->processPost($activity);
521 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
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
530 protected function processPost($activity)
532 if ($this->isGroup()) {
533 // @fixme validate these profiles in some way!
534 $oprofile = self::ensureActorProfile($activity);
536 $actorUri = self::getActorProfileURI($activity);
537 if ($actorUri == $this->uri) {
538 // @fixme check if profile info has changed and update it
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");
546 $sourceUri = $activity->object->id;
548 $dupe = Notice::staticGet('uri', $sourceUri);
551 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
557 if ($activity->object->link) {
558 $sourceUrl = $activity->object->link;
559 } else if (preg_match('!^https?://!', $activity->object->id)) {
560 $sourceUrl = $activity->object->id;
563 // @fixme sanitize and save HTML content if available
565 $content = $activity->object->title;
567 $params = array('is_local' => Notice::REMOTE_OMB,
569 'uri' => $sourceUri);
571 $location = $activity->context->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;
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);
589 if ($roprofile->isGroup()) {
590 // Deliver to local recipients of this remote group.
591 // @fixme sender verification?
592 $params['groups'][] = $roprofile->group_id;
595 // Delivery to remote users is the source service's job.
600 $user = User::staticGet('uri', $recipient);
602 // An @-reply directed to a local user.
603 // @fixme sender verification, spam etc?
604 $params['replies'][] = $recipient;
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)) {
616 $group = User_group::staticGet('id', $id);
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;
624 common_log(LOG_DEBUG, "not delivering to group $id $group->nickname because sender $profile->nickname is not a member");
628 common_log(LOG_DEBUG, "not delivering to missing group $id");
631 common_log(LOG_DEBUG, "not delivering to groups for $recipient");
637 $saved = Notice::saveNew($profile->id,
641 } catch (Exception $e) {
642 common_log(LOG_ERR, "Failed saving notice entry for $sourceUri: " . $e->getMessage());
646 // Record which feed this came through...
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());
655 * @param string $profile_url
656 * @return Ostatus_profile
657 * @throws FeedSubException
659 public static function ensureProfile($profile_uri, $hints=array())
661 // Get the canonical feed URI and check it
662 $discover = new FeedDiscovery();
663 $feeduri = $discover->discoverFromURL($profile_uri);
665 //$feedsub = FeedSub::ensureFeed($feeduri, $discover->feed);
666 $huburi = $discover->getAtomLink('hub');
667 $salmonuri = $discover->getAtomLink('salmon');
670 // We can only deal with folks with a PuSH hub
671 throw new FeedSubNoHubException();
674 // Try to get a profile from the feed activity:subject
676 $feedEl = $discover->feed->documentElement;
678 $subject = ActivityUtils::child($feedEl, Activity::SUBJECT, Activity::SPEC);
680 if (!empty($subject)) {
681 $subjObject = new ActivityObject($subject);
682 return self::ensureActivityObjectProfile($subjObject, $feeduri, $salmonuri, $hints);
685 // Otherwise, try the feed author
687 $author = ActivityUtils::child($feedEl, Activity::AUTHOR, Activity::ATOM);
689 if (!empty($author)) {
690 $authorObject = new ActivityObject($author);
691 return self::ensureActivityObjectProfile($authorObject, $feeduri, $salmonuri, $hints);
694 // Sheesh. Not a very nice feed! Let's try fingerpoken in the
697 $entries = $discover->feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
699 if (!empty($entries) && $entries->length > 0) {
701 $entry = $entries->item(0);
703 $actor = ActivityUtils::child($entry, Activity::ACTOR, Activity::SPEC);
705 if (!empty($actor)) {
706 $actorObject = new ActivityObject($actor);
707 return self::ensureActivityObjectProfile($actorObject, $feeduri, $salmonuri, $hints);
711 $author = ActivityUtils::child($entry, Activity::AUTHOR, Activity::ATOM);
713 if (!empty($author)) {
714 $authorObject = new ActivityObject($author);
715 return self::ensureActivityObjectProfile($authorObject, $feeduri, $salmonuri, $hints);
719 // XXX: make some educated guesses here
721 throw new FeedSubException("Can't find enough profile information to make a feed.");
726 * Download and update given avatar image
728 * @throws Exception in various failure cases
730 protected function updateAvatar($url)
732 if ($this->isGroup()) {
733 $self = $this->localGroup();
735 $self = $this->localProfile();
738 throw new ServerException(sprintf(
739 _m("Tried to update avatar for unsaved remote profile %s"),
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));
750 if ($this->isGroup()) {
751 $id = $this->group_id;
753 $id = $this->profile_id;
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),
761 rename($temp_filename, Avatar::path($filename));
762 $self->setOriginal($filename);
765 protected static function getActivityObjectAvatar($object)
767 // XXX: go poke around in the feed
768 return $object->avatar;
772 * Get an appropriate avatar image source URL, if available.
774 * @param ActivityObject $actor
775 * @param DOMElement $feed
779 protected static function getAvatar($actor, $feed)
783 if ($actor->avatar) {
784 $url = trim($actor->avatar);
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);
797 if (empty($icon) && $el->localName == 'icon') {
799 $icon = trim($el->textContent);
804 if ($icon && !$url) {
809 $opts = array('allowed_schemes' => array('http', 'https'));
810 if (Validate::uri($url, $opts)) {
814 return common_path('plugins/OStatus/images/96px-Feed-icon.svg.png');
818 * Fetch, or build if necessary, an Ostatus_profile for the actor
819 * in a given Activity Streams activity.
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
827 public static function ensureActorProfile($activity, $feeduri=null, $salmonuri=null)
829 return self::ensureActivityObjectProfile($activity->actor, $feeduri, $salmonuri);
832 public static function ensureActivityObjectProfile($object, $feeduri=null, $salmonuri=null, $hints=array())
834 $profile = self::getActivityObjectProfile($object);
836 $profile = self::createActivityObjectProfile($object, $feeduri, $salmonuri, $hints);
842 * @param Activity $activity
843 * @return mixed matching Ostatus_profile or false if none known
845 protected static function getActorProfile($activity)
847 return self::getActivityObjectProfile($activity->actor);
850 protected static function getActivityObjectProfile($object)
852 $uri = self::getActivityObjectProfileURI($object);
853 return Ostatus_profile::staticGet('uri', $uri);
856 protected static function getActorProfileURI($activity)
858 return self::getActivityObjectProfileURI($activity->actor);
862 * @param Activity $activity
864 * @throws ServerException
866 protected static function getActivityObjectProfileURI($object)
868 $opts = array('allowed_schemes' => array('http', 'https'));
869 if ($object->id && Validate::uri($object->id, $opts)) {
872 if ($object->link && Validate::uri($object->link, $opts)) {
873 return $object->link;
875 throw new ServerException("No author ID URI found");
879 * @fixme validate stuff somewhere
882 protected static function createActorProfile($activity, $feeduri=null, $salmonuri=null)
884 $actor = $activity->actor;
886 self::createActivityObjectProfile($actor, $feeduri, $salmonuri);
890 * Create local ostatus_profile and profile/user_group entries for
891 * the provided remote user or group.
893 * @param ActivityObject $object
894 * @param string $feeduri
895 * @param string $salmonuri
896 * @param array $hints
898 * @fixme fold $feeduri/$salmonuri into $hints
899 * @return Ostatus_profile
901 protected static function createActivityObjectProfile($object, $feeduri=null, $salmonuri=null, $hints=array())
903 $homeuri = $object->id;
904 $nickname = self::getActivityObjectNickname($object, $hints);
905 $avatar = self::getActivityObjectAvatar($object);
908 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
909 throw new ServerException("No profile URI");
912 if (empty($feeduri)) {
913 if (array_key_exists('feedurl', $hints)) {
914 $feeduri = $hints['feedurl'];
918 if (empty($salmonuri)) {
919 if (array_key_exists('salmon', $hints)) {
920 $salmonuri = $hints['salmon'];
924 if (!$feeduri || !$salmonuri) {
925 // Get the canonical feed URI and check it
926 $discover = new FeedDiscovery();
927 $feeduri = $discover->discoverFromURL($homeuri);
929 $huburi = $discover->getAtomLink('hub');
930 $salmonuri = $discover->getAtomLink('salmon');
933 // We can only deal with folks with a PuSH hub
934 throw new FeedSubNoHubException();
938 $oprofile = new Ostatus_profile();
940 $oprofile->uri = $homeuri;
941 $oprofile->feeduri = $feeduri;
942 $oprofile->salmonuri = $salmonuri;
944 $oprofile->created = common_sql_now();
945 $oprofile->modified = common_sql_now();
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'];
956 $profile->created = common_sql_now();
959 // @fixme tags/categories
961 // @todo tags from categories
962 // @todo lat/lon/location?
964 $oprofile->profile_id = $profile->insert();
966 if (!$oprofile->profile_id) {
967 throw new ServerException("Can't save local profile");
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();
979 // @fixme tags/categories
981 // @todo tags from categories
982 // @todo lat/lon/location?
984 $oprofile->group_id = $group->insert();
986 if (!$oprofile->group_id) {
987 throw new ServerException("Can't save local profile");
991 $ok = $oprofile->insert();
995 $oprofile->updateAvatar($avatar);
999 throw new ServerException("Can't save OStatus profile");
1003 protected static function getActivityObjectNickname($object, $hints=array())
1005 if (!empty($object->nickname)) {
1006 return common_nicknamize($object->nickname);
1009 // Try the definitive ID
1011 $nickname = self::nicknameFromURI($object->id);
1013 // Try a Webfinger if one was passed (way) down
1015 if (empty($nickname)) {
1016 if (array_key_exists('webfinger', $hints)) {
1017 $nickname = self::nicknameFromURI($hints['webfinger']);
1023 if (empty($nickname)) {
1024 $nickname = common_nicknamize($object->title);
1030 protected static function nicknameFromURI($uri)
1032 preg_match('/(\w+):/', $uri, $matches);
1034 $protocol = $matches[1];
1036 switch ($protocol) {
1039 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1040 return common_canonical_nickname($matches[1]);
1044 return common_url_to_nickname($uri);
1051 public static function ensureWebfinger($addr)
1053 // First, look it up
1055 $oprofile = Ostatus_profile::staticGet('uri', 'acct:'.$addr);
1057 if (!empty($oprofile)) {
1061 // Now, try some discovery
1063 $wf = new Webfinger();
1065 $result = $wf->lookup($addr);
1071 foreach ($result->links as $link) {
1072 switch ($link['rel']) {
1073 case Webfinger::PROFILEPAGE:
1074 $profileUrl = $link['href'];
1077 $salmonEndpoint = $link['href'];
1079 case Webfinger::UPDATESFROM:
1080 $feedUrl = $link['href'];
1083 common_log(LOG_NOTICE, "Don't know what to do with rel = '{$link['rel']}'");
1088 $hints = array('webfinger' => $addr,
1089 'profileurl' => $profileUrl,
1090 'feedurl' => $feedUrl,
1091 'salmon' => $salmonEndpoint);
1093 // If we got a feed URL, try that
1095 if (isset($feedUrl)) {
1097 $oprofile = self::ensureProfile($feedUrl, $hints);
1099 } catch (Exception $e) {
1100 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1105 // If we got a profile page, try that!
1107 if (isset($profileUrl)) {
1109 $oprofile = self::ensureProfile($profileUrl, $hints);
1111 } catch (Exception $e) {
1112 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1120 if (isset($salmonEndpoint)) {
1122 // An account URL, a salmon endpoint, and a dream? Not much to go
1123 // on, but let's give it a try
1125 $uri = 'acct:'.$addr;
1127 $profile = new Profile();
1129 $profile->nickname = self::nicknameFromUri($uri);
1130 $profile->created = common_sql_now();
1132 if (isset($profileUrl)) {
1133 $profile->profileurl = $profileUrl;
1136 $profile_id = $profile->insert();
1139 common_log_db_error($profile, 'INSERT', __FILE__);
1140 throw new Exception("Couldn't save profile for '$addr'");
1143 $oprofile = new Ostatus_profile();
1145 $oprofile->uri = $uri;
1146 $oprofile->salmonuri = $salmonEndpoint;
1147 $oprofile->profile_id = $profile_id;
1148 $oprofile->created = common_sql_now();
1150 if (isset($feedUrl)) {
1151 $profile->feeduri = $feedUrl;
1154 $result = $oprofile->insert();
1157 common_log_db_error($oprofile, 'INSERT', __FILE__);
1158 throw new Exception("Couldn't save ostatus_profile for '$addr'");