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