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