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