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