]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
Support for the new worker class
[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 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 = get_pconfig($notification_data["uid"], 'pumpio','host');
71         $username = get_pconfig($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  = get_config('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 = get_pconfig(local_user(), 'pumpio','consumer_key');
125         $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret');
126         $hostname = get_pconfig(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                 set_pconfig(local_user(), 'pumpio','consumer_key', $clientdata->client_id);
132                 set_pconfig(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret);
133
134                 $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key');
135                 $consumer_secret = get_pconfig(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                                 set_pconfig(local_user(), "pumpio", "oauth_token", $client->access_token);
173                                 set_pconfig(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 = get_pconfig(local_user(),'pumpio','post');
198         if(intval($pumpio_post) == 1) {
199                 $pumpio_defpost = get_pconfig(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 = get_pconfig(local_user(),'pumpio','import');
219         $import_checked = (($import_enabled) ? ' checked="checked" ' : '');
220
221         $enabled = get_pconfig(local_user(),'pumpio','post');
222         $checked = (($enabled) ? ' checked="checked" ' : '');
223         $css = (($enabled) ? '' : '-disabled');
224
225         $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default');
226         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
227
228         $public_enabled = get_pconfig(local_user(),'pumpio','public');
229         $public_checked = (($public_enabled) ? ' checked="checked" ' : '');
230
231         $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror');
232         $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : '');
233
234         $servername = get_pconfig(local_user(), "pumpio", "host");
235         $username = get_pconfig(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 = get_pconfig(local_user(), "pumpio", "oauth_token");
260                 $oauth_token_secret = get_pconfig(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                         set_pconfig(local_user(),'pumpio','consumer_key','');
313                         set_pconfig(local_user(),'pumpio','consumer_secret','');
314                         set_pconfig(local_user(),'pumpio','oauth_token','');
315                         set_pconfig(local_user(),'pumpio','oauth_token_secret','');
316                         set_pconfig(local_user(),'pumpio','post',false);
317                         set_pconfig(local_user(),'pumpio','import',false);
318                         set_pconfig(local_user(),'pumpio','host','');
319                         set_pconfig(local_user(),'pumpio','user','');
320                         set_pconfig(local_user(),'pumpio','public',false);
321                         set_pconfig(local_user(),'pumpio','mirror',false);
322                         set_pconfig(local_user(),'pumpio','post_by_default',false);
323                         set_pconfig(local_user(),'pumpio','lastdate', 0);
324                         set_pconfig(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                         set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio']));
340                         set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']);
341                         set_pconfig(local_user(),'pumpio','host',$host);
342                         set_pconfig(local_user(),'pumpio','user',$user);
343                         set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']);
344                         set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']);
345                         set_pconfig(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(get_pconfig(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(get_pconfig(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 (!get_pconfig($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 = get_pconfig($b['uid'], "pumpio", "oauth_token");
446         $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret");
447         $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key");
448         $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret");
449
450         $host = get_pconfig($b['uid'], "pumpio", "host");
451         $user = get_pconfig($b['uid'], "pumpio", "user");
452         $public = get_pconfig($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                                 set_pconfig($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 (!get_pconfig($uid,'pumpio','import'))
553                 return;
554
555         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
556         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
557         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
558         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
559         $hostname = get_pconfig($uid, 'pumpio','host');
560         $username = get_pconfig($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 = get_config('pumpio','last_poll');
632
633         $poll_interval = intval(get_config('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(get_config('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 = get_pconfig($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                                 set_pconfig($rr['uid'],'pumpio','contact_check',time());
684                         }
685                 }
686         }
687
688         logger('pumpio: cron_end');
689
690         set_config('pumpio','last_poll', time());
691 }
692
693 function pumpio_cron(&$a,$b) {
694         Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php");
695 }
696
697 function pumpio_fetchtimeline(&$a, $uid) {
698         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
699         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
700         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
701         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
702         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
703         $hostname = get_pconfig($uid, 'pumpio','host');
704         $username = get_pconfig($uid, "pumpio", "user");
705
706         //  get the application name for the pump.io app
707         //  1st try personal config, then system config and fallback to the
708         //  hostname of the node if neither one is set.
709         $application_name  = get_pconfig( $uid, 'pumpio', 'application_name');
710         if ($application_name == "")
711                 $application_name  = get_config('pumpio', 'application_name');
712         if ($application_name == "")
713                 $application_name = $a->get_hostname();
714
715         $first_time = ($lastdate == "");
716
717         $client = new oauth_client_class;
718         $client->oauth_version = '1.0a';
719         $client->authorization_header = true;
720         $client->url_parameters = false;
721
722         $client->client_id = $ckey;
723         $client->client_secret = $csecret;
724         $client->access_token = $otoken;
725         $client->access_token_secret = $osecret;
726
727         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
728
729         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
730
731         $username = $user.'@'.$host;
732
733         if (pumpio_reachable($url))
734                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
735         else
736                 $success = false;
737
738         if (!$success) {
739                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
740                 return;
741         }
742
743         $posts = array_reverse($user->items);
744
745         $initiallastdate = $lastdate;
746         $lastdate = '';
747
748         if (count($posts)) {
749                 foreach ($posts as $post) {
750                         if ($post->published <= $initiallastdate)
751                                 continue;
752
753                         if ($lastdate < $post->published)
754                                 $lastdate = $post->published;
755
756                         if ($first_time)
757                                 continue;
758
759                         $receiptians = array();
760                         if (@is_array($post->cc))
761                                 $receiptians = array_merge($receiptians, $post->cc);
762
763                         if (@is_array($post->to))
764                                 $receiptians = array_merge($receiptians, $post->to);
765
766                         $public = false;
767                         foreach ($receiptians AS $receiver)
768                                 if (is_string($receiver->objectType))
769                                         if ($receiver->id == "http://activityschema.org/collection/public")
770                                                 $public = true;
771
772                         if ($public && !stristr($post->generator->displayName, $application_name)) {
773                                 require_once('include/html2bbcode.php');
774
775                                 $_SESSION["authenticated"] = true;
776                                 $_SESSION["uid"] = $uid;
777
778                                 unset($_REQUEST);
779                                 $_REQUEST["type"] = "wall";
780                                 $_REQUEST["api_source"] = true;
781                                 $_REQUEST["profile_uid"] = $uid;
782                                 $_REQUEST["source"] = "pump.io";
783
784                                 if (isset($post->object->id)) {
785                                         $_REQUEST['message_id'] = NETWORK_PUMPIO.":".$post->object->id;
786                                 }
787
788                                 if ($post->object->displayName != "")
789                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
790                                 else
791                                         $_REQUEST["title"] = "";
792
793                                 $_REQUEST["body"] = html2bbcode($post->object->content);
794
795                                 // To-Do: Picture has to be cached and stored locally
796                                 if ($post->object->fullImage->url != "") {
797                                         if ($post->object->fullImage->pump_io->proxyURL != "")
798                                                 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
799                                         else
800                                                 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
801                                 }
802
803                                 logger('pumpio: posting for user '.$uid);
804
805                                 require_once('mod/item.php');
806
807                                 item_post($a);
808                                 logger('pumpio: posting done - user '.$uid);
809                         }
810                 }
811         }
812
813         if ($lastdate != 0)
814                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
815 }
816
817 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
818         // Searching for the unliked post
819         // Two queries for speed issues
820         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
821                                 dbesc($post->object->id),
822                                 intval($uid)
823                 );
824
825         if (count($r))
826                 $orig_post = $r[0];
827         else {
828                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
829                                         dbesc($post->object->id),
830                                         intval($uid)
831                         );
832
833                 if (!count($r))
834                         return;
835                 else
836                         $orig_post = $r[0];
837         }
838
839         $contactid = 0;
840
841         if(link_compare($post->actor->url, $own_id)) {
842                 $contactid = $self[0]['id'];
843         } else {
844                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
845                         dbesc(normalise_link($post->actor->url)),
846                         intval($uid)
847                 );
848
849                 if(count($r))
850                         $contactid = $r[0]['id'];
851
852                 if($contactid == 0)
853                         $contactid = $orig_post['contact-id'];
854         }
855
856         $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'",
857                 dbesc(datetime_convert()),
858                 dbesc(ACTIVITY_LIKE),
859                 intval($uid),
860                 intval($contactid),
861                 dbesc($orig_post['uri'])
862         );
863
864         if(count($r))
865                 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
866         else
867                 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
868 }
869
870 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
871         require_once('include/items.php');
872
873         if ($post->object->id == "") {
874                 logger('Got empty like: '.print_r($post, true), LOGGER_DEBUG);
875                 return;
876         }
877
878         // Searching for the liked post
879         // Two queries for speed issues
880         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
881                                 dbesc($post->object->id),
882                                 intval($uid),
883                                 dbesc(NETWORK_PUMPIO)
884                 );
885
886         if (count($r))
887                 $orig_post = $r[0];
888         else {
889                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
890                                         dbesc($post->object->id),
891                                         intval($uid),
892                                         dbesc(NETWORK_PUMPIO)
893                         );
894
895                 if (!count($r))
896                         return;
897                 else
898                         $orig_post = $r[0];
899         }
900
901         // thread completion
902         if ($threadcompletion)
903                 pumpio_fetchallcomments($a, $uid, $post->object->id);
904
905         $contactid = 0;
906
907         if(link_compare($post->actor->url, $own_id)) {
908                 $contactid = $self[0]['id'];
909                 $post->actor->displayName = $self[0]['name'];
910                 $post->actor->url = $self[0]['url'];
911                 $post->actor->image->url = $self[0]['photo'];
912         } else {
913                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
914                         dbesc(normalise_link($post->actor->url)),
915                         intval($uid)
916                 );
917
918                 if(count($r))
919                         $contactid = $r[0]['id'];
920
921                 if($contactid == 0)
922                         $contactid = $orig_post['contact-id'];
923         }
924
925         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
926                 dbesc(ACTIVITY_LIKE),
927                 intval($uid),
928                 intval($contactid),
929                 dbesc($orig_post['uri'])
930         );
931
932         if(count($r)) {
933                 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
934                 return;
935         }
936
937         $likedata = array();
938         $likedata['parent'] = $orig_post['id'];
939         $likedata['verb'] = ACTIVITY_LIKE;
940         $likedata['gravity'] = 3;
941         $likedata['uid'] = $uid;
942         $likedata['wall'] = 0;
943         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
944         $likedata['parent-uri'] = $orig_post["uri"];
945         $likedata['contact-id'] = $contactid;
946         $likedata['app'] = $post->generator->displayName;
947         $likedata['author-name'] = $post->actor->displayName;
948         $likedata['author-link'] = $post->actor->url;
949         $likedata['author-avatar'] = $post->actor->image->url;
950
951         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
952         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
953         $post_type = t('status');
954         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
955         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
956
957         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
958
959         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
960                 '<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>';
961
962         $ret = item_store($likedata);
963
964         logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
965 }
966
967 function pumpio_get_contact($uid, $contact, $no_insert = false) {
968
969         update_gcontact(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2,
970                         "photo" => $contact->image->url, "name" => $contact->displayName,  "hide" => true,
971                         "nick" => $contact->preferredUsername, "location" => $contact->location->displayName,
972                         "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)));
973         $cid = get_contact($contact->url, $uid);
974
975         if ($no_insert)
976                 return($cid);
977
978         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
979                 intval($uid), dbesc(normalise_link($contact->url)));
980
981         if (!count($r)) {
982                 // create contact record
983                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
984                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
985                                         `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
986                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
987                         intval($uid),
988                         dbesc(datetime_convert()),
989                         dbesc($contact->url),
990                         dbesc(normalise_link($contact->url)),
991                         dbesc(str_replace("acct:", "", $contact->id)),
992                         dbesc(''),
993                         dbesc($contact->id), // What is it for?
994                         dbesc('pump.io ' . $contact->id), // What is it for?
995                         dbesc($contact->displayName),
996                         dbesc($contact->preferredUsername),
997                         dbesc($contact->image->url),
998                         dbesc(NETWORK_PUMPIO),
999                         intval(CONTACT_IS_FRIEND),
1000                         intval(1),
1001                         dbesc($contact->location->displayName),
1002                         dbesc($contact->summary),
1003                         intval(1)
1004                 );
1005
1006                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1007                         dbesc(normalise_link($contact->url)),
1008                         intval($uid)
1009                         );
1010
1011                 if (!count($r)) {
1012                         return(false);
1013                 }
1014
1015                 $contact_id = $r[0]['id'];
1016
1017                 $g = q("select def_gid from user where uid = %d limit 1",
1018                         intval($uid)
1019                 );
1020
1021                 if($g && intval($g[0]['def_gid'])) {
1022                         require_once('include/group.php');
1023                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1024                 }
1025         } else {
1026                 $contact_id = $r[0]["id"];
1027
1028                 /*      if (DB_UPDATE_VERSION >= "1177")
1029                                 q("UPDATE `contact` SET `location` = '%s',
1030                                                         `about` = '%s'
1031                                                 WHERE `id` = %d",
1032                                         dbesc($contact->location->displayName),
1033                                         dbesc($contact->summary),
1034                                         intval($r[0]['id'])
1035                                 );
1036                 */
1037         }
1038
1039         if (function_exists("update_contact_avatar"))
1040                 update_contact_avatar($contact->image->url, $uid, $contact_id);
1041
1042         return($contact_id);
1043 }
1044
1045 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1046
1047         // Two queries for speed issues
1048         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1049                                 dbesc($post->object->id),
1050                                 intval($uid)
1051                 );
1052
1053         if (count($r))
1054                 return drop_item($r[0]["id"], $false);
1055
1056         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1057                                 dbesc($post->object->id),
1058                                 intval($uid)
1059                 );
1060
1061         if (count($r))
1062                 return drop_item($r[0]["id"], $false);
1063 }
1064
1065 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1066         require_once('include/items.php');
1067         require_once('include/html2bbcode.php');
1068
1069         if (($post->verb == "like") || ($post->verb == "favorite"))
1070                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1071
1072         if (($post->verb == "unlike") || ($post->verb == "unfavorite"))
1073                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1074
1075         if ($post->verb == "delete")
1076                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1077
1078         if ($post->verb != "update") {
1079                 // Two queries for speed issues
1080                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1081                                         dbesc($post->object->id),
1082                                         intval($uid)
1083                         );
1084
1085                 if (count($r))
1086                         return false;
1087
1088                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1089                                         dbesc($post->object->id),
1090                                         intval($uid)
1091                         );
1092
1093                 if (count($r))
1094                         return false;
1095         }
1096
1097         // Only handle these three types
1098         if (!strstr("post|share|update", $post->verb))
1099                 return false;
1100
1101         $receiptians = array();
1102         if (@is_array($post->cc))
1103                 $receiptians = array_merge($receiptians, $post->cc);
1104
1105         if (@is_array($post->to))
1106                 $receiptians = array_merge($receiptians, $post->to);
1107
1108         foreach ($receiptians AS $receiver)
1109                 if (is_string($receiver->objectType))
1110                         if ($receiver->id == "http://activityschema.org/collection/public")
1111                                 $public = true;
1112
1113         $postarray = array();
1114         $postarray['network'] = NETWORK_PUMPIO;
1115         $postarray['gravity'] = 0;
1116         $postarray['uid'] = $uid;
1117         $postarray['wall'] = 0;
1118         $postarray['uri'] = $post->object->id;
1119         $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1120
1121         if ($post->object->objectType != "comment") {
1122                 $contact_id = pumpio_get_contact($uid, $post->actor);
1123
1124                 if (!$contact_id)
1125                         $contact_id = $self[0]['id'];
1126
1127                 $postarray['parent-uri'] = $post->object->id;
1128
1129                 if (!$public) {
1130                         $postarray['private'] = 1;
1131                         $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1132                 }
1133         } else {
1134                 $contact_id = pumpio_get_contact($uid, $post->actor, true);
1135
1136                 if (link_compare($post->actor->url, $own_id)) {
1137                         $contact_id = $self[0]['id'];
1138                         $post->actor->displayName = $self[0]['name'];
1139                         $post->actor->url = $self[0]['url'];
1140                         $post->actor->image->url = $self[0]['photo'];
1141                 } elseif ($contact_id == 0) {
1142                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1143                         $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1144                                 dbesc(normalise_link($post->actor->url)),
1145                                 intval($uid)
1146                         );
1147
1148                         if(count($r))
1149                                 $contact_id = $r[0]['id'];
1150                         else {
1151                                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1152                                         dbesc(normalise_link($post->actor->url)),
1153                                         intval($uid)
1154                                 );
1155
1156                                 if(count($r))
1157                                         $contact_id = $r[0]['id'];
1158                                 else
1159                                         $contact_id = $self[0]['id'];
1160                         }
1161                 }
1162
1163                 $reply = new stdClass;
1164                 $reply->verb = "note";
1165                 $reply->cc = $post->cc;
1166                 $reply->to = $post->to;
1167                 $reply->object = new stdClass;
1168                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1169                 $reply->object->content = $post->object->inReplyTo->content;
1170                 $reply->object->id = $post->object->inReplyTo->id;
1171                 $reply->actor = $post->object->inReplyTo->author;
1172                 $reply->url = $post->object->inReplyTo->url;
1173                 $reply->generator = new stdClass;
1174                 $reply->generator->displayName = "pumpio";
1175                 $reply->published = $post->object->inReplyTo->published;
1176                 $reply->received = $post->object->inReplyTo->updated;
1177                 $reply->url = $post->object->inReplyTo->url;
1178                 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1179
1180                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1181         }
1182
1183         if ($post->object->pump_io->proxyURL)
1184                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1185
1186         $postarray['contact-id'] = $contact_id;
1187         $postarray['verb'] = ACTIVITY_POST;
1188         $postarray['owner-name'] = $post->actor->displayName;
1189         $postarray['owner-link'] = $post->actor->url;
1190         $postarray['owner-avatar'] = $post->actor->image->url;
1191         $postarray['author-name'] = $post->actor->displayName;
1192         $postarray['author-link'] = $post->actor->url;
1193         $postarray['author-avatar'] = $post->actor->image->url;
1194         $postarray['plink'] = $post->object->url;
1195         $postarray['app'] = $post->generator->displayName;
1196         $postarray['body'] = html2bbcode($post->object->content);
1197         $postarray['object'] = json_encode($post);
1198
1199         if ($post->object->fullImage->url != "")
1200                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1201
1202         if ($post->object->displayName != "")
1203                 $postarray['title'] = $post->object->displayName;
1204
1205         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1206         if (isset($post->updated))
1207                 $postarray['edited'] = datetime_convert('UTC','UTC',$post->updated);
1208         elseif (isset($post->received))
1209                 $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1210         else
1211                 $postarray['edited'] = $postarray['created'];
1212
1213         if ($post->verb == "share") {
1214                 if (!intval(get_config('system','wall-to-wall_share'))) {
1215                         if (isset($post->object->author->displayName) && ($post->object->author->displayName != ""))
1216                                 $share_author = $post->object->author->displayName;
1217                         elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != ""))
1218                                 $share_author = $post->object->author->preferredUsername;
1219                         else
1220                                 $share_author = $post->object->author->url;
1221
1222                         $postarray['body'] = share_header($share_author, $post->object->author->url,
1223                                                         $post->object->author->image->url, "",
1224                                                         datetime_convert('UTC','UTC',$post->object->created),
1225                                                         $post->links->self->href).
1226                                                 $postarray['body']."[/share]";
1227
1228                         /*
1229                         $postarray['body'] = "[share author='".$share_author.
1230                                         "' profile='".$post->object->author->url.
1231                                         "' avatar='".$post->object->author->image->url.
1232                                         "' posted='".datetime_convert('UTC','UTC',$post->object->created).
1233                                         "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1234                         */
1235                 } else {
1236                         // Let shares look like wall-to-wall posts
1237                         $postarray['author-name'] = $post->object->author->displayName;
1238                         $postarray['author-link'] = $post->object->author->url;
1239                         $postarray['author-avatar'] = $post->object->author->image->url;
1240                 }
1241         }
1242
1243         if (trim($postarray['body']) == "")
1244                 return false;
1245
1246         $top_item = item_store($postarray);
1247         $postarray["id"] = $top_item;
1248
1249         if (($top_item == 0) && ($post->verb == "update")) {
1250                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1251                         dbesc($postarray["title"]),
1252                         dbesc($postarray["body"]),
1253                         dbesc($postarray["edited"]),
1254                         dbesc($postarray["uri"]),
1255                         intval($uid)
1256                         );
1257         }
1258
1259         if ($post->object->objectType == "comment") {
1260
1261                 if ($threadcompletion)
1262                         pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1263
1264                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1265                                 intval($uid)
1266                         );
1267
1268                 if(!count($user))
1269                         return $top_item;
1270
1271                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1272
1273                 if (link_compare($own_id, $postarray['author-link']))
1274                         return $top_item;
1275
1276                 if (!function_exists("check_item_notification")) {
1277                         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1278                                         dbesc($postarray['parent-uri']),
1279                                         intval($uid)
1280                                         );
1281
1282                         if(count($myconv)) {
1283
1284                                 foreach($myconv as $conv) {
1285                                         // now if we find a match, it means we're in this conversation
1286
1287                                         if(!link_compare($conv['author-link'],$importer_url) && !link_compare($conv['author-link'],$own_id))
1288                                                 continue;
1289
1290                                         require_once('include/enotify.php');
1291
1292                                         $conv_parent = $conv['parent'];
1293
1294                                         notification(array(
1295                                                 'type'         => NOTIFY_COMMENT,
1296                                                 'notify_flags' => $user[0]['notify-flags'],
1297                                                 'language'     => $user[0]['language'],
1298                                                 'to_name'      => $user[0]['username'],
1299                                                 'to_email'     => $user[0]['email'],
1300                                                 'uid'          => $user[0]['uid'],
1301                                                 'item'         => $postarray,
1302                                                 'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1303                                                 'source_name'  => $postarray['author-name'],
1304                                                 'source_link'  => $postarray['author-link'],
1305                                                 'source_photo' => $postarray['author-avatar'],
1306                                                 'verb'         => ACTIVITY_POST,
1307                                                 'otype'        => 'item',
1308                                                 'parent'       => $conv_parent,
1309                                                 ));
1310
1311                                         // only send one notification
1312                                         break;
1313                                 }
1314                         }
1315                 }
1316         }
1317
1318         return $top_item;
1319 }
1320
1321 function pumpio_fetchinbox(&$a, $uid) {
1322
1323         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1324         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1325         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1326         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1327         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1328         $hostname = get_pconfig($uid, 'pumpio','host');
1329         $username = get_pconfig($uid, "pumpio", "user");
1330
1331         $own_id = "https://".$hostname."/".$username;
1332
1333         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1334                 intval($uid));
1335
1336         $lastitems = q("SELECT `uri` FROM `thread`
1337                         INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1338                         WHERE `thread`.`network` = '%s' AND `thread`.`uid` = %d AND `item`.`extid` != ''
1339                         ORDER BY `thread`.`commented` DESC LIMIT 10",
1340                                 dbesc(NETWORK_PUMPIO),
1341                                 intval($uid)
1342                         );
1343
1344         $client = new oauth_client_class;
1345         $client->oauth_version = '1.0a';
1346         $client->authorization_header = true;
1347         $client->url_parameters = false;
1348
1349         $client->client_id = $ckey;
1350         $client->client_secret = $csecret;
1351         $client->access_token = $otoken;
1352         $client->access_token_secret = $osecret;
1353
1354         $last_id = get_pconfig($uid,'pumpio','last_id');
1355
1356         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1357
1358         if ($last_id != "")
1359                 $url .= '?since='.urlencode($last_id);
1360
1361         if (pumpio_reachable($url))
1362                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1363         else
1364                 $success = false;
1365
1366         if ($user->items) {
1367             $posts = array_reverse($user->items);
1368
1369             if (count($posts))
1370                     foreach ($posts as $post) {
1371                             $last_id = $post->id;
1372                             pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1373                     }
1374         }
1375
1376         foreach ($lastitems AS $item)
1377                 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1378
1379         set_pconfig($uid,'pumpio','last_id', $last_id);
1380 }
1381
1382 function pumpio_getallusers(&$a, $uid) {
1383         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1384         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1385         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1386         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1387         $hostname = get_pconfig($uid, 'pumpio','host');
1388         $username = get_pconfig($uid, "pumpio", "user");
1389
1390         $client = new oauth_client_class;
1391         $client->oauth_version = '1.0a';
1392         $client->authorization_header = true;
1393         $client->url_parameters = false;
1394
1395         $client->client_id = $ckey;
1396         $client->client_secret = $csecret;
1397         $client->access_token = $otoken;
1398         $client->access_token_secret = $osecret;
1399
1400         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1401
1402         if (pumpio_reachable($url))
1403                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1404         else
1405                 $success = false;
1406
1407         if ($users->totalItems > count($users->items)) {
1408                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1409
1410                 if (pumpio_reachable($url))
1411                         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1412                 else
1413                         $success = false;
1414         }
1415
1416         if (is_array($users->items)) {
1417                 foreach ($users->items AS $user) {
1418                         pumpio_get_contact($uid, $user);
1419                 }
1420         }
1421 }
1422
1423 function pumpio_queue_hook(&$a,&$b) {
1424
1425         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1426                 dbesc(NETWORK_PUMPIO)
1427         );
1428         if(! count($qi))
1429                 return;
1430
1431         require_once('include/queue_fn.php');
1432
1433         foreach($qi as $x) {
1434                 if($x['network'] !== NETWORK_PUMPIO)
1435                         continue;
1436
1437                 logger('pumpio_queue: run');
1438
1439                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1440                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1441                         intval($x['cid'])
1442                 );
1443                 if(! count($r))
1444                         continue;
1445
1446                 $userdata = $r[0];
1447
1448                 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1449
1450                 $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token");
1451                 $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret");
1452                 $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key");
1453                 $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret");
1454
1455                 $host = get_pconfig($userdata['uid'], "pumpio", "host");
1456                 $user = get_pconfig($userdata['uid'], "pumpio", "user");
1457
1458                 $success = false;
1459
1460                 if ($oauth_token && $oauth_token_secret &&
1461                         $consumer_key && $consumer_secret) {
1462                         $username = $user.'@'.$host;
1463
1464                         logger('pumpio_queue: able to post for user '.$username);
1465
1466                         $z = unserialize($x['content']);
1467
1468                         $client = new oauth_client_class;
1469                         $client->oauth_version = '1.0a';
1470                         $client->url_parameters = false;
1471                         $client->authorization_header = true;
1472                         $client->access_token = $oauth_token;
1473                         $client->access_token_secret = $oauth_token_secret;
1474                         $client->client_id = $consumer_key;
1475                         $client->client_secret = $consumer_secret;
1476
1477                         if (pumpio_reachable($z['url']))
1478                                 $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1479                         else
1480                                 $success = false;
1481
1482                         if($success) {
1483                                 $post_id = $user->object->id;
1484                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1485                                 if($post_id && $iscomment) {
1486                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1487                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1488                                                 dbesc($post_id),
1489                                                 intval($z['item'])
1490                                         );
1491                                 }
1492                                 remove_queue_item($x['id']);
1493                         } else
1494                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1495                 } else
1496                         logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1497
1498                 if (!$success) {
1499                         logger('pumpio_queue: delayed');
1500                         update_queue_time($x['id']);
1501                 }
1502         }
1503 }
1504
1505 function pumpio_getreceiver(&$a, $b) {
1506
1507         $receiver = array();
1508
1509         if (!$b["private"]) {
1510
1511                 if(! strstr($b['postopts'],'pumpio'))
1512                         return $receiver;
1513
1514                 $public = get_pconfig($b['uid'], "pumpio", "public");
1515
1516                 if ($public)
1517                         $receiver["to"][] = Array(
1518                                                 "objectType" => "collection",
1519                                                 "id" => "http://activityschema.org/collection/public");
1520         } else {
1521                 $cids = explode("><", $b["allow_cid"]);
1522                 $gids = explode("><", $b["allow_gid"]);
1523
1524                 foreach ($cids AS $cid) {
1525                         $cid = trim($cid, " <>");
1526
1527                         $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",
1528                                 intval($cid),
1529                                 intval($b["uid"]),
1530                                 dbesc(NETWORK_PUMPIO)
1531                                 );
1532
1533                         if (count($r)) {
1534                                 $receiver["bcc"][] = Array(
1535                                                         "displayName" => $r[0]["name"],
1536                                                         "objectType" => "person",
1537                                                         "preferredUsername" => $r[0]["nick"],
1538                                                         "url" => $r[0]["url"]);
1539                         }
1540                 }
1541                 foreach ($gids AS $gid) {
1542                         $gid = trim($gid, " <>");
1543
1544                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1545                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1546                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1547                                         intval($gid),
1548                                         intval($b["uid"]),
1549                                         dbesc(NETWORK_PUMPIO)
1550                                 );
1551
1552                         foreach ($r AS $row)
1553                                 $receiver["bcc"][] = Array(
1554                                                         "displayName" => $row["name"],
1555                                                         "objectType" => "person",
1556                                                         "preferredUsername" => $row["nick"],
1557                                                         "url" => $row["url"]);
1558                 }
1559         }
1560
1561         if ($b["inform"] != "") {
1562
1563                 $inform = explode(",", $b["inform"]);
1564
1565                 foreach ($inform AS $cid) {
1566                         if (substr($cid, 0, 4) != "cid:")
1567                                 continue;
1568
1569                         $cid = str_replace("cid:", "", $cid);
1570
1571                         $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",
1572                                 intval($cid),
1573                                 intval($b["uid"]),
1574                                 dbesc(NETWORK_PUMPIO)
1575                                 );
1576
1577                         if (count($r)) {
1578                                         $receiver["to"][] = Array(
1579                                                                 "displayName" => $r[0]["name"],
1580                                                                 "objectType" => "person",
1581                                                                 "preferredUsername" => $r[0]["nick"],
1582                                                                 "url" => $r[0]["url"]);
1583                         }
1584                 }
1585         }
1586
1587         return $receiver;
1588 }
1589
1590 function pumpio_fetchallcomments(&$a, $uid, $id) {
1591         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1592         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1593         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1594         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1595         $hostname = get_pconfig($uid, 'pumpio','host');
1596         $username = get_pconfig($uid, "pumpio", "user");
1597
1598         logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1599
1600         $own_id = "https://".$hostname."/".$username;
1601
1602         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1603                 intval($uid));
1604
1605         // Fetching the original post
1606         $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1607                         dbesc($id),
1608                         intval($uid)
1609                 );
1610
1611         if (!count($r))
1612                 return false;
1613
1614         $url = $r[0]["extid"];
1615
1616         $client = new oauth_client_class;
1617         $client->oauth_version = '1.0a';
1618         $client->authorization_header = true;
1619         $client->url_parameters = false;
1620
1621         $client->client_id = $ckey;
1622         $client->client_secret = $csecret;
1623         $client->access_token = $otoken;
1624         $client->access_token_secret = $osecret;
1625
1626         logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1627
1628         if (pumpio_reachable($url))
1629                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1630         else
1631                 $success = false;
1632
1633         if (!$success)
1634                 return;
1635
1636         if ($item->likes->totalItems != 0) {
1637                 foreach ($item->likes->items AS $post) {
1638                         $like = new stdClass;
1639                         $like->object = new stdClass;
1640                         $like->object->id = $item->id;
1641                         $like->actor = new stdClass;
1642                         $like->actor->displayName = $item->displayName;
1643                         $like->actor->preferredUsername = $item->preferredUsername;
1644                         $like->actor->url = $item->url;
1645                         $like->actor->image = $item->image;
1646                         $like->generator = new stdClass;
1647                         $like->generator->displayName = "pumpio";
1648                         pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1649                 }
1650         }
1651
1652         if ($item->replies->totalItems == 0)
1653                 return;
1654
1655         foreach ($item->replies->items AS $item) {
1656                 if ($item->id == $id)
1657                         continue;
1658
1659                 // Checking if the comment already exists - Two queries for speed issues
1660                 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1661                                 dbesc($item->id),
1662                                 intval($uid)
1663                         );
1664
1665                 if (count($r))
1666                         continue;
1667
1668                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1669                                 dbesc($item->id),
1670                                 intval($uid)
1671                         );
1672
1673                 if (count($r))
1674                         continue;
1675
1676                 $post = new stdClass;
1677                 $post->verb = "post";
1678                 $post->actor = $item->author;
1679                 $post->published = $item->published;
1680                 $post->received = $item->updated;
1681                 $post->generator = new stdClass;
1682                 $post->generator->displayName = "pumpio";
1683                 // To-Do: Check for public post
1684
1685                 unset($item->author);
1686                 unset($item->published);
1687                 unset($item->updated);
1688
1689                 $post->object = $item;
1690
1691                 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1692                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1693         }
1694 }
1695
1696
1697 function pumpio_reachable($url) {
1698         $data = z_fetch_url($url, false, $redirects, array('timeout'=>10));
1699         return(intval($data['return_code']) != 0);
1700 }
1701
1702 /*
1703 To-Do:
1704  - edit own notes
1705  - delete own notes
1706 */