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