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