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 XML string fragment with profile information as an
142 * Activity Streams noun object with the given element type.
144 * Assumes that 'activity' namespace has been previously defined.
146 * @param string $element one of 'actor', 'subject', 'object', 'target'
149 function asActivityNoun($element)
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();
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];
171 $type = 'http://activitystrea.ms/schema/1.0/person';
172 $self = $this->localProfile();
173 $avatar = $self->getAvatar(AVATAR_PROFILE_SIZE);
175 $avatarHref = $avatar->url;
176 $avatarType = $avatar->mediatype;
179 $xs->elementStart('activity:' . $element);
181 'activity:object-type',
189 $xs->element('title', null, $self->getBestName());
193 'type' => $avatarType,
194 'href' => $avatarHref
199 $xs->elementEnd('activity:' . $element);
201 return $xs->getString();
209 return (strpos($this->feeduri, '/groups/') !== false);
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.
219 * @return boolean success
220 * @throws FeedException
222 public function subscribeLocalToRemote(User $user)
224 if ($this->isGroup()) {
225 throw new ServerException("Can't subscribe to a remote group");
228 if ($this->subscribe()) {
229 if ($user->subscribeTo($this->localProfile())) {
230 $this->notify($user->getProfile(), ActivityVerb::FOLLOW, $this);
238 * Mark this remote profile as subscribing to the given local user,
239 * and send appropriate notifications to the user.
241 * This will generally be in response to a subscription notification
242 * from a foreign site to our local Salmon response channel.
245 * @return boolean success
247 public function subscribeRemoteToLocal(User $user)
249 if ($this->isGroup()) {
250 throw new ServerException("Remote groups can't subscribe to local users");
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
259 if ($sub->insert()) {
260 // @fixme use subs_notify() if refactored to take profiles?
261 mail_subscribe_notify_profile($user, $this->localProfile());
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.
271 * @return bool true on success, false on failure
272 * @throws ServerException if feed state is not valid
274 public function subscribe()
276 $feedsub = FeedSub::ensureFeed($this->feeduri);
277 if ($feedsub->sub_state == 'active' || $feedsub->sub_state == 'subscribe') {
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...");
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.
290 * @return bool true on success, false on failure
291 * @throws ServerException if feed state is not valid
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') {
299 } else if ($feedsub->sub_state == 'subscribe') {
300 throw new FeedSubException("Feed is awaiting subscription, can't unsub...");
305 * Send an Activity Streams notification to the remote Salmon endpoint,
308 * @param Profile $actor
309 * @param $verb eg Activity::SUBSCRIBE or Activity::JOIN
310 * @param $object object of the action; if null, the remote entity itself is assumed
312 public function notify($actor, $verb, $object=null)
314 if (!($actor instanceof Profile)) {
315 $type = gettype($actor);
316 if ($type == 'object') {
317 $type = get_class($actor);
319 throw new ServerException("Invalid actor passed to " . __METHOD__ . ": " . $type);
321 if ($object == null) {
324 if ($this->salmonuri) {
325 $text = 'update'; // @fixme
326 $id = 'tag:' . common_config('site', 'server') .
329 ':' . time(); // @fixme
331 // @fixme consolidate all these NS settings somewhere
332 $attributes = array('xmlns' => Activity::ATOM,
333 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
334 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
335 'xmlns:georss' => 'http://www.georss.org/georss',
336 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
338 $entry = new XMLStringer();
339 $entry->elementStart('entry', $attributes);
340 $entry->element('id', null, $id);
341 $entry->element('title', null, $text);
342 $entry->element('summary', null, $text);
343 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
345 $entry->element('activity:verb', null, $verb);
346 $entry->raw($actor->asAtomAuthor());
347 $entry->raw($actor->asActivityActor());
348 $entry->raw($object->asActivityNoun('object'));
349 $entry->elementEnd('entry');
351 $xml = $entry->getString();
352 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
354 $salmon = new Salmon(); // ?
355 $salmon->post($this->salmonuri, $xml);
359 function getBestName()
361 if ($this->isGroup()) {
362 return $this->localGroup()->getBestName();
364 return $this->localProfile()->getBestName();
368 function atomFeed($actor)
370 $feed = new Atom10Feed();
371 // @fixme should these be set up somewhere else?
372 $feed->addNamespace('activity', 'http://activitystrea.ms/spec/1.0/');
373 $feed->addNamespace('thr', 'http://purl.org/syndication/thread/1.0');
374 $feed->addNamespace('georss', 'http://www.georss.org/georss');
375 $feed->addNamespace('ostatus', 'http://ostatus.org/schema/1.0');
377 $taguribase = common_config('integration', 'taguri');
378 $feed->setId("tag:{$taguribase}:UserTimeline:{$actor->id}"); // ???
380 $feed->setTitle($actor->getBestName() . ' timeline'); // @fixme
381 $feed->setUpdated(time());
382 $feed->setPublished(time());
384 $feed->addLink(common_local_url('ApiTimelineUser',
385 array('id' => $actor->id,
387 array('rel' => 'self',
388 'type' => 'application/atom+xml'));
390 $feed->addLink(common_local_url('userbyid',
391 array('id' => $actor->id)),
392 array('rel' => 'alternate',
393 'type' => 'text/html'));
399 * Read and post notices for updates from the feed.
400 * Currently assumes that all items in the feed are new,
401 * coming from a PuSH hub.
403 * @param DOMDocument $feed
405 public function processFeed($feed)
407 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
408 if ($entries->length == 0) {
409 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
413 for ($i = 0; $i < $entries->length; $i++) {
414 $entry = $entries->item($i);
415 $this->processEntry($entry, $feed);
420 * Process a posted entry from this feed source.
422 * @param DOMElement $entry
423 * @param DOMElement $feed for context
425 protected function processEntry($entry, $feed)
427 $activity = new Activity($entry, $feed);
429 $debug = var_export($activity, true);
430 common_log(LOG_DEBUG, $debug);
432 if ($activity->verb == ActivityVerb::POST) {
433 $this->processPost($activity);
435 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
440 * Process an incoming post activity from this remote feed.
441 * @param Activity $activity
443 protected function processPost($activity)
445 if ($this->isGroup()) {
446 // @fixme validate these profiles in some way!
447 $oprofile = self::ensureActorProfile($activity);
449 $actorUri = self::getActorProfileURI($activity);
450 if ($actorUri == $this->uri) {
451 // @fixme check if profile info has changed and update it
453 // @fixme drop or reject the messages once we've got the canonical profile URI recorded sanely
454 common_log(LOG_INFO, "OStatus: Warning: non-group post with unexpected author: $actorUri expected $this->uri");
460 if ($activity->object->link) {
461 $sourceUri = $activity->object->link;
462 } else if (preg_match('!^https?://!', $activity->object->id)) {
463 $sourceUri = $activity->object->id;
465 common_log(LOG_INFO, "OStatus: ignoring post with no source link: id $activity->object->id");
469 $dupe = Notice::staticGet('uri', $sourceUri);
471 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $noticeLink");
475 // @fixme sanitize and save HTML content if available
476 $content = $activity->object->title;
478 $params = array('is_local' => Notice::REMOTE_OMB,
479 'uri' => $sourceUri);
481 $location = $this->getEntryLocation($activity->entry);
483 $params['lat'] = $location->lat;
484 $params['lon'] = $location->lon;
485 if ($location->location_id) {
486 $params['location_ns'] = $location->location_ns;
487 $params['location_id'] = $location->location_id;
491 // @fixme save detailed ostatus source info
492 // @fixme ensure that groups get handled correctly
494 $saved = Notice::saveNew($oprofile->localProfile()->id,
501 * @param string $profile_url
502 * @return Ostatus_profile
503 * @throws FeedSubException
505 public static function ensureProfile($profile_uri)
507 // Get the canonical feed URI and check it
508 $discover = new FeedDiscovery();
509 $feeduri = $discover->discoverFromURL($profile_uri);
511 //$feedsub = FeedSub::ensureFeed($feeduri, $discover->feed);
512 $huburi = $discover->getAtomLink('hub');
513 $salmonuri = $discover->getAtomLink('salmon');
516 // We can only deal with folks with a PuSH hub
517 throw new FeedSubNoHubException();
520 // Ok this is going to be a terrible hack!
521 // Won't be suitable for groups, empty feeds, or getting
522 // info that's only available on the profile page.
523 $entries = $discover->feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
524 if (!$entries || $entries->length == 0) {
525 throw new FeedSubException('empty feed');
527 $first = new Activity($entries->item(0), $discover->feed);
528 return self::ensureActorProfile($first, $feeduri, $salmonuri);
532 * Download and update given avatar image
534 * @throws Exception in various failure cases
536 protected function updateAvatar($url)
538 // @fixme this should be better encapsulated
539 // ripped from oauthstore.php (for old OMB client)
540 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
541 copy($url, $temp_filename);
543 if ($this->isGroup()) {
544 $id = $this->group_id;
546 $id = $this->profile_id;
548 // @fixme should we be using different ids?
549 $imagefile = new ImageFile($id, $temp_filename);
550 $filename = Avatar::filename($id,
551 image_type_to_extension($imagefile->type),
554 rename($temp_filename, Avatar::path($filename));
555 if ($this->isGroup()) {
556 $group = $this->localGroup();
557 $group->setOriginal($filename);
559 $profile = $this->localProfile();
560 $profile->setOriginal($filename);
565 * Get an appropriate avatar image source URL, if available.
567 * @param ActivityObject $actor
568 * @param DOMElement $feed
571 protected static function getAvatar($actor, $feed)
575 if ($actor->avatar) {
576 $url = trim($actor->avatar);
579 // Check <atom:logo> and <atom:icon> on the feed
580 $els = $feed->childNodes();
581 if ($els && $els->length) {
582 for ($i = 0; $i < $els->length; $i++) {
583 $el = $els->item($i);
584 if ($el->namespaceURI == Activity::ATOM) {
585 if (empty($url) && $el->localName == 'logo') {
586 $url = trim($el->textContent);
589 if (empty($icon) && $el->localName == 'icon') {
591 $icon = trim($el->textContent);
596 if ($icon && !$url) {
601 $opts = array('allowed_schemes' => array('http', 'https'));
602 if (Validate::uri($url, $opts)) {
606 return common_path('plugins/OStatus/images/96px-Feed-icon.svg.png');
610 * Fetch, or build if necessary, an Ostatus_profile for the actor
611 * in a given Activity Streams activity.
613 * @param Activity $activity
614 * @param string $feeduri if we already know the canonical feed URI!
615 * @param string $salmonuri if we already know the salmon return channel URI
616 * @return Ostatus_profile
618 public static function ensureActorProfile($activity, $feeduri=null, $salmonuri=null)
620 $profile = self::getActorProfile($activity);
622 $profile = self::createActorProfile($activity, $feeduri, $salmonuri);
628 * @param Activity $activity
629 * @return mixed matching Ostatus_profile or false if none known
631 protected static function getActorProfile($activity)
633 $homeuri = self::getActorProfileURI($activity);
634 return self::staticGet('uri', $homeuri);
638 * @param Activity $activity
640 * @throws ServerException
642 protected static function getActorProfileURI($activity)
644 $opts = array('allowed_schemes' => array('http', 'https'));
645 $actor = $activity->actor;
646 if ($actor->id && Validate::uri($actor->id, $opts)) {
649 if ($actor->link && Validate::uri($actor->link, $opts)) {
652 throw new ServerException("No author ID URI found");
656 * @fixme validate stuff somewhere
658 protected static function createActorProfile($activity, $feeduri=null, $salmonuri=null)
660 $actor = $activity->actor;
661 $homeuri = self::getActorProfileURI($activity);
662 $nickname = self::getAuthorNick($activity);
663 $avatar = self::getAvatar($actor, $activity->feed);
666 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
667 throw new ServerException("No profile URI");
670 if (!$feeduri || !$salmonuri) {
671 // Get the canonical feed URI and check it
672 $discover = new FeedDiscovery();
673 $feeduri = $discover->discoverFromURL($homeuri);
675 $huburi = $discover->getAtomLink('hub');
676 $salmonuri = $discover->getAtomLink('salmon');
679 // We can only deal with folks with a PuSH hub
680 throw new FeedSubNoHubException();
684 $profile = new Profile();
685 $profile->nickname = $nickname;
686 $profile->fullname = $actor->displayName;
687 $profile->homepage = $actor->link; // @fixme
688 $profile->profileurl = $homeuri;
690 // @fixme tags/categories
692 // @todo tags from categories
693 // @todo lat/lon/location?
695 $ok = $profile->insert();
697 throw new ServerException("Can't save local profile");
700 // @fixme either need to do feed discovery here
701 // or need to split out some of the feed stuff
702 // so we can leave it empty until later.
703 $oprofile = new Ostatus_profile();
704 $oprofile->uri = $homeuri;
705 $oprofile->feeduri = $feeduri;
706 $oprofile->salmonuri = $salmonuri;
707 $oprofile->profile_id = $profile->id;
709 $oprofile->created = common_sql_now();
710 $oprofile->modified = common_sql_now();
712 $ok = $oprofile->insert();
714 $oprofile->updateAvatar($avatar);
717 throw new ServerException("Can't save OStatus profile");
722 * @fixme move this into Activity?
723 * @param Activity $activity
726 protected static function getAuthorNick($activity)
728 // @fixme not technically part of the actor?
729 foreach (array($activity->entry, $activity->feed) as $source) {
730 $author = ActivityUtils::child($source, 'author', Activity::ATOM);
732 $name = ActivityUtils::child($author, 'name', Activity::ATOM);
734 return trim($name->textContent);