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