]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - plugins/OStatus/classes/Ostatus_profile.php
wiring in magicsig
[quix0rs-gnu-social.git] / plugins / OStatus / classes / Ostatus_profile.php
index be01cdfe196236fb859e6feabe5f21260dc049b6..0e12f8fc6e14005b50648b22311c832f320e91f6 100644 (file)
  */
 
 /**
- * @package FeedSubPlugin
+ * @package OStatusPlugin
  * @maintainer Brion Vibber <brion@status.net>
  */
 
-/*
-PuSH subscription flow:
-
-    $profile->subscribe()
-        generate random verification token
-            save to verify_token
-        sends a sub request to the hub...
-
-    main/push/callback
-        hub sends confirmation back to us via GET
-        We verify the request, then echo back the challenge.
-        On our end, we save the time we subscribed and the lease expiration
-
-    main/push/callback
-        hub sends us updates via POST
-
-*/
-
-class FeedDBException extends FeedSubException
-{
-    public $obj;
-
-    function __construct($obj)
-    {
-        parent::__construct('Database insert failure');
-        $this->obj = $obj;
-    }
-}
-
 class Ostatus_profile extends Memcached_DataObject
 {
     public $__table = 'ostatus_profile';
 
-    public $id;
+    public $uri;
+
     public $profile_id;
     public $group_id;
 
     public $feeduri;
-    public $homeuri;
-
-    // PuSH subscription data
-    public $huburi;
-    public $secret;
-    public $verify_token;
-    public $sub_state; // subscribe, active, unsubscribe
-    public $sub_start;
-    public $sub_end;
-
     public $salmonuri;
 
     public $created;
-    public $lastupdate;
+    public $modified;
 
     public /*static*/ function staticGet($k, $v=null)
     {
@@ -91,56 +53,30 @@ class Ostatus_profile extends Memcached_DataObject
 
     function table()
     {
-        return array('id' => DB_DATAOBJECT_INT + DB_DATAOBJECT_NOTNULL,
+        return array('uri' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
                      'profile_id' => DB_DATAOBJECT_INT,
                      'group_id' => DB_DATAOBJECT_INT,
-                     'feeduri' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
-                     'homeuri' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
-                     'huburi' =>  DB_DATAOBJECT_STR,
-                     'secret' => DB_DATAOBJECT_STR,
-                     'verify_token' => DB_DATAOBJECT_STR,
-                     'sub_state' => DB_DATAOBJECT_STR,
-                     'sub_start' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
-                     'sub_end' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
+                     'feeduri' => DB_DATAOBJECT_STR,
                      'salmonuri' =>  DB_DATAOBJECT_STR,
                      'created' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL,
-                     'lastupdate' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL);
+                     'modified' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL);
     }
 
     static function schemaDef()
     {
-        return array(new ColumnDef('id', 'integer',
-                                   /*size*/ null,
-                                   /*nullable*/ false,
-                                   /*key*/ 'PRI',
-                                   /*default*/ '0',
-                                   /*extra*/ null,
-                                   /*auto_increment*/ true),
+        return array(new ColumnDef('uri', 'varchar',
+                                   255, false, 'PRI'),
                      new ColumnDef('profile_id', 'integer',
                                    null, true, 'UNI'),
                      new ColumnDef('group_id', 'integer',
                                    null, true, 'UNI'),
                      new ColumnDef('feeduri', 'varchar',
-                                   255, false, 'UNI'),
-                     new ColumnDef('homeuri', 'varchar',
-                                   255, false),
-                     new ColumnDef('huburi', 'text',
-                                   null, true),
-                     new ColumnDef('verify_token', 'varchar',
-                                   32, true),
-                     new ColumnDef('secret', 'varchar',
-                                   64, true),
-                     new ColumnDef('sub_state', "enum('subscribe','active','unsubscribe')",
-                                   null, true),
-                     new ColumnDef('sub_start', 'datetime',
-                                   null, true),
-                     new ColumnDef('sub_end', 'datetime',
-                                   null, true),
+                                   255, true, 'UNI'),
                      new ColumnDef('salmonuri', 'text',
                                    null, true),
                      new ColumnDef('created', 'datetime',
                                    null, false),
-                     new ColumnDef('lastupdate', 'datetime',
+                     new ColumnDef('modified', 'datetime',
                                    null, false));
     }
 
@@ -169,12 +105,12 @@ class Ostatus_profile extends Memcached_DataObject
 
     function keyTypes()
     {
-        return array('id' => 'K', 'profile_id' => 'U', 'group_id' => 'U', 'feeduri' => 'U');
+        return array('uri' => 'K', 'profile_id' => 'U', 'group_id' => 'U', 'feeduri' => 'U');
     }
 
     function sequenceKey()
     {
-        return array('id', true, false);
+        return array(false, false, false);
     }
 
     /**
@@ -201,101 +137,6 @@ class Ostatus_profile extends Memcached_DataObject
         return null;
     }
 
-    /**
-     * @param FeedMunger $munger
-     * @param boolean $isGroup is this a group record?
-     * @return Ostatus_profile
-     */
-    public static function ensureProfile($munger)
-    {
-        $profile = $munger->ostatusProfile();
-
-        $current = self::staticGet('feeduri', $profile->feeduri);
-        if ($current) {
-            // @fixme we should probably update info as necessary
-            return $current;
-        }
-
-        $profile->query('BEGIN');
-
-        try {
-            $local = $munger->profile();
-
-            if ($profile->isGroup()) {
-                $group = new User_group();
-                $group->nickname = $local->nickname . '@remote'; // @fixme
-                $group->fullname = $local->fullname;
-                $group->homepage = $local->homepage;
-                $group->location = $local->location;
-                $group->created = $local->created;
-                $group->insert();
-                if (empty($result)) {
-                    throw new FeedDBException($group);
-                }
-                $profile->group_id = $group->id;
-            } else {
-                $result = $local->insert();
-                if (empty($result)) {
-                    throw new FeedDBException($local);
-                }
-                $profile->profile_id = $local->id;
-            }
-
-            $profile->created = common_sql_now();
-            $profile->lastupdate = common_sql_now();
-            $result = $profile->insert();
-            if (empty($result)) {
-                throw new FeedDBException($profile);
-            }
-
-            $profile->query('COMMIT');
-        } catch (FeedDBException $e) {
-            common_log_db_error($e->obj, 'INSERT', __FILE__);
-            $profile->query('ROLLBACK');
-            return false;
-        }
-
-        $avatar = $munger->getAvatar();
-        if ($avatar) {
-            try {
-                $profile->updateAvatar($avatar);
-            } catch (Exception $e) {
-                common_log(LOG_ERR, "Exception setting OStatus avatar: " .
-                                    $e->getMessage());
-            }
-        }
-
-        return $profile;
-    }
-
-    /**
-     * Download and update given avatar image
-     * @param string $url
-     * @throws Exception in various failure cases
-     */
-    public function updateAvatar($url)
-    {
-        // @fixme this should be better encapsulated
-        // ripped from oauthstore.php (for old OMB client)
-        $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
-        copy($url, $temp_filename);
-        
-        // @fixme should we be using different ids?
-        $imagefile = new ImageFile($this->id, $temp_filename);
-        $filename = Avatar::filename($this->id,
-                                     image_type_to_extension($imagefile->type),
-                                     null,
-                                     common_timestamp());
-        rename($temp_filename, Avatar::path($filename));
-        if ($this->isGroup()) {
-            $group = $this->localGroup();
-            $group->setOriginal($filename);
-        } else {
-            $profile = $this->localProfile();
-            $profile->setOriginal($filename);
-        }
-    }
-
     /**
      * Returns an XML string fragment with profile information as an
      * Activity Streams noun object with the given element type.
@@ -308,7 +149,6 @@ class Ostatus_profile extends Memcached_DataObject
     function asActivityNoun($element)
     {
         $xs = new XMLStringer(true);
-
         $avatarHref = Avatar::defaultImage(AVATAR_PROFILE_SIZE);
         $avatarType = 'image/png';
         if ($this->isGroup()) {
@@ -332,8 +172,8 @@ class Ostatus_profile extends Memcached_DataObject
             $self = $this->localProfile();
             $avatar = $self->getAvatar(AVATAR_PROFILE_SIZE);
             if ($avatar) {
-                $avatarHref = $avatar->
-                $avatarType = $avatar->mediatype;
+                  $avatarHref = $avatar->url;
+                  $avatarType = $avatar->mediatype;
             }
         }
         $xs->elementStart('activity:' . $element);
@@ -345,7 +185,7 @@ class Ostatus_profile extends Memcached_DataObject
         $xs->element(
             'id',
             null,
-            $this->homeuri); // ?
+            $this->uri); // ?
         $xs->element('title', null, $self->getBestName());
 
         $xs->element(
@@ -370,188 +210,165 @@ class Ostatus_profile extends Memcached_DataObject
     }
 
     /**
-     * Send a subscription request to the hub for this feed.
-     * The hub will later send us a confirmation POST to /main/push/callback.
+     * Subscribe a local user to this remote user.
+     * PuSH subscription will be started if necessary, and we'll
+     * send a Salmon notification to the remote server if available
+     * notifying them of the sub.
      *
-     * @return bool true on success, false on failure
-     * @throws ServerException if feed state is not valid
+     * @param User $user
+     * @return boolean success
+     * @throws FeedException
      */
-    public function subscribe($mode='subscribe')
+    public function subscribeLocalToRemote(User $user)
     {
-        if ($this->sub_state != '') {
-            throw new ServerException("Attempting to start PuSH subscription to feed in state $this->sub_state");
+        if ($this->isGroup()) {
+            throw new ServerException("Can't subscribe to a remote group");
         }
-        if (empty($this->huburi)) {
-            if (common_config('feedsub', 'nohub')) {
-                // Fake it! We're just testing remote feeds w/o hubs.
+
+        if ($this->subscribe()) {
+            if ($user->subscribeTo($this->localProfile())) {
+                $this->notify($user->getProfile(), ActivityVerb::FOLLOW, $this);
                 return true;
-            } else {
-                throw new ServerException("Attempting to start PuSH subscription for feed with no hub");
             }
         }
-
-        return $this->doSubscribe('subscribe');
+        return false;
     }
 
     /**
-     * Send a PuSH unsubscription request to the hub for this feed.
-     * The hub will later send us a confirmation POST to /main/push/callback.
+     * Mark this remote profile as subscribing to the given local user,
+     * and send appropriate notifications to the user.
      *
-     * @return bool true on success, false on failure
-     * @throws ServerException if feed state is not valid
+     * This will generally be in response to a subscription notification
+     * from a foreign site to our local Salmon response channel.
+     *
+     * @param User $user
+     * @return boolean success
      */
-    public function unsubscribe() {
-        if ($this->sub_state != 'active') {
-            throw new ServerException("Attempting to end PuSH subscription to feed in state $this->sub_state");
-        }
-        if (empty($this->huburi)) {
-            if (common_config('feedsub', 'nohub')) {
-                // Fake it! We're just testing remote feeds w/o hubs.
-                return true;
-            } else {
-                throw new ServerException("Attempting to end PuSH subscription for feed with no hub");
-            }
-        }
-
-        return $this->doSubscribe('unsubscribe');
-    }
-
-    protected function doSubscribe($mode)
+    public function subscribeRemoteToLocal(User $user)
     {
-        $orig = clone($this);
-        $this->verify_token = common_good_rand(16);
-        if ($mode == 'subscribe') {
-            $this->secret = common_good_rand(32);
+        if ($this->isGroup()) {
+            throw new ServerException("Remote groups can't subscribe to local users");
         }
-        $this->sub_state = $mode;
-        $this->update($orig);
-        unset($orig);
-
-        try {
-            $callback = common_local_url('pushcallback', array('feed' => $this->id));
-            $headers = array('Content-Type: application/x-www-form-urlencoded');
-            $post = array('hub.mode' => $mode,
-                          'hub.callback' => $callback,
-                          'hub.verify' => 'async',
-                          'hub.verify_token' => $this->verify_token,
-                          'hub.secret' => $this->secret,
-                          //'hub.lease_seconds' => 0,
-                          'hub.topic' => $this->feeduri);
-            $client = new HTTPClient();
-            $response = $client->post($this->huburi, $headers, $post);
-            $status = $response->getStatus();
-            if ($status == 202) {
-                common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
-                return true;
-            } else if ($status == 204) {
-                common_log(LOG_INFO, __METHOD__ . ': sub req ok and verified');
-                return true;
-            } else if ($status >= 200 && $status < 300) {
-                common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
-                return false;
-            } else {
-                common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
-                return false;
-            }
-        } catch (Exception $e) {
-            // wtf!
-            common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub $this->huburi subscribing to $this->feeduri");
 
-            $orig = clone($this);
-            $this->verify_token = null;
-            $this->sub_state = null;
-            $this->update($orig);
-            unset($orig);
+        // @fixme use regular channels for subbing, once they accept remote profiles
+        $sub = new Subscription();
+        $sub->subscriber = $this->profile_id;
+        $sub->subscribed = $user->id;
+        $sub->created = common_sql_now(); // current time
 
-            return false;
+        if ($sub->insert()) {
+            // @fixme use subs_notify() if refactored to take profiles?
+            mail_subscribe_notify_profile($user, $this->localProfile());
+            return true;
         }
+        return false;
     }
 
     /**
-     * Save PuSH subscription confirmation.
-     * Sets approximate lease start and end times and finalizes state.
+     * Send a subscription request to the hub for this feed.
+     * The hub will later send us a confirmation POST to /main/push/callback.
      *
-     * @param int $lease_seconds provided hub.lease_seconds parameter, if given
+     * @return bool true on success, false on failure
+     * @throws ServerException if feed state is not valid
      */
-    public function confirmSubscribe($lease_seconds=0)
+    public function subscribe()
     {
-        $original = clone($this);
-
-        $this->sub_state = 'active';
-        $this->sub_start = common_sql_date(time());
-        if ($lease_seconds > 0) {
-            $this->sub_end = common_sql_date(time() + $lease_seconds);
-        } else {
-            $this->sub_end = null;
+        $feedsub = FeedSub::ensureFeed($this->feeduri);
+        if ($feedsub->sub_state == 'active' || $feedsub->sub_state == 'subscribe') {
+            return true;
+        } else if ($feedsub->sub_state == '' || $feedsub->sub_state == 'inactive') {
+            return $feedsub->subscribe();
+        } else if ('unsubscribe') {
+            throw new FeedSubException("Unsub is pending, can't subscribe...");
         }
-        $this->lastupdate = common_sql_date();
-
-        return $this->update($original);
     }
 
     /**
-     * Save PuSH unsubscription confirmation.
-     * Wipes active PuSH sub info and resets state.
+     * Send a PuSH unsubscription request to the hub for this feed.
+     * The hub will later send us a confirmation POST to /main/push/callback.
+     *
+     * @return bool true on success, false on failure
+     * @throws ServerException if feed state is not valid
      */
-    public function confirmUnsubscribe()
-    {
-        $original = clone($this);
-
-        $this->verify_token = null;
-        $this->secret = null;
-        $this->sub_state = null;
-        $this->sub_start = null;
-        $this->sub_end = null;
-        $this->lastupdate = common_sql_date();
-
-        return $this->update($original);
+    public function unsubscribe() {
+        $feedsub = FeedSub::staticGet('uri', $this->feeduri);
+        if ($feedsub->sub_state == 'active') {
+            return $feedsub->unsubscribe();
+        } else if ($feedsub->sub_state == '' || $feedsub->sub_state == 'inactive' || $feedsub->sub_state == 'unsubscribe') {
+            return true;
+        } else if ($feedsub->sub_state == 'subscribe') {
+            throw new FeedSubException("Feed is awaiting subscription, can't unsub...");
+        }
     }
 
     /**
      * Send an Activity Streams notification to the remote Salmon endpoint,
      * if so configured.
      *
-     * @param Profile $actor
-     * @param $verb eg Activity::SUBSCRIBE or Activity::JOIN
-     * @param $object object of the action; if null, the remote entity itself is assumed
+     * @param Profile $actor  Actor who did the activity
+     * @param string  $verb   Activity::SUBSCRIBE or Activity::JOIN
+     * @param Object  $object object of the action; must define asActivityNoun($tag)
      */
-    public function notify(Profile $actor, $verb, $object=null)
+    public function notify($actor, $verb, $object=null)
     {
+        if (!($actor instanceof Profile)) {
+            $type = gettype($actor);
+            if ($type == 'object') {
+                $type = get_class($actor);
+            }
+            throw new ServerException("Invalid actor passed to " . __METHOD__ . ": " . $type);
+        }
         if ($object == null) {
             $object = $this;
         }
         if ($this->salmonuri) {
-            $text = 'update'; // @fixme
-            $id = 'tag:' . common_config('site', 'server') .
-                ':' . $verb .
-                ':' . $actor->id .
-                ':' . time(); // @fixme
-
-            $entry = new Atom10Entry();
-            $entry->elementStart('entry');
+
+            $text = 'update';
+            $id = TagURI::mint('%s:%s:%s',
+                               $verb,
+                               $actor->getURI(),
+                               common_date_iso8601(time()));
+
+            // @fixme consolidate all these NS settings somewhere
+            $attributes = array('xmlns' => Activity::ATOM,
+                                'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
+                                'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
+                                'xmlns:georss' => 'http://www.georss.org/georss',
+                                'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
+
+            $entry = new XMLStringer();
+            $entry->elementStart('entry', $attributes);
             $entry->element('id', null, $id);
             $entry->element('title', null, $text);
             $entry->element('summary', null, $text);
-            $entry->element('published', null, common_date_w3dtf());
+            $entry->element('published', null, common_date_w3dtf(common_sql_now()));
 
             $entry->element('activity:verb', null, $verb);
-            $entry->raw($profile->asAtomAuthor());
-            $entry->raw($profile->asActivityActor());
+            $entry->raw($actor->asAtomAuthor());
+            $entry->raw($actor->asActivityActor());
             $entry->raw($object->asActivityNoun('object'));
-            $entry->elmentEnd('entry');
+            $entry->elementEnd('entry');
+
+            $xml = $entry->getString();
+            common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
 
-            $feed = $this->atomFeed($actor);
-            $feed->initFeed();
-            $feed->addEntry($entry);
-            $feed->renderEntries();
-            $feed->endFeed();
+            $salmon = new Salmon(); // ?
+            $salmon->post($this->salmonuri, $xml);
+        }
+    }
 
-            $xml = $feed->getString();
-            common_log(LOG_INFO, "Posting to Salmon endpoint $salmon: $xml");
+    public function notifyActivity($activity)
+    {
+        if ($this->salmonuri) {
+
+            $xml = $activity->asString(true);
 
             $salmon = new Salmon(); // ?
+
             $salmon->post($this->salmonuri, $xml);
         }
+
+        return;
     }
 
     function getBestName()
@@ -568,7 +385,7 @@ class Ostatus_profile extends Memcached_DataObject
         $feed = new Atom10Feed();
         // @fixme should these be set up somewhere else?
         $feed->addNamespace('activity', 'http://activitystrea.ms/spec/1.0/');
-        $feed->addNamesapce('thr', 'http://purl.org/syndication/thread/1.0');
+        $feed->addNamespace('thr', 'http://purl.org/syndication/thread/1.0');
         $feed->addNamespace('georss', 'http://www.georss.org/georss');
         $feed->addNamespace('ostatus', 'http://ostatus.org/schema/1.0');
 
@@ -579,14 +396,14 @@ class Ostatus_profile extends Memcached_DataObject
         $feed->setUpdated(time());
         $feed->setPublished(time());
 
-        $feed->addLink(common_url('ApiTimelineUser',
-                                  array('id' => $actor->id,
-                                        'type' => 'atom')),
+        $feed->addLink(common_local_url('ApiTimelineUser',
+                                        array('id' => $actor->id,
+                                              'type' => 'atom')),
                        array('rel' => 'self',
                              'type' => 'application/atom+xml'));
 
-        $feed->addLink(common_url('userbyid',
-                                  array('id' => $actor->id)),
+        $feed->addLink(common_local_url('userbyid',
+                                        array('id' => $actor->id)),
                        array('rel' => 'alternate',
                              'type' => 'text/html'));
 
@@ -598,36 +415,10 @@ class Ostatus_profile extends Memcached_DataObject
      * Currently assumes that all items in the feed are new,
      * coming from a PuSH hub.
      *
-     * @param string $post source of Atom or RSS feed
-     * @param string $hmac X-Hub-Signature header, if present
+     * @param DOMDocument $feed
      */
-    public function postUpdates($post, $hmac)
+    public function processFeed($feed)
     {
-        common_log(LOG_INFO, __METHOD__ . ": packet for \"$this->feeduri\"! $hmac $post");
-
-        if ($this->sub_state != 'active') {
-            common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH for inactive feed $this->feeduri (in state '$this->sub_state')");
-            return;
-        }
-
-        if ($post === '') {
-            common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
-            return;
-        }
-
-        if (!$this->validatePushSig($post, $hmac)) {
-            // Per spec we silently drop input with a bad sig,
-            // while reporting receipt to the server.
-            return;
-        }
-
-        $feed = new DOMDocument();
-        if (!$feed->loadXML($post)) {
-            // @fixme might help to include the err message
-            common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
-            return;
-        }
-
         $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
         if ($entries->length == 0) {
             common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
@@ -640,40 +431,6 @@ class Ostatus_profile extends Memcached_DataObject
         }
     }
 
-    /**
-     * Validate the given Atom chunk and HMAC signature against our
-     * shared secret that was set up at subscription time.
-     *
-     * If we don't have a shared secret, there should be no signature.
-     * If we we do, our the calculated HMAC should match theirs.
-     *
-     * @param string $post raw XML source as POSTed to us
-     * @param string $hmac X-Hub-Signature HTTP header value, or empty
-     * @return boolean true for a match
-     */
-    protected function validatePushSig($post, $hmac)
-    {
-        if ($this->secret) {
-            if (preg_match('/^sha1=([0-9a-fA-F]{40})$/', $hmac, $matches)) {
-                $their_hmac = strtolower($matches[1]);
-                $our_hmac = hash_hmac('sha1', $post, $this->secret);
-                if ($their_hmac === $our_hmac) {
-                    return true;
-                }
-                common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bad SHA-1 HMAC: got $their_hmac, expected $our_hmac");
-            } else {
-                common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bogus HMAC '$hmac'");
-            }
-        } else {
-            if (empty($hmac)) {
-                return true;
-            } else {
-                common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with unexpected HMAC '$hmac'");
-            }
-        }
-        return false;
-    }
-
     /**
      * Process a posted entry from this feed source.
      *
@@ -702,41 +459,46 @@ class Ostatus_profile extends Memcached_DataObject
     {
         if ($this->isGroup()) {
             // @fixme validate these profiles in some way!
-            $oprofile = $this->ensureActorProfile($activity);
+            $oprofile = self::ensureActorProfile($activity);
         } else {
-            $actorUri = $this->getActorProfileURI($activity);
-            if ($actorUri == $this->homeuri) {
+            $actorUri = self::getActorProfileURI($activity);
+            if ($actorUri == $this->uri) {
                 // @fixme check if profile info has changed and update it
             } else {
                 // @fixme drop or reject the messages once we've got the canonical profile URI recorded sanely
-                common_log(LOG_INFO, "OStatus: Warning: non-group post with unexpected author: $actorUri expected $this->homeuri");
+                common_log(LOG_INFO, "OStatus: Warning: non-group post with unexpected author: $actorUri expected $this->uri");
                 //return;
             }
             $oprofile = $this;
         }
 
-        if ($activity->object->link) {
-            $sourceUri = $activity->object->link;
-        } else if (preg_match('!^https?://!', $activity->object->id)) {
-            $sourceUri = $activity->object->id;
-        } else {
-            common_log(LOG_INFO, "OStatus: ignoring post with no source link: id $activity->object->id");
-            return;
-        }
+        $sourceUri = $activity->object->id;
 
         $dupe = Notice::staticGet('uri', $sourceUri);
+
         if ($dupe) {
-            common_log(LOG_INFO, "OStatus: ignoring duplicate post: $noticeLink");
+            common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
             return;
         }
 
+        $sourceUrl = null;
+
+        if ($activity->object->link) {
+            $sourceUrl = $activity->object->link;
+        } else if (preg_match('!^https?://!', $activity->object->id)) {
+            $sourceUrl = $activity->object->id;
+        }
+
         // @fixme sanitize and save HTML content if available
+
         $content = $activity->object->title;
 
         $params = array('is_local' => Notice::REMOTE_OMB,
+                        'url' => $sourceUrl,
                         'uri' => $sourceUri);
 
-        $location = $this->getEntryLocation($activity->entry);
+        $location = $activity->context->location;
+
         if ($location) {
             $params['lat'] = $location->lat;
             $params['lon'] = $location->lon;
@@ -746,43 +508,125 @@ class Ostatus_profile extends Memcached_DataObject
             }
         }
 
-        // @fixme save detailed ostatus source info
         // @fixme ensure that groups get handled correctly
 
         $saved = Notice::saveNew($oprofile->localProfile()->id,
                                  $content,
                                  'ostatus',
                                  $params);
+
+        // Record which feed this came through...
+        Ostatus_source::saveNew($saved, $this, 'push');
     }
 
     /**
-     * Parse location given as a GeoRSS-simple point, if provided.
-     * http://www.georss.org/simple
-     *
-     * @param feed item $entry
-     * @return mixed Location or false
+     * @param string $profile_url
+     * @return Ostatus_profile
+     * @throws FeedSubException
      */
-    function getLocation($dom)
-    {
-        $points = $dom->getElementsByTagNameNS('http://www.georss.org/georss', 'point');
-        
-        for ($i = 0; $i < $points->length; $i++) {
-            $point = $points->item(0)->textContent;
-            $point = str_replace(',', ' ', $point); // per spec "treat commas as whitespace"
-            $point = preg_replace('/\s+/', ' ', $point);
-            $point = trim($point);
-            $coords = explode(' ', $point);
-            if (count($coords) == 2) {
-                list($lat, $lon) = $coords;
-                if (is_numeric($lat) && is_numeric($lon)) {
-                    common_log(LOG_INFO, "Looking up location for $lat $lon from georss");
-                    return Location::fromLatLon($lat, $lon);
-                }
+    public static function ensureProfile($profile_uri, $hints=array())
+    {
+        // Get the canonical feed URI and check it
+        $discover = new FeedDiscovery();
+        $feeduri = $discover->discoverFromURL($profile_uri);
+
+        //$feedsub = FeedSub::ensureFeed($feeduri, $discover->feed);
+        $huburi = $discover->getAtomLink('hub');
+        $salmonuri = $discover->getAtomLink('salmon');
+
+        if (!$huburi) {
+            // We can only deal with folks with a PuSH hub
+            throw new FeedSubNoHubException();
+        }
+
+        // Try to get a profile from the feed activity:subject
+
+        $feedEl = $discover->feed->documentElement;
+
+        $subject = ActivityUtils::child($feedEl, Activity::SUBJECT, Activity::SPEC);
+
+        if (!empty($subject)) {
+            $subjObject = new ActivityObject($subject);
+            return self::ensureActivityObjectProfile($subjObject, $feeduri, $salmonuri, $hints);
+        }
+
+        // Otherwise, try the feed author
+
+        $author = ActivityUtils::child($feedEl, Activity::AUTHOR, Activity::ATOM);
+
+        if (!empty($author)) {
+            $authorObject = new ActivityObject($author);
+            return self::ensureActivityObjectProfile($authorObject, $feeduri, $salmonuri, $hints);
+        }
+
+        // Sheesh. Not a very nice feed! Let's try fingerpoken in the
+        // entries.
+
+        $entries = $discover->feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
+
+        if (!empty($entries) && $entries->length > 0) {
+
+            $entry = $entries->item(0);
+
+            $actor = ActivityUtils::child($entry, Activity::ACTOR, Activity::SPEC);
+
+            if (!empty($actor)) {
+                $actorObject = new ActivityObject($actor);
+                return self::ensureActivityObjectProfile($actorObject, $feeduri, $salmonuri, $hints);
+
+            }
+
+            $author = ActivityUtils::child($entry, Activity::AUTHOR, Activity::ATOM);
+
+            if (!empty($author)) {
+                $authorObject = new ActivityObject($author);
+                return self::ensureActivityObjectProfile($authorObject, $feeduri, $salmonuri, $hints);
             }
-            common_log(LOG_ERR, "Ignoring bogus georss:point value $point");
         }
 
-        return false;
+        // XXX: make some educated guesses here
+
+        throw new FeedSubException("Can't find enough profile information to make a feed.");
+    }
+
+    /**
+     *
+     * Download and update given avatar image
+     * @param string $url
+     * @throws Exception in various failure cases
+     */
+    protected function updateAvatar($url)
+    {
+        // @fixme this should be better encapsulated
+        // ripped from oauthstore.php (for old OMB client)
+        $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
+        copy($url, $temp_filename);
+
+        if ($this->isGroup()) {
+            $id = $this->group_id;
+        } else {
+            $id = $this->profile_id;
+        }
+        // @fixme should we be using different ids?
+        $imagefile = new ImageFile($id, $temp_filename);
+        $filename = Avatar::filename($id,
+                                     image_type_to_extension($imagefile->type),
+                                     null,
+                                     common_timestamp());
+        rename($temp_filename, Avatar::path($filename));
+        if ($this->isGroup()) {
+            $group = $this->localGroup();
+            $group->setOriginal($filename);
+        } else {
+            $profile = $this->localProfile();
+            $profile->setOriginal($filename);
+        }
+    }
+
+    protected static function getActivityObjectAvatar($object)
+    {
+        // XXX: go poke around in the feed
+        return $object->avatar;
     }
 
     /**
@@ -792,7 +636,8 @@ class Ostatus_profile extends Memcached_DataObject
      * @param DOMElement $feed
      * @return string
      */
-    function getAvatar($actor, $feed)
+
+    protected static function getAvatar($actor, $feed)
     {
         $url = '';
         $icon = '';
@@ -831,13 +676,25 @@ class Ostatus_profile extends Memcached_DataObject
     }
 
     /**
-     * @fixme move off of ostatus_profile or static?
+     * Fetch, or build if necessary, an Ostatus_profile for the actor
+     * in a given Activity Streams activity.
+     *
+     * @param Activity $activity
+     * @param string $feeduri if we already know the canonical feed URI!
+     * @param string $salmonuri if we already know the salmon return channel URI
+     * @return Ostatus_profile
      */
-    function ensureActorProfile($activity)
+
+    public static function ensureActorProfile($activity, $feeduri=null, $salmonuri=null)
     {
-        $profile = $this->getActorProfile($activity);
+        return self::ensureActivityObjectProfile($activity->actor, $feeduri, $salmonuri);
+    }
+
+    public static function ensureActivityObjectProfile($object, $feeduri=null, $salmonuri=null, $hints=array())
+    {
+        $profile = self::getActivityObjectProfile($object);
         if (!$profile) {
-            $profile = $this->createActorProfile($activity);
+            $profile = self::createActivityObjectProfile($object, $feeduri, $salmonuri, $hints);
         }
         return $profile;
     }
@@ -846,10 +703,20 @@ class Ostatus_profile extends Memcached_DataObject
      * @param Activity $activity
      * @return mixed matching Ostatus_profile or false if none known
      */
-    function getActorProfile($activity)
+    protected static function getActorProfile($activity)
     {
-        $homeuri = $this->getActorProfileURI($activity);
-        return Ostatus_profile::staticGet('homeuri', $homeuri);
+        return self::getActivityObjectProfile($activity->actor);
+    }
+
+    protected static function getActivityObjectProfile($object)
+    {
+        $uri = self::getActivityObjectProfileURI($object);
+        return Ostatus_profile::staticGet('uri', $uri);
+    }
+
+    protected static function getActorProfileURI($activity)
+    {
+        return self::getActivityObjectProfileURI($activity->actor);
     }
 
     /**
@@ -857,80 +724,273 @@ class Ostatus_profile extends Memcached_DataObject
      * @return string
      * @throws ServerException
      */
-    function getActorProfileURI($activity)
+    protected static function getActivityObjectProfileURI($object)
     {
         $opts = array('allowed_schemes' => array('http', 'https'));
-        $actor = $activity->actor;
-        if ($actor->id && Validate::uri($actor->id, $opts)) {
-            return $actor->id;
+        if ($object->id && Validate::uri($object->id, $opts)) {
+            return $object->id;
         }
-        if ($actor->link && Validate::uri($actor->link, $opts)) {
-            return $actor->link;
+        if ($object->link && Validate::uri($object->link, $opts)) {
+            return $object->link;
         }
         throw new ServerException("No author ID URI found");
     }
 
     /**
-     *
+     * @fixme validate stuff somewhere
      */
-    function createActorProfile($activity)
+
+    protected static function createActorProfile($activity, $feeduri=null, $salmonuri=null)
     {
-        $actor = $activity->actor();
-        $homeuri = $this->getActivityProfileURI($activity);
-        $nickname = $this->getAuthorNick($activity);
-        $avatar = $this->getAvatar($actor, $feed);
+        $actor = $activity->actor;
+
+        self::createActivityObjectProfile($actor, $feeduri, $salmonuri);
+    }
+
+    protected static function createActivityObjectProfile($object, $feeduri=null, $salmonuri=null, $hints=array())
+    {
+        $homeuri  = $object->id;
+        $nickname = self::getActivityObjectNickname($object, $hints);
+        $avatar   = self::getActivityObjectAvatar($object);
+
+        if (!$homeuri) {
+            common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
+            throw new ServerException("No profile URI");
+        }
+
+        if (empty($feeduri)) {
+            if (array_key_exists('feedurl', $hints)) {
+                $feeduri = $hints['feedurl'];
+            }
+        }
+
+        if (empty($salmonuri)) {
+            if (array_key_exists('salmon', $hints)) {
+                $salmonuri = $hints['salmon'];
+            }
+        }
+
+        if (!$feeduri || !$salmonuri) {
+            // Get the canonical feed URI and check it
+            $discover = new FeedDiscovery();
+            $feeduri = $discover->discoverFromURL($homeuri);
+
+            $huburi = $discover->getAtomLink('hub');
+            $salmonuri = $discover->getAtomLink('salmon');
+
+            if (!$huburi) {
+                // We can only deal with folks with a PuSH hub
+                throw new FeedSubNoHubException();
+            }
+        }
 
         $profile = new Profile();
         $profile->nickname   = $nickname;
-        $profile->fullname   = $actor->displayName;
-        $profile->homepage   = $actor->link; // @fixme
-        $profile->profileurl = $homeuri;
+        $profile->fullname   = $object->title;
+        if (!empty($object->link)) {
+            $profile->profileurl = $object->link;
+        } else if (array_key_exists('profileurl', $hints)) {
+            $profile->profileurl = $hints['profileurl'];
+        }
+        $profile->created    = common_sql_now();
+
         // @fixme bio
         // @fixme tags/categories
         // @fixme location?
         // @todo tags from categories
         // @todo lat/lon/location?
 
-        $ok = $profile->insert();
-        if ($ok) {
-            $this->updateAvatar($profile, $avatar);
-        } else {
+        $profile_id = $profile->insert();
+
+        if (!$profile_id) {
             throw new ServerException("Can't save local profile");
         }
 
         // @fixme either need to do feed discovery here
         // or need to split out some of the feed stuff
         // so we can leave it empty until later.
+
         $oprofile = new Ostatus_profile();
-        $oprofile->homeuri = $homeuri;
-        $oprofile->profile_id = $profile->id;
+
+        $oprofile->uri        = $homeuri;
+        $oprofile->feeduri    = $feeduri;
+        $oprofile->salmonuri  = $salmonuri;
+        $oprofile->profile_id = $profile_id;
+
+        $oprofile->created    = common_sql_now();
+        $oprofile->modified   = common_sql_now();
 
         $ok = $oprofile->insert();
+
         if ($ok) {
+            $oprofile->updateAvatar($avatar);
             return $oprofile;
         } else {
             throw new ServerException("Can't save OStatus profile");
         }
     }
 
-    /**
-     * @fixme move this into Activity?
-     * @param Activity $activity
-     * @return string
-     */
-    function getAuthorNick($activity)
-    {
-        // @fixme not technically part of the actor?
-        foreach (array($activity->entry, $activity->feed) as $source) {
-            $author = ActivityUtil::child($source, 'author', Activity::ATOM);
-            if ($author) {
-                $name = ActivityUtil::child($author, 'name', Activity::ATOM);
-                if ($name) {
-                    return trim($name->textContent);
-                }
+    protected static function getActivityObjectNickname($object, $hints=array())
+    {
+        if (!empty($object->nickname)) {
+            return common_nicknamize($object->nickname);
+        }
+
+        // Try the definitive ID
+
+        $nickname = self::nicknameFromURI($object->id);
+
+        // Try a Webfinger if one was passed (way) down
+
+        if (empty($nickname)) {
+            if (array_key_exists('webfinger', $hints)) {
+                $nickname = self::nicknameFromURI($hints['webfinger']);
             }
         }
-        return false;
+
+        // Try the name
+
+        if (empty($nickname)) {
+            $nickname = common_nicknamize($object->title);
+        }
+
+        return $nickname;
+    }
+
+    protected static function nicknameFromURI($uri)
+    {
+        preg_match('/(\w+):/', $uri, $matches);
+
+        $protocol = $matches[1];
+
+        switch ($protocol) {
+        case 'acct':
+        case 'mailto':
+            if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
+                return common_canonical_nickname($matches[1]);
+            }
+            return null;
+        case 'http':
+            return common_url_to_nickname($uri);
+            break;
+        default:
+            return null;
+        }
     }
 
+    public static function ensureWebfinger($addr)
+    {
+        // First, look it up
+
+        $oprofile = Ostatus_profile::staticGet('uri', 'acct:'.$addr);
+
+        if (!empty($oprofile)) {
+            return $oprofile;
+        }
+
+        // Now, try some discovery
+
+        $wf = new Webfinger();
+
+        $result = $wf->lookup($addr);
+
+        if (!$result) {
+            return null;
+        }
+
+        foreach ($result->links as $link) {
+            switch ($link['rel']) {
+            case Webfinger::PROFILEPAGE:
+                $profileUrl = $link['href'];
+                break;
+            case 'salmon':
+                $salmonEndpoint = $link['href'];
+                break;
+            case Webfinger::UPDATESFROM:
+                $feedUrl = $link['href'];
+                break;
+            default:
+                common_log(LOG_NOTICE, "Don't know what to do with rel = '{$link['rel']}'");
+                break;
+            }
+        }
+
+        $hints = array('webfinger' => $addr,
+                       'profileurl' => $profileUrl,
+                       'feedurl' => $feedUrl,
+                       'salmon' => $salmonEndpoint);
+
+        // If we got a feed URL, try that
+
+        if (isset($feedUrl)) {
+            try {
+                $oprofile = self::ensureProfile($feedUrl, $hints);
+                return $oprofile;
+            } catch (Exception $e) {
+                common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
+                // keep looking
+            }
+        }
+
+        // If we got a profile page, try that!
+
+        if (isset($profileUrl)) {
+            try {
+                $oprofile = self::ensureProfile($profileUrl, $hints);
+                return $oprofile;
+            } catch (Exception $e) {
+                common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
+                // keep looking
+            }
+        }
+
+        // XXX: try hcard
+        // XXX: try FOAF
+
+        if (isset($salmonEndpoint)) {
+
+            // An account URL, a salmon endpoint, and a dream? Not much to go
+            // on, but let's give it a try
+
+            $uri = 'acct:'.$addr;
+
+            $profile = new Profile();
+
+            $profile->nickname = self::nicknameFromUri($uri);
+            $profile->created  = common_sql_now();
+
+            if (isset($profileUrl)) {
+                $profile->profileurl = $profileUrl;
+            }
+
+            $profile_id = $profile->insert();
+
+            if (!$profile_id) {
+                common_log_db_error($profile, 'INSERT', __FILE__);
+                throw new Exception("Couldn't save profile for '$addr'");
+            }
+
+            $oprofile = new Ostatus_profile();
+
+            $oprofile->uri        = $uri;
+            $oprofile->salmonuri  = $salmonEndpoint;
+            $oprofile->profile_id = $profile_id;
+            $oprofile->created    = common_sql_now();
+
+            if (isset($feedUrl)) {
+                $profile->feeduri = $feedUrl;
+            }
+
+            $result = $oprofile->insert();
+
+            if (!$result) {
+                common_log_db_error($oprofile, 'INSERT', __FILE__);
+                throw new Exception("Couldn't save ostatus_profile for '$addr'");
+            }
+
+            return $oprofile;
+        }
+
+        return null;
+    }
 }