Issue 3873
[friendica-addons.git] / pumpio / pumpio.php
1 <?php
2 /**
3  * Name: pump.io Post Connector
4  * Description: Bidirectional (posting, relaying and reading) connector for pump.io.
5  * Version: 0.2
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 require_once('include/enotify.php');
11 require_once('include/socgraph.php');
12 require_once("include/Photo.php");
13 require_once("mod/share.php");
14
15 use Friendica\Core\Config;
16 use Friendica\Core\PConfig;
17
18 define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes
19
20 function pumpio_install() {
21         register_hook('post_local',           'addon/pumpio/pumpio.php', 'pumpio_post_local');
22         register_hook('notifier_normal',      'addon/pumpio/pumpio.php', 'pumpio_send');
23         register_hook('jot_networks',         'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
24         register_hook('connector_settings',      'addon/pumpio/pumpio.php', 'pumpio_settings');
25         register_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
26         register_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
27         register_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
28         register_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
29 }
30
31 function pumpio_uninstall() {
32         unregister_hook('post_local',       'addon/pumpio/pumpio.php', 'pumpio_post_local');
33         unregister_hook('notifier_normal',  'addon/pumpio/pumpio.php', 'pumpio_send');
34         unregister_hook('jot_networks',     'addon/pumpio/pumpio.php', 'pumpio_jot_nets');
35         unregister_hook('connector_settings',      'addon/pumpio/pumpio.php', 'pumpio_settings');
36         unregister_hook('connector_settings_post', 'addon/pumpio/pumpio.php', 'pumpio_settings_post');
37         unregister_hook('cron', 'addon/pumpio/pumpio.php', 'pumpio_cron');
38         unregister_hook('queue_predeliver', 'addon/pumpio/pumpio.php', 'pumpio_queue_hook');
39         unregister_hook('check_item_notification','addon/pumpio/pumpio.php', 'pumpio_check_item_notification');
40 }
41
42 function pumpio_module() {}
43
44 function pumpio_content(&$a) {
45
46         if(! local_user()) {
47                 notice( t('Permission denied.') . EOL);
48                 return '';
49         }
50
51         require_once("mod/settings.php");
52         settings_init($a);
53
54         if (isset($a->argv[1]))
55                 switch ($a->argv[1]) {
56                         case "connect":
57                                 $o = pumpio_connect($a);
58                                 break;
59                         default:
60                                 $o = print_r($a->argv, true);
61                                 break;
62                 }
63         else
64                 $o = pumpio_connect($a);
65
66         return $o;
67 }
68
69 function pumpio_check_item_notification($a, &$notification_data) {
70         $hostname = PConfig::get($notification_data["uid"], 'pumpio','host');
71         $username = PConfig::get($notification_data["uid"], "pumpio", "user");
72
73         $notification_data["profiles"][] = "https://".$hostname."/".$username;
74 }
75
76
77 function pumpio_registerclient(&$a, $host) {
78
79         $url = "https://".$host."/api/client/register";
80
81         $params = array();
82
83         $application_name  = Config::get('pumpio', 'application_name');
84
85         if ($application_name == "")
86                 $application_name = $a->get_hostname();
87
88         $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
89
90         $params["type"] = "client_associate";
91         $params["contacts"] = $adminlist[0];
92         $params["application_type"] = "native";
93         $params["application_name"] = $application_name;
94         $params["logo_url"] = $a->get_baseurl()."/images/friendica-256.png";
95         $params["redirect_uris"] = $a->get_baseurl()."/pumpio/connect";
96
97         logger("pumpio_registerclient: ".$url." parameters ".print_r($params, true), LOGGER_DEBUG);
98
99         $ch = curl_init($url);
100         curl_setopt($ch, CURLOPT_HEADER, false);
101         curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
102         curl_setopt($ch, CURLOPT_POST,1);
103         curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
104         curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
105
106         $s = curl_exec($ch);
107         $curl_info = curl_getinfo($ch);
108
109         if ($curl_info["http_code"] == "200") {
110                 $values = json_decode($s);
111                 logger("pumpio_registerclient: success ".print_r($values, true), LOGGER_DEBUG);
112                 return($values);
113         }
114         logger("pumpio_registerclient: failed: ".print_r($curl_info, true), LOGGER_DEBUG);
115         return(false);
116
117 }
118
119 function pumpio_connect(&$a) {
120         // Start a session.  This is necessary to hold on to  a few keys the callback script will also need
121         session_start();
122
123         // Define the needed keys
124         $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
125         $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
126         $hostname = PConfig::get(local_user(), 'pumpio','host');
127
128         if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) {
129                 logger("pumpio_connect: register client");
130                 $clientdata = pumpio_registerclient($a, $hostname);
131                 PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
132                 PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
133
134                 $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key');
135                 $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret');
136
137                 logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG);
138         }
139
140         if (($consumer_key == "") || ($consumer_secret == "")) {
141                 logger("pumpio_connect: ".sprintf("Unable to register the client at the pump.io server '%s'.", $hostname));
142
143                 $o .= sprintf(t("Unable to register the client at the pump.io server '%s'."), $hostname);
144                 return($o);
145         }
146
147         // The callback URL is the script that gets called after the user authenticates with pumpio
148         $callback_url = $a->get_baseurl()."/pumpio/connect";
149
150         // Let's begin.  First we need a Request Token.  The request token is required to send the user
151         // to pumpio's login page.
152
153         // Create a new instance of the TumblrOAuth library.  For this step, all we need to give the library is our
154         // Consumer Key and Consumer Secret
155         $client = new oauth_client_class;
156         $client->debug = 1;
157         $client->server = '';
158         $client->oauth_version = '1.0a';
159         $client->request_token_url = 'https://'.$hostname.'/oauth/request_token';
160         $client->dialog_url = 'https://'.$hostname.'/oauth/authorize';
161         $client->access_token_url = 'https://'.$hostname.'/oauth/access_token';
162         $client->url_parameters = false;
163         $client->authorization_header = true;
164         $client->redirect_uri = $callback_url;
165         $client->client_id = $consumer_key;
166         $client->client_secret = $consumer_secret;
167
168         if (($success = $client->Initialize())) {
169                 if (($success = $client->Process())) {
170                         if (strlen($client->access_token)) {
171                                 logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG);
172                                 PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token);
173                                 PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret);
174                         }
175                 }
176                 $success = $client->Finalize($success);
177         }
178         if($client->exit)
179                 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
180
181         if($success) {
182                 logger("pumpio_connect: authenticated");
183                 $o .= t("You are now authenticated to pumpio.");
184                 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
185         } else {
186                 logger("pumpio_connect: could not connect");
187                 $o = 'Could not connect to pumpio. Refresh the page or try again later.';
188         }
189
190         return($o);
191 }
192
193 function pumpio_jot_nets(&$a,&$b) {
194         if(! local_user())
195                 return;
196
197         $pumpio_post = PConfig::get(local_user(),'pumpio','post');
198         if(intval($pumpio_post) == 1) {
199                 $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default');
200                 $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : '');
201                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="pumpio_enable"' . $selected . ' value="1" /> '
202                         . t('Post to pumpio') . '</div>';
203         }
204 }
205
206
207 function pumpio_settings(&$a,&$s) {
208
209         if(! local_user())
210                 return;
211
212         /* Add our stylesheet to the page so we can make our settings look nice */
213
214         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/pumpio/pumpio.css' . '" media="all" />' . "\r\n";
215
216         /* Get the current state of our config variables */
217
218         $import_enabled = PConfig::get(local_user(),'pumpio','import');
219         $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
220
221         $enabled = PConfig::get(local_user(),'pumpio','post');
222         $checked = (($enabled) ? ' checked="checked" ' : '');
223         $css = (($enabled) ? '' : '-disabled');
224
225         $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default');
226         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
227
228         $public_enabled = PConfig::get(local_user(),'pumpio','public');
229         $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
230
231         $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror');
232         $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
233
234         $servername = PConfig::get(local_user(), "pumpio", "host");
235         $username = PConfig::get(local_user(), "pumpio", "user");
236
237         /* Add some HTML to the existing form */
238
239         $s .= '<span id="settings_pumpio_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
240         $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
241         $s .= '</span>';
242         $s .= '<div id="settings_pumpio_expanded" class="settings-block" style="display: none;">';
243         $s .= '<span class="fakelink" onclick="openClose(\'settings_pumpio_expanded\'); openClose(\'settings_pumpio_inflated\');">';
244         $s .= '<img class="connector'.$css.'" src="images/pumpio.png" /><h3 class="connector">'. t('Pump.io Import/Export/Mirror').'</h3>';
245         $s .= '</span>';
246
247         $s .= '<div id="pumpio-username-wrapper">';
248         $s .= '<label id="pumpio-username-label" for="pumpio-username">'.t('pump.io username (without the servername)').'</label>';
249         $s .= '<input id="pumpio-username" type="text" name="pumpio_user" value="'.$username.'" />';
250         $s .= '</div><div class="clear"></div>';
251
252         $s .= '<div id="pumpio-servername-wrapper">';
253         $s .= '<label id="pumpio-servername-label" for="pumpio-servername">'.t('pump.io servername (without "http://" or "https://" )').'</label>';
254         $s .= '<input id="pumpio-servername" type="text" name="pumpio_host" value="'.$servername.'" />';
255         $s .= '</div><div class="clear"></div>';
256
257         if (($username != '') && ($servername != '')) {
258
259                 $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token");
260                 $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret");
261
262                 $s .= '<div id="pumpio-password-wrapper">';
263                 if (($oauth_token == "") || ($oauth_token_secret == "")) {
264                         $s .= '<div id="pumpio-authenticate-wrapper">';
265                         $s .= '<a href="'.$a->get_baseurl().'/pumpio/connect">'.t("Authenticate your pump.io connection").'</a>';
266                         $s .= '</div><div class="clear"></div>';
267                 } else {
268                         $s .= '<div id="pumpio-import-wrapper">';
269                         $s .= '<label id="pumpio-import-label" for="pumpio-import">' . t('Import the remote timeline') . '</label>';
270                         $s .= '<input id="pumpio-import" type="checkbox" name="pumpio_import" value="1" ' . $import_checked . '/>';
271                         $s .= '</div><div class="clear"></div>';
272
273                         $s .= '<div id="pumpio-enable-wrapper">';
274                         $s .= '<label id="pumpio-enable-label" for="pumpio-checkbox">' . t('Enable pump.io Post Plugin') . '</label>';
275                         $s .= '<input id="pumpio-checkbox" type="checkbox" name="pumpio" value="1" ' . $checked . '/>';
276                         $s .= '</div><div class="clear"></div>';
277
278                         $s .= '<div id="pumpio-bydefault-wrapper">';
279                         $s .= '<label id="pumpio-bydefault-label" for="pumpio-bydefault">' . t('Post to pump.io by default') . '</label>';
280                         $s .= '<input id="pumpio-bydefault" type="checkbox" name="pumpio_bydefault" value="1" ' . $def_checked . '/>';
281                         $s .= '</div><div class="clear"></div>';
282
283                         $s .= '<div id="pumpio-public-wrapper">';
284                         $s .= '<label id="pumpio-public-label" for="pumpio-public">' . t('Should posts be public?') . '</label>';
285                         $s .= '<input id="pumpio-public" type="checkbox" name="pumpio_public" value="1" ' . $public_checked . '/>';
286                         $s .= '</div><div class="clear"></div>';
287
288                         $s .= '<div id="pumpio-mirror-wrapper">';
289                         $s .= '<label id="pumpio-mirror-label" for="pumpio-mirror">' . t('Mirror all public posts') . '</label>';
290                         $s .= '<input id="pumpio-mirror" type="checkbox" name="pumpio_mirror" value="1" ' . $mirror_checked . '/>';
291                         $s .= '</div><div class="clear"></div>';
292
293                         $s .= '<div id="pumpio-delete-wrapper">';
294                         $s .= '<label id="pumpio-delete-label" for="pumpio-delete">' . t('Check to delete this preset') . '</label>';
295                         $s .= '<input id="pumpio-delete" type="checkbox" name="pumpio_delete" value="1" />';
296                         $s .= '</div><div class="clear"></div>';
297                 }
298
299                 $s .= '</div><div class="clear"></div>';
300         }
301
302         /* provide a submit button */
303
304         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="pumpio-submit" name="pumpio-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
305 }
306
307
308 function pumpio_settings_post(&$a,&$b) {
309
310         if(x($_POST,'pumpio-submit')) {
311                 if(x($_POST,'pumpio_delete')) {
312                         PConfig::set(local_user(),'pumpio','consumer_key','');
313                         PConfig::set(local_user(),'pumpio','consumer_secret','');
314                         PConfig::set(local_user(),'pumpio','oauth_token','');
315                         PConfig::set(local_user(),'pumpio','oauth_token_secret','');
316                         PConfig::set(local_user(),'pumpio','post',false);
317                         PConfig::set(local_user(),'pumpio','import',false);
318                         PConfig::set(local_user(),'pumpio','host','');
319                         PConfig::set(local_user(),'pumpio','user','');
320                         PConfig::set(local_user(),'pumpio','public',false);
321                         PConfig::set(local_user(),'pumpio','mirror',false);
322                         PConfig::set(local_user(),'pumpio','post_by_default',false);
323                         PConfig::set(local_user(),'pumpio','lastdate', 0);
324                         PConfig::set(local_user(),'pumpio','last_id', '');
325                 } else {
326                         // filtering the username if it is filled wrong
327                         $user = $_POST['pumpio_user'];
328                         if (strstr($user, "@")) {
329                                 $pos = strpos($user, "@");
330                                 if ($pos > 0)
331                                         $user = substr($user, 0, $pos);
332                         }
333
334                         // Filtering the hostname if someone is entering it with "http"
335                         $host = $_POST['pumpio_host'];
336                         $host = trim($host);
337                         $host = str_replace(array("https://", "http://"), array("", ""), $host);
338
339                         PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio']));
340                         PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']);
341                         PConfig::set(local_user(),'pumpio','host',$host);
342                         PConfig::set(local_user(),'pumpio','user',$user);
343                         PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']);
344                         PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
345                         PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault']));
346
347                         if (!$_POST['pumpio_mirror'])
348                                 del_pconfig(local_user(),'pumpio','lastdate');
349
350                         //header("Location: ".$a->get_baseurl()."/pumpio/connect");
351                 }
352         }
353 }
354
355 function pumpio_post_local(&$a, &$b) {
356
357         if (!local_user() || (local_user() != $b['uid'])) {
358                 return;
359         }
360
361         $pumpio_post   = intval(PConfig::get(local_user(), 'pumpio', 'post'));
362
363         $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0);
364
365         if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) {
366                 $pumpio_enable = 1;
367         }
368
369         if (!$pumpio_enable) {
370                 return;
371         }
372
373         if (strlen($b['postopts'])) {
374                 $b['postopts'] .= ',';
375         }
376
377         $b['postopts'] .= 'pumpio';
378 }
379
380
381
382
383 function pumpio_send(&$a,&$b) {
384
385         if (!PConfig::get($b["uid"],'pumpio','import')) {
386                 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
387                         return;
388         }
389
390         logger("pumpio_send: parameter ".print_r($b, true), LOGGER_DATA);
391
392         if($b['parent'] != $b['id']) {
393                 // Looking if its a reply to a pumpio post
394                 $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",
395                         intval($b["parent"]),
396                         intval($b["uid"]),
397                         dbesc(NETWORK_PUMPIO));
398
399                 if(!count($r)) {
400                         logger("pumpio_send: no pumpio post ".$b["parent"]);
401                         return;
402                 } else {
403                         $iscomment = true;
404                         $orig_post = $r[0];
405                 }
406         } else {
407                 $iscomment = false;
408
409                 $receiver = pumpio_getreceiver($a, $b);
410
411                 logger("pumpio_send: receiver ".print_r($receiver, true));
412
413                 if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio')))
414                         return;
415         }
416
417         if($b['verb'] == ACTIVITY_LIKE) {
418                 if ($b['deleted'])
419                         pumpio_action($a, $b["uid"], $b["thr-parent"], "unlike");
420                 else
421                         pumpio_action($a, $b["uid"], $b["thr-parent"], "like");
422                 return;
423         }
424
425         if($b['verb'] == ACTIVITY_DISLIKE)
426                 return;
427
428         if (($b['verb'] == ACTIVITY_POST) && ($b['created'] !== $b['edited']) && !$b['deleted'])
429                         pumpio_action($a, $b["uid"], $b["uri"], "update", $b["body"]);
430
431         if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
432                         pumpio_action($a, $b["uid"], $b["uri"], "delete");
433
434         if($b['deleted'] || ($b['created'] !== $b['edited']))
435                 return;
436
437         // if post comes from pump.io don't send it back
438         if($b['app'] == "pump.io")
439                 return;
440
441         // To-Do;
442         // Support for native shares
443         // http://<hostname>/api/<type>/shares?id=<the-object-id>
444
445         $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token");
446         $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret");
447         $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key");
448         $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret");
449
450         $host = PConfig::get($b['uid'], "pumpio", "host");
451         $user = PConfig::get($b['uid'], "pumpio", "user");
452         $public = PConfig::get($b['uid'], "pumpio", "public");
453
454         if($oauth_token && $oauth_token_secret) {
455
456                 require_once('include/bbcode.php');
457
458                 $title = trim($b['title']);
459
460                 $content = bbcode($b['body'], false, false, 4);
461
462                 $params = array();
463
464                 $params["verb"] = "post";
465
466                 if (!$iscomment) {
467                         $params["object"] = array(
468                                                 'objectType' => "note",
469                                                 'content' => $content);
470
471                         if ($title != "")
472                                 $params["object"]["displayName"] = $title;
473
474                         if (count($receiver["to"]))
475                                 $params["to"] = $receiver["to"];
476
477                         if (count($receiver["bto"]))
478                                 $params["bto"] = $receiver["bto"];
479
480                         if (count($receiver["cc"]))
481                                 $params["cc"] = $receiver["cc"];
482
483                         if (count($receiver["bcc"]))
484                                 $params["bcc"] = $receiver["bcc"];
485
486                  } else {
487                         $inReplyTo = array("id" => $orig_post["uri"],
488                                         "objectType" => "note");
489
490                         if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
491                                 $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
492
493                         $params["object"] = array(
494                                                 'objectType' => "comment",
495                                                 'content' => $content,
496                                                 'inReplyTo' => $inReplyTo);
497
498                         if ($title != "")
499                                 $params["object"]["displayName"] = $title;
500                 }
501
502                 $client = new oauth_client_class;
503                 $client->oauth_version = '1.0a';
504                 $client->url_parameters = false;
505                 $client->authorization_header = true;
506                 $client->access_token = $oauth_token;
507                 $client->access_token_secret = $oauth_token_secret;
508                 $client->client_id = $consumer_key;
509                 $client->client_secret = $consumer_secret;
510
511                 $username = $user.'@'.$host;
512                 $url = 'https://'.$host.'/api/user/'.$user.'/feed';
513
514                 if (pumpio_reachable($url))
515                         $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
516                 else
517                         $success = false;
518
519                 if($success) {
520
521                         if ($user->generator->displayName)
522                                 PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName);
523
524                         $post_id = $user->object->id;
525                         logger('pumpio_send '.$username.': success '.$post_id);
526                         if($post_id && $iscomment) {
527                                 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
528                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
529                                         dbesc($post_id),
530                                         intval($b['id'])
531                                 );
532                         }
533                 } else {
534                         logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
535
536                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
537                         if (count($r))
538                                 $a->contact = $r[0]["id"];
539
540                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
541                         require_once('include/queue_fn.php');
542                         add_to_queue($a->contact,NETWORK_PUMPIO,$s);
543                         notice(t('Pump.io post failed. Queued for retry.').EOL);
544                 }
545
546         }
547 }
548
549 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
550
551         // Don't do likes and other stuff if you don't import the timeline
552         if (!PConfig::get($uid,'pumpio','import'))
553                 return;
554
555         $ckey    = PConfig::get($uid, 'pumpio', 'consumer_key');
556         $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
557         $otoken  = PConfig::get($uid, 'pumpio', 'oauth_token');
558         $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
559         $hostname = PConfig::get($uid, 'pumpio','host');
560         $username = PConfig::get($uid, "pumpio", "user");
561
562         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
563                                 dbesc($uri),
564                                 intval($uid)
565         );
566
567         if (!count($r))
568                 return;
569
570         $orig_post = $r[0];
571
572         if ($orig_post["extid"] && !strstr($orig_post["extid"], "/proxy/"))
573                 $uri = $orig_post["extid"];
574         else
575                 $uri = $orig_post["uri"];
576
577         if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
578                 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
579         elseif (strstr($uri, "/api/comment/"))
580                 $objectType = "comment";
581         elseif (strstr($uri, "/api/note/"))
582                 $objectType = "note";
583         elseif (strstr($uri, "/api/image/"))
584                 $objectType = "image";
585
586         $params["verb"] = $action;
587         $params["object"] = array('id' => $uri,
588                                 "objectType" => $objectType,
589                                 "content" => $content);
590
591         $client = new oauth_client_class;
592         $client->oauth_version = '1.0a';
593         $client->authorization_header = true;
594         $client->url_parameters = false;
595
596         $client->client_id = $ckey;
597         $client->client_secret = $csecret;
598         $client->access_token = $otoken;
599         $client->access_token_secret = $osecret;
600
601         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
602
603         if (pumpio_reachable($url))
604                 $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
605         else
606                 $success = false;
607
608         if($success)
609                 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
610         else {
611                 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
612
613                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
614                 if (count($r))
615                         $a->contact = $r[0]["id"];
616
617                 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
618                 require_once('include/queue_fn.php');
619                 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
620                 notice(t('Pump.io like failed. Queued for retry.').EOL);
621         }
622 }
623
624 function pumpio_sync(&$a) {
625         $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = 'pumpio'",
626                 $plugin);
627
628         if (!count($r))
629                 return;
630
631         $last = Config::get('pumpio','last_poll');
632
633         $poll_interval = intval(Config::get('pumpio','poll_interval'));
634         if(! $poll_interval)
635                 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
636
637         if($last) {
638                 $next = $last + ($poll_interval * 60);
639                 if($next > time()) {
640                         logger('pumpio: poll intervall not reached');
641                         return;
642                 }
643         }
644         logger('pumpio: cron_start');
645
646         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
647         if(count($r)) {
648                 foreach($r as $rr) {
649                         logger('pumpio: mirroring user '.$rr['uid']);
650                         pumpio_fetchtimeline($a, $rr['uid']);
651                 }
652         }
653
654         $abandon_days = intval(Config::get('system','account_abandon_days'));
655         if ($abandon_days < 1)
656                 $abandon_days = 0;
657
658         $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
659
660         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
661         if(count($r)) {
662                 foreach($r as $rr) {
663                         if ($abandon_days != 0) {
664                                 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
665                                 if (!count($user)) {
666                                         logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
667                                         continue;
668                                 }
669                         }
670
671                         logger('pumpio: importing timeline from user '.$rr['uid']);
672                         pumpio_fetchinbox($a, $rr['uid']);
673
674                         // check for new contacts once a day
675                         $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
676                         if($last_contact_check)
677                                 $next_contact_check = $last_contact_check + 86400;
678                         else
679                                 $next_contact_check = 0;
680
681                         if($next_contact_check <= time()) {
682                                 pumpio_getallusers($a, $rr["uid"]);
683                                 PConfig::set($rr['uid'],'pumpio','contact_check',time());
684                         }
685                 }
686         }
687
688         logger('pumpio: cron_end');
689
690         Config::set('pumpio','last_poll', time());
691 }
692
693 function pumpio_cron(&$a,$b) {
694         //pumpio_sync($a);
695         proc_run("php","addon/pumpio/pumpio_sync.php");
696 }
697
698 function pumpio_fetchtimeline(&$a, $uid) {
699         $ckey    = PConfig::get($uid, 'pumpio', 'consumer_key');
700         $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
701         $otoken  = PConfig::get($uid, 'pumpio', 'oauth_token');
702         $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
703         $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
704         $hostname = PConfig::get($uid, 'pumpio','host');
705         $username = PConfig::get($uid, "pumpio", "user");
706
707         //  get the application name for the pump.io app
708         //  1st try personal config, then system config and fallback to the
709         //  hostname of the node if neither one is set.
710         $application_name  = PConfig::get( $uid, 'pumpio', 'application_name');
711         if ($application_name == "")
712                 $application_name  = Config::get('pumpio', 'application_name');
713         if ($application_name == "")
714                 $application_name = $a->get_hostname();
715
716         $first_time = ($lastdate == "");
717
718         $client = new oauth_client_class;
719         $client->oauth_version = '1.0a';
720         $client->authorization_header = true;
721         $client->url_parameters = false;
722
723         $client->client_id = $ckey;
724         $client->client_secret = $csecret;
725         $client->access_token = $otoken;
726         $client->access_token_secret = $osecret;
727
728         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
729
730         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
731
732         $username = $user.'@'.$host;
733
734         if (pumpio_reachable($url))
735                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
736         else
737                 $success = false;
738
739         if (!$success) {
740                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
741                 return;
742         }
743
744         $posts = array_reverse($user->items);
745
746         $initiallastdate = $lastdate;
747         $lastdate = '';
748
749         if (count($posts)) {
750                 foreach ($posts as $post) {
751                         if ($post->published <= $initiallastdate)
752                                 continue;
753
754                         if ($lastdate < $post->published)
755                                 $lastdate = $post->published;
756
757                         if ($first_time)
758                                 continue;
759
760                         $receiptians = array();
761                         if (@is_array($post->cc))
762                                 $receiptians = array_merge($receiptians, $post->cc);
763
764                         if (@is_array($post->to))
765                                 $receiptians = array_merge($receiptians, $post->to);
766
767                         $public = false;
768                         foreach ($receiptians AS $receiver)
769                                 if (is_string($receiver->objectType))
770                                         if ($receiver->id == "http://activityschema.org/collection/public")
771                                                 $public = true;
772
773                         if ($public && !stristr($post->generator->displayName, $application_name)) {
774                                 require_once('include/html2bbcode.php');
775
776                                 $_SESSION["authenticated"] = true;
777                                 $_SESSION["uid"] = $uid;
778
779                                 unset($_REQUEST);
780                                 $_REQUEST["type"] = "wall";
781                                 $_REQUEST["api_source"] = true;
782                                 $_REQUEST["profile_uid"] = $uid;
783                                 $_REQUEST["source"] = "pump.io";
784
785                                 if (isset($post->object->id)) {
786                                         $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
787                                 }
788
789                                 if ($post->object->displayName != "")
790                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
791                                 else
792                                         $_REQUEST["title"] = "";
793
794                                 $_REQUEST["body"] = html2bbcode($post->object->content);
795
796                                 // To-Do: Picture has to be cached and stored locally
797                                 if ($post->object->fullImage->url != "") {
798                                         if ($post->object->fullImage->pump_io->proxyURL != "")
799                                                 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
800                                         else
801                                                 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
802                                 }
803
804                                 logger('pumpio: posting for user '.$uid);
805
806                                 require_once('mod/item.php');
807
808                                 item_post($a);
809                                 logger('pumpio: posting done - user '.$uid);
810                         }
811                 }
812         }
813
814         if ($lastdate != 0)
815                 PConfig::set($uid,'pumpio','lastdate', $lastdate);
816 }
817
818 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
819         // Searching for the unliked post
820         // Two queries for speed issues
821         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
822                                 dbesc($post->object->id),
823                                 intval($uid)
824                 );
825
826         if (count($r))
827                 $orig_post = $r[0];
828         else {
829                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
830                                         dbesc($post->object->id),
831                                         intval($uid)
832                         );
833
834                 if (!count($r))
835                         return;
836                 else
837                         $orig_post = $r[0];
838         }
839
840         $contactid = 0;
841
842         if(link_compare($post->actor->url, $own_id)) {
843                 $contactid = $self[0]['id'];
844         } else {
845                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
846                         dbesc(normalise_link($post->actor->url)),
847                         intval($uid)
848                 );
849
850                 if(count($r))
851                         $contactid = $r[0]['id'];
852
853                 if($contactid == 0)
854                         $contactid = $orig_post['contact-id'];
855         }
856
857         $r = q("UPDATE `item` SET `deleted` = 1, `unseen` = 1, `changed` = '%s' WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s'",
858                 dbesc(datetime_convert()),
859                 dbesc(ACTIVITY_LIKE),
860                 intval($uid),
861                 intval($contactid),
862                 dbesc($orig_post['uri'])
863         );
864
865         if(count($r))
866                 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
867         else
868                 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
869 }
870
871 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
872         require_once('include/items.php');
873
874         if ($post->object->id == "") {
875                 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
876                 return;
877         }
878
879         // Searching for the liked post
880         // Two queries for speed issues
881         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
882                                 dbesc($post->object->id),
883                                 intval($uid),
884                                 dbesc(NETWORK_PUMPIO)
885                 );
886
887         if (count($r))
888                 $orig_post = $r[0];
889         else {
890                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
891                                         dbesc($post->object->id),
892                                         intval($uid),
893                                         dbesc(NETWORK_PUMPIO)
894                         );
895
896                 if (!count($r))
897                         return;
898                 else
899                         $orig_post = $r[0];
900         }
901
902         // thread completion
903         if ($threadcompletion)
904                 pumpio_fetchallcomments($a, $uid, $post->object->id);
905
906         $contactid = 0;
907
908         if(link_compare($post->actor->url, $own_id)) {
909                 $contactid = $self[0]['id'];
910                 $post->actor->displayName = $self[0]['name'];
911                 $post->actor->url = $self[0]['url'];
912                 $post->actor->image->url = $self[0]['photo'];
913         } else {
914                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
915                         dbesc(normalise_link($post->actor->url)),
916                         intval($uid)
917                 );
918
919                 if(count($r))
920                         $contactid = $r[0]['id'];
921
922                 if($contactid == 0)
923                         $contactid = $orig_post['contact-id'];
924         }
925
926         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
927                 dbesc(ACTIVITY_LIKE),
928                 intval($uid),
929                 intval($contactid),
930                 dbesc($orig_post['uri'])
931         );
932
933         if(count($r)) {
934                 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
935                 return;
936         }
937
938         $likedata = array();
939         $likedata['parent'] = $orig_post['id'];
940         $likedata['verb'] = ACTIVITY_LIKE;
941         $likedata['gravity'] = 3;
942         $likedata['uid'] = $uid;
943         $likedata['wall'] = 0;
944         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
945         $likedata['parent-uri'] = $orig_post["uri"];
946         $likedata['contact-id'] = $contactid;
947         $likedata['app'] = $post->generator->displayName;
948         $likedata['author-name'] = $post->actor->displayName;
949         $likedata['author-link'] = $post->actor->url;
950         $likedata['author-avatar'] = $post->actor->image->url;
951
952         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
953         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
954         $post_type = t('status');
955         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
956         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
957
958         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
959
960         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
961                 '<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>';
962
963         $ret = item_store($likedata);
964
965         logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
966 }
967
968 function pumpio_get_contact($uid, $contact, $no_insert = false) {
969
970         update_gcontact(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
971                         "photo" => $contact->image->url, "name" => $contact->displayName,  "hide" => true,
972                         "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
973                         "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
974         $cid = get_contact($contact->url, $uid);
975
976         if ($no_insert)
977                 return($cid);
978
979         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
980                 intval($uid), dbesc(normalise_link($contact->url)));
981
982         if (!count($r)) {
983                 // create contact record
984                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
985                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
986                                         `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
987                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
988                         intval($uid),
989                         dbesc(datetime_convert()),
990                         dbesc($contact->url),
991                         dbesc(normalise_link($contact->url)),
992                         dbesc(str_replace("acct:", "", $contact->id)),
993                         dbesc(''),
994                         dbesc($contact->id), // What is it for?
995                         dbesc('pump.io ' . $contact->id), // What is it for?
996                         dbesc($contact->displayName),
997                         dbesc($contact->preferredUsername),
998                         dbesc($contact->image->url),
999                         dbesc(NETWORK_PUMPIO),
1000                         intval(CONTACT_IS_FRIEND),
1001                         intval(1),
1002                         dbesc($contact->location->displayName),
1003                         dbesc($contact->summary),
1004                         intval(1)
1005                 );
1006
1007                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1008                         dbesc(normalise_link($contact->url)),
1009                         intval($uid)
1010                         );
1011
1012                 if (!count($r)) {
1013                         return(false);
1014                 }
1015
1016                 $contact_id = $r[0]['id'];
1017
1018                 $g = q("select def_gid from user where uid = %d limit 1",
1019                         intval($uid)
1020                 );
1021
1022                 if($g && intval($g[0]['def_gid'])) {
1023                         require_once('include/group.php');
1024                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1025                 }
1026         } else {
1027                 $contact_id = $r[0]["id"];
1028
1029                 /*      if (DB_UPDATE_VERSION >= "1177")
1030                                 q("UPDATE `contact` SET `location` = '%s',
1031                                                         `about` = '%s'
1032                                                 WHERE `id` = %d",
1033                                         dbesc($contact->location->displayName),
1034                                         dbesc($contact->summary),
1035                                         intval($r[0]['id'])
1036                                 );
1037                 */
1038         }
1039
1040         if (function_exists("update_contact_avatar"))
1041                 update_contact_avatar($contact->image->url, $uid, $contact_id);
1042
1043         return($contact_id);
1044 }
1045
1046 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1047
1048         // Two queries for speed issues
1049         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1050                                 dbesc($post->object->id),
1051                                 intval($uid)
1052                 );
1053
1054         if (count($r))
1055                 return drop_item($r[0]["id"], $false);
1056
1057         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1058                                 dbesc($post->object->id),
1059                                 intval($uid)
1060                 );
1061
1062         if (count($r))
1063                 return drop_item($r[0]["id"], $false);
1064 }
1065
1066 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1067         require_once('include/items.php');
1068         require_once('include/html2bbcode.php');
1069
1070         if (($post->verb == "like") || ($post->verb == "favorite"))
1071                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1072
1073         if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1074                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1075
1076         if ($post->verb == "delete")
1077                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1078
1079         if ($post->verb != "update") {
1080                 // Two queries for speed issues
1081                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1082                                         dbesc($post->object->id),
1083                                         intval($uid)
1084                         );
1085
1086                 if (count($r))
1087                         return false;
1088
1089                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1090                                         dbesc($post->object->id),
1091                                         intval($uid)
1092                         );
1093
1094                 if (count($r))
1095                         return false;
1096         }
1097
1098         // Only handle these three types
1099         if (!strstr("post|share|update", $post->verb))
1100                 return false;
1101
1102         $receiptians = array();
1103         if (@is_array($post->cc))
1104                 $receiptians = array_merge($receiptians, $post->cc);
1105
1106         if (@is_array($post->to))
1107                 $receiptians = array_merge($receiptians, $post->to);
1108
1109         foreach ($receiptians AS $receiver)
1110                 if (is_string($receiver->objectType))
1111                         if ($receiver->id == "http://activityschema.org/collection/public")
1112                                 $public = true;
1113
1114         $postarray = array();
1115         $postarray['network'] = NETWORK_PUMPIO;
1116         $postarray['gravity'] = 0;
1117         $postarray['uid'] = $uid;
1118         $postarray['wall'] = 0;
1119         $postarray['uri'] = $post->object->id;
1120         $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1121
1122         if ($post->object->objectType != "comment") {
1123                 $contact_id = pumpio_get_contact($uid, $post->actor);
1124
1125                 if (!$contact_id)
1126                         $contact_id = $self[0]['id'];
1127
1128                 $postarray['parent-uri'] = $post->object->id;
1129
1130                 if (!$public) {
1131                         $postarray['private'] = 1;
1132                         $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1133                 }
1134         } else {
1135                 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1136
1137                 if (link_compare($post->actor->url, $own_id)) {
1138                         $contact_id = $self[0]['id'];
1139                         $post->actor->displayName = $self[0]['name'];
1140                         $post->actor->url = $self[0]['url'];
1141                         $post->actor->image->url = $self[0]['photo'];
1142                 } elseif ($contact_id == 0) {
1143                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1144                         $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1145                                 dbesc(normalise_link($post->actor->url)),
1146                                 intval($uid)
1147                         );
1148
1149                         if(count($r))
1150                                 $contact_id = $r[0]['id'];
1151                         else {
1152                                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1153                                         dbesc(normalise_link($post->actor->url)),
1154                                         intval($uid)
1155                                 );
1156
1157                                 if(count($r))
1158                                         $contact_id = $r[0]['id'];
1159                                 else
1160                                         $contact_id = $self[0]['id'];
1161                         }
1162                 }
1163
1164                 $reply = new stdClass;
1165                 $reply->verb = "note";
1166                 $reply->cc = $post->cc;
1167                 $reply->to = $post->to;
1168                 $reply->object = new stdClass;
1169                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1170                 $reply->object->content = $post->object->inReplyTo->content;
1171                 $reply->object->id = $post->object->inReplyTo->id;
1172                 $reply->actor = $post->object->inReplyTo->author;
1173                 $reply->url = $post->object->inReplyTo->url;
1174                 $reply->generator = new stdClass;
1175                 $reply->generator->displayName = "pumpio";
1176                 $reply->published = $post->object->inReplyTo->published;
1177                 $reply->received = $post->object->inReplyTo->updated;
1178                 $reply->url = $post->object->inReplyTo->url;
1179                 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1180
1181                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1182         }
1183
1184         if ($post->object->pump_io->proxyURL)
1185                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1186
1187         $postarray['contact-id'] = $contact_id;
1188         $postarray['verb'] = ACTIVITY_POST;
1189         $postarray['owner-name'] = $post->actor->displayName;
1190         $postarray['owner-link'] = $post->actor->url;
1191         $postarray['owner-avatar'] = $post->actor->image->url;
1192         $postarray['author-name'] = $post->actor->displayName;
1193         $postarray['author-link'] = $post->actor->url;
1194         $postarray['author-avatar'] = $post->actor->image->url;
1195         $postarray['plink'] = $post->object->url;
1196         $postarray['app'] = $post->generator->displayName;
1197         $postarray['body'] = html2bbcode($post->object->content);
1198         $postarray['object'] = json_encode($post);
1199
1200         if ($post->object->fullImage->url != "")
1201                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1202
1203         if ($post->object->displayName != "")
1204                 $postarray['title'] = $post->object->displayName;
1205
1206         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1207         if (isset($post->updated))
1208                 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1209         elseif (isset($post->received))
1210                 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1211         else
1212                 $postarray['edited'] = $postarray['created'];
1213
1214         if ($post->verb == "share") {
1215                 if (!intval(Config::get('system','wall-to-wall_share'))) {
1216                         if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1217                                 $share_author = $post->object->author->displayName;
1218                         elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1219                                 $share_author = $post->object->author->preferredUsername;
1220                         else
1221                                 $share_author = $post->object->author->url;
1222
1223                         $postarray['body'] = share_header($share_author, $post->object->author->url,
1224                                                         $post->object->author->image->url, "",
1225                                                         datetime_convert('UTC','UTC',$post->object->created),
1226                                                         $post->links->self->href).
1227                                                 $postarray['body']."[/share]";
1228
1229                         /*
1230                         $postarray['body'] = "[share author='".$share_author.
1231                                         "' profile='".$post->object->author->url.
1232                                         "' avatar='".$post->object->author->image->url.
1233                                         "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1234                                         "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1235                         */
1236                 } else {
1237                         // Let shares look like wall-to-wall posts
1238                         $postarray['author-name'] = $post->object->author->displayName;
1239                         $postarray['author-link'] = $post->object->author->url;
1240                         $postarray['author-avatar'] = $post->object->author->image->url;
1241                 }
1242         }
1243
1244         if (trim($postarray['body']) == "")
1245                 return false;
1246
1247         $top_item = item_store($postarray);
1248         $postarray["id"] = $top_item;
1249
1250         if (($top_item == 0) && ($post->verb == "update")) {
1251                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1252                         dbesc($postarray["title"]),
1253                         dbesc($postarray["body"]),
1254                         dbesc($postarray["edited"]),
1255                         dbesc($postarray["uri"]),
1256                         intval($uid)
1257                         );
1258         }
1259
1260         if ($post->object->objectType == "comment") {
1261
1262                 if ($threadcompletion)
1263                         pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1264
1265                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1266                                 intval($uid)
1267                         );
1268
1269                 if(!count($user))
1270                         return $top_item;
1271
1272                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1273
1274                 if (link_compare($own_id, $postarray['author-link']))
1275                         return $top_item;
1276
1277                 if (!function_exists("check_item_notification")) {
1278                         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1279                                         dbesc($postarray['parent-uri']),
1280                                         intval($uid)
1281                                         );
1282
1283                         if(count($myconv)) {
1284
1285                                 foreach($myconv as $conv) {
1286                                         // now if we find a match, it means we're in this conversation
1287
1288                                         if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1289                                                 continue;
1290
1291                                         require_once('include/enotify.php');
1292
1293                                         $conv_parent = $conv['parent'];
1294
1295                                         notification(array(
1296                                                 'type'         => NOTIFY_COMMENT,
1297                                                 'notify_flags' => $user[0]['notify-flags'],
1298                                                 'language'     => $user[0]['language'],
1299                                                 'to_name'      => $user[0]['username'],
1300                                                 'to_email'     => $user[0]['email'],
1301                                                 'uid'          => $user[0]['uid'],
1302                                                 'item'         => $postarray,
1303                                                 'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1304                                                 'source_name'  => $postarray['author-name'],
1305                                                 'source_link'  => $postarray['author-link'],
1306                                                 'source_photo' => $postarray['author-avatar'],
1307                                                 'verb'         => ACTIVITY_POST,
1308                                                 'otype'        => 'item',
1309                                                 'parent'       => $conv_parent,
1310                                                 ));
1311
1312                                         // only send one notification
1313                                         break;
1314                                 }
1315                         }
1316                 }
1317         }
1318
1319         return $top_item;
1320 }
1321
1322 function pumpio_fetchinbox(&$a, $uid) {
1323
1324         $ckey    = PConfig::get($uid, 'pumpio', 'consumer_key');
1325         $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1326         $otoken  = PConfig::get($uid, 'pumpio', 'oauth_token');
1327         $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1328         $lastdate = PConfig::get($uid, 'pumpio', 'lastdate');
1329         $hostname = PConfig::get($uid, 'pumpio','host');
1330         $username = PConfig::get($uid, "pumpio", "user");
1331
1332         $own_id = "https://".$hostname."/".$username;
1333
1334         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1335                 intval($uid));
1336
1337         $lastitems = q("SELECT `uri` FROM `thread`
1338                         INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1339                         WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1340                         ORDER BY `thread`.`commented` DESC LIMIT 10",
1341                                 dbesc(NETWORK_PUMPIO),
1342                                 intval($uid)
1343                         );
1344
1345         $client = new oauth_client_class;
1346         $client->oauth_version = '1.0a';
1347         $client->authorization_header = true;
1348         $client->url_parameters = false;
1349
1350         $client->client_id = $ckey;
1351         $client->client_secret = $csecret;
1352         $client->access_token = $otoken;
1353         $client->access_token_secret = $osecret;
1354
1355         $last_id = PConfig::get($uid,'pumpio','last_id');
1356
1357         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1358
1359         if ($last_id != "")
1360                 $url .= '?since='.urlencode($last_id);
1361
1362         if (pumpio_reachable($url))
1363                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1364         else
1365                 $success = false;
1366
1367         if ($user->items) {
1368             $posts = array_reverse($user->items);
1369
1370             if (count($posts))
1371                     foreach ($posts as $post) {
1372                             $last_id = $post->id;
1373                             pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1374                     }
1375         }
1376
1377         foreach ($lastitems AS $item)
1378                 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1379
1380         PConfig::set($uid,'pumpio','last_id', $last_id);
1381 }
1382
1383 function pumpio_getallusers(&$a, $uid) {
1384         $ckey    = PConfig::get($uid, 'pumpio', 'consumer_key');
1385         $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1386         $otoken  = PConfig::get($uid, 'pumpio', 'oauth_token');
1387         $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1388         $hostname = PConfig::get($uid, 'pumpio','host');
1389         $username = PConfig::get($uid, "pumpio", "user");
1390
1391         $client = new oauth_client_class;
1392         $client->oauth_version = '1.0a';
1393         $client->authorization_header = true;
1394         $client->url_parameters = false;
1395
1396         $client->client_id = $ckey;
1397         $client->client_secret = $csecret;
1398         $client->access_token = $otoken;
1399         $client->access_token_secret = $osecret;
1400
1401         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1402
1403         if (pumpio_reachable($url))
1404                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1405         else
1406                 $success = false;
1407
1408         if ($users->totalItems > count($users->items)) {
1409                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1410
1411                 if (pumpio_reachable($url))
1412                         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1413                 else
1414                         $success = false;
1415         }
1416
1417         if (is_array($users->items)) {
1418                 foreach ($users->items AS $user) {
1419                         pumpio_get_contact($uid, $user);
1420                 }
1421         }
1422 }
1423
1424 function pumpio_queue_hook(&$a,&$b) {
1425
1426         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1427                 dbesc(NETWORK_PUMPIO)
1428         );
1429         if(! count($qi))
1430                 return;
1431
1432         require_once('include/queue_fn.php');
1433
1434         foreach($qi as $x) {
1435                 if($x['network'] !== NETWORK_PUMPIO)
1436                         continue;
1437
1438                 logger('pumpio_queue: run');
1439
1440                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1441                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1442                         intval($x['cid'])
1443                 );
1444                 if(! count($r))
1445                         continue;
1446
1447                 $userdata = $r[0];
1448
1449                 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1450
1451                 $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token");
1452                 $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret");
1453                 $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key");
1454                 $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret");
1455
1456                 $host = PConfig::get($userdata['uid'], "pumpio", "host");
1457                 $user = PConfig::get($userdata['uid'], "pumpio", "user");
1458
1459                 $success = false;
1460
1461                 if ($oauth_token && $oauth_token_secret &&
1462                         $consumer_key && $consumer_secret) {
1463                         $username = $user.'@'.$host;
1464
1465                         logger('pumpio_queue: able to post for user '.$username);
1466
1467                         $z = unserialize($x['content']);
1468
1469                         $client = new oauth_client_class;
1470                         $client->oauth_version = '1.0a';
1471                         $client->url_parameters = false;
1472                         $client->authorization_header = true;
1473                         $client->access_token = $oauth_token;
1474                         $client->access_token_secret = $oauth_token_secret;
1475                         $client->client_id = $consumer_key;
1476                         $client->client_secret = $consumer_secret;
1477
1478                         if (pumpio_reachable($z['url']))
1479                                 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1480                         else
1481                                 $success = false;
1482
1483                         if($success) {
1484                                 $post_id = $user->object->id;
1485                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1486                                 if($post_id && $iscomment) {
1487                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1488                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1489                                                 dbesc($post_id),
1490                                                 intval($z['item'])
1491                                         );
1492                                 }
1493                                 remove_queue_item($x['id']);
1494                         } else
1495                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1496                 } else
1497                         logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1498
1499                 if (!$success) {
1500                         logger('pumpio_queue: delayed');
1501                         update_queue_time($x['id']);
1502                 }
1503         }
1504 }
1505
1506 function pumpio_getreceiver(&$a, $b) {
1507
1508         $receiver = array();
1509
1510         if (!$b["private"]) {
1511
1512                 if(! strstr($b['postopts'],'pumpio'))
1513                         return $receiver;
1514
1515                 $public = PConfig::get($b['uid'], "pumpio", "public");
1516
1517                 if ($public)
1518                         $receiver["to"][] = Array(
1519                                                 "objectType" => "collection",
1520                                                 "id" => "http://activityschema.org/collection/public");
1521         } else {
1522                 $cids = explode("><", $b["allow_cid"]);
1523                 $gids = explode("><", $b["allow_gid"]);
1524
1525                 foreach ($cids AS $cid) {
1526                         $cid = trim($cid, " <>");
1527
1528                         $r = q("SELECT `name`, `nick`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `network` = '%s' AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1529                                 intval($cid),
1530                                 intval($b["uid"]),
1531                                 dbesc(NETWORK_PUMPIO)
1532                                 );
1533
1534                         if (count($r)) {
1535                                 $receiver["bcc"][] = Array(
1536                                                         "displayName" => $r[0]["name"],
1537                                                         "objectType" => "person",
1538                                                         "preferredUsername" => $r[0]["nick"],
1539                                                         "url" => $r[0]["url"]);
1540                         }
1541                 }
1542                 foreach ($gids AS $gid) {
1543                         $gid = trim($gid, " <>");
1544
1545                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1546                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1547                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1548                                         intval($gid),
1549                                         intval($b["uid"]),
1550                                         dbesc(NETWORK_PUMPIO)
1551                                 );
1552
1553                         foreach ($r AS $row)
1554                                 $receiver["bcc"][] = Array(
1555                                                         "displayName" => $row["name"],
1556                                                         "objectType" => "person",
1557                                                         "preferredUsername" => $row["nick"],
1558                                                         "url" => $row["url"]);
1559                 }
1560         }
1561
1562         if ($b["inform"] != "") {
1563
1564                 $inform = explode(",", $b["inform"]);
1565
1566                 foreach ($inform AS $cid) {
1567                         if (substr($cid, 0, 4) != "cid:")
1568                                 continue;
1569
1570                         $cid = str_replace("cid:", "", $cid);
1571
1572                         $r = q("SELECT `name`, `nick`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `network` = '%s' AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1573                                 intval($cid),
1574                                 intval($b["uid"]),
1575                                 dbesc(NETWORK_PUMPIO)
1576                                 );
1577
1578                         if (count($r)) {
1579                                         $receiver["to"][] = Array(
1580                                                                 "displayName" => $r[0]["name"],
1581                                                                 "objectType" => "person",
1582                                                                 "preferredUsername" => $r[0]["nick"],
1583                                                                 "url" => $r[0]["url"]);
1584                         }
1585                 }
1586         }
1587
1588         return $receiver;
1589 }
1590
1591 function pumpio_fetchallcomments(&$a, $uid, $id) {
1592         $ckey    = PConfig::get($uid, 'pumpio', 'consumer_key');
1593         $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret');
1594         $otoken  = PConfig::get($uid, 'pumpio', 'oauth_token');
1595         $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret');
1596         $hostname = PConfig::get($uid, 'pumpio','host');
1597         $username = PConfig::get($uid, "pumpio", "user");
1598
1599         logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1600
1601         $own_id = "https://".$hostname."/".$username;
1602
1603         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1604                 intval($uid));
1605
1606         // Fetching the original post
1607         $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1608                         dbesc($id),
1609                         intval($uid)
1610                 );
1611
1612         if (!count($r))
1613                 return false;
1614
1615         $url = $r[0]["extid"];
1616
1617         $client = new oauth_client_class;
1618         $client->oauth_version = '1.0a';
1619         $client->authorization_header = true;
1620         $client->url_parameters = false;
1621
1622         $client->client_id = $ckey;
1623         $client->client_secret = $csecret;
1624         $client->access_token = $otoken;
1625         $client->access_token_secret = $osecret;
1626
1627         logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1628
1629         if (pumpio_reachable($url))
1630                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1631         else
1632                 $success = false;
1633
1634         if (!$success)
1635                 return;
1636
1637         if ($item->likes->totalItems != 0) {
1638                 foreach ($item->likes->items AS $post) {
1639                         $like = new stdClass;
1640                         $like->object = new stdClass;
1641                         $like->object->id = $item->id;
1642                         $like->actor = new stdClass;
1643                         $like->actor->displayName = $item->displayName;
1644                         $like->actor->preferredUsername = $item->preferredUsername;
1645                         $like->actor->url = $item->url;
1646                         $like->actor->image = $item->image;
1647                         $like->generator = new stdClass;
1648                         $like->generator->displayName = "pumpio";
1649                         pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1650                 }
1651         }
1652
1653         if ($item->replies->totalItems == 0)
1654                 return;
1655
1656         foreach ($item->replies->items AS $item) {
1657                 if ($item->id == $id)
1658                         continue;
1659
1660                 // Checking if the comment already exists - Two queries for speed issues
1661                 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1662                                 dbesc($item->id),
1663                                 intval($uid)
1664                         );
1665
1666                 if (count($r))
1667                         continue;
1668
1669                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1670                                 dbesc($item->id),
1671                                 intval($uid)
1672                         );
1673
1674                 if (count($r))
1675                         continue;
1676
1677                 $post = new stdClass;
1678                 $post->verb = "post";
1679                 $post->actor = $item->author;
1680                 $post->published = $item->published;
1681                 $post->received = $item->updated;
1682                 $post->generator = new stdClass;
1683                 $post->generator->displayName = "pumpio";
1684                 // To-Do: Check for public post
1685
1686                 unset($item->author);
1687                 unset($item->published);
1688                 unset($item->updated);
1689
1690                 $post->object = $item;
1691
1692                 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1693                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1694         }
1695 }
1696
1697
1698 function pumpio_reachable($url) {
1699         $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
1700         return(intval($data['return_code']) != 0);
1701 }
1702
1703 /*
1704 To-Do:
1705  - edit own notes
1706  - delete own notes
1707 */