]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitterstreamreader.php
Escape argument to prevent SQL injection attack in
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitterstreamreader.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * PHP version 5
6  *
7  * LICENCE: This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  * @category  Plugin
21  * @package   StatusNet
22  * @author    Brion Vibber <brion@status.net>
23  * @copyright 2010 StatusNet, Inc.
24  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
25  * @link      http://status.net/
26  */
27
28 /**
29  * Base class for reading Twitter's User Streams and Site Streams
30  * real-time streaming APIs.
31  *
32  * Caller can hook event callbacks for various types of messages;
33  * the data from the stream and some context info will be passed
34  * on to the callbacks.
35  */
36 abstract class TwitterStreamReader extends JsonStreamReader
37 {
38     protected $callbacks = array();
39
40     function __construct(TwitterOAuthClient $auth, $baseUrl)
41     {
42         $this->baseUrl = $baseUrl;
43         $this->oauth = $auth;
44     }
45
46     public function connect($method, $params=array())
47     {
48         $url = $this->oAuthUrl($this->baseUrl . '/' . $method, $params);
49         return parent::connect($url);
50     }
51
52     /**
53      * Sign our target URL with OAuth auth stuff.
54      *
55      * @param string $url
56      * @param array $params
57      * @return string
58      */
59     protected function oAuthUrl($url, $params=array())
60     {
61         // In an ideal world this would be better encapsulated. :)
62         $request = OAuthRequest::from_consumer_and_token($this->oauth->consumer,
63             $this->oauth->token, 'GET', $url, $params);
64         $request->sign_request($this->oauth->sha1_method,
65             $this->oauth->consumer, $this->oauth->token);
66
67         return $request->to_url();
68     }
69
70     /**
71      * Add an event callback to receive notifications when things come in
72      * over the wire.
73      *
74      * Callbacks should be in the form: function(object $data, array $context)
75      * where $context may list additional data on some streams, such as the
76      * user to whom the message should be routed.
77      *
78      * Available events:
79      *
80      * Messaging:
81      *
82      * 'status': $data contains a status update in standard Twitter JSON format.
83      *      $data->user: sending user in standard Twitter JSON format.
84      *      $data->text... etc
85      *
86      * 'direct_message': $data contains a direct message in standard Twitter JSON format.
87      *      $data->sender: sending user in standard Twitter JSON format.
88      *      $data->recipient: receiving user in standard Twitter JSON format.
89      *      $data->text... etc
90      *
91      *
92      * Out of band events:
93      *
94      * 'follow': User has either started following someone, or is being followed.
95      *      $data->source: following user in standard Twitter JSON format.
96      *      $data->target: followed user in standard Twitter JSON format.
97      *
98      * 'favorite': Someone has favorited a status update.
99      *      $data->source: user doing the favoriting, in standard Twitter JSON format.
100      *      $data->target: user whose status was favorited, in standard Twitter JSON format.
101      *      $data->target_object: the favorited status update in standard Twitter JSON format.
102      *
103      * 'unfavorite': Someone has unfavorited a status update.
104      *      $data->source: user doing the unfavoriting, in standard Twitter JSON format.
105      *      $data->target: user whose status was unfavorited, in standard Twitter JSON format.
106      *      $data->target_object: the unfavorited status update in standard Twitter JSON format.
107      *
108      *
109      * Meta information:
110      *
111      * 'friends':
112      *      $data->friends: array of user IDs of the current user's friends.
113      *
114      * 'delete': Advisory that a Twitter status has been deleted; nice clients
115      *           should follow suit.
116      *      $data->id: ID of status being deleted
117      *      $data->user_id: ID of its owning user
118      *
119      * 'scrub_geo': Advisory that a user is clearing geo data from their status
120      *              stream; nice clients should follow suit.
121      *      $data->user_id: ID of user
122      *      $data->up_to_status_id: any notice older than this should be scrubbed.
123      *
124      * 'limit': Advisory that tracking has hit a resource limit.
125      *      $data->track
126      *
127      * 'raw': receives the full JSON data for all message types.
128      *
129      * @param string $event
130      * @param callable $callback
131      */
132     public function hookEvent($event, $callback)
133     {
134         $this->callbacks[$event][] = $callback;
135     }
136
137     /**
138      * Call event handler callbacks for the given event.
139      *
140      * @param string $event
141      * @param mixed $arg1 ... one or more params to pass on
142      */
143     protected function fireEvent($event, $arg1)
144     {
145         if (array_key_exists($event, $this->callbacks)) {
146             $args = array_slice(func_get_args(), 1);
147             foreach ($this->callbacks[$event] as $callback) {
148                 call_user_func_array($callback, $args);
149             }
150         }
151     }
152
153     protected function handleJson(stdClass $data)
154     {
155         $this->routeMessage($data);
156     }
157
158     abstract protected function routeMessage(stdClass $data);
159
160     /**
161      * Send the decoded JSON object out to any event listeners.
162      *
163      * @param array $data
164      * @param array $context optional additional context data to pass on
165      */
166     protected function handleMessage(stdClass $data, array $context=array())
167     {
168         $this->fireEvent('raw', $data, $context);
169
170         if (isset($data->text)) {
171             $this->fireEvent('status', $data, $context);
172             return;
173         }
174         if (isset($data->event)) {
175             $this->fireEvent($data->event, $data, $context);
176             return;
177         }
178         if (isset($data->friends)) {
179             $this->fireEvent('friends', $data, $context);
180         }
181
182         $knownMeta = array('delete', 'scrub_geo', 'limit', 'direct_message');
183         foreach ($knownMeta as $key) {
184             if (isset($data->$key)) {
185                 $this->fireEvent($key, $data->$key, $context);
186                 return;
187             }
188         }
189     }
190 }
191
192 /**
193  * Multiuser stream listener for Twitter Site Streams API
194  * http://dev.twitter.com/pages/site_streams
195  *
196  * The site streams API allows listening to updates for multiple users.
197  * Pass in the user IDs to listen to in via followUser() -- note they
198  * must each have a valid OAuth token for the application ID we're
199  * connecting as.
200  *
201  * You'll need to be connecting with the auth keys for the user who
202  * owns the application registration.
203  *
204  * The user each message is destined for will be passed to event handlers
205  * in $context['for_user_id'].
206  */
207 class TwitterSiteStream extends TwitterStreamReader
208 {
209     protected $userIds;
210
211     public function __construct(TwitterOAuthClient $auth, $baseUrl='http://betastream.twitter.com')
212     {
213         parent::__construct($auth, $baseUrl);
214     }
215
216     public function connect($method='2b/site.json')
217     {
218         $params = array();
219         if ($this->userIds) {
220             $params['follow'] = implode(',', $this->userIds);
221         }
222         return parent::connect($method, $params);
223     }
224
225     /**
226      * Set the users whose home streams should be pulled.
227      * They all must have valid oauth tokens for this application.
228      *
229      * Must be called before connect().
230      *
231      * @param array $userIds
232      */
233     function followUsers($userIds)
234     {
235         $this->userIds = $userIds;
236     }
237
238     /**
239      * Each message in the site stream tells us which user ID it should be
240      * routed to; we'll need that to let the caller know what to do.
241      *
242      * @param array $data
243      */
244     function routeMessage(stdClass $data)
245     {
246         $context = array(
247             'source' => 'sitestream',
248             'for_user' => $data->for_user
249         );
250         parent::handleMessage($data->message, $context);
251     }
252 }
253
254 /**
255  * Stream listener for Twitter User Streams API
256  * http://dev.twitter.com/pages/user_streams
257  *
258  * This will pull the home stream and additional events just for the user
259  * we've authenticated as.
260  */
261 class TwitterUserStream extends TwitterStreamReader
262 {
263     public function __construct(TwitterOAuthClient $auth, $baseUrl='https://userstream.twitter.com')
264     {
265         parent::__construct($auth, $baseUrl);
266     }
267
268     public function connect($method='2/user.json')
269     {
270         return parent::connect($method);
271     }
272
273     /**
274      * Each message in the user stream is just ready to go.
275      *
276      * @param array $data
277      */
278     function routeMessage(stdClass $data)
279     {
280         $context = array(
281             'source' => 'userstream'
282         );
283         parent::handleMessage($data, $context);
284     }
285 }