]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
Pumpio: The connector now is bidrectional.
[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         }
87         return(false);
88 }
89
90 function pumpio_connect($a) {
91         // Start a session.  This is necessary to hold on to  a few keys the callback script will also need
92         session_start();
93
94         // Define the needed keys
95         $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
96         $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
97         $hostname = get_pconfig(local_user(), 'pumpio','host');
98
99         if ((($consumer_key == "") OR ($consumer_secret == "")) AND ($hostname != "")) {
100                 $clientdata = pumpio_registerclient($a, $hostname);
101                 set_pconfig(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
102                 set_pconfig(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
103
104                 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
105                 $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
106         }
107
108         if (($consumer_key == "") OR ($consumer_secret == ""))
109                 return;
110
111         // The callback URL is the script that gets called after the user authenticates with pumpio
112         $callback_url = $a->get_baseurl()."/pumpio/connect";
113
114         // Let's begin.  First we need a Request Token.  The request token is required to send the user
115         // to pumpio's login page.
116
117         // Create a new instance of the TumblrOAuth library.  For this step, all we need to give the library is our
118         // Consumer Key and Consumer Secret
119         $client = new oauth_client_class;
120         $client->debug = 1;
121         $client->server = '';
122         $client->oauth_version = '1.0a';
123         $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
124         $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
125         $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
126         $client->url_parameters = false;
127         $client->authorization_header = true;
128         $client->redirect_uri = $callback_url;
129         $client->client_id = $consumer_key;
130         $client->client_secret = $consumer_secret;
131
132         if (($success = $client->Initialize())) {
133                 if (($success = $client->Process())) {
134                         if (strlen($client->access_token)) {
135                                 set_pconfig(local_user(), "pumpio", "oauth_token", $client->access_token);
136                                 set_pconfig(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
137                         }
138                 }
139                 $success = $client->Finalize($success);
140         }
141         if($client->exit)
142             $o = 'Could not connect to pumpio. Refresh the page or try again later.';
143
144         if($success) {
145                 $o .= t("You are now authenticated to pumpio.");
146                 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
147         }
148
149         return($o);
150 }
151
152 function pumpio_jot_nets(&$a,&$b) {
153     if(! local_user())
154         return;
155
156     $pumpio_post = get_pconfig(local_user(),'pumpio','post');
157     if(intval($pumpio_post) == 1) {
158         $pumpio_defpost = get_pconfig(local_user(),'pumpio','post_by_default');
159         $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
160         $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
161             . t('Post to pumpio') . '</div>';
162     }
163 }
164
165
166 function pumpio_settings(&$a,&$s) {
167
168     if(! local_user())
169         return;
170
171     /* Add our stylesheet to the page so we can make our settings look nice */
172
173     $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
174
175     /* Get the current state of our config variables */
176
177     $import_enabled = get_pconfig(local_user(),'pumpio','import');
178     $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
179
180     $enabled = get_pconfig(local_user(),'pumpio','post');
181     $checked = (($enabled) ? ' checked="checked" ' : '');
182
183     $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default');
184     $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
185
186     $public_enabled = get_pconfig(local_user(),'pumpio','public');
187     $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
188
189     $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror');
190     $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
191
192     $servername = get_pconfig(local_user(), "pumpio", "host");
193     $username = get_pconfig(local_user(), "pumpio", "user");
194
195     /* Add some HTML to the existing form */
196
197     $s .= '<div class="settings-block">';
198     $s .= '<h3>' . t('Pump.io Post Settings') . '</h3>';
199
200     $s .= '<div id="pumpio-username-wrapper">';
201     $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
202     $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
203     $s .= '</div><div class="clear"></div>';
204
205     $s .= '<div id="pumpio-servername-wrapper">';
206     $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
207     $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
208     $s .= '</div><div class="clear"></div>';
209
210     if (($username != '') AND ($servername != '')) {
211
212         $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token");
213         $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret");
214
215         $s .= '<div id="pumpio-password-wrapper">';
216         if (($oauth_token == "") OR ($oauth_token_secret == "")) {
217                 $s .= '<div id="pumpio-authenticate-wrapper">';
218                 $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
219                 $s .= '</div><div class="clear"></div>';
220
221                 //$s .= t("You are not authenticated to pumpio");
222         } else {
223                 $s .= '<div id="pumpio-import-wrapper">';
224                 $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
225                 $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
226                 $s .= '</div><div class="clear"></div>';
227
228                 $s .= '<div id="pumpio-enable-wrapper">';
229                 $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
230                 $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
231                 $s .= '</div><div class="clear"></div>';
232
233                 $s .= '<div id="pumpio-bydefault-wrapper">';
234                 $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
235                 $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
236                 $s .= '</div><div class="clear"></div>';
237
238                 $s .= '<div id="pumpio-public-wrapper">';
239                 $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
240                 $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
241                 $s .= '</div><div class="clear"></div>';
242
243                 $s .= '<div id="pumpio-mirror-wrapper">';
244                 $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
245                 $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
246                 $s .= '</div><div class="clear"></div>';
247
248                 $s .= '<div id="pumpio-delete-wrapper">';
249                 $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
250                 $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
251                 $s .= '</div><div class="clear"></div>';
252
253                 //$s .= '<div id="pumpio-authenticate-wrapper">';
254                 //$s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Reauthenticate your pump.io connection").'</a>';
255                 //$s .= '</div><div class="clear"></div>';
256
257         }
258
259         $s .= '</div><div class="clear"></div>';
260     }
261
262     /* provide a submit button */
263
264     $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
265
266 }
267
268
269 function pumpio_settings_post(&$a,&$b) {
270
271         if(x($_POST,'pumpio-submit')) {
272                 if(x($_POST,'pumpio_delete')) {
273                         set_pconfig(local_user(),'pumpio','consumer_key','');
274                         set_pconfig(local_user(),'pumpio','consumer_secret','');
275                         set_pconfig(local_user(),'pumpio','host','');
276                         set_pconfig(local_user(),'pumpio','oauth_token','');
277                         set_pconfig(local_user(),'pumpio','oauth_token_secret','');
278                         set_pconfig(local_user(),'pumpio','post',false);
279                         set_pconfig(local_user(),'pumpio','post_by_default',false);
280                         set_pconfig(local_user(),'pumpio','user','');
281                 } else {
282                         // filtering the username if it is filled wrong
283                         $user = $_POST['pumpio_user'];
284                         if (strstr($user, "@")) {
285                                 $pos = strpos($user, "@");
286                                 if ($pos > 0)
287                                         $user = substr($user, 0, $pos);
288                         }
289
290                         // Filtering the hostname if someone is entering it with "http"
291                         $host = $_POST['pumpio_host'];
292                         $host = trim($host);
293                         $host = str_replace(array("https://", "http://"), array("", ""), $host);
294
295                         set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
296                         set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
297                         set_pconfig(local_user(),'pumpio','host',$host);
298                         set_pconfig(local_user(),'pumpio','user',$user);
299                         set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
300                         set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
301                         set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
302                 }
303         }
304 }
305
306 function pumpio_post_local(&$a,&$b) {
307
308         // This can probably be changed to allow editing by pointing to a different API endpoint
309
310         if($b['edit'])
311                 return;
312
313         if((! local_user()) || (local_user() != $b['uid']))
314                 return;
315
316         if($b['private'] || $b['parent'])
317                 return;
318
319         $pumpio_post   = intval(get_pconfig(local_user(),'pumpio','post'));
320
321         $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
322
323         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'pumpio','post_by_default')))
324                 $pumpio_enable = 1;
325
326         if(! $pumpio_enable)
327                 return;
328
329         if(strlen($b['postopts']))
330                 $b['postopts'] .= ',';
331
332         $b['postopts'] .= 'pumpio';
333 }
334
335
336
337
338 function pumpio_send(&$a,&$b) {
339         if($b['deleted'] || ($b['created'] !== $b['edited']))
340                 return;
341
342         if($b['parent'] != $b['id']) {
343                 // Looking if its a reply to a pumpio post
344                 $r = q("SELECT item.* FROM item, contact WHERE item.id = %d AND item.uid = %d AND contact.id = `contact-id` AND contact.network='%s'LIMIT 1",
345                         intval($b["parent"]),
346                         intval($b["uid"]),
347                         dbesc(NETWORK_PUMPIO));
348
349                 if(!count($r))
350                         return;
351                 else {
352                         $iscomment = true;
353                         $orig_post = $r[0];
354                 }
355         } else {
356                 $iscomment = false;
357
358                 if(! strstr($b['postopts'],'pumpio'))
359                         return;
360
361                 if($b['private'])
362                         return;
363         }
364
365         // if post comes from pump.io don't send it back
366         if($b['app'] == "pump.io")
367                 return;
368
369         $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token");
370         $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
371         $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
372         $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
373
374         $host = get_pconfig($b['uid'], "pumpio", "host");
375         $user = get_pconfig($b['uid'], "pumpio", "user");
376         $public = get_pconfig($b['uid'], "pumpio", "public");
377
378         if($oauth_token && $oauth_token_secret) {
379
380                 require_once('include/bbcode.php');
381
382                 $title = trim($b['title']);
383
384                 if ($title != '')
385                         $title = "<h4>".$title."</h4>";
386
387                 $content = bbcode($b['body'], false, false);
388
389                 // Enhance the way, videos are displayed
390                 $content = preg_replace('/<a.*?href="(https?:\/\/www.youtube.com\/.*?)".*?>(.*?)<\/a>/ism',"\n[url]$1[/url]\n",$content);
391                 $content = preg_replace('/<a.*?href="(https?:\/\/youtu.be\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
392                 $content = preg_replace('/<a.*?href="(https?:\/\/vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
393                 $content = preg_replace('/<a.*?href="(https?:\/\/player.vimeo.com\/.*?)".*?>(.*?)<\/a>/ism',"\n$1\n",$content);
394
395                 $URLSearchString = "^\[\]";
396                 $content = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism",'tryoembed',$content);
397
398                 $params = array();
399
400                 $params["verb"] = "post";
401
402                 if (!$iscomment) {
403                         $params["object"] = array(
404                                                 'objectType' => "note",
405                                                 'content' => $title.$content);
406
407                         if ($public)
408                                 $params["to"] = array(Array(
409                                                         "objectType" => "collection",
410                                                         "id" => "http://activityschema.org/collection/public"));
411                  } else {
412                         $inReplyTo = array("id" => $orig_post["uri"],
413                                         "objectType" => "note");
414
415                         $params["object"] = array(
416                                                 'objectType' => "comment",
417                                                 'content' => $title.$content,
418                                                 'inReplyTo' => $inReplyTo);
419                 }
420
421                 $client = new oauth_client_class;
422                 $client->oauth_version = '1.0a';
423                 $client->url_parameters = false;
424                 $client->authorization_header = true;
425                 $client->access_token = $oauth_token;
426                 $client->access_token_secret = $oauth_token_secret;
427                 $client->client_id = $consumer_key;
428                 $client->client_secret = $consumer_secret;
429
430                 $username = $user.'@'.$host;
431                 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
432
433                 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
434
435                 if($success) {
436                         $post_id = $user->object->id;
437                         logger('pumpio_send '.$username.': success '.$post_id);
438                         if($post_id AND $iscomment) {
439                                 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
440                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
441                                         dbesc($post_id),
442                                         intval($b['id'])
443                                 );
444                         }
445                 } else {
446                         logger('pumpio_send '.$username.': general error: ' . print_r($user,true));
447
448                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
449                         require_once('include/queue_fn.php');
450                         add_to_queue($a->contact,NETWORK_PUMPIO,$s);
451                         notice(t('Pump.io post failed. Queued for retry.').EOL);
452                 }
453
454         }
455 }
456
457 function pumpio_cron($a,$b) {
458         $last = get_config('pumpio','last_poll');
459
460         $poll_interval = intval(get_config('pumpio','poll_interval'));
461         if(! $poll_interval)
462                 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
463
464         if($last) {
465                 $next = $last + ($poll_interval * 60);
466                 if($next > time()) {
467                         logger('pumpio: poll intervall not reached');
468                         return;
469                 }
470         }
471         logger('pumpio: cron_start');
472
473         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
474         if(count($r)) {
475                 foreach($r as $rr) {
476                         logger('pumpio: mirroring user '.$rr['uid']);
477                         pumpio_fetchtimeline($a, $rr['uid']);
478                 }
479         }
480
481         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
482         if(count($r)) {
483                 foreach($r as $rr) {
484                         logger('pumpio: importing timeline from user '.$rr['uid']);
485                         pumpio_fetchinbox($a, $rr['uid']);
486                 }
487         }
488
489         // To-Do:
490         //pumpio_getallusers($a, $uid);
491
492         logger('pumpio: cron_end');
493
494         set_config('pumpio','last_poll', time());
495 }
496
497 function pumpio_fetchtimeline($a, $uid) {
498         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
499         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
500         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
501         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
502         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
503         $hostname = get_pconfig($uid, 'pumpio','host');
504         $username = get_pconfig($uid, "pumpio", "user");
505
506         $application_name  = get_config('pumpio', 'application_name');
507
508         if ($application_name == "")
509                 $application_name = $a->get_hostname();
510
511         $first_time = ($lastdate == "");
512
513         $client = new oauth_client_class;
514         $client->oauth_version = '1.0a';
515         $client->authorization_header = true;
516         $client->url_parameters = false;
517
518         $client->client_id = $ckey;
519         $client->client_secret = $csecret;
520         $client->access_token = $otoken;
521         $client->access_token_secret = $osecret;
522
523         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
524
525         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
526
527         $username = $user.'@'.$host;
528
529         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
530
531         if (!$success) {
532                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
533                 return;
534         }
535
536         $posts = array_reverse($user->items);
537
538         $initiallastdate = $lastdate;
539         $lastdate = '';
540
541         if (count($posts)) {
542                 foreach ($posts as $post) {
543                         if ($post->generator->published <= $initiallastdate)
544                                 continue;
545
546                         if ($lastdate < $post->generator->published)
547                                 $lastdate = $post->generator->published;
548
549                         if ($first_time)
550                                 continue;
551
552                         $receiptians = array();
553                         if (@is_array($post->cc))
554                                 $receiptians = array_merge($receiptians, $post->cc);
555
556                         if (@is_array($post->to))
557                                 $receiptians = array_merge($receiptians, $post->to);
558
559                         $public = false;
560                         foreach ($receiptians AS $receiver)
561                                 if (is_string($receiver->objectType))
562                                         if ($receiver->id == "http://activityschema.org/collection/public")
563                                                 $public = true;
564
565                         if ($public AND !strstr($post->generator->displayName, $application_name)) {
566                                 require_once('include/html2bbcode.php');
567
568                                 $_SESSION["authenticated"] = true;
569                                 $_SESSION["uid"] = $uid;
570
571                                 unset($_REQUEST);
572                                 $_REQUEST["type"] = "wall";
573                                 $_REQUEST["api_source"] = true;
574                                 $_REQUEST["profile_uid"] = $uid;
575                                 $_REQUEST["source"] = "pump.io";
576
577                                 if ($post->object->displayName != "")
578                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
579                                 else
580                                         $_REQUEST["title"] = "";
581
582                                 $_REQUEST["body"] = html2bbcode($post->object->content);
583
584                                 if ($post->object->fullImage->url != "")
585                                         $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
586
587                                 logger('pumpio: posting for user '.$uid);
588
589                                 require_once('mod/item.php');
590                                 //print_r($_REQUEST);
591                                 item_post($a);
592                                 logger('pumpio: posting done - user '.$uid);
593                         }
594                 }
595         }
596
597         //$lastdate = '2013-05-16T20:22:12Z';
598
599         if ($lastdate != 0)
600                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
601 }
602
603 function pumpio_dolike(&$a, $uid, $self, $post) {
604
605 /*
606     // If we posted the like locally, it will be found with our url, not the FB url.
607
608     $second_url = (($likes->id == $fb_id) ? $self[0]['url'] : 'http://facebook.com/profile.php?id=' . $likes->id);
609
610     $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
611         AND ( `author-link` = '%s' OR `author-link` = '%s' ) LIMIT 1",
612         dbesc($orig_post['uri']),
613         intval($uid),
614         dbesc(ACTIVITY_LIKE),
615         dbesc('http://facebook.com/profile.php?id=' . $likes->id),
616         dbesc($second_url)
617     );
618
619     if(count($r))
620         return;
621 */
622
623         // To-Do
624         $own_id = "123455678";
625
626         // Two queries for speed issues
627         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
628                                 dbesc($post->object->id),
629                                 intval($uid)
630                 );
631
632         if (count($r))
633                 $orig_post = $r[0];
634         else {
635                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
636                                         dbesc($post->object->id),
637                                         intval($uid)
638                         );
639
640                 if (!count($r))
641                         return;
642                 else
643                         $orig_post = $r[0];
644         }
645
646         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `author-link` = '%s' AND parent = %d LIMIT 1",
647                 dbesc(ACTIVITY_LIKE),
648                 intval($uid),
649                 dbesc($post->actor->url),
650                 intval($orig_post['id'])
651         );
652
653         if(count($r))
654                 return;
655
656         $likedata = array();
657         $likedata['parent'] = $orig_post['id'];
658         $likedata['verb'] = ACTIVITY_LIKE;
659         $likedata['gravity'] = 3;
660         $likedata['uid'] = $uid;
661         $likedata['wall'] = 0;
662         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
663         $likedata['parent-uri'] = $orig_post["uri"];
664
665         if($likes->id == $own_id)
666                 $likedata['contact-id'] = $self[0]['id'];
667         else {
668                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
669                         dbesc($post->actor->url),
670                         intval($uid)
671                 );
672
673                 if(count($r))
674                         $likedata['contact-id'] = $r[0]['id'];
675         }
676         if(! x($likedata,'contact-id'))
677                 $likedata['contact-id'] = $orig_post['contact-id'];
678
679         $likedata['app'] = $post->generator->displayName;
680         $likedata['verb'] = ACTIVITY_LIKE;
681         $likedata['author-name'] = $post->actor->displayName;
682         $likedata['author-link'] = $post->actor->url;
683         $likedata['author-avatar'] = $post->actor->image->url;
684
685         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
686         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
687         $post_type = t('status');
688         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
689         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
690
691         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
692
693         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
694                 '<id>' . $orig_post['uri'] . '</id><link>' . xmlify('<link rel="alternate" type="text/html" href="' . xmlify($orig_post['plink']) . '" />') . '</link><title>' . $orig_post['title'] . '</title><content>' . $orig_post['body'] . '</content></object>';
695
696         item_store($likedata);
697 }
698
699 function pumpio_get_contact($uid, $contact) {
700
701         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
702                 intval($uid), dbesc($contact->url));
703
704         if(!count($r)) {
705                 // create contact record
706                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
707                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
708                                         `writable`, `blocked`, `readonly`, `pending` )
709                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
710                         intval($uid),
711                         dbesc(datetime_convert()),
712                         dbesc($contact->url),
713                         dbesc(normalise_link($contact->url)),
714                         dbesc(str_replace("acct:", "", $contact->id)),
715                         dbesc(''),
716                         dbesc($contact->id), // To-Do?
717                         dbesc('pump.io ' . $contact->id), // To-Do?
718                         dbesc($contact->displayName),
719                         dbesc($contact->preferredUsername),
720                         dbesc($contact->image->url),
721                         dbesc(NETWORK_PUMPIO),
722                         intval(CONTACT_IS_FRIEND),
723                         intval(1),
724                         intval(1)
725                 );
726
727                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
728                         dbesc($contact->url),
729                         intval($uid)
730                         );
731
732                 if(! count($r))
733                         return(false);
734
735                 $contact_id  = $r[0]['id'];
736
737                 $g = q("select def_gid from user where uid = %d limit 1",
738                         intval($uid)
739                 );
740
741                 if($g && intval($g[0]['def_gid'])) {
742                         require_once('include/group.php');
743                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
744                 }
745
746                 require_once("Photo.php");
747
748                 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
749
750                 q("UPDATE `contact` SET `photo` = '%s',
751                                         `thumb` = '%s',
752                                         `micro` = '%s',
753                                         `name-date` = '%s',
754                                         `uri-date` = '%s',
755                                         `avatar-date` = '%s'
756                                 WHERE `id` = %d LIMIT 1
757                         ",
758                 dbesc($photos[0]),
759                 dbesc($photos[1]),
760                 dbesc($photos[2]),
761                 dbesc(datetime_convert()),
762                 dbesc(datetime_convert()),
763                 dbesc(datetime_convert()),
764                 intval($contact_id)
765                 );
766         } else {
767                 // update profile photos once every two weeks as we have no notification of when they change.
768
769                 $update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
770
771                 // check that we have all the photos, this has been known to fail on occasion
772
773                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
774                         require_once("Photo.php");
775
776                         $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
777
778                         q("UPDATE `contact` SET `photo` = '%s',
779                                         `thumb` = '%s',
780                                         `micro` = '%s',
781                                         `name-date` = '%s',
782                                         `uri-date` = '%s',
783                                         `avatar-date` = '%s'
784                                         WHERE `id` = %d LIMIT 1
785                                 ",
786                         dbesc($photos[0]),
787                         dbesc($photos[1]),
788                         dbesc($photos[2]),
789                         dbesc(datetime_convert()),
790                         dbesc(datetime_convert()),
791                         dbesc(datetime_convert()),
792                         intval($r[0]['id'])
793                         );
794                 }
795
796         }
797
798         return($r[0]["id"]);
799 }
800
801 function pumpio_dodelete(&$a, $client, $uid, $self, $post) {
802
803         // Two queries for speed issues
804         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
805                                 dbesc($post->object->id),
806                                 intval($uid)
807                 );
808
809         if (count($r)) {
810                 drop_item($r[0]["id"], $false);
811                 return;
812         }
813
814         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
815                                 dbesc($post->object->id),
816                                 intval($uid)
817                 );
818
819         if (count($r)) {
820                 drop_item($r[0]["id"], $false);
821                 return;
822         }
823 }
824
825 function pumpio_dopost(&$a, $client, $uid, $self, $post) {
826         require_once('include/items.php');
827
828         if ($post->verb == "like") {
829                 pumpio_dolike(&$a, $uid, $self, $post);
830                 return;
831         }
832
833         if ($post->verb == "delete") {
834                 pumpio_dodelete(&$a, $uid, $self, $post);
835                 return;
836         }
837
838         // Only handle these three types
839         if (!strstr("post|share|update", $post->verb))
840                 return;
841
842         if ($post->verb != "update") {
843                 // Two queries for speed issues
844                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
845                                         dbesc($post->object->id),
846                                         intval($uid)
847                         );
848
849                 if (count($r))
850                         return;
851
852                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
853                                         dbesc($post->object->id),
854                                         intval($uid)
855                         );
856
857                 if (count($r))
858                         return;
859         }
860
861         $receiptians = array();
862         if (@is_array($post->cc))
863                 $receiptians = array_merge($receiptians, $post->cc);
864
865         if (@is_array($post->to))
866                 $receiptians = array_merge($receiptians, $post->to);
867
868         foreach ($receiptians AS $receiver)
869                 if (is_string($receiver->objectType))
870                         if ($receiver->id == "http://activityschema.org/collection/public")
871                                 $public = true;
872
873         $contact_id = pumpio_get_contact($uid, $post->actor);
874
875         if (!$contact_id)
876                 $contact_id = $self[0]['id'];
877
878         $postarray = array();
879         $postarray['gravity'] = 0;
880         $postarray['uid'] = $uid;
881         $postarray['wall'] = 0;
882         $postarray['uri'] = $post->object->id;
883
884         if ($post->object->objectType != "comment") {
885                 $postarray['parent-uri'] = $post->object->id;
886         } else {
887                 //echo($post->object->inReplyTo->url."\n");
888                 //print_r($post->object->inReplyTo);
889                 //echo $post->object->inReplyTo->likes->url."\n";
890                 //$replies = $post->object->inReplyTo->replies->url;
891                 //$replies = $post->object->likes->pump_io->proxyURL;
892                 //$replies = $post->object->replies->pump_io->proxyURL;
893
894                 /*
895                 //$replies = $post->object->replies->pump_io->proxyURL;
896
897                 if ($replies != "") {
898                         $success = $client->CallAPI($replies, 'GET', array(), array('FailOnAccessError'=>true), $replydata);
899                         print_r($replydata);
900                 } else
901                         print_r($post);
902                 */
903
904                 $reply->verb = "note";
905                 $reply->cc = $post->cc;
906                 $reply->to = $post->to;
907                 $reply->object->objectType = $post->object->inReplyTo->objectType;
908                 $reply->object->content = $post->object->inReplyTo->content;
909                 $reply->object->id = $post->object->inReplyTo->id;
910                 $reply->actor = $post->object->inReplyTo->author;
911                 $reply->url = $post->object->inReplyTo->url;
912                 $reply->generator->displayName = "pumpio";
913                 $reply->published = $post->object->inReplyTo->published;
914                 $reply->received = $post->object->inReplyTo->updated;
915                 $reply->url = $post->object->inReplyTo->url;
916                 pumpio_dopost(&$a, $client, $uid, $self, $reply);
917
918                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
919         }
920
921         $postarray['contact-id'] = $contact_id;
922         $postarray['verb'] = ACTIVITY_POST;
923         $postarray['owner-name'] = $post->actor->displayName;
924         $postarray['owner-link'] = $post->actor->url;
925         $postarray['owner-avatar'] = $post->actor->image->url;
926         $postarray['author-name'] = $post->actor->displayName;
927         $postarray['author-link'] = $post->actor->url;
928         $postarray['author-avatar'] = $post->actor->image->url;
929         $postarray['plink'] = $post->object->url;
930         $postarray['app'] = $post->generator->displayName;
931         $postarray['body'] = html2bbcode($post->object->content);
932
933         if ($post->object->fullImage->url != "")
934                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
935
936         if ($post->object->displayName != "")
937                 $postarray['title'] = $post->object->displayName;
938
939         //$postarray['location'] = ""
940         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
941         $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
942         if (!$public) {
943                 $postarray['private'] = 1;
944                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
945         }
946
947         if ($post->verb == "share") {
948                 $postarray['body'] = "[share author='".$post->object->author->displayName.
949                                 "' profile='".$post->object->author->url.
950                                 "' avatar='".$post->object->author->image->url.
951                                 "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
952         }
953
954         if (trim($postarray['body']) == "")
955                 return;
956
957         $top_item = item_store($postarray);
958
959         if (($top_item == 0) AND ($post->verb == "update")) {
960                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
961                         dbesc($postarray["title"]),
962                         dbesc($postarray["body"]),
963                         dbesc($postarray["edited"]),
964                         dbesc($postarray["uri"]),
965                         intval($uid)
966                         );
967         }
968
969         if ($post->object->objectType == "comment") {
970
971                 $hostname = get_pconfig($uid, 'pumpio','host');
972                 $username = get_pconfig($uid, "pumpio", "user");
973
974                 $foreign_url = "https://".$hostname."/".$username;
975
976                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
977                                 intval($uid)
978                         );
979
980                 if(!count($user))
981                         return;
982
983                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
984
985                 if (link_compare($foreign_url, $postarray['author-link']))
986                         return;
987
988                 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
989                                 dbesc($postarray['parent-uri']),
990                                 intval($uid)
991                                 );
992
993                 if(count($myconv)) {
994
995                         foreach($myconv as $conv) {
996                                 // now if we find a match, it means we're in this conversation
997
998                                 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$foreign_url))
999                                         continue;
1000
1001                                 require_once('include/enotify.php');
1002
1003                                 $conv_parent = $conv['parent'];
1004
1005                                 notification(array(
1006                                         'type'         => NOTIFY_COMMENT,
1007                                         'notify_flags' => $user[0]['notify-flags'],
1008                                         'language'     => $user[0]['language'],
1009                                         'to_name'      => $user[0]['username'],
1010                                         'to_email'     => $user[0]['email'],
1011                                         'uid'          => $user[0]['uid'],
1012                                         'item'         => $cmntdata,
1013                                         'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1014                                         'source_name'  => $postarray['author-name'],
1015                                         'source_link'  => $postarray['author-link'],
1016                                         'source_photo' => $postarray['author-avatar'],
1017                                         'verb'         => ACTIVITY_POST,
1018                                         'otype'        => 'item',
1019                                         'parent'       => $conv_parent,
1020                                         ));
1021
1022                                 // only send one notification
1023                                 break;
1024                         }
1025                 }
1026         }
1027 }
1028
1029 function pumpio_fetchinbox($a, $uid) {
1030
1031         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1032         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1033         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1034         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1035         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1036         $hostname = get_pconfig($uid, 'pumpio','host');
1037         $username = get_pconfig($uid, "pumpio", "user");
1038
1039         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1040                 intval($uid));
1041
1042         $client = new oauth_client_class;
1043         $client->oauth_version = '1.0a';
1044         $client->authorization_header = true;
1045         $client->url_parameters = false;
1046
1047         $client->client_id = $ckey;
1048         $client->client_secret = $csecret;
1049         $client->access_token = $otoken;
1050         $client->access_token_secret = $osecret;
1051
1052         $last_id = get_pconfig($uid,'pumpio','last_id');
1053
1054         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1055
1056         if ($last_id != "")
1057                 $url .= '?since='.urlencode($last_id);
1058
1059         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1060         $posts = array_reverse($user->items);
1061
1062         if (count($posts))
1063                 foreach ($posts as $post) {
1064                         $last_id = $post->id;
1065                         pumpio_dopost(&$a, $client, $uid, $self, $post);
1066                 }
1067
1068         set_pconfig($uid,'pumpio','last_id', $last_id);
1069 }
1070
1071 function pumpio_getallusers($a, $uid) {
1072         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1073         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1074         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1075         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1076         $hostname = get_pconfig($uid, 'pumpio','host');
1077         $username = get_pconfig($uid, "pumpio", "user");
1078
1079         $client = new oauth_client_class;
1080         $client->oauth_version = '1.0a';
1081         $client->authorization_header = true;
1082         $client->url_parameters = false;
1083
1084         $client->client_id = $ckey;
1085         $client->client_secret = $csecret;
1086         $client->access_token = $otoken;
1087         $client->access_token_secret = $osecret;
1088
1089         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1090
1091         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1092
1093         if ($users->totalItems > count($users->items)) {
1094                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1095
1096                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1097         }
1098
1099         foreach ($users->items AS $user)
1100                 echo pumpio_get_contact($uid, $user)."\n";
1101 }
1102
1103
1104 /*
1105 To-Do:
1106  - Queues
1107  - unlike
1108
1109 Aufwand:
1110  - eigene Inhalte editieren
1111  - eigene Inhalte löschen
1112
1113 Problem:
1114  - vervollständigen der Threads
1115  - Aktualisieren nach Antworten
1116
1117 */