]> git.mxchange.org Git - friendica-addons.git/blob - appnet/appnet.php
Appnet: Bidirectional sync with app.net
[friendica-addons.git] / appnet / appnet.php
1 <?php
2
3 /**
4  * Name: App.net Connector
5  * Description: app.net postings import and export
6  * Version: 0.2
7  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8  */
9
10 /*
11  Some marker in the post so that reimported posts can be treated better. (BBCode over app.net?)
12 */
13
14 define('APPNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
15
16 function appnet_install() {
17         register_hook('post_local',             'addon/appnet/appnet.php', 'appnet_post_local');
18         register_hook('notifier_normal',        'addon/appnet/appnet.php', 'appnet_send');
19         register_hook('jot_networks',           'addon/appnet/appnet.php', 'appnet_jot_nets');
20         register_hook('cron',                   'addon/appnet/appnet.php', 'appnet_cron');
21         register_hook('connector_settings',     'addon/appnet/appnet.php', 'appnet_settings');
22         register_hook('connector_settings_post','addon/appnet/appnet.php', 'appnet_settings_post');
23 }
24
25
26 function appnet_uninstall() {
27         unregister_hook('post_local',       'addon/appnet/appnet.php', 'appnet_post_local');
28         unregister_hook('notifier_normal',  'addon/appnet/appnet.php', 'appnet_send');
29         unregister_hook('jot_networks',     'addon/appnet/appnet.php', 'appnet_jot_nets');
30         unregister_hook('cron',                 'addon/appnet/appnet.php', 'appnet_cron');
31         unregister_hook('connector_settings',      'addon/appnet/appnet.php', 'appnet_settings');
32         unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post');
33 }
34
35 function appnet_module() {}
36
37 function appnet_content(&$a) {
38         if(! local_user()) {
39                 notice( t('Permission denied.') . EOL);
40                 return '';
41         }
42
43         require_once("mod/settings.php");
44         settings_init($a);
45
46         if (isset($a->argv[1]))
47                 switch ($a->argv[1]) {
48                         case "connect":
49                                 $o = appnet_connect($a);
50                                 break;
51                         default:
52                                 $o = print_r($a->argv, true);
53                                 break;
54                 }
55         else
56                 $o = appnet_connect($a);
57
58         return $o;
59 }
60
61 function appnet_connect(&$a) {
62         require_once 'addon/appnet/AppDotNet.php';
63
64         $clientId     = get_pconfig(local_user(),'appnet','clientid');
65         $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
66
67         $app = new AppDotNet($clientId, $clientSecret);
68
69         try {
70                 $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect');
71
72                 logger("appnet_connect: authenticated");
73                 $o .= t("You are now authenticated to app.net. ");
74                 set_pconfig(local_user(),'appnet','token', $token);
75         }
76         catch (AppDotNetException $e) {
77                 $o .= t("<p>Error fetching token. Please try again.</p>");
78         }
79
80         $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
81
82         return($o);
83 }
84
85 function appnet_jot_nets(&$a,&$b) {
86         if(! local_user())
87                 return;
88
89         $post = get_pconfig(local_user(),'appnet','post');
90         if(intval($post) == 1) {
91                 $defpost = get_pconfig(local_user(),'appnet','post_by_default');
92                 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
93                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="appnet_enable"' . $selected . ' value="1" /> '
94                         . t('Post to app.net') . '</div>';
95     }
96 }
97
98 function appnet_settings(&$a,&$s) {
99         require_once 'addon/appnet/AppDotNet.php';
100
101         if(! local_user())
102                 return;
103
104         $token = get_pconfig(local_user(),'appnet','token');
105         $app_clientId     = get_pconfig(local_user(),'appnet','clientid');
106         $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
107
108         /* Add our stylesheet to the page so we can make our settings look nice */
109         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/appnet/appnet.css' . '" media="all" />' . "\r\n";
110
111         $enabled = get_pconfig(local_user(),'appnet','post');
112         $checked = (($enabled) ? ' checked="checked" ' : '');
113
114         $css = (($enabled) ? '' : '-disabled');
115
116         $def_enabled = get_pconfig(local_user(),'appnet','post_by_default');
117         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
118
119         $importenabled = get_pconfig(local_user(),'appnet','import');
120         $importchecked = (($importenabled) ? ' checked="checked" ' : '');
121
122         $ownid =  get_pconfig(local_user(),'appnet','ownid');
123
124         $s .= '<span id="settings_appnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
125         $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Export').'</h3>';
126         $s .= '</span>';
127         $s .= '<div id="settings_appnet_expanded" class="settings-block" style="display: none;">';
128         $s .= '<span class="fakelink" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
129         $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Export').'</h3>';
130         $s .= '</span>';
131
132         if ($token != "") {
133                 $app = new AppDotNet($app_clientId, $app_clientSecret);
134                 $app->setAccessToken($token);
135
136                 try {
137                         $userdata = $app->getUser();
138
139                         if ($ownid != $userdata["id"])
140                                 set_pconfig(local_user(),'appnet','ownid', $userdata["id"]);
141
142                         $s .= '<div id="appnet-info" ><img id="appnet-avatar" src="'.$userdata["avatar_image"]["url"].'" /><p id="appnet-info-block">'. t('Currently connected to: ') .'<a href="'.$userdata["canonical_url"].'" target="_appnet">'.$userdata["username"].'</a><br /><em>'.$userdata["description"]["text"].'</em></p></div>';
143                         $s .= '<div id="appnet-enable-wrapper">';
144                         $s .= '<label id="appnet-enable-label" for="appnet-checkbox">' . t('Enable App.net Post Plugin') . '</label>';
145                         $s .= '<input id="appnet-checkbox" type="checkbox" name="appnet" value="1" ' . $checked . '/>';
146                         $s .= '</div><div class="clear"></div>';
147
148                         $s .= '<div id="appnet-bydefault-wrapper">';
149                         $s .= '<label id="appnet-bydefault-label" for="appnet-bydefault">' . t('Post to App.net by default') . '</label>';
150                         $s .= '<input id="appnet-bydefault" type="checkbox" name="appnet_bydefault" value="1" ' . $def_checked . '/>';
151                         $s .= '</div><div class="clear"></div>';
152
153                         $s .= '<label id="appnet-import-label" for="appnet-import">'.t('Import the remote timeline').'</label>';
154                         $s .= '<input id="appnet-import" type="checkbox" name="appnet_import" value="1" '. $importchecked . '/>';
155                         $s .= '<div class="clear"></div>';
156
157                 }
158                 catch (AppDotNetException $e) {
159                         $s .= t("<p>Error fetching user profile. Please clear the configuration and try again.</p>");
160                 }
161                 //$s .= print_r($userdata, true);
162
163         } elseif (($app_clientId == '') OR ($app_clientSecret == '')) {
164                 $s .= t("<p>You have two ways to connect to App.net.</p>");
165                 $s .= "<hr />";
166                 $s .= t('<p>First way: Register an application at <a href="https://account.app.net/developer/apps/">https://account.app.net/developer/apps/</a> and enter Client ID and Client Secret. ');
167                 $s .= sprintf(t("Use '%s' as Redirect URI<p>"), $a->get_baseurl().'/appnet/connect');
168                 $s .= '<div id="appnet-clientid-wrapper">';
169                 $s .= '<label id="appnet-clientid-label" for="appnet-clientid">' . t('Client ID') . '</label>';
170                 $s .= '<input id="appnet-clientid" type="text" name="clientid" value="'.$app_clientId.'" />';
171                 $s .= '</div><div class="clear"></div>';
172                 $s .= '<div id="appnet-clientsecret-wrapper">';
173                 $s .= '<label id="appnet-clientsecret-label" for="appnet-clientsecret">' . t('Client Secret') . '</label>';
174                 $s .= '<input id="appnet-clientsecret" type="text" name="clientsecret" value="'.$app_clientSecret.'" />';
175                 $s .= '</div><div class="clear"></div>';
176                 $s .= "<hr />";
177                 $s .= t('<p>Second way: fetch a token at <a href="http://dev-lite.jonathonduerig.com/">http://dev-lite.jonathonduerig.com/</a>. ');
178                 $s .= t("Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.</p>");
179                 $s .= '<div id="appnet-token-wrapper">';
180                 $s .= '<label id="appnet-token-label" for="appnet-token">' . t('Token') . '</label>';
181                 $s .= '<input id="appnet-token" type="text" name="token" value="'.$token.'" />';
182                 $s .= '</div><div class="clear"></div>';
183
184         } else {
185                 $app = new AppDotNet($app_clientId, $app_clientSecret);
186
187                 $scope =  array('basic', 'stream', 'write_post',
188                                 'public_messages', 'messages');
189
190                 $url = $app->getAuthUrl($a->get_baseurl().'/appnet/connect', $scope);
191                 $s .= '<div class="clear"></div>';
192                 $s .= '<a href="'.$url.'">'.t("Sign in using App.net").'</a>';
193         }
194
195         if (($app_clientId != '') OR ($app_clientSecret != '') OR ($token !='')) {
196                 $s .= '<div id="appnet-disconnect-wrapper">';
197                 $s .= '<label id="appnet-disconnect-label" for="appnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
198
199                 $s .= '<input id="appnet-disconnect" type="checkbox" name="appnet-disconnect" value="1" />';
200                 $s .= '</div><div class="clear"></div>';
201         }
202
203         /* provide a submit button */
204         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="appnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
205
206         $s .= '</div>';
207 }
208
209 function appnet_settings_post(&$a,&$b) {
210
211         if(x($_POST,'appnet-submit')) {
212
213                 if (isset($_POST['appnet-disconnect'])) {
214                         del_pconfig(local_user(), 'appnet', 'clientsecret');
215                         del_pconfig(local_user(), 'appnet', 'clientid');
216                         del_pconfig(local_user(), 'appnet', 'token');
217                         del_pconfig(local_user(), 'appnet', 'post');
218                         del_pconfig(local_user(), 'appnet', 'post_by_default');
219                         del_pconfig(local_user(), 'appnet', 'import');
220                 }
221
222                 if (isset($_POST["clientsecret"]))
223                         set_pconfig(local_user(),'appnet','clientsecret', $_POST['clientsecret']);
224
225                 if (isset($_POST["clientid"]))
226                         set_pconfig(local_user(),'appnet','clientid', $_POST['clientid']);
227
228                 if (isset($_POST["token"]) AND ($_POST["token"] != ""))
229                         set_pconfig(local_user(),'appnet','token', $_POST['token']);
230
231                 set_pconfig(local_user(), 'appnet', 'post', intval($_POST['appnet']));
232                 set_pconfig(local_user(), 'appnet', 'post_by_default', intval($_POST['appnet_bydefault']));
233                 set_pconfig(local_user(), 'appnet', 'import', intval($_POST['appnet_import']));
234         }
235 }
236
237 function appnet_post_local(&$a,&$b) {
238         if($b['edit'])
239                 return;
240
241         if((local_user()) && (local_user() == $b['uid']) && (!$b['private']) && (!$b['parent'])) {
242                 $appnet_post = intval(get_pconfig(local_user(),'appnet','post'));
243                 $appnet_enable = (($appnet_post && x($_REQUEST,'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0);
244
245                 // if API is used, default to the chosen settings
246                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnet','post_by_default')))
247                         $appnet_enable = 1;
248
249                 if(! $appnet_enable)
250                         return;
251
252                 if(strlen($b['postopts']))
253                         $b['postopts'] .= ',';
254
255                 $b['postopts'] .= 'appnet';
256         }
257 }
258
259 function appnet_send(&$a,&$b) {
260
261         logger('appnet_send: invoked for post '.$b['id']." ".$b['app']);
262
263         if (!get_pconfig($b["uid"],'appnet','import')) {
264                 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
265                         return;
266         }
267
268         if($b['parent'] != $b['id']) {
269                 logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA);
270
271                 // Looking if its a reply to an app.net post
272                 if ((substr($b["parent-uri"], 0, 5) != "adn::") AND (substr($b["extid"], 0, 5) != "adn::") AND (substr($b["thr-parent"], 0, 5) != "adn::")) {
273                         logger("appnet_send: no app.net post ".$b["parent"]);
274                         return;
275                 }
276
277                 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
278                         dbesc($b["thr-parent"]),
279                         intval($b["uid"]));
280
281                 if(!count($r)) {
282                         logger("appnet_send: no parent found ".$b["thr-parent"]);
283                         return;
284                 } else {
285                         $iscomment = true;
286                         $orig_post = $r[0];
287                 }
288
289                 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
290                 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
291                 $nicknameplain = "@".$nicknameplain;
292
293                 logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
294                 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
295                         $b["body"] = $nickname." ".$b["body"];
296
297                 logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA);
298         } else {
299                 $iscomment = false;
300
301                 if($b['private'] OR !strstr($b['postopts'],'appnet'))
302                         return;
303         }
304
305         if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
306                 appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete");
307
308         if($b['verb'] == ACTIVITY_LIKE) {
309                 logger("appnet_send: ".print_r($b, true), LOGGER_DEBUG);
310                 logger("appnet_send: parameter 2 ".substr($b["thr-parent"], 5), LOGGER_DEBUG);
311                 if ($b['deleted'])
312                         appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "unlike");
313                 else
314                         appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "like");
315                 return;
316         }
317
318         if($b['deleted'] || ($b['created'] !== $b['edited']))
319                 return;
320
321         $token = get_pconfig($b['uid'],'appnet','token');
322
323         if($token) {
324
325                 // If it's a repeated message from app.net then do a native repost and exit
326                 if (appnet_is_repost($a, $b['uid'], $b['body']))
327                         return;
328
329
330                 require_once 'addon/appnet/AppDotNet.php';
331
332                 $clientId     = get_pconfig($b["uid"],'appnet','clientid');
333                 $clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
334
335                 $app = new AppDotNet($clientId, $clientSecret);
336                 $app->setAccessToken($token);
337
338                 $data = array();
339
340                 require_once("include/plaintext.php");
341                 require_once("include/network.php");
342
343                 $post = plaintext($a, $b, 256, false);
344                 logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG);
345
346                 if (isset($post["image"])) {
347                         $img_str = fetch_url($post['image'],true, $redirects, 10);
348                         $tempfile = tempnam(get_config("system","temppath"), "cache");
349                         file_put_contents($tempfile, $img_str);
350
351                         try {
352                                 $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo"));
353
354                                 $data["annotations"][] = array(
355                                                                 "type" => "net.app.core.oembed",
356                                                                 "value" => array(
357                                                                         "+net.app.core.file" => array(
358                                                                                 "file_id" => $photoFile["id"],
359                                                                                 "file_token" => $photoFile["file_token"],
360                                                                                 "format" => "oembed")
361                                                                         )
362                                                                 );
363                         }
364                         catch (AppDotNetException $e) {
365                                 logger("appnet_send: Error creating file");
366                         }
367
368                         unlink($tempfile);
369                 }
370
371                 // Adding a link to the original post, if it is a root post
372                 if($b['parent'] == $b['id'])
373                         $data["annotations"][] = array(
374                                                         "type" => "net.app.core.crosspost",
375                                                         "value" => array("canonical_url" => $b["plink"])
376                                                         );
377
378                 // Adding the original post
379                 $data["annotations"][] = array(
380                                                 "type" => "com.friendica.post",
381                                                 "value" => array(
382                                                                 "uri" => $b["uri"],
383                                                                 "title" => $b["title"],
384                                                                 "body" => substr($b["body"], 0, 4000), // To-Do: Better shortening
385                                                                 "tag" => $b["tag"],
386                                                                 "author-name" => $b["author-name"],
387                                                                 "author-link" => $b["author-link"],
388                                                                 "author-avatar" => $b["author-avatar"],
389                                                                 )
390                                                 );
391
392
393                 // To-Do
394                 // Alle Links verkürzen
395
396                 if (isset($post["url"]) AND !isset($post["title"])) {
397                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
398                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
399
400                         if (strlen($display_url) > 26)
401                                 $display_url = substr($display_url, 0, 25)."…";
402
403                         $post["title"] = $display_url;
404                 }
405
406                 if (isset($post["url"]) AND isset($post["title"])) {
407                         $post["title"] = shortenmsg($post["title"], 90);
408                         $post["text"] = shortenmsg($post["text"], 256 - strlen($post["title"]));
409                         $post["text"] .= "\n[".$post["title"]."](".$post["url"].")";
410                 } elseif (isset($post["url"])) {
411                         $post["url"] = short_link($post["url"]);
412                         $post["text"] = shortenmsg($post["text"], 240);
413                         $post["text"] .= " ".$post["url"];
414                 }
415
416                 //print_r($post);
417                 $data["entities"]["parse_links"] = true;
418                 $data["entities"]["parse_markdown_links"] = true;
419
420                 if ($iscomment)
421                         $data["reply_to"] = substr($orig_post["uri"], 5);
422
423                 try {
424                         $ret = $app->createPost($post["text"], $data);
425                         logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG);
426
427                         if ($iscomment) {
428                                 logger('appnet_send: Update extid '.$ret["id"]." for post id ".$b['id']);
429                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
430                                         dbesc("adn::".$ret["id"]),
431                                         intval($b['id'])
432                                 );
433                         }
434                 }
435                 catch (AppDotNetException $e) {
436                         logger("appnet_send: Error sending message ".$b["id"]);
437                 }
438         }
439 }
440
441 function appnet_action($a, $uid, $pid, $action) {
442         require_once 'addon/appnet/AppDotNet.php';
443
444         $token        = get_pconfig($uid,'appnet','token');
445         $clientId     = get_pconfig($uid,'appnet','clientid');
446         $clientSecret = get_pconfig($uid,'appnet','clientsecret');
447
448         $app = new AppDotNet($clientId, $clientSecret);
449         $app->setAccessToken($token);
450
451         logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
452
453         try {
454                 switch ($action) {
455                         case "delete":
456                                 $result = $app->deletePost($pid);
457                                 break;
458                         case "like":
459                                 $result = $app->starPost($pid);
460                                 break;
461                         case "unlike":
462                                 $result = $app->unstarPost($pid);
463                                 break;
464                 }
465                 logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
466         }
467         catch (AppDotNetException $e) {
468                 logger("appnet_action: Error sending action ".$action." pid ".$pid, LOGGER_DEBUG);
469         }
470 }
471
472 function appnet_is_repost($a, $uid, $body) {
473         $body = trim($body);
474
475         // Skip if it isn't a pure repeated messages
476         // Does it start with a share?
477         if (strpos($body, "[share") > 0)
478                 return(false);
479
480         // Does it end with a share?
481         if (strlen($body) > (strrpos($body, "[/share]") + 8))
482                 return(false);
483
484         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
485         // Skip if there is no shared message in there
486         if ($body == $attributes)
487                 return(false);
488
489         $link = "";
490         preg_match("/link='(.*?)'/ism", $attributes, $matches);
491         if ($matches[1] != "")
492                 $link = $matches[1];
493
494         preg_match('/link="(.*?)"/ism', $attributes, $matches);
495         if ($matches[1] != "")
496                 $link = $matches[1];
497
498         $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link);
499         if ($id == $link)
500                 return(false);
501
502         logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG);
503
504         require_once 'addon/appnet/AppDotNet.php';
505
506         $token        = get_pconfig($uid,'appnet','token');
507         $clientId     = get_pconfig($uid,'appnet','clientid');
508         $clientSecret = get_pconfig($uid,'appnet','clientsecret');
509
510         $app = new AppDotNet($clientId, $clientSecret);
511         $app->setAccessToken($token);
512
513         try {
514                 $result = $app->repost($id);
515                 logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG);
516                 return true;
517         }
518         catch (AppDotNetException $e) {
519                 logger('appnet_is_repost: error doing repost', LOGGER_DEBUG);
520                 return false;
521         }
522 }
523
524 function appnet_fetchstream($a, $uid) {
525         require_once("addon/appnet/AppDotNet.php");
526         require_once('include/items.php');
527
528         $token = get_pconfig($uid,'appnet','token');
529         $clientId     = get_pconfig($uid,'appnet','clientid');
530         $clientSecret = get_pconfig($uid,'appnet','clientsecret');
531
532         $app = new AppDotNet($clientId, $clientSecret);
533         $app->setAccessToken($token);
534
535         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
536                 intval($uid));
537
538         if(count($r))
539                 $me = $r[0];
540         else {
541                 logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG);
542                 return;
543         }
544
545         $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
546                 intval($uid)
547         );
548
549         if(count($user))
550                 $user = $user[0];
551         else {
552                 logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG);
553                 return;
554         }
555
556         $ownid = get_pconfig($uid,'appnet','ownid');
557
558         // Fetch stream
559         $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
560                         "include_html" => false, "include_post_annotations" => true);
561
562         $lastid  = get_pconfig($uid, 'appnet', 'laststreamid');
563
564         if ($lastid <> "")
565                 $param["since_id"] = $lastid;
566
567         try {
568                 $stream = $app->getUserStream($param);
569         }
570         catch (AppDotNetException $e) {
571                 logger("appnet_fetchstream: Error fetching stream for user ".$uid);
572         }
573
574         $stream = array_reverse($stream);
575         foreach ($stream AS $post) {
576                 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
577
578                 $item = item_store($postarray);
579                 logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
580
581                 $lastid = $post["id"];
582
583                 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
584                         $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
585                                 INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
586                                 WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
587
588                         if (count($r)) {
589                                 require_once('include/enotify.php');
590                                 notification(array(
591                                         'type'         => NOTIFY_COMMENT,
592                                         'notify_flags' => $user['notify-flags'],
593                                         'language'     => $user['language'],
594                                         'to_name'      => $user['username'],
595                                         'to_email'     => $user['email'],
596                                         'uid'          => $user['uid'],
597                                         'item'         => $postarray,
598                                         'link'         => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
599                                         'source_name'  => $postarray['author-name'],
600                                         'source_link'  => $postarray['author-link'],
601                                         'source_photo' => $postarray['author-avatar'],
602                                         'verb'         => ACTIVITY_POST,
603                                         'otype'        => 'item',
604                                         'parent'       => $r[0]["parent"],
605                                 ));
606                         }
607                 }
608         }
609
610         set_pconfig($uid, 'appnet', 'laststreamid', $lastid);
611
612         // Fetch mentions
613         $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
614                         "include_html" => false, "include_post_annotations" => true);
615
616         $lastid  = get_pconfig($uid, 'appnet', 'lastmentionid');
617
618         if ($lastid <> "")
619                 $param["since_id"] = $lastid;
620
621         try {
622                 $mentions = $app->getUserMentions("me", $param);
623         }
624         catch (AppDotNetException $e) {
625                 logger("appnet_fetchstream: Error fetching mentions for user ".$uid);
626         }
627
628         $mentions = array_reverse($mentions);
629         foreach ($mentions AS $post) {
630                 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
631
632                 if (isset($postarray["id"]))
633                         $item = $postarray["id"];
634                 elseif (isset($postarray["body"])) {
635                         $item = item_store($postarray);
636                         logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
637                 } else
638                         $item = 0;
639
640                 $lastid = $post["id"];
641
642                 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
643                         require_once('include/enotify.php');
644                         notification(array(
645                                 'type'         => NOTIFY_TAGSELF,
646                                 'notify_flags' => $user['notify-flags'],
647                                 'language'     => $user['language'],
648                                 'to_name'      => $user['username'],
649                                 'to_email'     => $user['email'],
650                                 'uid'          => $user['uid'],
651                                 'item'         => $postarray,
652                                 'link'         => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
653                                 'source_name'  => $postarray['author-name'],
654                                 'source_link'  => $postarray['author-link'],
655                                 'source_photo' => $postarray['author-avatar'],
656                                 'verb'         => ACTIVITY_TAG,
657                                 'otype'        => 'item'
658                         ));
659                 }
660         }
661
662         set_pconfig($uid, 'appnet', 'lastmentionid', $lastid);
663
664
665 /* To-Do
666         $param = array("interaction_actions" => "star");
667         $interactions = $app->getMyInteractions($param);
668         foreach ($interactions AS $interaction)
669                 appnet_dolike($a, $uid, $interaction);
670 */
671 }
672
673 function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true) {
674         require_once('include/items.php');
675
676         if ($post["machine_only"])
677                 return;
678
679         if ($post["is_deleted"])
680                 return;
681
682         $postarray = array();
683         $postarray['gravity'] = 0;
684         $postarray['uid'] = $uid;
685         $postarray['wall'] = 0;
686         $postarray['verb'] = ACTIVITY_POST;
687         $postarray['network'] =  dbesc(NETWORK_APPNET);
688         $postarray['uri'] = "adn::".$post["id"];
689
690         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
691                 dbesc($postarray['uri']),
692                 intval($uid)
693                 );
694
695         if (count($r))
696                 return($r[0]);
697
698         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
699                 dbesc($postarray['uri']),
700                 intval($uid)
701                 );
702
703         if (count($r))
704                 return($r[0]);
705
706         $postarray['parent-uri'] = "adn::".$post["thread_id"];
707         if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
708                 $postarray['thr-parent'] = "adn::".$post["reply_to"];
709
710                 // Complete the thread if the parent doesn't exists
711                 if ($threadcompletion) {
712                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
713                                 dbesc($postarray['thr-parent']),
714                                 intval($uid)
715                                 );
716                         if (!count($r)) {
717                                 require_once("addon/appnet/AppDotNet.php");
718
719                                 $token = get_pconfig($uid,'appnet','token');
720                                 $clientId     = get_pconfig($uid,'appnet','clientid');
721                                 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
722
723                                 $app = new AppDotNet($clientId, $clientSecret);
724                                 $app->setAccessToken($token);
725
726                                 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
727                                                 "include_html" => false, "include_post_annotations" => true);
728                                 try {
729                                         $thread = $app->getPostReplies($post["thread_id"], $param);
730                                 }
731                                 catch (AppDotNetException $e) {
732                                         logger("appnet_createpost: Error fetching thread for user ".$uid);
733                                 }
734                                 $thread = array_reverse($thread);
735                                 foreach ($thread AS $tpost) {
736                                         $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, $createuser, false);
737                                         $item = item_store($threadpost);
738                                 }
739                         }
740                 }
741         } else
742                 $postarray['thr-parent'] = $postarray['uri'];
743
744         $postarray['plink'] = $post["canonical_url"];
745
746         if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) {
747                 $postarray['owner-name'] = $post["user"]["name"];
748                 $postarray['owner-link'] = $post["user"]["canonical_url"];
749                 $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"];
750                 $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser);
751         } else {
752                 $postarray['owner-name'] = $me["name"];
753                 $postarray['owner-link'] = $me["url"];
754                 $postarray['owner-avatar'] = $me["thumb"];
755                 $postarray['contact-id'] = $me["id"];
756         }
757
758         $links = array();
759
760         if (is_array($post["repost_of"])) {
761                 $postarray['author-name'] = $post["repost_of"]["user"]["name"];
762                 $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"];
763                 $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"];
764
765                 $content = $post["repost_of"];
766         } else {
767                 $postarray['author-name'] = $postarray['owner-name'];
768                 $postarray['author-link'] = $postarray['owner-link'];
769                 $postarray['author-avatar'] = $postarray['owner-avatar'];
770
771                 $content = $post;
772         }
773
774         if (is_array($content["entities"])) {
775                 $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
776                 $postarray['body'] = $converted["body"];
777                 $postarray['tag'] = $converted["tags"];
778         } else
779                 $postarray['body'] = $content["text"];
780
781         if (is_array($content["annotations"]))
782                 $postarray['body'] = appnet_expand_annotations($a, $postarray['body'], $content["annotations"]);
783
784         if (sizeof($content["entities"]["links"]))
785                 foreach($content["entities"]["links"] AS $link) {
786                         $url = normalise_link($link["url"]);
787                         $links[$url] = $link["url"];
788                 }
789
790         if (sizeof($content["annotations"]))
791                 foreach($content["annotations"] AS $annotation) {
792                         if ($annotation[type] == "net.app.core.oembed") {
793                                 if (isset($annotation["value"]["embeddable_url"])) {
794                                         $url = normalise_link($annotation["value"]["embeddable_url"]);
795                                         if (isset($links[$url]))
796                                                 unset($links[$url]);
797                                 }
798                         } elseif ($annotation[type] == "com.friendica.post") {
799                                 $links = array();
800                                 if (isset($annotation["value"]["embeddable_url"]))
801                                         $postarray['title'] = $annotation["value"]["title"];
802
803                                 if (isset($annotation["value"]["body"]))
804                                         $postarray['body'] = $annotation["value"]["body"];
805
806                                 if (isset($annotation["value"]["tag"]))
807                                         $postarray['tag'] = $annotation["value"]["tag"];
808
809                                 if (isset($annotation["value"]["author-name"]))
810                                         $postarray['author-name'] = $annotation["value"]["author-name"];
811
812                                 if (isset($annotation["value"]["author-link"]))
813                                         $postarray['author-link'] = $annotation["value"]["author-link"];
814
815                                 if (isset($annotation["value"]["author-avatar"]))
816                                         $postarray['author-avatar'] = $annotation["value"]["author-avatar"];
817                         }
818
819                 }
820
821         if (sizeof($links)) {
822                 $link = array_pop($links);
823                 $url = "[url=".$link."]".$link."[/url]";
824
825                 $removedlink = trim(str_replace($url, "", $postarray['body']));
826
827                 if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
828                         $postarray['body'] = $removedlink;
829
830                 $postarray['body'] .= add_page_info($link);
831         }
832
833         $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]);
834         $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]);
835
836         $postarray['app'] = $post["source"]["name"];
837
838         return($postarray);
839         //print_r($postarray);
840         //print_r($post);
841 }
842
843 function appnet_expand_entities($a, $body, $entities) {
844
845         if (!function_exists('substr_unicode')) {
846                 function substr_unicode($str, $s, $l = null) {
847                         return join("", array_slice(
848                                 preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
849                 }
850         }
851
852         $tags_arr = array();
853         $replace = array();
854
855         foreach ($entities["mentions"] AS $mention) {
856                 $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]";
857                 $tags_arr["@".$mention["name"]] = $url;
858                 $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url);
859         }
860
861         foreach ($entities["hashtags"] AS $hashtag) {
862                 $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]";
863                 $tags_arr["#".$hashtag["name"]] = $url;
864                 $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url);
865         }
866
867         foreach ($entities["links"] AS $links) {
868                 $url = "[url=".$links["url"]."]".$links["text"]."[/url]";
869                 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url);
870         }
871
872
873         if (sizeof($replace)) {
874                 krsort($replace);
875                 foreach ($replace AS $entity) {
876                         $pre = substr_unicode($body, 0, $entity["pos"]);
877                         $post = substr_unicode($body, $entity["pos"] + $entity["len"]);
878
879                         $body = $pre.$entity["replace"].$post;
880                 }
881         }
882
883         return(array("body" => $body, "tags" => implode($tags_arr, ",")));
884 }
885
886 function appnet_expand_annotations($a, $body, $annotations) {
887         foreach ($annotations AS $annotation) {
888                 if ($annotation["value"]["type"] == "photo") {
889                         if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != ""))
890                                 $body .= "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]";
891                         elseif ($annotation["value"]["url"] != "")
892                                 $body .= "\n[img]".$annotation["value"]["url"]."[/img]";
893                 }
894         }
895         return $body;
896 }
897
898 function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
899         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
900                 intval($uid), dbesc("adn::".$contact["id"]));
901
902         if(!count($r) AND !$create_user)
903                 return($me);
904
905
906         if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
907                 logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
908                 return(-1);
909         }
910
911         if(!count($r)) {
912                 // create contact record
913                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
914                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
915                                         `writable`, `blocked`, `readonly`, `pending` )
916                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
917                         intval($uid),
918                         dbesc(datetime_convert()),
919                         dbesc($contact["canonical_url"]),
920                         dbesc(normalise_link($contact["canonical_url"])),
921                         dbesc($contact["username"]."@app.net"),
922                         dbesc("adn::".$contact["id"]),
923                         dbesc(''),
924                         dbesc("adn::".$contact["id"]),
925                         dbesc($contact["name"]),
926                         dbesc($contact["username"]),
927                         dbesc($contact["avatar_image"]["url"]),
928                         dbesc(NETWORK_APPNET),
929                         intval(CONTACT_IS_FRIEND),
930                         intval(1),
931                         intval(1)
932                 );
933
934                 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
935                         dbesc("adn::".$contact["id"]),
936                         intval($uid)
937                         );
938
939                 if(! count($r))
940                         return(false);
941
942                 $contact_id  = $r[0]['id'];
943
944                 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
945                         intval($uid)
946                 );
947
948                 if($g && intval($g[0]['def_gid'])) {
949                         require_once('include/group.php');
950                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
951                 }
952
953                 require_once("Photo.php");
954
955                 $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id);
956
957                 q("UPDATE `contact` SET `photo` = '%s',
958                                         `thumb` = '%s',
959                                         `micro` = '%s',
960                                         `name-date` = '%s',
961                                         `uri-date` = '%s',
962                                         `avatar-date` = '%s'
963                                 WHERE `id` = %d",
964                         dbesc($photos[0]),
965                         dbesc($photos[1]),
966                         dbesc($photos[2]),
967                         dbesc(datetime_convert()),
968                         dbesc(datetime_convert()),
969                         dbesc(datetime_convert()),
970                         intval($contact_id)
971                 );
972
973         } else {
974                 // update profile photos once every two weeks as we have no notification of when they change.
975
976                 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
977                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
978 $update_photo = true;
979                 // check that we have all the photos, this has been known to fail on occasion
980
981                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
982
983                         logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG);
984
985                         require_once("Photo.php");
986
987                         $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']);
988
989                         q("UPDATE `contact` SET `photo` = '%s',
990                                                 `thumb` = '%s',
991                                                 `micro` = '%s',
992                                                 `name-date` = '%s',
993                                                 `uri-date` = '%s',
994                                                 `avatar-date` = '%s',
995                                                 `url` = '%s',
996                                                 `nurl` = '%s',
997                                                 `addr` = '%s',
998                                                 `name` = '%s',
999                                                 `nick` = '%s'
1000                                         WHERE `id` = %d",
1001                                 dbesc($photos[0]),
1002                                 dbesc($photos[1]),
1003                                 dbesc($photos[2]),
1004                                 dbesc(datetime_convert()),
1005                                 dbesc(datetime_convert()),
1006                                 dbesc(datetime_convert()),
1007                                 dbesc($contact["canonical_url"]),
1008                                 dbesc(normalise_link($contact["canonical_url"])),
1009                                 dbesc($contact["username"]."@app.net"),
1010                                 dbesc($contact["name"]),
1011                                 dbesc($contact["username"]),
1012                                 intval($r[0]['id'])
1013                         );
1014                 }
1015         }
1016
1017         return($r[0]["id"]);
1018 }
1019
1020 function appnet_cron($a,$b) {
1021         $last = get_config('appnet','last_poll');
1022
1023         $poll_interval = intval(get_config('appnet','poll_interval'));
1024         if(! $poll_interval)
1025                 $poll_interval = APPNET_DEFAULT_POLL_INTERVAL;
1026
1027         if($last) {
1028                 $next = $last + ($poll_interval * 60);
1029                 if($next > time()) {
1030                         logger('appnet_cron: poll intervall not reached');
1031                         return;
1032                 }
1033         }
1034         logger('appnet_cron: cron_start');
1035
1036         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
1037         if(count($r)) {
1038                 foreach($r as $rr) {
1039                         logger('appnet_cron: importing timeline from user '.$rr['uid']);
1040                         appnet_fetchstream($a, $rr["uid"]);
1041                 }
1042         }
1043
1044         logger('appnet_cron: cron_end');
1045
1046         set_config('appnet','last_poll', time());
1047 }