]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
pumpio: Preparing mirroring
[friendica-addons.git] / pumpio / pumpio.php
1 <?php
2 /**
3  * Name: pump.io Post Connector
4  * Description: Post to pump.io
5  * Version: 0.1
6  * Author: Michael Vogel <http://pirati.ca/profile/heluecht>
7  */
8
9 //require_once('library/OAuth1.php');
10 //require_once('addon/pumpio/pumpiooauth/pumpiooauth.php');
11
12 require('addon/pumpio/oauth/http.php');
13 require('addon/pumpio/oauth/oauth_client.php');
14
15 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
16
17 function pumpio_install() {
18     register_hook('post_local',           'addon/pumpio/pumpio.php', 'pumpio_post_local');
19     register_hook('notifier_normal',      'addon/pumpio/pumpio.php', 'pumpio_send');
20     register_hook('jot_networks',         'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
21     register_hook('connector_settings',      'addon/pumpio/pumpio.php', 'pumpio_settings');
22     register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
23     register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
24
25 }
26 function pumpio_uninstall() {
27     unregister_hook('post_local',       'addon/pumpio/pumpio.php', 'pumpio_post_local');
28     unregister_hook('notifier_normal',  'addon/pumpio/pumpio.php', 'pumpio_send');
29     unregister_hook('jot_networks',     'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
30     unregister_hook('connector_settings',      'addon/pumpio/pumpio.php', 'pumpio_settings');
31     unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
32     unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
33 }
34
35 function pumpio_module() {}
36
37 function pumpio_content(&$a) {
38
39         if(! local_user()) {
40                 notice( t('Permission denied.') . EOL);
41                 return '';
42         }
43
44         if (isset($a->argv[1]))
45                 switch ($a->argv[1]) {
46                         case "connect":
47                                 $o = pumpio_connect($a);
48                                 break;
49                         default:
50                                 $o = print_r($a->argv, true);
51                                 break;
52                 }
53         else
54                 $o = pumpio_connect($a);
55
56         return $o;
57 }
58
59 function pumpio_registerclient($a, $host) {
60
61         $url = "https://".$host."/api/client/register";
62
63         $params = array();
64
65         $application_name  = get_config('pumpio', 'application_name');
66
67         if ($application_name == "")
68                 $application_name = $a->get_hostname();
69
70
71         $params["type"] = "client_associate";
72         //$params["contacts"] = "icarus@dabo.de";
73         $params["application_type"] = "native";
74         $params["application_name"] = $application_name;
75         //$params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
76         //$params["redirect_uris"] = $a->get_baseurl()."a/addon/pumpio/pumpio.php";
77
78         $ch = curl_init($url);
79         curl_setopt($ch, CURLOPT_HEADER, false);
80         curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
81         curl_setopt($ch, CURLOPT_POST,1);
82         curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
83         curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
84
85         $s = curl_exec($ch);
86         $curl_info = curl_getinfo($ch);
87
88         if ($curl_info["http_code"] == "200") {
89                 $values = json_decode($s);
90                 return($values);
91                 $pumpio = array();
92                 $pumpio["client_id"] = $values->client_id;
93                 $pumpio["client_secret"] = $values->client_secret;
94                 print_r($values);
95         }
96         return(false);
97 }
98
99 function pumpio_connect($a) {
100         // Start a session.  This is necessary to hold on to  a few keys the callback script will also need
101         session_start();
102
103         // Define the needed keys
104         $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
105         $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
106         $hostname = get_pconfig(local_user(), 'pumpio','host');
107
108         if ((($consumer_key == "") OR ($consumer_secret == "")) AND ($hostname != "")) {
109                 $clientdata = pumpio_registerclient($a, $hostname);
110                 set_pconfig(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
111                 set_pconfig(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
112
113                 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
114                 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
115         }
116
117         if (($consumer_key == "") OR ($consumer_secret == ""))
118                 return;
119
120         // The callback URL is the script that gets called after the user authenticates with pumpio
121         $callback_url = $a->get_baseurl()."/pumpio/connect";
122
123         // Let's begin.  First we need a Request Token.  The request token is required to send the user
124         // to pumpio's login page.
125
126         // Create a new instance of the TumblrOAuth library.  For this step, all we need to give the library is our
127         // Consumer Key and Consumer Secret
128         $client = new oauth_client_class;
129         $client->debug = 1;
130         $client->server = '';
131         $client->oauth_version = '1.0a';
132         $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
133         $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
134         $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
135         $client->url_parameters = false;
136         $client->authorization_header = true;
137         $client->redirect_uri = $callback_url;
138         $client->client_id = $consumer_key;
139         $client->client_secret = $consumer_secret;
140
141         if (($success = $client->Initialize())) {
142                 if (($success = $client->Process())) {
143                         if (strlen($client->access_token)) {
144                                 set_pconfig(local_user(), "pumpio", "oauth_token", $client->access_token);
145                                 set_pconfig(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
146                         }
147                 }
148                 $success = $client->Finalize($success);
149         }
150         if($client->exit)
151             $o = 'Could not connect to pumpio. Refresh the page or try again later.';
152
153         if($success) {
154                 $o .= t("You are now authenticated to pumpio.");
155                 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
156         }
157
158         return($o);
159 }
160
161 function pumpio_jot_nets(&$a,&$b) {
162     if(! local_user())
163         return;
164
165     $pumpio_post = get_pconfig(local_user(),'pumpio','post');
166     if(intval($pumpio_post) == 1) {
167         $pumpio_defpost = get_pconfig(local_user(),'pumpio','post_by_default');
168         $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
169         $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
170             . t('Post to pumpio') . '</div>';
171     }
172 }
173
174
175 function pumpio_settings(&$a,&$s) {
176
177     if(! local_user())
178         return;
179
180     /* Add our stylesheet to the page so we can make our settings look nice */
181
182     $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
183
184     /* Get the current state of our config variables */
185
186     $enabled = get_pconfig(local_user(),'pumpio','post');
187     $checked = (($enabled) ? ' checked="checked" ' : '');
188
189     $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default');
190     $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
191
192     $public_enabled = get_pconfig(local_user(),'pumpio','public');
193     $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
194
195     $servername = get_pconfig(local_user(), "pumpio", "host");
196     $username = get_pconfig(local_user(), "pumpio", "user");
197
198     /* Add some HTML to the existing form */
199
200     $s .= '<div class="settings-block">';
201     $s .= '<h3>' . t('Pump.io Post Settings') . '</h3>';
202
203     $s .= '<div id="pumpio-servername-wrapper">';
204     $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
205     $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
206     $s .= '</div><div class="clear"></div>';
207
208     $s .= '<div id="pumpio-username-wrapper">';
209     $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username').'</label>';
210     $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
211     $s .= '</div><div class="clear"></div>';
212
213     if (($username != '') AND ($servername != '')) {
214         $s .= '<div id="pumpio-authenticate-wrapper">';
215         $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("(Re-)Authenticate your pump.io connection").'</a>';
216         $s .= '</div><div class="clear"></div>';
217
218         $s .= '<div id="pumpio-enable-wrapper">';
219         $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
220         $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
221         $s .= '</div><div class="clear"></div>';
222
223         $s .= '<div id="pumpio-bydefault-wrapper">';
224         $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
225         $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
226         $s .= '</div><div class="clear"></div>';
227
228         $s .= '<div id="pumpio-public-wrapper">';
229         $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
230         $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
231         $s .= '</div><div class="clear"></div>';
232
233         $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token");
234         $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret");
235
236         $s .= '<div id="pumpio-password-wrapper">';
237         if (($oauth_token == "") OR ($oauth_token_secret == ""))
238                 $s .= t("You are not authenticated to pumpio");
239
240         $s .= '</div><div class="clear"></div>';
241     }
242
243     /* provide a submit button */
244
245     $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
246
247 }
248
249
250 function pumpio_settings_post(&$a,&$b) {
251
252         if(x($_POST,'pumpio-submit')) {
253
254                 set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
255                 set_pconfig(local_user(),'pumpio','host',$_POST['pumpio_host']);
256                 set_pconfig(local_user(),'pumpio','user',$_POST['pumpio_user']);
257                 set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
258                 set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
259
260         }
261
262 }
263
264 function pumpio_post_local(&$a,&$b) {
265
266         // This can probably be changed to allow editing by pointing to a different API endpoint
267
268         if($b['edit'])
269                 return;
270
271         if((! local_user()) || (local_user() != $b['uid']))
272                 return;
273
274         if($b['private'] || $b['parent'])
275                 return;
276
277         $pumpio_post   = intval(get_pconfig(local_user(),'pumpio','post'));
278
279         $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
280
281         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
282                 $pumpio_enable = 1;
283
284         if(! $pumpio_enable)
285                 return;
286
287         if(strlen($b['postopts']))
288                 $b['postopts'] .= ',';
289
290         $b['postopts'] .= 'pumpio';
291 }
292
293
294
295
296 function pumpio_send(&$a,&$b) {
297
298         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
299                 return;
300
301         if(! strstr($b['postopts'],'pumpio'))
302                 return;
303
304         if($b['parent'] != $b['id'])
305                 return;
306
307         // if post comes from pump.io don't send it back
308         if($b['app'] == "pump.io")
309                 return;
310
311         $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
312         $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
313         $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
314         $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
315
316         $host = get_pconfig($b['uid'], "pumpio", "host");
317         $user = get_pconfig($b['uid'], "pumpio", "user");
318         $public = get_pconfig($b['uid'], "pumpio", "public");
319
320         if($oauth_token && $oauth_token_secret) {
321
322                 require_once('include/bbcode.php');
323
324                 $title = trim($b['title']);
325
326                 if ($title != '')
327                         $title = "<h4>".$title."</h4>";
328
329                 $params->verb = "post";
330
331                 $params->object = array(
332                                         'objectType' => "note",
333                                         'content' => $title.bbcode($b['body'], false, false));
334
335                 if ($public)
336                         $params->to = array(Array(
337                                                 "objectType" => "collection",
338                                                 "id" => "http://activityschema.org/collection/public"));
339
340                 $client = new oauth_client_class;
341                 $client->oauth_version = '1.0a';
342                 $client->url_parameters = false;
343                 $client->authorization_header = true;
344                 $client->access_token = $oauth_token;
345                 $client->access_token_secret = $oauth_token_secret;
346                 $client->client_id = $consumer_key;
347                 $client->client_secret = $consumer_secret;
348
349                 $success = $client->CallAPI(
350                                         'https://'.$host.'/api/user/'.$user.'/feed',
351                                         'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
352
353                 if($success)
354                         logger('pumpio_send: success');
355                 else
356                         logger('pumpio_send: general error: ' . print_r($user,true));
357
358         }
359 }
360
361 function pumpio_cron($a,$b) {
362         $last = get_config('pumpio','last_poll');
363
364         $poll_interval = intval(get_config('pumpio','poll_interval'));
365         if(! $poll_interval)
366                 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
367
368         if($last) {
369                 $next = $last + ($poll_interval * 60);
370                 if($next > time()) {
371                         logger('pumpio: poll intervall not reached');
372                         return;
373                 }
374         }
375         logger('pumpio: cron_start');
376
377         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
378         if(count($r)) {
379                 foreach($r as $rr) {
380                         logger('pumpio: fetching for user '.$rr['uid']);
381                         pumpio_fetchtimeline($a, $rr['uid']);
382                 }
383         }
384
385         logger('pumpio: cron_end');
386
387         set_config('pumpio','last_poll', time());
388 }
389
390 function pumpio_fetchtimeline($a, $uid) {
391         $ckey    = get_pconfig($uid, 'pumpio', 'consumerkey');
392         $csecret = get_pconfig($uid, 'pumpio', 'consumersecret');
393         $otoken  = get_pconfig($uid, 'pumpio', 'oauthtoken');
394         $osecret = get_pconfig($uid, 'pumpio', 'oauthsecret');
395         $lastid  = get_pconfig($uid, 'pumpio', 'lastid');
396         $hostname = get_pconfig($uid, 'pumpio','host');
397         $username = get_pconfig($uid, "pumpio", "user");
398
399         $application_name  = get_config('pumpio', 'application_name');
400
401         if ($application_name == "")
402                 $application_name = $a->get_hostname();
403
404         $first_time = ($lastid == "");
405
406         require('oauth/http.php');
407         require('oauth/oauth_client.php');
408
409         $client = new oauth_client_class;
410         $client->oauth_version = '1.0a';
411         $client->authorization_header = true;
412         $client->url_parameters = false;
413
414         $client->client_id = $ckey;
415         $client->client_secret = $csekret;
416         $client->access_token = $otoken;
417         $client->access_token_secret = $osecret;
418
419         $success = $client->CallAPI(
420                                 'https://'.$hostname.'/api/user/'.$username.'/feed/major',
421                                 'GET', array(), array('FailOnAccessError'=>true), $user);
422
423         $posts = array_reverse($items);
424
425         if (count($posts)) {
426                 foreach ($posts as $post) {
427                         if ($post->id_str > $lastid) // To-Do
428                                 $lastid = $post->id_str; // To-Do
429
430                         if ($first_time)
431                                 continue;
432
433                         if (!strpos($post->source, $application_name)) {
434                                 require_once('include/html2bbcode.php');
435
436                                 $_SESSION["authenticated"] = true;
437                                 $_SESSION["uid"] = $uid;
438
439                                 $_REQUEST["type"] = "wall";
440                                 $_REQUEST["api_source"] = true;
441                                 $_REQUEST["profile_uid"] = $uid;
442                                 $_REQUEST["source"] = "pump.io";
443
444                                 $_REQUEST["body"] = html2bbcode($post->object->content);
445
446                                 logger('pumpio: posting for user '.$uid);
447
448                                 require_once('mod/item.php');
449                                 item_post($a);
450                         }
451                 }
452         }
453
454 }