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