]> git.mxchange.org Git - friendica-addons.git/blob - pumpio/pumpio.php
Merge pull request #246 from annando/1503-pumpio-bugfix-comments
[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' => $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                         $post_id = $user->object->id;
506                         logger('pumpio_send '.$username.': success '.$post_id);
507                         if($post_id AND $iscomment) {
508                                 logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$b['id']);
509                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
510                                         dbesc($post_id),
511                                         intval($b['id'])
512                                 );
513                         }
514                 } else {
515                         logger('pumpio_send '.$username.': '.$url.' general error: ' . print_r($user,true));
516
517                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
518                         if (count($r))
519                                 $a->contact = $r[0]["id"];
520
521                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params));
522                         require_once('include/queue_fn.php');
523                         add_to_queue($a->contact,NETWORK_PUMPIO,$s);
524                         notice(t('Pump.io post failed. Queued for retry.').EOL);
525                 }
526
527         }
528 }
529
530 function pumpio_action(&$a, $uid, $uri, $action, $content = "") {
531
532         // Don't do likes and other stuff if you don't import the timeline
533         if (!get_pconfig($uid,'pumpio','import'))
534                 return;
535
536         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
537         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
538         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
539         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
540         $hostname = get_pconfig($uid, 'pumpio','host');
541         $username = get_pconfig($uid, "pumpio", "user");
542
543         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
544                                 dbesc($uri),
545                                 intval($uid)
546         );
547
548         if (!count($r))
549                 return;
550
551         $orig_post = $r[0];
552
553         if ($orig_post["extid"] AND !strstr($orig_post["extid"], "/proxy/"))
554                 $uri = $orig_post["extid"];
555         else
556                 $uri = $orig_post["uri"];
557
558         if (($orig_post["object-type"] != "") AND (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA)))
559                 $objectType = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]);
560         elseif (strstr($uri, "/api/comment/"))
561                 $objectType = "comment";
562         elseif (strstr($uri, "/api/note/"))
563                 $objectType = "note";
564         elseif (strstr($uri, "/api/image/"))
565                 $objectType = "image";
566
567         $params["verb"] = $action;
568         $params["object"] = array('id' => $uri,
569                                 "objectType" => $objectType,
570                                 "content" => $content);
571
572         $client = new oauth_client_class;
573         $client->oauth_version = '1.0a';
574         $client->authorization_header = true;
575         $client->url_parameters = false;
576
577         $client->client_id = $ckey;
578         $client->client_secret = $csecret;
579         $client->access_token = $otoken;
580         $client->access_token_secret = $osecret;
581
582         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed';
583
584         $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
585
586         if($success)
587                 logger('pumpio_action '.$username.' '.$action.': success '.$uri);
588         else {
589                 logger('pumpio_action '.$username.' '.$action.': general error: '.$uri.' '.print_r($user,true));
590
591                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
592                 if (count($r))
593                         $a->contact = $r[0]["id"];
594
595                 $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params));
596                 require_once('include/queue_fn.php');
597                 add_to_queue($a->contact,NETWORK_PUMPIO,$s);
598                 notice(t('Pump.io like failed. Queued for retry.').EOL);
599         }
600 }
601
602
603 function pumpio_cron(&$a,$b) {
604         $last = get_config('pumpio','last_poll');
605
606         $poll_interval = intval(get_config('pumpio','poll_interval'));
607         if(! $poll_interval)
608                 $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL;
609
610         if($last) {
611                 $next = $last + ($poll_interval * 60);
612                 if($next > time()) {
613                         logger('pumpio: poll intervall not reached');
614                         return;
615                 }
616         }
617         logger('pumpio: cron_start');
618
619         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'mirror' AND `v` = '1' ORDER BY RAND() ");
620         if(count($r)) {
621                 foreach($r as $rr) {
622                         logger('pumpio: mirroring user '.$rr['uid']);
623                         pumpio_fetchtimeline($a, $rr['uid']);
624                 }
625         }
626
627         $abandon_days = intval(get_config('system','account_abandon_days'));
628         if ($abandon_days < 1)
629                 $abandon_days = 0;
630
631         $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
632
633         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'pumpio' AND `k` = 'import' AND `v` = '1' ORDER BY RAND() ");
634         if(count($r)) {
635                 foreach($r as $rr) {
636                         if ($abandon_days != 0) {
637                                 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
638                                 if (!count($user)) {
639                                         logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
640                                         continue;
641                                 }
642                         }
643
644                         logger('pumpio: importing timeline from user '.$rr['uid']);
645                         pumpio_fetchinbox($a, $rr['uid']);
646
647                         // check for new contacts once a day
648                         $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check');
649                         if($last_contact_check)
650                                 $next_contact_check = $last_contact_check + 86400;
651                         else
652                                 $next_contact_check = 0;
653
654                         if($next_contact_check <= time()) {
655                                 pumpio_getallusers($a, $rr["uid"]);
656                                 set_pconfig($rr['uid'],'pumpio','contact_check',time());
657                         }
658                 }
659         }
660
661         logger('pumpio: cron_end');
662
663         set_config('pumpio','last_poll', time());
664 }
665
666 function pumpio_fetchtimeline(&$a, $uid) {
667         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
668         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
669         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
670         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
671         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
672         $hostname = get_pconfig($uid, 'pumpio','host');
673         $username = get_pconfig($uid, "pumpio", "user");
674
675         $application_name  = get_config('pumpio', 'application_name');
676
677         if ($application_name == "")
678                 $application_name = $a->get_hostname();
679
680         $first_time = ($lastdate == "");
681
682         $client = new oauth_client_class;
683         $client->oauth_version = '1.0a';
684         $client->authorization_header = true;
685         $client->url_parameters = false;
686
687         $client->client_id = $ckey;
688         $client->client_secret = $csecret;
689         $client->access_token = $otoken;
690         $client->access_token_secret = $osecret;
691
692         $url = 'https://'.$hostname.'/api/user/'.$username.'/feed/major';
693
694         logger('pumpio: fetching for user '.$uid.' '.$url.' C:'.$client->client_id.' CS:'.$client->client_secret.' T:'.$client->access_token.' TS:'.$client->access_token_secret);
695
696         $username = $user.'@'.$host;
697
698         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
699
700         if (!$success) {
701                 logger('pumpio: error fetching posts for user '.$uid." ".$username." ".print_r($user, true));
702                 return;
703         }
704
705         $posts = array_reverse($user->items);
706
707         $initiallastdate = $lastdate;
708         $lastdate = '';
709
710         if (count($posts)) {
711                 foreach ($posts as $post) {
712                         if ($post->published <= $initiallastdate)
713                                 continue;
714
715                         if ($lastdate < $post->published)
716                                 $lastdate = $post->published;
717
718                         if ($first_time)
719                                 continue;
720
721                         $receiptians = array();
722                         if (@is_array($post->cc))
723                                 $receiptians = array_merge($receiptians, $post->cc);
724
725                         if (@is_array($post->to))
726                                 $receiptians = array_merge($receiptians, $post->to);
727
728                         $public = false;
729                         foreach ($receiptians AS $receiver)
730                                 if (is_string($receiver->objectType))
731                                         if ($receiver->id == "http://activityschema.org/collection/public")
732                                                 $public = true;
733
734                         if ($public AND !stristr($post->generator->displayName, $application_name)) {
735                                 require_once('include/html2bbcode.php');
736
737                                 $_SESSION["authenticated"] = true;
738                                 $_SESSION["uid"] = $uid;
739
740                                 unset($_REQUEST);
741                                 $_REQUEST["type"] = "wall";
742                                 $_REQUEST["api_source"] = true;
743                                 $_REQUEST["profile_uid"] = $uid;
744                                 $_REQUEST["source"] = "pump.io";
745
746                                 if ($post->object->displayName != "")
747                                         $_REQUEST["title"] = html2bbcode($post->object->displayName);
748                                 else
749                                         $_REQUEST["title"] = "";
750
751                                 $_REQUEST["body"] = html2bbcode($post->object->content);
752
753                                 // To-Do: Picture has to be cached and stored locally
754                                 if ($post->object->fullImage->url != "") {
755                                         if ($post->object->fullImage->pump_io->proxyURL != "")
756                                                 $_REQUEST["body"] = "[url=".$post->object->fullImage->pump_io->proxyURL."][img]".$post->object->image->pump_io->proxyURL."[/img][/url]\n".$_REQUEST["body"];
757                                         else
758                                                 $_REQUEST["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$_REQUEST["body"];
759                                 }
760
761                                 logger('pumpio: posting for user '.$uid);
762
763                                 require_once('mod/item.php');
764
765                                 item_post($a);
766                                 logger('pumpio: posting done - user '.$uid);
767                         }
768                 }
769         }
770
771         if ($lastdate != 0)
772                 set_pconfig($uid,'pumpio','lastdate', $lastdate);
773 }
774
775 function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) {
776         // Searching for the unliked post
777         // Two queries for speed issues
778         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
779                                 dbesc($post->object->id),
780                                 intval($uid)
781                 );
782
783         if (count($r))
784                 $orig_post = $r[0];
785         else {
786                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
787                                         dbesc($post->object->id),
788                                         intval($uid)
789                         );
790
791                 if (!count($r))
792                         return;
793                 else
794                         $orig_post = $r[0];
795         }
796
797         $contactid = 0;
798
799         if(link_compare($post->actor->url, $own_id)) {
800                 $contactid = $self[0]['id'];
801         } else {
802                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
803                         dbesc($post->actor->url),
804                         intval($uid)
805                 );
806
807                 if(count($r))
808                         $contactid = $r[0]['id'];
809
810                 if($contactid == 0)
811                         $contactid = $orig_post['contact-id'];
812         }
813
814         $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'",
815                 dbesc(datetime_convert()),
816                 dbesc(ACTIVITY_LIKE),
817                 intval($uid),
818                 intval($contactid),
819                 dbesc($orig_post['uri'])
820         );
821
822         if(count($r))
823                 logger("pumpio_dounlike: unliked existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
824         else
825                 logger("pumpio_dounlike: not found. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
826 }
827
828 function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = true) {
829         require_once('include/items.php');
830
831         // Searching for the liked post
832         // Two queries for speed issues
833         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
834                                 dbesc($post->object->id),
835                                 intval($uid)
836                 );
837
838         if (count($r))
839                 $orig_post = $r[0];
840         else {
841                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
842                                         dbesc($post->object->id),
843                                         intval($uid)
844                         );
845
846                 if (!count($r))
847                         return;
848                 else
849                         $orig_post = $r[0];
850         }
851
852         // thread completion
853         if ($threadcompletion)
854                 pumpio_fetchallcomments($a, $uid, $post->object->id);
855
856         $contactid = 0;
857
858         if(link_compare($post->actor->url, $own_id)) {
859                 $contactid = $self[0]['id'];
860                 $post->actor->displayName = $self[0]['name'];
861                 $post->actor->url = $self[0]['url'];
862                 $post->actor->image->url = $self[0]['photo'];
863         } else {
864                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
865                         dbesc($post->actor->url),
866                         intval($uid)
867                 );
868
869                 if(count($r))
870                         $contactid = $r[0]['id'];
871
872                 if($contactid == 0)
873                         $contactid = $orig_post['contact-id'];
874         }
875
876         $r = q("SELECT parent FROM `item` WHERE `verb` = '%s' AND `uid` = %d AND `contact-id` = %d AND `thr-parent` = '%s' LIMIT 1",
877                 dbesc(ACTIVITY_LIKE),
878                 intval($uid),
879                 intval($contactid),
880                 dbesc($orig_post['uri'])
881         );
882
883         if(count($r)) {
884                 logger("pumpio_dolike: found existing like. User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
885                 return;
886         }
887
888         $likedata = array();
889         $likedata['parent'] = $orig_post['id'];
890         $likedata['verb'] = ACTIVITY_LIKE;
891         $likedata['gravity'] = 3;
892         $likedata['uid'] = $uid;
893         $likedata['wall'] = 0;
894         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
895         $likedata['parent-uri'] = $orig_post["uri"];
896         $likedata['contact-id'] = $contactid;
897         $likedata['app'] = $post->generator->displayName;
898         $likedata['author-name'] = $post->actor->displayName;
899         $likedata['author-link'] = $post->actor->url;
900         $likedata['author-avatar'] = $post->actor->image->url;
901
902         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
903         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
904         $post_type = t('status');
905         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
906         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
907
908         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
909
910         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
911                 '<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>';
912
913         $ret = item_store($likedata);
914
915         logger("pumpio_dolike: ".$ret." User ".$own_id." ".$uid." Contact: ".$contactid." Url ".$orig_post['uri']);
916 }
917
918 function pumpio_get_contact($uid, $contact) {
919
920         $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
921                 dbesc(normalise_link($contact->url)));
922
923         if (count($r) == 0)
924                 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
925                         dbesc(normalise_link($contact->url)),
926                         dbesc($contact->displayName),
927                         dbesc($contact->preferredUsername),
928                         dbesc($contact->image->url));
929         else
930                 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
931                         dbesc($contact->displayName),
932                         dbesc($contact->preferredUsername),
933                         dbesc($contact->image->url),
934                         dbesc(normalise_link($contact->url)));
935
936         if (DB_UPDATE_VERSION >= "1177")
937                 q("UPDATE `unique_contacts` SET `location` = '%s', `about` = '%s' WHERE url = '%s'",
938                         dbesc($contact->location->displayName),
939                         dbesc($contact->summary),
940                         dbesc(normalise_link($contact->url)));
941
942         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
943                 intval($uid), dbesc($contact->url));
944
945         if(!count($r)) {
946                 // create contact record
947                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
948                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
949                                         `writable`, `blocked`, `readonly`, `pending` )
950                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
951                         intval($uid),
952                         dbesc(datetime_convert()),
953                         dbesc($contact->url),
954                         dbesc(normalise_link($contact->url)),
955                         dbesc(str_replace("acct:", "", $contact->id)),
956                         dbesc(''),
957                         dbesc($contact->id), // What is it for?
958                         dbesc('pump.io ' . $contact->id), // What is it for?
959                         dbesc($contact->displayName),
960                         dbesc($contact->preferredUsername),
961                         dbesc($contact->image->url),
962                         dbesc(NETWORK_PUMPIO),
963                         intval(CONTACT_IS_FRIEND),
964                         intval(1),
965                         intval(1)
966                 );
967
968                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
969                         dbesc($contact->url),
970                         intval($uid)
971                         );
972
973                 if(! count($r))
974                         return(false);
975
976                 $contact_id  = $r[0]['id'];
977
978                 $g = q("select def_gid from user where uid = %d limit 1",
979                         intval($uid)
980                 );
981
982                 if($g && intval($g[0]['def_gid'])) {
983                         require_once('include/group.php');
984                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
985                 }
986
987                 require_once("Photo.php");
988
989                 $photos = import_profile_photo($contact->image->url,$uid,$contact_id);
990
991                 q("UPDATE `contact` SET `photo` = '%s',
992                                         `thumb` = '%s',
993                                         `micro` = '%s',
994                                         `name-date` = '%s',
995                                         `uri-date` = '%s',
996                                         `avatar-date` = '%s'
997                                 WHERE `id` = %d
998                         ",
999                 dbesc($photos[0]),
1000                 dbesc($photos[1]),
1001                 dbesc($photos[2]),
1002                 dbesc(datetime_convert()),
1003                 dbesc(datetime_convert()),
1004                 dbesc(datetime_convert()),
1005                 intval($contact_id)
1006                 );
1007
1008                 if (DB_UPDATE_VERSION >= "1177")
1009                         q("UPDATE `contact` SET `location` = '%s',
1010                                                 `about` = '%s'
1011                                         WHERE `id` = %d",
1012                                 dbesc($contact->location->displayName),
1013                                 dbesc($contact->summary),
1014                                 intval($contact_id)
1015                         );
1016         } else {
1017                 // update profile photos once every two weeks as we have no notification of when they change.
1018                 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -14 days')) ? true : false);
1019                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1020
1021                 // check that we have all the photos, this has been known to fail on occasion
1022
1023                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1024                         require_once("Photo.php");
1025
1026                         $photos = import_profile_photo($contact->image->url, $uid, $r[0]['id']);
1027
1028                         q("UPDATE `contact` SET `photo` = '%s',
1029                                         `thumb` = '%s',
1030                                         `micro` = '%s',
1031                                         `name-date` = '%s',
1032                                         `uri-date` = '%s',
1033                                         `avatar-date` = '%s',
1034                                         `name` = '%s',
1035                                         `nick` = '%s'
1036                                         WHERE `id` = %d
1037                                 ",
1038                         dbesc($photos[0]),
1039                         dbesc($photos[1]),
1040                         dbesc($photos[2]),
1041                         dbesc(datetime_convert()),
1042                         dbesc(datetime_convert()),
1043                         dbesc(datetime_convert()),
1044                         dbesc($contact->displayName),
1045                         dbesc($contact->preferredUsername),
1046                         intval($r[0]['id'])
1047                         );
1048
1049                         if (DB_UPDATE_VERSION >= "1177")
1050                                 q("UPDATE `contact` SET `location` = '%s',
1051                                                         `about` = '%s'
1052                                                 WHERE `id` = %d",
1053                                         dbesc($contact->location->displayName),
1054                                         dbesc($contact->summary),
1055                                         intval($r[0]['id'])
1056                                 );
1057                 }
1058
1059         }
1060
1061         return($r[0]["id"]);
1062 }
1063
1064 function pumpio_dodelete(&$a, $uid, $self, $post, $own_id) {
1065
1066         // Two queries for speed issues
1067         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1068                                 dbesc($post->object->id),
1069                                 intval($uid)
1070                 );
1071
1072         if (count($r))
1073                 return drop_item($r[0]["id"], $false);
1074
1075         $r = q("SELECT * FROM `item` WHERE `extid` = '%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
1084 function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcompletion = true) {
1085         require_once('include/items.php');
1086         require_once('include/html2bbcode.php');
1087
1088         if (($post->verb == "like") OR ($post->verb == "favorite"))
1089                 return pumpio_dolike($a, $uid, $self, $post, $own_id);
1090
1091         if (($post->verb == "unlike") OR ($post->verb == "unfavorite"))
1092                 return pumpio_dounlike($a, $uid, $self, $post, $own_id);
1093
1094         if ($post->verb == "delete")
1095                 return pumpio_dodelete($a, $uid, $self, $post, $own_id);
1096
1097         if ($post->verb != "update") {
1098                 // Two queries for speed issues
1099                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1100                                         dbesc($post->object->id),
1101                                         intval($uid)
1102                         );
1103
1104                 if (count($r))
1105                         return false;
1106
1107                 $r = q("SELECT * FROM `item` WHERE `extid` = '%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
1116         // Only handle these three types
1117         if (!strstr("post|share|update", $post->verb))
1118                 return false;
1119
1120         $receiptians = array();
1121         if (@is_array($post->cc))
1122                 $receiptians = array_merge($receiptians, $post->cc);
1123
1124         if (@is_array($post->to))
1125                 $receiptians = array_merge($receiptians, $post->to);
1126
1127         foreach ($receiptians AS $receiver)
1128                 if (is_string($receiver->objectType))
1129                         if ($receiver->id == "http://activityschema.org/collection/public")
1130                                 $public = true;
1131
1132         $postarray = array();
1133         $postarray['network'] = NETWORK_PUMPIO;
1134         $postarray['gravity'] = 0;
1135         $postarray['uid'] = $uid;
1136         $postarray['wall'] = 0;
1137         $postarray['uri'] = $post->object->id;
1138         $postarray['object-type'] = NAMESPACE_ACTIVITY_SCHEMA.strtolower($post->object->objectType);
1139
1140         if ($post->object->objectType != "comment") {
1141                 $contact_id = pumpio_get_contact($uid, $post->actor);
1142
1143                 if (!$contact_id)
1144                         $contact_id = $self[0]['id'];
1145
1146                 $postarray['parent-uri'] = $post->object->id;
1147
1148                 if (!$public) {
1149                         $postarray['private'] = 1;
1150                         $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1151                 }
1152         } else {
1153                 $contact_id = 0;
1154
1155                 if(link_compare($post->actor->url, $own_id)) {
1156                         $contact_id = $self[0]['id'];
1157                         $post->actor->displayName = $self[0]['name'];
1158                         $post->actor->url = $self[0]['url'];
1159                         $post->actor->image->url = $self[0]['photo'];
1160                 } else {
1161                         // Take an existing contact, the contact of the note or - as a fallback - the id of the user
1162                         $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1163                                 dbesc($post->actor->url),
1164                                 intval($uid)
1165                         );
1166
1167                         if(count($r))
1168                                 $contact_id = $r[0]['id'];
1169                         else {
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                                         $contact_id = $self[0]['id'];
1179                         }
1180                 }
1181
1182                 $reply = new stdClass;
1183                 $reply->verb = "note";
1184                 $reply->cc = $post->cc;
1185                 $reply->to = $post->to;
1186                 $reply->object = new stdClass;
1187                 $reply->object->objectType = $post->object->inReplyTo->objectType;
1188                 $reply->object->content = $post->object->inReplyTo->content;
1189                 $reply->object->id = $post->object->inReplyTo->id;
1190                 $reply->actor = $post->object->inReplyTo->author;
1191                 $reply->url = $post->object->inReplyTo->url;
1192                 $reply->generator = new stdClass;
1193                 $reply->generator->displayName = "pumpio";
1194                 $reply->published = $post->object->inReplyTo->published;
1195                 $reply->received = $post->object->inReplyTo->updated;
1196                 $reply->url = $post->object->inReplyTo->url;
1197                 pumpio_dopost($a, $client, $uid, $self, $reply, $own_id, false);
1198
1199                 $postarray['parent-uri'] = $post->object->inReplyTo->id;
1200         }
1201
1202         if ($post->object->pump_io->proxyURL)
1203                 $postarray['extid'] = $post->object->pump_io->proxyURL;
1204
1205         $postarray['contact-id'] = $contact_id;
1206         $postarray['verb'] = ACTIVITY_POST;
1207         $postarray['owner-name'] = $post->actor->displayName;
1208         $postarray['owner-link'] = $post->actor->url;
1209         $postarray['owner-avatar'] = $post->actor->image->url;
1210         $postarray['author-name'] = $post->actor->displayName;
1211         $postarray['author-link'] = $post->actor->url;
1212         $postarray['author-avatar'] = $post->actor->image->url;
1213         $postarray['plink'] = $post->object->url;
1214         $postarray['app'] = $post->generator->displayName;
1215         $postarray['body'] = html2bbcode($post->object->content);
1216
1217         if ($post->object->fullImage->url != "")
1218                 $postarray["body"] = "[url=".$post->object->fullImage->url."][img]".$post->object->image->url."[/img][/url]\n".$postarray["body"];
1219
1220         if ($post->object->displayName != "")
1221                 $postarray['title'] = $post->object->displayName;
1222
1223         $postarray['created'] = datetime_convert('UTC','UTC',$post->published);
1224         $postarray['edited'] = datetime_convert('UTC','UTC',$post->received);
1225
1226         if ($post->verb == "share") {
1227                 if (!intval(get_config('system','wall-to-wall_share'))) {
1228                         $postarray['body'] = "[share author='".$post->object->author->displayName.
1229                                         "' profile='".$post->object->author->url.
1230                                         "' avatar='".$post->object->author->image->url.
1231                                         "' link='".$post->links->self->href."']".$postarray['body']."[/share]";
1232                 } else {
1233                         // Let shares look like wall-to-wall posts
1234                         $postarray['author-name'] = $post->object->author->displayName;
1235                         $postarray['author-link'] = $post->object->author->url;
1236                         $postarray['author-avatar'] = $post->object->author->image->url;
1237                 }
1238         }
1239
1240         if (trim($postarray['body']) == "")
1241                 return false;
1242
1243         $top_item = item_store($postarray);
1244
1245         if (($top_item == 0) AND ($post->verb == "update")) {
1246                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s' , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1247                         dbesc($postarray["title"]),
1248                         dbesc($postarray["body"]),
1249                         dbesc($postarray["edited"]),
1250                         dbesc($postarray["uri"]),
1251                         intval($uid)
1252                         );
1253         }
1254
1255         if ($post->object->objectType == "comment") {
1256
1257                 if ($threadcompletion)
1258                         pumpio_fetchallcomments($a, $uid, $postarray['parent-uri']);
1259
1260                 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1261                                 intval($uid)
1262                         );
1263
1264                 if(!count($user))
1265                         return $top_item;
1266
1267                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1268
1269                 if (link_compare($own_id, $postarray['author-link']))
1270                         return $top_item;
1271
1272                 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1273                                 dbesc($postarray['parent-uri']),
1274                                 intval($uid)
1275                                 );
1276
1277                 if(count($myconv)) {
1278
1279                         foreach($myconv as $conv) {
1280                                 // now if we find a match, it means we're in this conversation
1281
1282                                 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_id))
1283                                         continue;
1284
1285                                 require_once('include/enotify.php');
1286
1287                                 $conv_parent = $conv['parent'];
1288
1289                                 notification(array(
1290                                         'type'         => NOTIFY_COMMENT,
1291                                         'notify_flags' => $user[0]['notify-flags'],
1292                                         'language'     => $user[0]['language'],
1293                                         'to_name'      => $user[0]['username'],
1294                                         'to_email'     => $user[0]['email'],
1295                                         'uid'          => $user[0]['uid'],
1296                                         'item'         => $postarray,
1297                                         'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1298                                         'source_name'  => $postarray['author-name'],
1299                                         'source_link'  => $postarray['author-link'],
1300                                         'source_photo' => $postarray['author-avatar'],
1301                                         'verb'         => ACTIVITY_POST,
1302                                         'otype'        => 'item',
1303                                         'parent'       => $conv_parent,
1304                                         ));
1305
1306                                 // only send one notification
1307                                 break;
1308                         }
1309                 }
1310         }
1311
1312         return $top_item;
1313 }
1314
1315 function pumpio_fetchinbox(&$a, $uid) {
1316
1317         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1318         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1319         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1320         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1321         $lastdate = get_pconfig($uid, 'pumpio', 'lastdate');
1322         $hostname = get_pconfig($uid, 'pumpio','host');
1323         $username = get_pconfig($uid, "pumpio", "user");
1324
1325         $own_id = "https://".$hostname."/".$username;
1326
1327         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1328                 intval($uid));
1329
1330         $lastitems = q("SELECT uri FROM `item` WHERE `network` = '%s' AND `uid` = %d AND
1331                         `extid` != '' AND `id` = `parent`
1332                         ORDER BY `commented` DESC LIMIT 10",
1333                                 dbesc(NETWORK_PUMPIO),
1334                                 intval($uid)
1335                         );
1336
1337         $client = new oauth_client_class;
1338         $client->oauth_version = '1.0a';
1339         $client->authorization_header = true;
1340         $client->url_parameters = false;
1341
1342         $client->client_id = $ckey;
1343         $client->client_secret = $csecret;
1344         $client->access_token = $otoken;
1345         $client->access_token_secret = $osecret;
1346
1347         $last_id = get_pconfig($uid,'pumpio','last_id');
1348
1349         $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox';
1350
1351         if ($last_id != "")
1352                 $url .= '?since='.urlencode($last_id);
1353
1354         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user);
1355
1356         if ($user->items) {
1357             $posts = array_reverse($user->items);
1358
1359             if (count($posts))
1360                     foreach ($posts as $post) {
1361                             $last_id = $post->id;
1362                             pumpio_dopost($a, $client, $uid, $self, $post, $own_id, true);
1363                     }
1364         }
1365
1366         foreach ($lastitems AS $item)
1367                 pumpio_fetchallcomments($a, $uid, $item["uri"]);
1368
1369         set_pconfig($uid,'pumpio','last_id', $last_id);
1370 }
1371
1372 function pumpio_getallusers(&$a, $uid) {
1373         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1374         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1375         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1376         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1377         $hostname = get_pconfig($uid, 'pumpio','host');
1378         $username = get_pconfig($uid, "pumpio", "user");
1379
1380         $client = new oauth_client_class;
1381         $client->oauth_version = '1.0a';
1382         $client->authorization_header = true;
1383         $client->url_parameters = false;
1384
1385         $client->client_id = $ckey;
1386         $client->client_secret = $csecret;
1387         $client->access_token = $otoken;
1388         $client->access_token_secret = $osecret;
1389
1390         $url = 'https://'.$hostname.'/api/user/'.$username.'/following';
1391
1392         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1393
1394         if ($users->totalItems > count($users->items)) {
1395                 $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems;
1396
1397                 $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users);
1398         }
1399
1400         foreach ($users->items AS $user)
1401                 pumpio_get_contact($uid, $user);
1402 }
1403
1404 function pumpio_queue_hook(&$a,&$b) {
1405
1406         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1407                 dbesc(NETWORK_PUMPIO)
1408         );
1409         if(! count($qi))
1410                 return;
1411
1412         require_once('include/queue_fn.php');
1413
1414         foreach($qi as $x) {
1415                 if($x['network'] !== NETWORK_PUMPIO)
1416                         continue;
1417
1418                 logger('pumpio_queue: run');
1419
1420                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
1421                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1422                         intval($x['cid'])
1423                 );
1424                 if(! count($r))
1425                         continue;
1426
1427                 $userdata = $r[0];
1428
1429                 //logger('pumpio_queue: fetching userdata '.print_r($userdata, true));
1430
1431                 $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token");
1432                 $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret");
1433                 $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key");
1434                 $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret");
1435
1436                 $host = get_pconfig($userdata['uid'], "pumpio", "host");
1437                 $user = get_pconfig($userdata['uid'], "pumpio", "user");
1438
1439                 $success = false;
1440
1441                 if ($oauth_token AND $oauth_token_secret AND
1442                         $consumer_key AND $consumer_secret) {
1443                         $username = $user.'@'.$host;
1444
1445                         logger('pumpio_queue: able to post for user '.$username);
1446
1447                         $z = unserialize($x['content']);
1448
1449                         $client = new oauth_client_class;
1450                         $client->oauth_version = '1.0a';
1451                         $client->url_parameters = false;
1452                         $client->authorization_header = true;
1453                         $client->access_token = $oauth_token;
1454                         $client->access_token_secret = $oauth_token_secret;
1455                         $client->client_id = $consumer_key;
1456                         $client->client_secret = $consumer_secret;
1457
1458                         $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
1459
1460                         if($success) {
1461                                 $post_id = $user->object->id;
1462                                 logger('pumpio_queue: send '.$username.': success '.$post_id);
1463                                 if($post_id AND $iscomment) {
1464                                         logger('pumpio_send '.$username.': Update extid '.$post_id." for post id ".$z['item']);
1465                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
1466                                                 dbesc($post_id),
1467                                                 intval($z['item'])
1468                                         );
1469                                 }
1470                                 remove_queue_item($x['id']);
1471                         } else
1472                                 logger('pumpio_queue: send '.$username.': '.$url.' general error: ' . print_r($user,true));
1473                 } else
1474                         logger("pumpio_queue: Error getting tokens for user ".$userdata['uid']);
1475
1476                 if (!$success) {
1477                         logger('pumpio_queue: delayed');
1478                         update_queue_time($x['id']);
1479                 }
1480         }
1481 }
1482
1483 function pumpio_getreceiver(&$a, $b) {
1484
1485         $receiver = array();
1486
1487         if (!$b["private"]) {
1488
1489                 if(! strstr($b['postopts'],'pumpio'))
1490                         return $receiver;
1491
1492                 $public = get_pconfig($b['uid'], "pumpio", "public");
1493
1494                 if ($public)
1495                         $receiver["to"][] = Array(
1496                                                 "objectType" => "collection",
1497                                                 "id" => "http://activityschema.org/collection/public");
1498         } else {
1499                 $cids = explode("><", $b["allow_cid"]);
1500                 $gids = explode("><", $b["allow_gid"]);
1501
1502                 foreach ($cids AS $cid) {
1503                         $cid = trim($cid, " <>");
1504
1505                         $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",
1506                                 intval($cid),
1507                                 intval($b["uid"]),
1508                                 dbesc(NETWORK_PUMPIO)
1509                                 );
1510
1511                         if (count($r)) {
1512                                 $receiver["bcc"][] = Array(
1513                                                         "displayName" => $r[0]["name"],
1514                                                         "objectType" => "person",
1515                                                         "preferredUsername" => $r[0]["nick"],
1516                                                         "url" => $r[0]["url"]);
1517                         }
1518                 }
1519                 foreach ($gids AS $gid) {
1520                         $gid = trim($gid, " <>");
1521
1522                         $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ".
1523                                 "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ".
1524                                 "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'",
1525                                         intval($gid),
1526                                         intval($b["uid"]),
1527                                         dbesc(NETWORK_PUMPIO)
1528                                 );
1529
1530                         foreach ($r AS $row)
1531                                 $receiver["bcc"][] = Array(
1532                                                         "displayName" => $row["name"],
1533                                                         "objectType" => "person",
1534                                                         "preferredUsername" => $row["nick"],
1535                                                         "url" => $row["url"]);
1536                 }
1537         }
1538
1539         if ($b["inform"] != "") {
1540
1541                 $inform = explode(",", $b["inform"]);
1542
1543                 foreach ($inform AS $cid) {
1544                         if (substr($cid, 0, 4) != "cid:")
1545                                 continue;
1546
1547                         $cid = str_replace("cid:", "", $cid);
1548
1549                         $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",
1550                                 intval($cid),
1551                                 intval($b["uid"]),
1552                                 dbesc(NETWORK_PUMPIO)
1553                                 );
1554
1555                         if (count($r)) {
1556                                         $receiver["to"][] = Array(
1557                                                                 "displayName" => $r[0]["name"],
1558                                                                 "objectType" => "person",
1559                                                                 "preferredUsername" => $r[0]["nick"],
1560                                                                 "url" => $r[0]["url"]);
1561                         }
1562                 }
1563         }
1564
1565         return $receiver;
1566 }
1567
1568 function pumpio_fetchallcomments(&$a, $uid, $id) {
1569         $ckey    = get_pconfig($uid, 'pumpio', 'consumer_key');
1570         $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret');
1571         $otoken  = get_pconfig($uid, 'pumpio', 'oauth_token');
1572         $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret');
1573         $hostname = get_pconfig($uid, 'pumpio','host');
1574         $username = get_pconfig($uid, "pumpio", "user");
1575
1576         logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id);
1577
1578         $own_id = "https://".$hostname."/".$username;
1579
1580         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1581                 intval($uid));
1582
1583         // Fetching the original post
1584         $r = q("SELECT `extid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `extid` != '' LIMIT 1",
1585                         dbesc($id),
1586                         intval($uid)
1587                 );
1588
1589         if (!count($r))
1590                 return false;
1591
1592         $url = $r[0]["extid"];
1593
1594         $client = new oauth_client_class;
1595         $client->oauth_version = '1.0a';
1596         $client->authorization_header = true;
1597         $client->url_parameters = false;
1598
1599         $client->client_id = $ckey;
1600         $client->client_secret = $csecret;
1601         $client->access_token = $otoken;
1602         $client->access_token_secret = $osecret;
1603
1604         logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url);
1605
1606         $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item);
1607
1608         if (!$success)
1609                 return;
1610
1611         if ($item->likes->totalItems != 0) {
1612                 foreach ($item->likes->items AS $post) {
1613                         $like = new stdClass;
1614                         $like->object = new stdClass;
1615                         $like->object->id = $item->id;
1616                         $like->actor = new stdClass;
1617                         $like->actor->displayName = $item->displayName;
1618                         $like->actor->preferredUsername = $item->preferredUsername;
1619                         $like->actor->url = $item->url;
1620                         $like->actor->image = $item->image;
1621                         $like->generator = new stdClass;
1622                         $like->generator->displayName = "pumpio";
1623                         pumpio_dolike($a, $uid, $self, $post, $own_id, false);
1624                 }
1625         }
1626
1627         if ($item->replies->totalItems == 0)
1628                 return;
1629
1630         foreach ($item->replies->items AS $item) {
1631                 if ($item->id == $id)
1632                         continue;
1633
1634                 // Checking if the comment already exists - Two queries for speed issues
1635                 $r = q("SELECT extid FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1636                                 dbesc($item->id),
1637                                 intval($uid)
1638                         );
1639
1640                 if (count($r))
1641                         continue;
1642
1643                 $r = q("SELECT extid FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1644                                 dbesc($item->id),
1645                                 intval($uid)
1646                         );
1647
1648                 if (count($r))
1649                         continue;
1650
1651                 $post = new stdClass;
1652                 $post->verb = "post";
1653                 $post->actor = $item->author;
1654                 $post->published = $item->published;
1655                 $post->received = $item->updated;
1656                 $post->generator = new stdClass;
1657                 $post->generator->displayName = "pumpio";
1658                 // To-Do: Check for public post
1659
1660                 unset($item->author);
1661                 unset($item->published);
1662                 unset($item->updated);
1663
1664                 $post->object = $item;
1665
1666                 logger("pumpio_fetchallcomments: posting comment ".$post->object->id." ".print_r($post, true));
1667                 pumpio_dopost($a, $client, $uid, $self, $post, $own_id, false);
1668         }
1669 }
1670
1671 /*
1672 To-Do:
1673  - edit own notes
1674  - delete own notes
1675 */