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