]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
pumpio: Posting works - mirroring not
[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"; // To-Do
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()."/pumpio/connect";
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     $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror');
196     $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
197
198     $servername = get_pconfig(local_user(), "pumpio", "host");
199     $username = get_pconfig(local_user(), "pumpio", "user");
200
201     /* Add some HTML to the existing form */
202
203     $s .= '<div class="settings-block">';
204     $s .= '<h3>' . t('Pump.io Post Settings') . '</h3>';
205
206     $s .= '<div id="pumpio-servername-wrapper">';
207     $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
208     $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
209     $s .= '</div><div class="clear"></div>';
210
211     $s .= '<div id="pumpio-username-wrapper">';
212     $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username').'</label>';
213     $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
214     $s .= '</div><div class="clear"></div>';
215
216     if (($username != '') AND ($servername != '')) {
217         $s .= '<div id="pumpio-authenticate-wrapper">';
218         $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("(Re-)Authenticate your pump.io connection").'</a>';
219         $s .= '</div><div class="clear"></div>';
220
221         $s .= '<div id="pumpio-enable-wrapper">';
222         $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
223         $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
224         $s .= '</div><div class="clear"></div>';
225
226         $s .= '<div id="pumpio-bydefault-wrapper">';
227         $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
228         $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
229         $s .= '</div><div class="clear"></div>';
230
231         $s .= '<div id="pumpio-public-wrapper">';
232         $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
233         $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
234         $s .= '</div><div class="clear"></div>';
235
236         $s .= '<div id="pumpio-mirror-wrapper">';
237         $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
238         $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
239         $s .= '</div><div class="clear"></div>';
240
241         $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token");
242         $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret");
243
244         $s .= '<div id="pumpio-password-wrapper">';
245         if (($oauth_token == "") OR ($oauth_token_secret == ""))
246                 $s .= t("You are not authenticated to pumpio");
247
248         $s .= '</div><div class="clear"></div>';
249     }
250
251     /* provide a submit button */
252
253     $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
254
255 }
256
257
258 function pumpio_settings_post(&$a,&$b) {
259
260         if(x($_POST,'pumpio-submit')) {
261
262                 set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
263                 set_pconfig(local_user(),'pumpio','host',$_POST['pumpio_host']);
264                 set_pconfig(local_user(),'pumpio','user',$_POST['pumpio_user']);
265                 set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
266                 set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
267                 set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
268
269         }
270
271 }
272
273 function pumpio_post_local(&$a,&$b) {
274
275         // This can probably be changed to allow editing by pointing to a different API endpoint
276
277         if($b['edit'])
278                 return;
279
280         if((! local_user()) || (local_user() != $b['uid']))
281                 return;
282
283         if($b['private'] || $b['parent'])
284                 return;
285
286         $pumpio_post   = intval(get_pconfig(local_user(),'pumpio','post'));
287
288         $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
289
290         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
291                 $pumpio_enable = 1;
292
293         if(! $pumpio_enable)
294                 return;
295
296         if(strlen($b['postopts']))
297                 $b['postopts'] .= ',';
298
299         $b['postopts'] .= 'pumpio';
300 }
301
302
303
304
305 function pumpio_send(&$a,&$b) {
306
307         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
308                 return;
309
310         if(! strstr($b['postopts'],'pumpio'))
311                 return;
312
313         if($b['parent'] != $b['id'])
314                 return;
315
316         // if post comes from pump.io don't send it back
317         if($b['app'] == "pump.io")
318                 return;
319
320         $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
321         $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
322         $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
323         $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
324
325         $host = get_pconfig($b['uid'], "pumpio", "host");
326         $user = get_pconfig($b['uid'], "pumpio", "user");
327         $public = get_pconfig($b['uid'], "pumpio", "public");
328
329         if($oauth_token && $oauth_token_secret) {
330
331                 require_once('include/bbcode.php');
332
333                 $title = trim($b['title']);
334
335                 if ($title != '')
336                         $title = "<h4>".$title."</h4>";
337
338                 $params = array();
339
340                 $params["verb"] = "post";
341
342                 $params["object"] = array(
343                                         'objectType' => "note",
344                                         'content' => $title.bbcode($b['body'], false, false));
345
346                 if ($public)
347                         $params["to"] = array(Array(
348                                                 "objectType" => "collection",
349                                                 "id" => "http://activityschema.org/collection/public"));
350
351                 $client = new oauth_client_class;
352                 $client->oauth_version = '1.0a';
353                 $client->url_parameters = false;
354                 $client->authorization_header = true;
355                 $client->access_token = $oauth_token;
356                 $client->access_token_secret = $oauth_token_secret;
357                 $client->client_id = $consumer_key;
358                 $client->client_secret = $consumer_secret;
359
360                 $success = $client->CallAPI(
361                                         'https://'.$host.'/api/user/'.$user.'/feed',
362                                         'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
363
364                 if($success)
365                         logger('pumpio_send: success');
366                 else
367                         logger('pumpio_send: general error: ' . print_r($user,true));
368
369         }
370 }
371
372 function pumpio_cron($a,$b) {
373         $last = get_config('pumpio','last_poll');
374
375         $poll_interval = intval(get_config('pumpio','poll_interval'));
376         if(! $poll_interval)
377                 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
378
379 //        if($last) {
380 //                $next = $last + ($poll_interval * 60);
381 //                if($next > time()) {
382 //                        logger('pumpio: poll intervall not reached');
383 //                        return;
384 //                }
385 //        }
386         logger('pumpio: cron_start');
387
388         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
389         if(count($r)) {
390                 foreach($r as $rr) {
391                         logger('pumpio: fetching for user '.$rr['uid']);
392                         pumpio_fetchtimeline($a, $rr['uid']);
393                 }
394         }
395
396         logger('pumpio: cron_end');
397
398         set_config('pumpio','last_poll', time());
399 }
400
401 function pumpio_fetchtimeline($a, $uid) {
402         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
403         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
404         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
405         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
406         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
407         $hostname = get_pconfig($uid, 'pumpio','host');
408         $username = get_pconfig($uid, "pumpio", "user");
409
410         $application_name  = get_config('pumpio', 'application_name');
411
412         if ($application_name == "")
413                 $application_name = $a->get_hostname();
414
415         $first_time = ($lastid == "");
416
417 //      require('addon/pumpio/oauth/http.php');
418 //      require('addon/pumpio/oauth/oauth_client.php');
419         $client = new oauth_client_class;
420         $client->oauth_version = '1.0a';
421         $client->authorization_header = true;
422         $client->url_parameters = false;
423
424         $client->client_id = $ckey;
425         $client->client_secret = $csecret;
426         $client->access_token = $otoken;
427         $client->access_token_secret = $osecret;
428
429         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
430
431         //echo 'pumpio: fetching for user '.$uid.' '.$url.' '.$client->access_token;
432         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
433
434         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
435
436         if (!$success) {
437                 logger('pumpio: error fetching posts for user '.$uid." ".print_r($user, true));
438                 return;
439         }
440
441         $posts = array_reverse($user->items);
442
443         $initiallastdate = $lastdate;
444         $lastdate = 0;
445
446         if (count($posts)) {
447                 foreach ($posts as $post) {
448                         if (strtotime($post->published) <= $initiallastdate)
449                                 continue;
450
451                         if ($lastdate < strtotime($post->published))
452                                 $lastdate = strtotime($post->published);
453
454                         //if ($first_time)
455                         //      continue;
456
457                         if (!strpos($post->source, $application_name)) {
458                                 require_once('include/html2bbcode.php');
459
460                                 $_SESSION["authenticated"] = true;
461                                 $_SESSION["uid"] = $uid;
462
463                                 $_REQUEST["type"] = "wall";
464                                 $_REQUEST["api_source"] = true;
465                                 $_REQUEST["profile_uid"] = $uid;
466                                 $_REQUEST["source"] = "pump.io";
467
468                                 $_REQUEST["body"] = html2bbcode($post->object->content);
469
470                                 logger('pumpio: posting for user '.$uid);
471
472                                 require_once('mod/item.php');
473                                 item_post($a);
474                         }
475                 }
476         }
477
478         if ($lastdate != 0)
479                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
480 }
481 /*
482 require_once("boot.php");
483
484 if(@is_null($a)) {
485         $a = new App;
486 }
487
488 if(is_null($db)) {
489         @include(".htconfig.php");
490         require_once("dba.php");
491         $db = new dba($db_host, $db_user, $db_pass, $db_data);
492         unset($db_host, $db_user, $db_pass, $db_data);
493 };
494
495 $a->set_baseurl(get_config('system','url'));
496
497 $uid = 1;
498
499 pumpio_fetchtimeline($a, $uid);
500 */
501 ?>