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