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