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