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