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