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