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