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