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 + DB_DATAOBJECT_NOTNULL,
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);
153 $avatarHref = Avatar::defaultImage(AVATAR_PROFILE_SIZE);
154 $avatarType = 'image/png';
155 if ($this->isGroup()) {
156 $type = 'http://activitystrea.ms/schema/1.0/group';
157 $self = $this->localGroup();
159 // @fixme put a standard getAvatar() interface on groups too
160 if ($self->homepage_logo) {
161 $avatarHref = $self->homepage_logo;
162 $map = array('png' => 'image/png',
163 'jpg' => 'image/jpeg',
164 'jpeg' => 'image/jpeg',
165 'gif' => 'image/gif');
166 $extension = pathinfo(parse_url($avatarHref, PHP_URL_PATH), PATHINFO_EXTENSION);
167 if (isset($map[$extension])) {
168 $avatarType = $map[$extension];
172 $type = 'http://activitystrea.ms/schema/1.0/person';
173 $self = $this->localProfile();
174 $avatar = $self->getAvatar(AVATAR_PROFILE_SIZE);
176 $avatarHref = $avatar->
177 $avatarType = $avatar->mediatype;
180 $xs->elementStart('activity:' . $element);
182 'activity:object-type',
190 $xs->element('title', null, $self->getBestName());
194 'type' => $avatarType,
195 'href' => $avatarHref
200 $xs->elementEnd('activity:' . $element);
202 return $xs->getString();
210 return (strpos($this->feeduri, '/groups/') !== false);
214 * Subscribe a local user to this remote user.
215 * PuSH subscription will be started if necessary, and we'll
216 * send a Salmon notification to the remote server if available
217 * notifying them of the sub.
220 * @return boolean success
221 * @throws FeedException
223 public function subscribeLocalToRemote(User $user)
225 if ($this->isGroup()) {
226 throw new ServerException("Can't subscribe to a remote group");
229 if ($this->subscribe()) {
230 if ($user->subscribeTo($this->localProfile())) {
231 $this->notify($user->getProfile(), ActivityVerb::FOLLOW, $this);
239 * Mark this remote profile as subscribing to the given local user,
240 * and send appropriate notifications to the user.
242 * This will generally be in response to a subscription notification
243 * from a foreign site to our local Salmon response channel.
246 * @return boolean success
248 public function subscribeRemoteToLocal(User $user)
250 if ($this->isGroup()) {
251 throw new ServerException("Remote groups can't subscribe to local users");
254 // @fixme use regular channels for subbing, once they accept remote profiles
255 $sub = new Subscription();
256 $sub->subscriber = $this->profile_id;
257 $sub->subscribed = $user->id;
258 $sub->created = common_sql_now(); // current time
260 if ($sub->insert()) {
261 // @fixme use subs_notify() if refactored to take profiles?
262 mail_subscribe_notify_profile($user, $this->localProfile());
269 * Send a subscription request to the hub for this feed.
270 * The hub will later send us a confirmation POST to /main/push/callback.
272 * @return bool true on success, false on failure
273 * @throws ServerException if feed state is not valid
275 public function subscribe($mode='subscribe')
277 $feedsub = FeedSub::ensureFeed($this->feeduri);
278 if ($feedsub->sub_state == 'active' || $feedsub->sub_state == 'subscribe') {
280 } else if ($feedsub->sub_state == '' || $feedsub->sub_state == 'inactive') {
281 return $feedsub->subscribe();
282 } else if ('unsubscribe') {
283 throw new FeedSubException("Unsub is pending, can't subscribe...");
288 * Send a PuSH unsubscription request to the hub for this feed.
289 * The hub will later send us a confirmation POST to /main/push/callback.
291 * @return bool true on success, false on failure
292 * @throws ServerException if feed state is not valid
294 public function unsubscribe() {
295 $feedsub = FeedSub::staticGet('uri', $this->feeduri);
296 if ($feedsub->sub_state == 'active') {
297 return $feedsub->unsubscribe();
298 } else if ($feedsub->sub_state == '' || $feedsub->sub_state == 'inactive' || $feedsub->sub_state == 'unsubscribe') {
300 } else if ($feedsub->sub_state == 'subscribe') {
301 throw new FeedSubException("Feed is awaiting subscription, can't unsub...");
306 * Send an Activity Streams notification to the remote Salmon endpoint,
309 * @param Profile $actor
310 * @param $verb eg Activity::SUBSCRIBE or Activity::JOIN
311 * @param $object object of the action; if null, the remote entity itself is assumed
313 public function notify(Profile $actor, $verb, $object=null)
315 if ($object == null) {
318 if ($this->salmonuri) {
319 $text = 'update'; // @fixme
320 $id = 'tag:' . common_config('site', 'server') .
323 ':' . time(); // @fixme
325 //$entry = new Atom10Entry();
326 $entry = new XMLStringer();
327 $entry->elementStart('entry');
328 $entry->element('id', null, $id);
329 $entry->element('title', null, $text);
330 $entry->element('summary', null, $text);
331 $entry->element('published', null, common_date_w3dtf(time()));
333 $entry->element('activity:verb', null, $verb);
334 $entry->raw($actor->asAtomAuthor());
335 $entry->raw($actor->asActivityActor());
336 $entry->raw($object->asActivityNoun('object'));
337 $entry->elementEnd('entry');
339 $feed = $this->atomFeed($actor);
340 $feed->addEntry($entry);
342 $xml = $feed->getString();
343 common_log(LOG_INFO, "Posting to Salmon endpoint $salmon: $xml");
345 $salmon = new Salmon(); // ?
346 $salmon->post($this->salmonuri, $xml);
350 function getBestName()
352 if ($this->isGroup()) {
353 return $this->localGroup()->getBestName();
355 return $this->localProfile()->getBestName();
359 function atomFeed($actor)
361 $feed = new Atom10Feed();
362 // @fixme should these be set up somewhere else?
363 $feed->addNamespace('activity', 'http://activitystrea.ms/spec/1.0/');
364 $feed->addNamespace('thr', 'http://purl.org/syndication/thread/1.0');
365 $feed->addNamespace('georss', 'http://www.georss.org/georss');
366 $feed->addNamespace('ostatus', 'http://ostatus.org/schema/1.0');
368 $taguribase = common_config('integration', 'taguri');
369 $feed->setId("tag:{$taguribase}:UserTimeline:{$actor->id}"); // ???
371 $feed->setTitle($actor->getBestName() . ' timeline'); // @fixme
372 $feed->setUpdated(time());
373 $feed->setPublished(time());
375 $feed->addLink(common_local_url('ApiTimelineUser',
376 array('id' => $actor->id,
378 array('rel' => 'self',
379 'type' => 'application/atom+xml'));
381 $feed->addLink(common_local_url('userbyid',
382 array('id' => $actor->id)),
383 array('rel' => 'alternate',
384 'type' => 'text/html'));
390 * Read and post notices for updates from the feed.
391 * Currently assumes that all items in the feed are new,
392 * coming from a PuSH hub.
394 * @param DOMDocument $feed
396 public function processFeed($feed)
398 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
399 if ($entries->length == 0) {
400 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
404 for ($i = 0; $i < $entries->length; $i++) {
405 $entry = $entries->item($i);
406 $this->processEntry($entry, $feed);
411 * Process a posted entry from this feed source.
413 * @param DOMElement $entry
414 * @param DOMElement $feed for context
416 protected function processEntry($entry, $feed)
418 $activity = new Activity($entry, $feed);
420 $debug = var_export($activity, true);
421 common_log(LOG_DEBUG, $debug);
423 if ($activity->verb == ActivityVerb::POST) {
424 $this->processPost($activity);
426 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
431 * Process an incoming post activity from this remote feed.
432 * @param Activity $activity
434 protected function processPost($activity)
436 if ($this->isGroup()) {
437 // @fixme validate these profiles in some way!
438 $oprofile = self::ensureActorProfile($activity);
440 $actorUri = self::getActorProfileURI($activity);
441 if ($actorUri == $this->uri) {
442 // @fixme check if profile info has changed and update it
444 // @fixme drop or reject the messages once we've got the canonical profile URI recorded sanely
445 common_log(LOG_INFO, "OStatus: Warning: non-group post with unexpected author: $actorUri expected $this->uri");
451 if ($activity->object->link) {
452 $sourceUri = $activity->object->link;
453 } else if (preg_match('!^https?://!', $activity->object->id)) {
454 $sourceUri = $activity->object->id;
456 common_log(LOG_INFO, "OStatus: ignoring post with no source link: id $activity->object->id");
460 $dupe = Notice::staticGet('uri', $sourceUri);
462 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $noticeLink");
466 // @fixme sanitize and save HTML content if available
467 $content = $activity->object->title;
469 $params = array('is_local' => Notice::REMOTE_OMB,
470 'uri' => $sourceUri);
472 $location = $this->getEntryLocation($activity->entry);
474 $params['lat'] = $location->lat;
475 $params['lon'] = $location->lon;
476 if ($location->location_id) {
477 $params['location_ns'] = $location->location_ns;
478 $params['location_id'] = $location->location_id;
482 // @fixme save detailed ostatus source info
483 // @fixme ensure that groups get handled correctly
485 $saved = Notice::saveNew($oprofile->localProfile()->id,
492 * Parse location given as a GeoRSS-simple point, if provided.
493 * http://www.georss.org/simple
495 * @param feed item $entry
496 * @return mixed Location or false
498 function getLocation($dom)
500 $points = $dom->getElementsByTagNameNS('http://www.georss.org/georss', 'point');
502 for ($i = 0; $i < $points->length; $i++) {
503 $point = $points->item(0)->textContent;
504 $point = str_replace(',', ' ', $point); // per spec "treat commas as whitespace"
505 $point = preg_replace('/\s+/', ' ', $point);
506 $point = trim($point);
507 $coords = explode(' ', $point);
508 if (count($coords) == 2) {
509 list($lat, $lon) = $coords;
510 if (is_numeric($lat) && is_numeric($lon)) {
511 common_log(LOG_INFO, "Looking up location for $lat $lon from georss");
512 return Location::fromLatLon($lat, $lon);
515 common_log(LOG_ERR, "Ignoring bogus georss:point value $point");
522 * @param string $profile_url
523 * @return Ostatus_profile
524 * @throws FeedSubException
526 public static function ensureProfile($profile_uri)
528 // Get the canonical feed URI and check it
529 $discover = new FeedDiscovery();
530 $feeduri = $discover->discoverFromURL($profile_uri);
532 $feedsub = FeedSub::ensureFeed($feeduri, $discover->feed);
533 $huburi = $discover->getAtomLink('hub');
534 $salmonuri = $discover->getAtomLink('salmon');
537 // We can only deal with folks with a PuSH hub
538 throw new FeedSubNoHubException();
541 // Ok this is going to be a terrible hack!
542 // Won't be suitable for groups, empty feeds, or getting
543 // info that's only available on the profile page.
544 $entries = $discover->feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
545 if (!$entries || $entries->length == 0) {
546 throw new FeedSubException('empty feed');
548 $first = new Activity($entries->item(0), $discover->feed);
549 return self::ensureActorProfile($first, $feeduri);
553 * Download and update given avatar image
555 * @throws Exception in various failure cases
557 protected function updateAvatar($url)
559 // @fixme this should be better encapsulated
560 // ripped from oauthstore.php (for old OMB client)
561 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
562 copy($url, $temp_filename);
564 // @fixme should we be using different ids?
565 $imagefile = new ImageFile($this->id, $temp_filename);
566 $filename = Avatar::filename($this->id,
567 image_type_to_extension($imagefile->type),
570 rename($temp_filename, Avatar::path($filename));
571 if ($this->isGroup()) {
572 $group = $this->localGroup();
573 $group->setOriginal($filename);
575 $profile = $this->localProfile();
576 $profile->setOriginal($filename);
581 * Get an appropriate avatar image source URL, if available.
583 * @param ActivityObject $actor
584 * @param DOMElement $feed
587 protected static function getAvatar($actor, $feed)
591 if ($actor->avatar) {
592 $url = trim($actor->avatar);
595 // Check <atom:logo> and <atom:icon> on the feed
596 $els = $feed->childNodes();
597 if ($els && $els->length) {
598 for ($i = 0; $i < $els->length; $i++) {
599 $el = $els->item($i);
600 if ($el->namespaceURI == Activity::ATOM) {
601 if (empty($url) && $el->localName == 'logo') {
602 $url = trim($el->textContent);
605 if (empty($icon) && $el->localName == 'icon') {
607 $icon = trim($el->textContent);
612 if ($icon && !$url) {
617 $opts = array('allowed_schemes' => array('http', 'https'));
618 if (Validate::uri($url, $opts)) {
622 return common_path('plugins/OStatus/images/96px-Feed-icon.svg.png');
626 * Fetch, or build if necessary, an Ostatus_profile for the actor
627 * in a given Activity Streams activity.
629 * @param Activity $activity
630 * @param string $feeduri if we already know the canonical feed URI!
631 * @return Ostatus_profile
633 public static function ensureActorProfile($activity, $feeduri=null)
635 $profile = self::getActorProfile($activity);
637 $profile = self::createActorProfile($activity, $feeduri);
643 * @param Activity $activity
644 * @return mixed matching Ostatus_profile or false if none known
646 protected static function getActorProfile($activity)
648 $homeuri = self::getActorProfileURI($activity);
649 return self::staticGet('uri', $homeuri);
653 * @param Activity $activity
655 * @throws ServerException
657 protected static function getActorProfileURI($activity)
659 $opts = array('allowed_schemes' => array('http', 'https'));
660 $actor = $activity->actor;
661 if ($actor->id && Validate::uri($actor->id, $opts)) {
664 if ($actor->link && Validate::uri($actor->link, $opts)) {
667 throw new ServerException("No author ID URI found");
671 * @fixme validate stuff somewhere
673 protected static function createActorProfile($activity, $feeduri=null)
675 $actor = $activity->actor;
676 $homeuri = self::getActorProfileURI($activity);
677 $nickname = self::getAuthorNick($activity);
678 $avatar = self::getAvatar($actor, $feed);
681 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
682 throw new ServerException("No profile URI");
685 $profile = new Profile();
686 $profile->nickname = $nickname;
687 $profile->fullname = $actor->displayName;
688 $profile->homepage = $actor->link; // @fixme
689 $profile->profileurl = $homeuri;
691 // @fixme tags/categories
693 // @todo tags from categories
694 // @todo lat/lon/location?
696 $ok = $profile->insert();
698 throw new ServerException("Can't save local profile");
701 // @fixme either need to do feed discovery here
702 // or need to split out some of the feed stuff
703 // so we can leave it empty until later.
704 $oprofile = new Ostatus_profile();
705 $oprofile->uri = $homeuri;
707 $oprofile->feeduri = $feeduri;
709 $oprofile->profile_id = $profile->id;
711 $ok = $oprofile->insert();
713 $oprofile->updateAvatar($avatar);
716 throw new ServerException("Can't save OStatus profile");
721 * @fixme move this into Activity?
722 * @param Activity $activity
725 protected static function getAuthorNick($activity)
727 // @fixme not technically part of the actor?
728 foreach (array($activity->entry, $activity->feed) as $source) {
729 $author = ActivityUtils::child($source, 'author', Activity::ATOM);
731 $name = ActivityUtils::child($author, 'name', Activity::ATOM);
733 return trim($name->textContent);