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