]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/HubSub.php
6388f8e87335fe98139096cc0491383b162d1384
[quix0rs-gnu-social.git] / plugins / OStatus / classes / HubSub.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET')) {
21     exit(1);
22 }
23
24 /**
25  * PuSH feed subscription record
26  * @package Hub
27  * @author Brion Vibber <brion@status.net>
28  */
29 class HubSub extends Managed_DataObject
30 {
31     public $__table = 'hubsub';
32
33     public $hashkey; // sha1(topic . '|' . $callback); (topic, callback) key is too long for myisam in utf8
34     public $topic;      // varchar(191)   not 255 because utf8mb4 takes more space
35     public $callback;   // varchar(191)   not 255 because utf8mb4 takes more space
36     public $secret;
37     public $lease;
38     public $sub_start;
39     public $sub_end;
40     public $created;
41     public $modified;
42
43     protected static function hashkey($topic, $callback)
44     {
45         return sha1($topic . '|' . $callback);
46     }
47
48     public static function getByHashkey($topic, $callback)
49     {
50         return self::getKV('hashkey', self::hashkey($topic, $callback));
51     }
52
53     public static function schemaDef()
54     {
55         return array(
56             'fields' => array(
57                 'hashkey' => array('type' => 'char', 'not null' => true, 'length' => 40, 'description' => 'HubSub hashkey'),
58                 'topic' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub topic'),
59                 'callback' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub callback'),
60                 'secret' => array('type' => 'text', 'description' => 'HubSub stored secret'),
61                 'lease' => array('type' => 'int', 'description' => 'HubSub leasetime'),
62                 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
63                 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
64                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
65                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
66             ),
67             'primary key' => array('hashkey'),
68             'indexes' => array(
69                 'hubsub_topic_idx' => array('topic'),
70             ),
71         );
72     }
73
74     /**
75      * Validates a requested lease length, sets length plus
76      * subscription start & end dates.
77      *
78      * Does not save to database -- use before insert() or update().
79      *
80      * @param int $length in seconds
81      */
82     function setLease($length)
83     {
84         assert(is_int($length));
85
86         $min = 86400;
87         $max = 86400 * 30;
88
89         if ($length == 0) {
90             // We want to garbage collect dead subscriptions!
91             $length = $max;
92         } elseif( $length < $min) {
93             $length = $min;
94         } else if ($length > $max) {
95             $length = $max;
96         }
97
98         $this->lease = $length;
99         $this->start_sub = common_sql_now();
100         $this->end_sub = common_sql_date(time() + $length);
101     }
102
103     /**
104      * Schedule a future verification ping to the subscriber.
105      * If queues are disabled, will be immediate.
106      *
107      * @param string $mode 'subscribe' or 'unsubscribe'
108      * @param string $token hub.verify_token value, if provided by client
109      */
110     function scheduleVerify($mode, $token=null, $retries=null)
111     {
112         if ($retries === null) {
113             $retries = intval(common_config('ostatus', 'hub_retries'));
114         }
115         $data = array('sub' => clone($this),
116                       'mode' => $mode,
117                       'token' => $token,    // let's put it in there if remote uses PuSH <0.4
118                       'retries' => $retries);
119         $qm = QueueManager::get();
120         $qm->enqueue($data, 'hubconf');
121     }
122
123     /**
124      * Send a verification ping to subscriber, and if confirmed apply the changes.
125      * This may create, update, or delete the database record.
126      *
127      * @param string $mode 'subscribe' or 'unsubscribe'
128      * @param string $token hub.verify_token value, if provided by client
129      * @throws ClientException on failure
130      */
131     function verify($mode, $token=null)
132     {
133         assert($mode == 'subscribe' || $mode == 'unsubscribe');
134
135         $challenge = common_random_hexstr(32);
136         $params = array('hub.mode' => $mode,
137                         'hub.topic' => $this->topic,
138                         'hub.challenge' => $challenge);
139         if ($mode == 'subscribe') {
140             $params['hub.lease_seconds'] = $this->lease;
141         }
142         if ($token !== null) {  // TODO: deprecated in PuSH 0.4
143             $params['hub.verify_token'] = $token;   // let's put it in there if remote uses PuSH <0.4
144         }
145
146         // Any existing query string parameters must be preserved
147         $url = $this->callback;
148         if (strpos($url, '?') !== false) {
149             $url .= '&';
150         } else {
151             $url .= '?';
152         }
153         $url .= http_build_query($params, '', '&');
154
155         $request = new HTTPClient();
156         $response = $request->get($url);
157         $status = $response->getStatus();
158
159         if ($status >= 200 && $status < 300) {
160             common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->topic}");
161         } else {
162             // TRANS: Client exception. %s is a HTTP status code.
163             throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
164         }
165
166         $old = HubSub::getByHashkey($this->topic, $this->callback);
167         if ($mode == 'subscribe') {
168             if ($old instanceof HubSub) {
169                 $this->update($old);
170             } else {
171                 $ok = $this->insert();
172             }
173         } else if ($mode == 'unsubscribe') {
174             if ($old instanceof HubSub) {
175                 $old->delete();
176             } else {
177                 // That's ok, we're already unsubscribed.
178             }
179         }
180     }
181
182     /**
183      * Insert wrapper; transparently set the hash key from topic and callback columns.
184      * @return mixed success
185      */
186     function insert()
187     {
188         $this->hashkey = self::hashkey($this->topic, $this->callback);
189         $this->created = common_sql_now();
190         $this->modified = common_sql_now();
191         return parent::insert();
192     }
193
194     /**
195      * Schedule delivery of a 'fat ping' to the subscriber's callback
196      * endpoint. If queues are disabled, this will run immediately.
197      *
198      * @param string $atom well-formed Atom feed
199      * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
200      */
201     function distribute($atom, $retries=null)
202     {
203         if ($retries === null) {
204             $retries = intval(common_config('ostatus', 'hub_retries'));
205         }
206
207         // We dare not clone() as when the clone is discarded it'll
208         // destroy the result data for the parent query.
209         // @fixme use clone() again when it's safe to copy an
210         // individual item from a multi-item query again.
211         $sub = HubSub::getByHashkey($this->topic, $this->callback);
212         $data = array('sub' => $sub,
213                       'atom' => $atom,
214                       'retries' => $retries);
215         common_log(LOG_INFO, "Queuing PuSH: $this->topic to $this->callback");
216         $qm = QueueManager::get();
217         $qm->enqueue($data, 'hubout');
218     }
219
220     /**
221      * Queue up a large batch of pushes to multiple subscribers
222      * for this same topic update.
223      *
224      * If queues are disabled, this will run immediately.
225      *
226      * @param string $atom well-formed Atom feed
227      * @param array $pushCallbacks list of callback URLs
228      */
229     function bulkDistribute($atom, $pushCallbacks)
230     {
231         if (empty($pushCallbacks)) {
232             common_log(LOG_ERR, 'Callback list empty for bulkDistribute.');
233             return false;
234         }
235         $data = array('atom' => $atom,
236                       'topic' => $this->topic,
237                       'pushCallbacks' => $pushCallbacks);
238         common_log(LOG_INFO, "Queuing PuSH batch: $this->topic to " .
239                              count($pushCallbacks) . " sites");
240         $qm = QueueManager::get();
241         $qm->enqueue($data, 'hubprep');
242         return true;
243     }
244
245     /**
246      * Send a 'fat ping' to the subscriber's callback endpoint
247      * containing the given Atom feed chunk.
248      *
249      * Determination of which items to send should be done at
250      * a higher level; don't just shove in a complete feed!
251      *
252      * @param string $atom well-formed Atom feed
253      * @throws Exception (HTTP or general)
254      */
255     function push($atom)
256     {
257         $headers = array('Content-Type: application/atom+xml');
258         if ($this->secret) {
259             $hmac = hash_hmac('sha1', $atom, $this->secret);
260             $headers[] = "X-Hub-Signature: sha1=$hmac";
261         } else {
262             $hmac = '(none)';
263         }
264         common_log(LOG_INFO, "About to push feed to $this->callback for $this->topic, HMAC $hmac");
265
266         $request = new HTTPClient();
267         $request->setBody($atom);
268         $response = $request->post($this->callback, $headers);
269
270         if ($response->isOk()) {
271             return true;
272         } else {
273             // TRANS: Exception. %1$s is a response status code, %2$s is the body of the response.
274             throw new Exception(sprintf(_m('Callback returned status: %1$s. Body: %2$s'),
275                                 $response->getStatus(),trim($response->getBody())));
276         }
277     }
278 }