]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/HubSub.php
Merge branch 'testing' of gitorious.org:statusnet/mainline into 0.9.x
[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 /**
21  * PuSH feed subscription record
22  * @package Hub
23  * @author Brion Vibber <brion@status.net>
24  */
25 class HubSub extends Memcached_DataObject
26 {
27     public $__table = 'hubsub';
28
29     public $hashkey; // sha1(topic . '|' . $callback); (topic, callback) key is too long for myisam in utf8
30     public $topic;
31     public $callback;
32     public $secret;
33     public $verify_token;
34     public $challenge;
35     public $lease;
36     public $sub_start;
37     public $sub_end;
38     public $created;
39
40     public /*static*/ function staticGet($topic, $callback)
41     {
42         return parent::staticGet(__CLASS__, 'hashkey', self::hashkey($topic, $callback));
43     }
44
45     protected static function hashkey($topic, $callback)
46     {
47         return sha1($topic . '|' . $callback);
48     }
49
50     /**
51      * return table definition for DB_DataObject
52      *
53      * DB_DataObject needs to know something about the table to manipulate
54      * instances. This method provides all the DB_DataObject needs to know.
55      *
56      * @return array array of column definitions
57      */
58
59     function table()
60     {
61         return array('hashkey' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
62                      'topic' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
63                      'callback' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
64                      'secret' => DB_DATAOBJECT_STR,
65                      'verify_token' => DB_DATAOBJECT_STR,
66                      'challenge' => DB_DATAOBJECT_STR,
67                      'lease' =>  DB_DATAOBJECT_INT,
68                      'sub_start' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
69                      'sub_end' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
70                      'created' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL);
71     }
72
73     static function schemaDef()
74     {
75         return array(new ColumnDef('hashkey', 'char',
76                                    /*size*/40,
77                                    /*nullable*/false,
78                                    /*key*/'PRI'),
79                      new ColumnDef('topic', 'varchar',
80                                    /*size*/255,
81                                    /*nullable*/false,
82                                    /*key*/'KEY'),
83                      new ColumnDef('callback', 'varchar',
84                                    255, false),
85                      new ColumnDef('secret', 'text',
86                                    null, true),
87                      new ColumnDef('verify_token', 'text',
88                                    null, true),
89                      new ColumnDef('challenge', 'varchar',
90                                    32, true),
91                      new ColumnDef('lease', 'int',
92                                    null, true),
93                      new ColumnDef('sub_start', 'datetime',
94                                    null, true),
95                      new ColumnDef('sub_end', 'datetime',
96                                    null, true),
97                      new ColumnDef('created', 'datetime',
98                                    null, false));
99     }
100
101     function keys()
102     {
103         return array_keys($this->keyTypes());
104     }
105
106     function sequenceKeys()
107     {
108         return array(false, false, false);
109     }
110
111     /**
112      * return key definitions for DB_DataObject
113      *
114      * DB_DataObject needs to know about keys that the table has; this function
115      * defines them.
116      *
117      * @return array key definitions
118      */
119
120     function keyTypes()
121     {
122         return array('hashkey' => 'K');
123     }
124
125     /**
126      * Validates a requested lease length, sets length plus
127      * subscription start & end dates.
128      *
129      * Does not save to database -- use before insert() or update().
130      *
131      * @param int $length in seconds
132      */
133     function setLease($length)
134     {
135         assert(is_int($length));
136
137         $min = 86400;
138         $max = 86400 * 30;
139
140         if ($length == 0) {
141             // We want to garbage collect dead subscriptions!
142             $length = $max;
143         } elseif( $length < $min) {
144             $length = $min;
145         } else if ($length > $max) {
146             $length = $max;
147         }
148
149         $this->lease = $length;
150         $this->start_sub = common_sql_now();
151         $this->end_sub = common_sql_date(time() + $length);
152     }
153
154     /**
155      * Send a verification ping to subscriber
156      * @param string $mode 'subscribe' or 'unsubscribe'
157      */
158     function verify($mode)
159     {
160         assert($mode == 'subscribe' || $mode == 'unsubscribe');
161
162         // Is this needed? data object fun...
163         $clone = clone($this);
164         $clone->challenge = common_good_rand(16);
165         $clone->update($this);
166         $this->challenge = $clone->challenge;
167         unset($clone);
168
169         $params = array('hub.mode' => $mode,
170                         'hub.topic' => $this->topic,
171                         'hub.challenge' => $this->challenge);
172         if ($mode == 'subscribe') {
173             $params['hub.lease_seconds'] = $this->lease;
174         }
175         if ($this->verify_token) {
176             $params['hub.verify_token'] = $this->verify_token;
177         }
178         $url = $this->callback . '?' . http_build_query($params, '', '&'); // @fixme ugly urls
179
180         try {
181             $request = new HTTPClient();
182             $response = $request->get($url);
183             $status = $response->getStatus();
184
185             if ($status >= 200 && $status < 300) {
186                 $fail = false;
187             } else {
188                 // @fixme how can we schedule a second attempt?
189                 // Or should we?
190                 $fail = "Returned HTTP $status";
191             }
192         } catch (Exception $e) {
193             $fail = $e->getMessage();
194         }
195         if ($fail) {
196             // @fixme how can we schedule a second attempt?
197             // or save a fail count?
198             // Or should we?
199             common_log(LOG_ERR, "Failed to verify $mode for $this->topic at $this->callback: $fail");
200             return false;
201         } else {
202             if ($mode == 'subscribe') {
203                 // Establish or renew the subscription!
204                 // This seems unnecessary... dataobject fun!
205                 $clone = clone($this);
206                 $clone->challenge = null;
207                 $clone->setLease($this->lease);
208                 $clone->update($this);
209                 unset($clone);
210
211                 $this->challenge = null;
212                 $this->setLease($this->lease);
213                 common_log(LOG_ERR, "Verified $mode of $this->callback:$this->topic for $this->lease seconds");
214             } else if ($mode == 'unsubscribe') {
215                 common_log(LOG_ERR, "Verified $mode of $this->callback:$this->topic");
216                 $this->delete();
217             }
218             return true;
219         }
220     }
221
222     /**
223      * Insert wrapper; transparently set the hash key from topic and callback columns.
224      * @return boolean success
225      */
226     function insert()
227     {
228         $this->hashkey = self::hashkey($this->topic, $this->callback);
229         return parent::insert();
230     }
231
232     /**
233      * Send a 'fat ping' to the subscriber's callback endpoint
234      * containing the given Atom feed chunk.
235      *
236      * Determination of which items to send should be done at
237      * a higher level; don't just shove in a complete feed!
238      *
239      * @param string $atom well-formed Atom feed
240      */
241     function push($atom)
242     {
243         $headers = array('Content-Type: application/atom+xml');
244         if ($this->secret) {
245             $hmac = hash_hmac('sha1', $atom, $this->secret);
246             $headers[] = "X-Hub-Signature: sha1=$hmac";
247         } else {
248             $hmac = '(none)';
249         }
250         common_log(LOG_INFO, "About to push feed to $this->callback for $this->topic, HMAC $hmac");
251         try {
252             $request = new HTTPClient();
253             $request->setBody($atom);
254             $response = $request->post($this->callback, $headers);
255
256             if ($response->isOk()) {
257                 return true;
258             }
259             common_log(LOG_ERR, "Error sending PuSH content " .
260                                 "to $this->callback for $this->topic: " .
261                                 $response->getStatus());
262             return false;
263
264         } catch (Exception $e) {
265             common_log(LOG_ERR, "Error sending PuSH content " .
266                                 "to $this->callback for $this->topic: " .
267                                 $e->getMessage());
268             return false;
269         }
270     }
271 }
272