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