5 * Description: Posts to a Google+ page with the help of Hootsuite
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
11 function gpluspost_install() {
12 register_hook('post_local', 'addon/gpluspost/gpluspost.php', 'gpluspost_post_local');
13 register_hook('notifier_normal', 'addon/gpluspost/gpluspost.php', 'gpluspost_send');
14 register_hook('jot_networks', 'addon/gpluspost/gpluspost.php', 'gpluspost_jot_nets');
15 register_hook('connector_settings', 'addon/gpluspost/gpluspost.php', 'gpluspost_settings');
16 register_hook('connector_settings_post', 'addon/gpluspost/gpluspost.php', 'gpluspost_settings_post');
17 register_hook('queue_predeliver', 'addon/gpluspost/gpluspost.php', 'gpluspost_queue_hook');
21 function gpluspost_uninstall() {
22 unregister_hook('post_local', 'addon/gpluspost/gpluspost.php', 'gpluspost_post_local');
23 unregister_hook('notifier_normal', 'addon/gpluspost/gpluspost.php', 'gpluspost_send');
24 unregister_hook('jot_networks', 'addon/gpluspost/gpluspost.php', 'gpluspost_jot_nets');
25 unregister_hook('connector_settings', 'addon/gpluspost/gpluspost.php', 'gpluspost_settings');
26 unregister_hook('connector_settings_post', 'addon/gpluspost/gpluspost.php', 'gpluspost_settings_post');
27 unregister_hook('queue_predeliver', 'addon/gpluspost/gpluspost.php', 'gpluspost_queue_hook');
30 function gpluspost_jot_nets(&$a,&$b) {
34 $post = get_pconfig(local_user(),'gpluspost','post');
35 if(intval($post) == 1) {
36 $defpost = get_pconfig(local_user(),'gpluspost','post_by_default');
37 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
38 $b .= '<div class="profile-jot-net"><input type="checkbox" name="gpluspost_enable"' . $selected . ' value="1" /> '
39 . t('Post to Google+') . '</div>';
43 function gpluspost_nextscripts() {
45 return file_exists($a->get_basepath()."/addon/gpluspost/postToGooglePlus.php");
48 function gpluspost_settings(&$a,&$s) {
53 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fromgplus' AND `installed`");
54 $fromgplus_enabled = count($result) > 0;
56 /* Add our stylesheet to the page so we can make our settings look nice */
58 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/gpluspost/gpluspost.css' . '" media="all" />' . "\r\n";
60 $enabled = get_pconfig(local_user(),'gpluspost','post');
61 $checked = (($enabled) ? ' checked="checked" ' : '');
62 $css = (($enabled) ? '' : '-disabled');
64 $def_enabled = get_pconfig(local_user(),'gpluspost','post_by_default');
65 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
67 $noloop_enabled = get_pconfig(local_user(),'gpluspost','no_loop_prevention');
68 $noloop_checked = (($noloop_enabled) ? ' checked="checked" ' : '');
70 $skip_enabled = get_pconfig(local_user(),'gpluspost','skip_without_link');
71 $skip_checked = (($skip_enabled) ? ' checked="checked" ' : '');
73 $mirror_enable_checked = (intval(get_pconfig(local_user(),'fromgplus','enable')) ? ' checked="checked"' : '');
74 $mirror_account = get_pconfig(local_user(),'fromgplus','account');
76 $username = get_pconfig(local_user(), 'gpluspost', 'username');
77 $password = get_pconfig(local_user(), 'gpluspost', 'password');
78 $page = get_pconfig(local_user(), 'gpluspost', 'page');
80 if ($fromgplus_enabled)
81 $title = "Google+ Export/Mirror";
83 $title = "Google+ Export";
85 $s .= '<span id="settings_gpluspost_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_gpluspost_expanded\'); openClose(\'settings_gpluspost_inflated\');">';
86 $s .= '<img class="connector'.$css.'" src="images/googleplus.png" /><h3 class="connector">'. t($title).'</h3>';
88 $s .= '<div id="settings_gpluspost_expanded" class="settings-block" style="display: none;">';
89 $s .= '<span class="fakelink" onclick="openClose(\'settings_gpluspost_expanded\'); openClose(\'settings_gpluspost_inflated\');">';
90 $s .= '<img class="connector'.$css.'" src="images/googleplus.png" /><h3 class="connector">'. t($title).'</h3>';
92 $s .= '<div id="gpluspost-enable-wrapper">';
94 $s .= '<label id="gpluspost-enable-label" for="gpluspost-checkbox">' . t('Enable Google+ Post Plugin') . '</label>';
95 $s .= '<input id="gpluspost-checkbox" type="checkbox" name="gpluspost" value="1" ' . $checked . '/>';
96 $s .= '</div><div class="clear"></div>';
98 if (gpluspost_nextscripts()) {
100 // To-Do: Option to check the credentials if requested
101 if (($username != "") AND ($password != "")) {
102 require_once("addon/gpluspost/postToGooglePlus.php");
103 $loginError = doConnectToGooglePlus2($username, $password);
105 $s .= '<p>Login Error. Please enter the correct credentials.</p>';
108 $s .= '<div id="gpluspost-username-wrapper">';
109 $s .= '<label id="gpluspost-username-label" for="gpluspost-username">' . t('Google+ username') . '</label>';
110 $s .= '<input id="gpluspost-username" type="text" name="username" value="' . $username . '" />';
111 $s .= '</div><div class="clear"></div>';
113 $s .= '<div id="gpluspost-password-wrapper">';
114 $s .= '<label id="gpluspost-password-label" for="gpluspost-password">' . t('Google+ password') . '</label>';
115 $s .= '<input id="gpluspost-password" type="password" name="password" value="' . $password . '" />';
116 $s .= '</div><div class="clear"></div>';
118 $s .= '<div id="gpluspost-page-wrapper">';
119 $s .= '<label id="gpluspost-page-label" for="gpluspost-page">' . t('Google+ page number') . '</label>';
120 $s .= '<input id="gpluspost-page" type="text" name="page" value="' . $page . '" />';
121 $s .= '</div><div class="clear"></div>';
124 $s .= '<div id="gpluspost-bydefault-wrapper">';
125 $s .= '<label id="gpluspost-bydefault-label" for="gpluspost-bydefault">' . t('Post to Google+ by default') . '</label>';
126 $s .= '<input id="gpluspost-bydefault" type="checkbox" name="gpluspost_bydefault" value="1" ' . $def_checked . '/>';
127 $s .= '</div><div class="clear"></div>';
129 $s .= '<div id="gpluspost-noloopprevention-wrapper">';
130 $s .= '<label id="gpluspost-noloopprevention-label" for="gpluspost-noloopprevention">' . t('Do not prevent posting loops') . '</label>';
131 $s .= '<input id="gpluspost-noloopprevention" type="checkbox" name="gpluspost_noloopprevention" value="1" ' . $noloop_checked . '/>';
132 $s .= '</div><div class="clear"></div>';
134 if (!gpluspost_nextscripts()) {
135 $s .= '<div id="gpluspost-skipwithoutlink-wrapper">';
136 $s .= '<label id="gpluspost-skipwithoutlink-label" for="gpluspost-skipwithoutlink">' . t('Skip messages without links') . '</label>';
137 $s .= '<input id="gpluspost-skipwithoutlink" type="checkbox" name="gpluspost_skipwithoutlink" value="1" ' . $skip_checked . '/>';
138 $s .= '</div><div class="clear"></div>';
141 if ($fromgplus_enabled) {
142 $s .= '<div id="gpluspost-mirror-wrapper">';
143 $s .= '<label id="gpluspost-mirror-label" for="gpluspost-mirror">'.t('Mirror all public posts').'</label>';
144 $s .= '<input id="gpluspost-mirror" type="checkbox" name="fromgplus-enable" value="1"'.$mirror_enable_checked.' />';
145 $s .= '</div><div class="clear"></div>';
146 $s .= '<div id="gpluspost-mirroraccount-wrapper">';
147 $s .= '<label id="gpluspost-account-label" for="gpluspost-account">'.t('Mirror Google Account ID').' </label>';
148 $s .= '<input id="gpluspost-account" type="text" name="fromgplus-account" value="'.$mirror_account.'" />';
149 $s .= '</div><div class="clear"></div>';
152 /* provide a submit button */
154 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="gpluspost-submit" name="gpluspost-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
156 if (gpluspost_nextscripts()) {
157 $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>. ";
158 $s .= 'At this page please click on "Continue". Then your posts should arrive in several minutes.</p>';
160 $s .= '<p>Register an account at <a href="https://hootsuite.com">Hootsuite</a>, add your G+ page and add the feed-url there.<br />';
161 $s .= 'Feed-url: '.$a->get_baseurl().'/gpluspost/'.urlencode($a->user["nickname"]).'</p>';
166 function gpluspost_settings_post(&$a,&$b) {
168 if(x($_POST,'gpluspost-submit')) {
169 set_pconfig(local_user(),'gpluspost','post',intval($_POST['gpluspost']));
170 set_pconfig(local_user(),'gpluspost','post_by_default',intval($_POST['gpluspost_bydefault']));
171 set_pconfig(local_user(),'gpluspost','no_loop_prevention',intval($_POST['gpluspost_noloopprevention']));
173 if (!gpluspost_nextscripts()) {
174 set_pconfig(local_user(),'gpluspost','skip_without_link',intval($_POST['gpluspost_skipwithoutlink']));
176 set_pconfig(local_user(),'gpluspost','username',trim($_POST['username']));
177 set_pconfig(local_user(),'gpluspost','password',trim($_POST['password']));
178 set_pconfig(local_user(),'gpluspost','page',trim($_POST['page']));
181 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fromgplus' AND `installed`");
182 if (count($result) > 0) {
183 set_pconfig(local_user(),'fromgplus','account',trim($_POST['fromgplus-account']));
184 $enable = ((x($_POST,'fromgplus-enable')) ? intval($_POST['fromgplus-enable']) : 0);
185 set_pconfig(local_user(),'fromgplus','enable', $enable);
188 del_pconfig(local_user(),'fromgplus','lastdate');
193 function gpluspost_post_local(&$a,&$b) {
198 if((! local_user()) || (local_user() != $b['uid']))
201 if($b['private'] || $b['parent'])
204 $post = intval(get_pconfig(local_user(),'gpluspost','post'));
206 $enable = (($post && x($_REQUEST,'gpluspost_enable')) ? intval($_REQUEST['gpluspost_enable']) : 0);
208 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'gpluspost','post_by_default')))
214 if(strlen($b['postopts']))
215 $b['postopts'] .= ',';
217 $b['postopts'] .= 'gplus';
220 function gpluspost_send(&$a,&$b) {
222 logger('gpluspost_send: invoked for post '.$b['id']." ".$b['app']);
224 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
227 if(! strstr($b['postopts'],'gplus'))
230 if($b['parent'] != $b['id'])
233 // if post comes from Google+ don't send it back
234 if (!get_pconfig($b["uid"],'gpluspost','no_loop_prevention') and (($b['app'] == "Google+") OR ($b["extid"] == NETWORK_GPLUS)))
237 if (!gpluspost_nextscripts()) {
238 // Posting via RSS-Feed and Hootsuite
239 $itemlist = get_pconfig($b["uid"],'gpluspost','itemlist');
240 $items = explode(",", $itemlist);
243 $newitems = array($b['id']);
244 foreach ($items AS $item)
248 $itemlist = implode(",", $newitems);
250 logger('gpluspost_send: new itemlist: '.$itemlist." for uid ".$b["uid"]);
252 set_pconfig($b["uid"],'gpluspost','itemlist', $itemlist);
255 // Posting via NextScripts
256 $username = get_pconfig($b['uid'],'gpluspost','username');
257 $password = get_pconfig($b['uid'],'gpluspost','password');
258 $page = get_pconfig($b['uid'],'gpluspost','page');
262 if($username && $password) {
263 require_once("addon/gpluspost/postToGooglePlus.php");
264 require_once("include/plaintext.php");
268 // Markup for Google+
269 if ($item["title"] != "")
270 $item["title"] = "*".$item["title"]."*";
272 $item["body"] = preg_replace("(\[b\](.*?)\[\/b\])ism",'*$1*',$item["body"]);
273 $item["body"] = preg_replace("(\[i\](.*?)\[\/i\])ism",'_$1_',$item["body"]);
274 $item["body"] = preg_replace("(\[s\](.*?)\[\/s\])ism",'-$1-',$item["body"]);
276 $data = plaintext($a, $item, 0, false, 9);
278 logger('gpluspost_send: data: '.print_r($data, true), LOGGER_DEBUG);
280 $loginError = doConnectToGooglePlus2($username, $password);
282 if ($data["url"] != "")
283 $lnk = doGetGoogleUrlInfo2($data["url"]);
284 elseif ($data["image"] != "")
285 $lnk = array('img'=>$data["image"]);
289 // Send a special blank to identify the post through the "fromgplus" addon
290 $blank = html_entity_decode(" ", ENT_QUOTES, 'UTF-8');
292 doPostToGooglePlus2($data["text"].$blank, $lnk, $page);
296 logger('gpluspost_send: '.$b['uid'].' success', LOGGER_DEBUG);
298 logger('gpluspost_send: '.$b['uid'].' failed '.$loginError, LOGGER_DEBUG);
301 logger('gpluspost_send: requeueing '.$b['uid'], LOGGER_DEBUG);
303 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
305 $a->contact = $r[0]["id"];
307 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $data));
308 require_once('include/queue_fn.php');
309 add_to_queue($a->contact,NETWORK_GPLUS,$s);
310 notice(t('Google+ post failed. Queued for retry.').EOL);
313 logger('gpluspost_send: '.$b['uid'].' missing username or password', LOGGER_DEBUG);
318 function gpluspost_queue_hook(&$a,&$b) {
320 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
326 require_once('include/queue_fn.php');
329 if($x['network'] !== NETWORK_GPLUS)
332 logger('gpluspost_queue: run');
334 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
335 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
343 //logger('gpluspost_queue: fetching userdata '.print_r($userdata, true));
345 $username = get_pconfig($userdata['uid'],'gpluspost','username');
346 $password = get_pconfig($userdata['uid'],'gpluspost','password');
347 $page = get_pconfig($userdata['uid'],'gpluspost','page');
351 if($username && $password) {
352 require_once("addon/gpluspost/postToGooglePlus.php");
354 logger('gpluspost_queue: able to post for user '.$username);
356 $z = unserialize($x['content']);
361 logger('gpluspost_send: data: '.print_r($data, true), LOGGER_DATA);
363 $loginError = doConnectToGooglePlus2($username, $password);
365 if ($data["url"] != "")
366 $lnk = doGetGoogleUrlInfo2($data["url"]);
367 elseif ($data["image"] != "")
368 $lnk = array('img'=>$data["image"]);
372 // Send a special blank to identify the post through the "fromgplus" addon
373 $blank = html_entity_decode(" ", ENT_QUOTES, 'UTF-8');
375 doPostToGooglePlus2($data["text"].$blank, $lnk, $page);
377 logger('gpluspost_queue: send '.$userdata['uid'].' success', LOGGER_DEBUG);
381 remove_queue_item($x['id']);
383 logger('gpluspost_queue: send '.$userdata['uid'].' failed '.$loginError, LOGGER_DEBUG);
385 logger('gpluspost_queue: send '.$userdata['uid'].' missing username or password', LOGGER_DEBUG);
388 logger('gpluspost_queue: delayed');
389 update_queue_time($x['id']);
394 function gpluspost_module() {}
396 function gpluspost_init() {
401 if (isset($a->argv[1])) {
402 $uid = (int)$a->argv[1];
404 $contacts = q("SELECT `username`, `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1", dbesc($a->argv[1]));
406 $uid = $contacts[0]["uid"];
410 $contacts = q("SELECT `username` FROM `user` WHERE `uid`=%d LIMIT 1", intval($uid));
415 header("content-type: application/atom+xml");
416 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
417 echo '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
418 echo "\t".'<title type="html"><![CDATA['.$a->config['sitename'].']]></title>'."\n";
420 echo "\t".'<subtitle type="html"><![CDATA['.$contacts[0]["username"]."]]></subtitle>\n";
421 echo "\t".'<link rel="self" href="'.$a->get_baseurl().'/gpluspost/'.$nick.'"/>'."\n";
423 echo "\t".'<link rel="self" href="'.$a->get_baseurl().'/gpluspost"/>'."\n";
424 echo "\t<id>".$a->get_baseurl()."/</id>\n";
425 echo "\t".'<link rel="alternate" type="text/html" href="'.$a->get_baseurl().'"/>'."\n";
426 echo "\t<updated>".date("c")."</updated>\n"; // To-Do
427 // <rights>Copyright ... </rights>
428 echo "\t".'<generator uri="'.$a->get_baseurl().'">'.$a->config['sitename'].'</generator>'."\n";
431 $itemlist = get_pconfig($uid,'gpluspost','itemlist');
432 $items = explode(",", $itemlist);
434 foreach ($items AS $item)
435 gpluspost_feeditem($item, $uid);
437 $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");
438 foreach ($items AS $item)
439 gpluspost_feeditem($item["id"], $uid);
445 function gpluspost_feeditem($pid, $uid) {
448 require_once('include/api.php');
449 require_once('include/bbcode.php');
450 require_once("include/html2plain.php");
451 require_once("include/network.php");
453 $skipwithoutlink = get_pconfig($uid,'gpluspost','skip_without_link');
455 $items = q("SELECT `uri`, `plink`, `author-link`, `author-name`, `created`, `edited`, `id`, `title`, `body` from `item` WHERE id=%d", intval($pid));
456 foreach ($items AS $item) {
458 $item['body'] = bb_CleanPictureLinks($item['body']);
460 $item['body'] = bb_remove_share_information($item['body'], true);
462 if ($item["title"] != "")
463 $item['body'] = "*".$item["title"]."*\n\n".$item['body'];
465 // Looking for the first image
467 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$item['body'],$matches))
468 $image = $matches[3];
471 if(preg_match("/\[img\](.*?)\[\/img\]/is",$item['body'],$matches))
472 $image = $matches[1];
474 $multipleimages = (strpos($item['body'], "[img") != strrpos($item['body'], "[img"));
476 // When saved into the database the content is sent through htmlspecialchars
477 // That means that we have to decode all image-urls
478 $image = htmlspecialchars_decode($image);
481 // look for bookmark-bbcode and handle it with priority
482 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$item['body'],$matches))
485 $multiplelinks = (strpos($item['body'], "[bookmark") != strrpos($item['body'], "[bookmark"));
487 $body = $item['body'];
489 $body = preg_replace("(\[b\](.*?)\[\/b\])ism",'*$1*',$body);
490 $body = preg_replace("(\[i\](.*?)\[\/i\])ism",'_$1_',$body);
491 $body = preg_replace("(\[s\](.*?)\[\/s\])ism",'-$1-',$body);
493 // At first convert the text to html
494 $html = bbcode(api_clean_plain_items($body), false, false, 2);
496 // Then convert it to plain text
497 $msg = trim(html2plain($html, 0, true));
498 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
500 // If there is no bookmark element then take the first link
502 $links = collecturls($html);
503 if (sizeof($links) > 0) {
505 $link = current($links);
507 $multiplelinks = (sizeof($links) > 1);
509 if ($multiplelinks) {
510 $html2 = bbcode($msg, false, false);
511 $links2 = collecturls($html2);
512 if (sizeof($links2) > 0) {
514 $link = current($links2);
515 $multiplelinks = (sizeof($links2) > 1);
522 $msglink = $item["plink"];
523 else if ($link != "")
525 else if ($multipleimages)
526 $msglink = $item["plink"];
527 else if ($image != "")
530 if (($msglink == "") AND $skipwithoutlink)
532 else if ($msglink == "")
533 $msglink = $item["plink"];
535 // Fetching the title - or the first line
536 if ($item["title"] != "")
537 $title = $item["title"];
539 $lines = explode("\n", $msg);
543 //if ($image != $msglink)
544 // $html = trim(str_replace($msglink, "", $html));
546 $title = trim(str_replace($msglink, "", $title));
548 $msglink = original_url($msglink);
551 $title = $item["author-name"].": ".$title;
553 $msglink = htmlspecialchars(html_entity_decode($msglink));
555 if (strpos($msg, $msglink) == 0)
556 $msg .= "\n".$msglink;
560 $title = str_replace("&", "&", $title);
561 //$html = str_replace("&", "&", $html);
563 echo "\t".'<entry xmlns="http://www.w3.org/2005/Atom">'."\n";
564 echo "\t\t".'<title type="html" xml:space="preserve"><![CDATA['.$title."]]></title>\n";
565 echo "\t\t".'<link rel="alternate" type="text/html" href="'.$msglink.'" />'."\n";
566 // <link rel="enclosure" type="audio/mpeg" length="1337" href="http://example.org/audio/ph34r_my_podcast.mp3"/>
567 echo "\t\t<id>".$item["uri"]."</id>\n";
568 echo "\t\t<updated>".date("c", strtotime($item["edited"]))."</updated>\n";
569 echo "\t\t<published>".date("c", strtotime($item["created"]))."</published>\n";
570 echo "\t\t<author>\n\t\t\t<name><![CDATA[".$item["author-name"]."]]></name>\n";
571 echo "\t\t\t<uri>".$item["author-link"]."</uri>\n\t\t</author>\n";
572 //echo '<content type="image/png" src="http://media.example.org/the_beach.png"/>';
573 echo "\t\t".'<content type="html" xml:space="preserve" xml:base="'.$item["plink"].'"><![CDATA['.$msg."]]></content>\n";