]> git.mxchange.org Git - friendica-addons.git/blob - gpluspost/gpluspost.php
gpluspost: Some design changes to the output.
[friendica-addons.git] / gpluspost / gpluspost.php
1 <?php
2
3 /**
4  * Name: G+ Post
5  * Description: Posts to a Google+ page with the help of Hootsuite
6  * Version: 0.1
7  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8  */
9
10 function gpluspost_install() {
11         register_hook('post_local',           'addon/gpluspost/gpluspost.php', 'gpluspost_post_local');
12         register_hook('notifier_normal',      'addon/gpluspost/gpluspost.php', 'gpluspost_send');
13         register_hook('jot_networks',         'addon/gpluspost/gpluspost.php', 'gpluspost_jot_nets');
14         register_hook('connector_settings',      'addon/gpluspost/gpluspost.php', 'gpluspost_settings');
15         register_hook('connector_settings_post', 'addon/gpluspost/gpluspost.php', 'gpluspost_settings_post');
16         register_hook('queue_predeliver', 'addon/gpluspost/gpluspost.php', 'gpluspost_queue_hook');
17 }
18
19
20 function gpluspost_uninstall() {
21         unregister_hook('post_local',       'addon/gpluspost/gpluspost.php', 'gpluspost_post_local');
22         unregister_hook('notifier_normal',  'addon/gpluspost/gpluspost.php', 'gpluspost_send');
23         unregister_hook('jot_networks',     'addon/gpluspost/gpluspost.php', 'gpluspost_jot_nets');
24         unregister_hook('connector_settings',      'addon/gpluspost/gpluspost.php', 'gpluspost_settings');
25         unregister_hook('connector_settings_post', 'addon/gpluspost/gpluspost.php', 'gpluspost_settings_post');
26         unregister_hook('queue_predeliver', 'addon/gpluspost/gpluspost.php', 'gpluspost_queue_hook');
27 }
28
29 function gpluspost_jot_nets(&$a,&$b) {
30         if(! local_user())
31                 return;
32
33         $post = get_pconfig(local_user(),'gpluspost','post');
34         if(intval($post) == 1) {
35                 $defpost = get_pconfig(local_user(),'gpluspost','post_by_default');
36                 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
37                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="gpluspost_enable"' . $selected . ' value="1" /> '
38                         . t('Post to Google+') . '</div>';
39     }
40 }
41
42 function gpluspost_nextscripts() {
43         $a = get_app();
44         return file_exists($a->get_basepath()."/addon/gpluspost/postToGooglePlus.php");
45 }
46
47 function gpluspost_settings(&$a,&$s) {
48
49         if(! local_user())
50                 return;
51
52         $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fromgplus' AND `installed`");
53         $fromgplus_enabled = count($result) > 0;
54
55         /* Add our stylesheet to the page so we can make our settings look nice */
56
57         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/gpluspost/gpluspost.css' . '" media="all" />' . "\r\n";
58
59         $enabled = get_pconfig(local_user(),'gpluspost','post');
60         $checked = (($enabled) ? ' checked="checked" ' : '');
61         $css = (($enabled) ? '' : '-disabled');
62
63         $def_enabled = get_pconfig(local_user(),'gpluspost','post_by_default');
64         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
65
66         $noloop_enabled = get_pconfig(local_user(),'gpluspost','no_loop_prevention');
67         $noloop_checked = (($noloop_enabled) ? ' checked="checked" ' : '');
68
69         $skip_enabled = get_pconfig(local_user(),'gpluspost','skip_without_link');
70         $skip_checked = (($skip_enabled) ? ' checked="checked" ' : '');
71
72         $mirror_enable_checked = (intval(get_pconfig(local_user(),'fromgplus','enable')) ? ' checked="checked"' : '');
73         $mirror_account = get_pconfig(local_user(),'fromgplus','account');
74
75         $username = get_pconfig(local_user(), 'gpluspost', 'username');
76         $password = get_pconfig(local_user(), 'gpluspost', 'password');
77         $page = get_pconfig(local_user(), 'gpluspost', 'page');
78
79         if ($fromgplus_enabled)
80                 $title = "Google+ Export/Mirror";
81         else
82                 $title = "Google+ Export";
83
84         $s .= '<span id="settings_gpluspost_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_gpluspost_expanded\'); openClose(\'settings_gpluspost_inflated\');">';
85         $s .= '<img class="connector'.$css.'" src="images/googleplus.png" /><h3 class="connector">'. t($title).'</h3>';
86         $s .= '</span>';
87         $s .= '<div id="settings_gpluspost_expanded" class="settings-block" style="display: none;">';
88         $s .= '<span class="fakelink" onclick="openClose(\'settings_gpluspost_expanded\'); openClose(\'settings_gpluspost_inflated\');">';
89         $s .= '<img class="connector'.$css.'" src="images/googleplus.png" /><h3 class="connector">'. t($title).'</h3>';
90         $s .= '</span>';
91         $s .= '<div id="gpluspost-enable-wrapper">';
92
93         $s .= '<label id="gpluspost-enable-label" for="gpluspost-checkbox">' . t('Enable Google+ Post Plugin') . '</label>';
94         $s .= '<input id="gpluspost-checkbox" type="checkbox" name="gpluspost" value="1" ' . $checked . '/>';
95         $s .= '</div><div class="clear"></div>';
96
97         if (gpluspost_nextscripts()) {
98                 /*
99                 // To-Do: Option to check the credentials if requested
100                 if (($username != "") AND ($password != "")) {
101                         require_once("addon/googleplus/postToGooglePlus.php");
102                         $loginError = doConnectToGooglePlus2($username, $password);
103                         if ($loginError)
104                                 $s .= '<p>Login Error. Please enter the correct credentials.</p>';
105                 }*/
106
107                 $s .= '<div id="gpluspost-username-wrapper">';
108                 $s .= '<label id="gpluspost-username-label" for="gpluspost-username">' . t('Google+ username') . '</label>';
109                 $s .= '<input id="gpluspost-username" type="text" name="username" value="' . $username . '" />';
110                 $s .= '</div><div class="clear"></div>';
111
112                 $s .= '<div id="gpluspost-password-wrapper">';
113                 $s .= '<label id="gpluspost-password-label" for="gpluspost-password">' . t('Google+ password') . '</label>';
114                 $s .= '<input id="gpluspost-password" type="password" name="password" value="' . $password . '" />';
115                 $s .= '</div><div class="clear"></div>';
116
117                 $s .= '<div id="gpluspost-page-wrapper">';
118                 $s .= '<label id="gpluspost-page-label" for="gpluspost-page">' . t('Google+ page number') . '</label>';
119                 $s .= '<input id="gpluspost-page" type="text" name="page" value="' . $page . '" />';
120                 $s .= '</div><div class="clear"></div>';
121         }
122
123         $s .= '<div id="gpluspost-bydefault-wrapper">';
124         $s .= '<label id="gpluspost-bydefault-label" for="gpluspost-bydefault">' . t('Post to Google+ by default') . '</label>';
125         $s .= '<input id="gpluspost-bydefault" type="checkbox" name="gpluspost_bydefault" value="1" ' . $def_checked . '/>';
126         $s .= '</div><div class="clear"></div>';
127
128         $s .= '<div id="gpluspost-noloopprevention-wrapper">';
129         $s .= '<label id="gpluspost-noloopprevention-label" for="gpluspost-noloopprevention">' . t('Do not prevent posting loops') . '</label>';
130         $s .= '<input id="gpluspost-noloopprevention" type="checkbox" name="gpluspost_noloopprevention" value="1" ' . $noloop_checked . '/>';
131         $s .= '</div><div class="clear"></div>';
132
133         if (!gpluspost_nextscripts()) {
134                 $s .= '<div id="gpluspost-skipwithoutlink-wrapper">';
135                 $s .= '<label id="gpluspost-skipwithoutlink-label" for="gpluspost-skipwithoutlink">' . t('Skip messages without links') . '</label>';
136                 $s .= '<input id="gpluspost-skipwithoutlink" type="checkbox" name="gpluspost_skipwithoutlink" value="1" ' . $skip_checked . '/>';
137                 $s .= '</div><div class="clear"></div>';
138         }
139
140         if ($fromgplus_enabled) {
141                 $s .= '<div id="gpluspost-mirror-wrapper">';
142                 $s .= '<label id="gpluspost-mirror-label" for="gpluspost-mirror">'.t('Mirror all public posts').'</label>';
143                 $s .= '<input id="gpluspost-mirror" type="checkbox" name="fromgplus-enable" value="1"'.$mirror_enable_checked.' />';
144                 $s .= '</div><div class="clear"></div>';
145                 $s .= '<div id="gpluspost-mirroraccount-wrapper">';
146                 $s .= '<label id="gpluspost-account-label" for="gpluspost-account">'.t('Mirror Google Account ID').' </label>';
147                 $s .= '<input id="gpluspost-account" type="text" name="fromgplus-account" value="'.$mirror_account.'" />';
148                 $s .= '</div><div class="clear"></div>';
149         }
150
151         /* provide a submit button */
152
153         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="gpluspost-submit" name="gpluspost-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
154
155         if (gpluspost_nextscripts()) {
156                 $s .= "<p>If the plugin doesn't work or if it stopped, please login to Google+, then unlock your account by following this <a href='https://www.google.com/accounts/UnlockCaptcha'>link</a>. ";
157                 $s .= 'At this page please click on "Continue". Then your posts should arrive in several minutes.</p>';
158         } else {
159                 $s .= '<p>Register an account at <a href="https://hootsuite.com">Hootsuite</a>, add your G+ page and add the feed-url there.<br />';
160                 $s .= 'Feed-url: '.$a->get_baseurl().'/gpluspost/'.urlencode($a->user["nickname"]).'</p>';
161         }
162         $s .= '</div>';
163 }
164
165 function gpluspost_settings_post(&$a,&$b) {
166
167         if(x($_POST,'gpluspost-submit')) {
168                 set_pconfig(local_user(),'gpluspost','post',intval($_POST['gpluspost']));
169                 set_pconfig(local_user(),'gpluspost','post_by_default',intval($_POST['gpluspost_bydefault']));
170                 set_pconfig(local_user(),'gpluspost','no_loop_prevention',intval($_POST['gpluspost_noloopprevention']));
171
172                 if (!gpluspost_nextscripts()) {
173                         set_pconfig(local_user(),'gpluspost','skip_without_link',intval($_POST['gpluspost_skipwithoutlink']));
174                 } else {
175                         set_pconfig(local_user(),'gpluspost','username',trim($_POST['username']));
176                         set_pconfig(local_user(),'gpluspost','password',trim($_POST['password']));
177                         set_pconfig(local_user(),'gpluspost','page',trim($_POST['page']));
178                 }
179
180                 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fromgplus' AND `installed`");
181                 if (count($result) > 0) {
182                         set_pconfig(local_user(),'fromgplus','account',trim($_POST['fromgplus-account']));
183                         $enable = ((x($_POST,'fromgplus-enable')) ? intval($_POST['fromgplus-enable']) : 0);
184                         set_pconfig(local_user(),'fromgplus','enable', $enable);
185                 }
186         }
187 }
188
189 function gpluspost_post_local(&$a,&$b) {
190
191         if($b['edit'])
192                 return;
193
194         if((! local_user()) || (local_user() != $b['uid']))
195                 return;
196
197         if($b['private'] || $b['parent'])
198                 return;
199
200         $post   = intval(get_pconfig(local_user(),'gpluspost','post'));
201
202         $enable = (($post && x($_REQUEST,'gpluspost_enable')) ? intval($_REQUEST['gpluspost_enable']) : 0);
203
204         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'gpluspost','post_by_default')))
205                 $enable = 1;
206
207         if(!$enable)
208                 return;
209
210         if(strlen($b['postopts']))
211                 $b['postopts'] .= ',';
212
213         $b['postopts'] .= 'gplus';
214 }
215
216 function gpluspost_send(&$a,&$b) {
217
218         logger('gpluspost_send: invoked for post '.$b['id']." ".$b['app']);
219
220         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
221                 return;
222
223         if(! strstr($b['postopts'],'gplus'))
224                 return;
225
226         if($b['parent'] != $b['id'])
227                 return;
228
229         // if post comes from Google+ don't send it back
230         if (!get_pconfig($b["uid"],'gpluspost','no_loop_prevention') and ($b['app'] == "Google+"))
231                 return;
232
233         // Always do the export via RSS-Feed (even if NextScripts is enabled), since it doesn't hurt
234         $itemlist = get_pconfig($b["uid"],'gpluspost','itemlist');
235         $items = explode(",", $itemlist);
236
237         $i = 0;
238         $newitems = array($b['id']);
239         foreach ($items AS $item)
240                 if ($i++ < 9)
241                         $newitems[] = $item;
242
243         $itemlist = implode(",", $newitems);
244
245         logger('gpluspost_send: new itemlist: '.$itemlist." for uid ".$b["uid"]);
246
247         set_pconfig($b["uid"],'gpluspost','itemlist', $itemlist);
248
249         // Posting via NextScripts
250         if (gpluspost_nextscripts()) {
251                 $username = get_pconfig($b['uid'],'gpluspost','username');
252                 $password = get_pconfig($b['uid'],'gpluspost','password');
253                 $page = get_pconfig($b['uid'],'gpluspost','page');
254
255                 $success = false;
256
257                 if($username && $password) {
258                         require_once("addon/gpluspost/postToGooglePlus.php");
259
260                         $data = gpluspost_createmsg($b);
261
262                         logger('gpluspost_send: data: '.print_r($data, true), LOGGER_DEBUG);
263
264                         $loginError = doConnectToGooglePlus2($username, $password);
265                         if (!$loginError) {
266                                 if ($data["link"] != "")
267                                         $lnk = doGetGoogleUrlInfo2($data["link"]);
268                                 elseif ($data["image"] != "")
269                                         $lnk = array('img'=>$data["image"]);
270                                 else
271                                         $lnk = "";
272
273                                 // Send a special blank to identify the post through the "fromgplus" addon
274                                 $blank = html_entity_decode("&#x00A0;", ENT_QUOTES, 'UTF-8');
275
276                                 doPostToGooglePlus2($data["msg"].$blank, $lnk, $page);
277
278                                 $success = true;
279
280                                 logger('gpluspost_send: '.$b['uid'].' success', LOGGER_DEBUG);
281                         } else
282                                 logger('gpluspost_send: '.$b['uid'].' failed '.$loginError, LOGGER_DEBUG);
283
284                         if (!$success) {
285                                 logger('gpluspost_send: requeueing '.$b['uid'], LOGGER_DEBUG);
286
287                                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
288                                 if (count($r))
289                                         $a->contact = $r[0]["id"];
290
291                                 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $data));
292                                 require_once('include/queue_fn.php');
293                                 add_to_queue($a->contact,NETWORK_GPLUS,$s);
294                                 notice(t('Google+ post failed. Queued for retry.').EOL);
295                         }
296                 } else
297                                 logger('gpluspost_send: '.$b['uid'].' missing username or password', LOGGER_DEBUG);
298         }
299
300 }
301
302 function gpluspost_createmsg($b) {
303         require_once("include/bbcode.php");
304         require_once("include/html2plain.php");
305
306         $b['body'] = bb_CleanPictureLinks($b['body']);
307
308         // Looking for the first image
309         $image = '';
310         if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
311                 $image = $matches[3];
312
313         if ($image == '')
314                 if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
315                         $image = $matches[1];
316
317         $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
318
319         // When saved into the database the content is sent through htmlspecialchars
320         // That means that we have to decode all image-urls
321         $image = htmlspecialchars_decode($image);
322
323         $body = $b["body"];
324
325         if ($b["title"] != "")
326                 $body = "*".$b["title"]."*\n\n".$body;
327
328         if (strpos($body, "[bookmark") !== false) {
329                 // splitting the text in two parts:
330                 // before and after the bookmark
331                 $pos = strpos($body, "[bookmark");
332                 $body1 = substr($body, 0, $pos);
333                 $body2 = substr($body, $pos);
334
335                 // Removing all quotes after the bookmark
336                 // they are mostly only the content after the bookmark.
337                 $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
338                 $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
339
340                 $pos2 = strpos($body2, "[/bookmark]");
341                 if ($pos2)
342                         $body2 = substr($body2, $pos2 + 11);
343
344                 $body = $body1.$body2;
345         }
346
347         // Add some newlines so that the message could be cut better
348         $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
349                                 array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
350
351         // remove the recycle signs and the names since they aren't helpful on twitter
352         // recycle 1
353         $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
354         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
355
356         // remove the share element
357         //$body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
358
359         $body = preg_replace("(\[b\](.*?)\[\/b\])ism",'*$1*',$body);
360         $body = preg_replace("(\[i\](.*?)\[\/i\])ism",'_$1_',$body);
361         $body = preg_replace("(\[s\](.*?)\[\/s\])ism",'-$1-',$body);
362
363         // At first convert the text to html
364         $html = bbcode($body, false, false, 2);
365
366         // Then convert it to plain text
367         //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
368         $msg = trim(html2plain($html, 0, true));
369         $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
370
371         // Removing multiple newlines
372         while (strpos($msg, "\n\n\n") !== false)
373                 $msg = str_replace("\n\n\n", "\n\n", $msg);
374
375         // Removing multiple spaces
376         while (strpos($msg, "  ") !== false)
377                 $msg = str_replace("  ", " ", $msg);
378
379         // Removing URLs
380         $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
381
382         $msg = trim($msg);
383
384         $link = '';
385         // look for bookmark-bbcode and handle it with priority
386         if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
387                 $link = $matches[1];
388
389         $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
390
391         // If there is no bookmark element then take the first link
392         if ($link == '') {
393                 $links = collecturls($html);
394                 if (sizeof($links) > 0) {
395                         reset($links);
396                         $link = current($links);
397                 }
398                 $multiplelinks = (sizeof($links) > 1);
399         }
400
401         $msglink = "";
402         if ($multiplelinks)
403                 $msglink = $b["plink"];
404         else if ($link != "")
405                 $msglink = $link;
406         else if ($multipleimages)
407                 $msglink = $b["plink"];
408         else if ($image != "")
409                 $msglink = $image;
410
411         // Removing multiple spaces - again
412         while (strpos($msg, "  ") !== false)
413                 $msg = str_replace("  ", " ", $msg);
414
415         if ($msglink != "") {
416                 // Looking if the link points to an image
417                 $img_str = fetch_url($msglink);
418
419                 $tempfile = tempnam(get_config("system","temppath"), "cache");
420                 file_put_contents($tempfile, $img_str);
421                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
422                 unlink($tempfile);
423         } else
424                 $mime = "";
425
426         if (($image == $msglink) OR (substr($mime, 0, 6) == "image/"))
427                 return(array("msg"=>trim($msg), "link"=>"", "image"=>$msglink));
428         else
429                 return(array("msg"=>trim($msg), "link"=>$msglink, "image"=>""));
430 }
431
432 function gpluspost_queue_hook(&$a,&$b) {
433
434         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
435                 dbesc(NETWORK_GPLUS)
436         );
437         if(! count($qi))
438                 return;
439
440         require_once('include/queue_fn.php');
441
442         foreach($qi as $x) {
443                 if($x['network'] !== NETWORK_GPLUS)
444                         continue;
445
446                 logger('gpluspost_queue: run');
447
448                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
449                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
450                         intval($x['cid'])
451                 );
452                 if(! count($r))
453                         continue;
454
455                 $userdata = $r[0];
456
457                 //logger('gpluspost_queue: fetching userdata '.print_r($userdata, true));
458
459                 $username = get_pconfig($userdata['uid'],'gpluspost','username');
460                 $password = get_pconfig($userdata['uid'],'gpluspost','password');
461                 $page = get_pconfig($userdata['uid'],'gpluspost','page');
462
463                 $success = false;
464
465                 if($username && $password) {
466                         require_once("addon/googleplus/postToGooglePlus.php");
467
468                         logger('gpluspost_queue: able to post for user '.$username);
469
470                         $z = unserialize($x['content']);
471
472                         $data = $z['post'];
473                         // $z['url']
474
475                         logger('gpluspost_send: data: '.print_r($data, true), LOGGER_DATA);
476
477                         $loginError = doConnectToGooglePlus2($username, $password);
478                         if (!$loginError) {
479                                 if ($data["link"] != "")
480                                         $lnk = doGetGoogleUrlInfo2($data["link"]);
481                                 elseif ($data["image"] != "")
482                                         $lnk = array('img'=>$data["image"]);
483                                 else
484                                         $lnk = "";
485
486                                 // Send a special blank to identify the post through the "fromgplus" addon
487                                 $blank = html_entity_decode("&#x00A0;", ENT_QUOTES, 'UTF-8');
488
489                                 doPostToGooglePlus2($data["msg"].$blank, $lnk, $page);
490
491                                 logger('gpluspost_queue: send '.$userdata['uid'].' success', LOGGER_DEBUG);
492
493                                 $success = true;
494
495                                 remove_queue_item($x['id']);
496                         } else
497                                 logger('gpluspost_queue: send '.$userdata['uid'].' failed '.$loginError, LOGGER_DEBUG);
498                 } else
499                         logger('gpluspost_queue: send '.$userdata['uid'].' missing username or password', LOGGER_DEBUG);
500
501                 if (!$success) {
502                         logger('gpluspost_queue: delayed');
503                         update_queue_time($x['id']);
504                 }
505         }
506 }
507
508 function gpluspost_module() {}
509
510 function gpluspost_init() {
511         global $a, $_SERVER;
512
513         $uid = 0;
514
515         if (isset($a->argv[1])) {
516                 $uid = (int)$a->argv[1];
517                 if ($uid == 0) {
518                         $contacts = q("SELECT `username`, `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1", dbesc($a->argv[1]));
519                         if ($contacts) {
520                                 $uid = $contacts[0]["uid"];
521                                 $nick = $a->argv[1];
522                         }
523                 } else {
524                         $contacts = q("SELECT `username` FROM `user` WHERE `uid`=%d LIMIT 1", intval($uid));
525                         $nick = $uid;
526                 }
527         }
528
529         header("content-type: application/atom+xml");
530         echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
531         echo '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
532         echo "\t".'<title type="html"><![CDATA['.$a->config['sitename'].']]></title>'."\n";
533         if ($uid != 0) {
534                 echo "\t".'<subtitle type="html"><![CDATA['.$contacts[0]["username"]."]]></subtitle>\n";
535                 echo "\t".'<link rel="self" href="'.$a->get_baseurl().'/gpluspost/'.$nick.'"/>'."\n";
536         } else
537                 echo "\t".'<link rel="self" href="'.$a->get_baseurl().'/gpluspost"/>'."\n";
538         echo "\t<id>".$a->get_baseurl()."/</id>\n";
539         echo "\t".'<link rel="alternate" type="text/html" href="'.$a->get_baseurl().'"/>'."\n";
540         echo "\t<updated>".date("c")."</updated>\n"; // To-Do
541         // <rights>Copyright ... </rights>
542         echo "\t".'<generator uri="'.$a->get_baseurl().'">'.$a->config['sitename'].'</generator>'."\n";
543
544         if ($uid != 0) {
545                 $itemlist = get_pconfig($uid,'gpluspost','itemlist');
546                 $items = explode(",", $itemlist);
547
548                 foreach ($items AS $item)
549                         gpluspost_feeditem($item, $uid);
550         } else {
551                 $items = q("SELECT `id` FROM `item` FORCE INDEX (`received`) WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0 AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `item`.`id` = `item`.`parent` ORDER BY `received` DESC LIMIT 10");
552                 foreach ($items AS $item)
553                         gpluspost_feeditem($item["id"], $uid);
554         }
555         echo "</feed>\n";
556         killme();
557 }
558
559 function gpluspost_feeditem($pid, $uid) {
560         global $a;
561
562         require_once('include/api.php');
563         require_once('include/bbcode.php');
564         require_once("include/html2plain.php");
565         require_once("include/network.php");
566
567         $skipwithoutlink = get_pconfig($uid,'gpluspost','skip_without_link');
568
569         $items = q("SELECT `uri`, `plink`, `author-link`, `author-name`, `created`, `edited`, `id`, `title`, `body` from `item` WHERE id=%d", intval($pid));
570         foreach ($items AS $item) {
571
572                 $item['body'] = bb_CleanPictureLinks($item['body']);
573
574                 $item['body'] = bb_remove_share_information($item['body'], true);
575
576                 if ($item["title"] != "")
577                         $item['body'] = "*".$item["title"]."*\n\n".$item['body'];
578
579                 // Looking for the first image
580                 $image = '';
581                 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$item['body'],$matches))
582                         $image = $matches[3];
583
584                 if ($image == '')
585                         if(preg_match("/\[img\](.*?)\[\/img\]/is",$item['body'],$matches))
586                                 $image = $matches[1];
587
588                 $multipleimages = (strpos($item['body'], "[img") != strrpos($item['body'], "[img"));
589
590                 // When saved into the database the content is sent through htmlspecialchars
591                 // That means that we have to decode all image-urls
592                 $image = htmlspecialchars_decode($image);
593
594                 $link = '';
595                 // look for bookmark-bbcode and handle it with priority
596                 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$item['body'],$matches))
597                         $link = $matches[1];
598
599                 $multiplelinks = (strpos($item['body'], "[bookmark") != strrpos($item['body'], "[bookmark"));
600
601                 $body = $item['body'];
602
603                 $body = preg_replace("(\[b\](.*?)\[\/b\])ism",'*$1*',$body);
604                 $body = preg_replace("(\[i\](.*?)\[\/i\])ism",'_$1_',$body);
605                 $body = preg_replace("(\[s\](.*?)\[\/s\])ism",'-$1-',$body);
606
607                 // At first convert the text to html
608                 $html = bbcode(api_clean_plain_items($body), false, false, 2);
609
610                 // Then convert it to plain text
611                 $msg = trim(html2plain($html, 0, true));
612                 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
613
614                 // If there is no bookmark element then take the first link
615                 if ($link == '') {
616                         $links = collecturls($html);
617                         if (sizeof($links) > 0) {
618                                 reset($links);
619                                 $link = current($links);
620                         }
621                         $multiplelinks = (sizeof($links) > 1);
622
623                         if ($multiplelinks) {
624                                 $html2 = bbcode($msg, false, false);
625                                 $links2 = collecturls($html2);
626                                 if (sizeof($links2) > 0) {
627                                         reset($links2);
628                                         $link = current($links2);
629                                         $multiplelinks = (sizeof($links2) > 1);
630                                 }
631                         }
632                 }
633
634                 $msglink = "";
635                 if ($multiplelinks)
636                         $msglink = $item["plink"];
637                 else if ($link != "")
638                         $msglink = $link;
639                 else if ($multipleimages)
640                         $msglink = $item["plink"];
641                 else if ($image != "")
642                         $msglink = $image;
643
644                 if (($msglink == "") AND $skipwithoutlink)
645                         continue;
646                 else if ($msglink == "")
647                         $msglink = $item["plink"];
648
649                 // Fetching the title - or the first line
650                 if ($item["title"] != "")
651                         $title = $item["title"];
652                 else {
653                         $lines = explode("\n", $msg);
654                         $title = $lines[0];
655                 }
656
657                 //if ($image != $msglink)
658                 //      $html = trim(str_replace($msglink, "", $html));
659
660                 $title = trim(str_replace($msglink, "", $title));
661
662                 $msglink = original_url($msglink);
663
664                 if ($uid == 0)
665                         $title = $item["author-name"].": ".$title;
666
667                 $msglink = htmlspecialchars(html_entity_decode($msglink));
668
669                 if (strpos($msg, $msglink) == 0)
670                         $msg .= "\n".$msglink;
671
672                 $msg = nl2br($msg);
673
674                 $title = str_replace("&", "&amp;", $title);
675                 //$html = str_replace("&", "&amp;", $html);
676
677                 echo "\t".'<entry xmlns="http://www.w3.org/2005/Atom">'."\n";
678                 echo "\t\t".'<title type="html" xml:space="preserve"><![CDATA['.$title."]]></title>\n";
679                 echo "\t\t".'<link rel="alternate" type="text/html" href="'.$msglink.'" />'."\n";
680                 // <link rel="enclosure" type="audio/mpeg" length="1337" href="http://example.org/audio/ph34r_my_podcast.mp3"/>
681                 echo "\t\t<id>".$item["uri"]."</id>\n";
682                 echo "\t\t<updated>".date("c", strtotime($item["edited"]))."</updated>\n";
683                 echo "\t\t<published>".date("c", strtotime($item["created"]))."</published>\n";
684                 echo "\t\t<author>\n\t\t\t<name><![CDATA[".$item["author-name"]."]]></name>\n";
685                 echo "\t\t\t<uri>".$item["author-link"]."</uri>\n\t\t</author>\n";
686                 //echo '<content type="image/png" src="http://media.example.org/the_beach.png"/>';
687                 echo "\t\t".'<content type="html" xml:space="preserve" xml:base="'.$item["plink"].'"><![CDATA['.$msg."]]></content>\n";
688                 echo "\t</entry>\n";
689         }
690 }