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