5 * Description: Posts to a Google+ page with the help of Hootsuite
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
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');
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');
29 function gpluspost_jot_nets(&$a,&$b) {
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>';
42 function gpluspost_nextscripts() {
44 return file_exists($a->get_basepath()."/addon/gpluspost/postToGooglePlus.php");
47 function gpluspost_settings(&$a,&$s) {
52 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fromgplus' AND `installed`");
53 $fromgplus_enabled = count($result) > 0;
55 /* Add our stylesheet to the page so we can make our settings look nice */
57 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/gpluspost/gpluspost.css' . '" media="all" />' . "\r\n";
59 $enabled = get_pconfig(local_user(),'gpluspost','post');
60 $checked = (($enabled) ? ' checked="checked" ' : '');
61 $css = (($enabled) ? '' : '-disabled');
63 $def_enabled = get_pconfig(local_user(),'gpluspost','post_by_default');
64 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
66 $noloop_enabled = get_pconfig(local_user(),'gpluspost','no_loop_prevention');
67 $noloop_checked = (($noloop_enabled) ? ' checked="checked" ' : '');
69 $skip_enabled = get_pconfig(local_user(),'gpluspost','skip_without_link');
70 $skip_checked = (($skip_enabled) ? ' checked="checked" ' : '');
72 $mirror_enable_checked = (intval(get_pconfig(local_user(),'fromgplus','enable')) ? ' checked="checked"' : '');
73 $mirror_account = get_pconfig(local_user(),'fromgplus','account');
75 $username = get_pconfig(local_user(), 'gpluspost', 'username');
76 $password = get_pconfig(local_user(), 'gpluspost', 'password');
77 $page = get_pconfig(local_user(), 'gpluspost', 'page');
79 if ($fromgplus_enabled)
80 $title = "Google+ Export/Mirror";
82 $title = "Google+ Export";
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>';
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>';
91 $s .= '<div id="gpluspost-enable-wrapper">';
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>';
97 if (gpluspost_nextscripts()) {
99 // To-Do: Option to check the credentials if requested
100 if (($username != "") AND ($password != "")) {
101 require_once("addon/gpluspost/postToGooglePlus.php");
102 $loginError = doConnectToGooglePlus2($username, $password);
104 $s .= '<p>Login Error. Please enter the correct credentials.</p>';
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>';
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>';
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>';
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>';
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>';
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>';
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>';
151 /* provide a submit button */
153 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="gpluspost-submit" name="gpluspost-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
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>';
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>';
165 function gpluspost_settings_post(&$a,&$b) {
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']));
172 if (!gpluspost_nextscripts()) {
173 set_pconfig(local_user(),'gpluspost','skip_without_link',intval($_POST['gpluspost_skipwithoutlink']));
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']));
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);
187 del_pconfig(local_user(),'fromgplus','lastdate');
192 function gpluspost_post_local(&$a,&$b) {
197 if((! local_user()) || (local_user() != $b['uid']))
200 if($b['private'] || $b['parent'])
203 $post = intval(get_pconfig(local_user(),'gpluspost','post'));
205 $enable = (($post && x($_REQUEST,'gpluspost_enable')) ? intval($_REQUEST['gpluspost_enable']) : 0);
207 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'gpluspost','post_by_default')))
213 if(strlen($b['postopts']))
214 $b['postopts'] .= ',';
216 $b['postopts'] .= 'gplus';
219 function gpluspost_send(&$a,&$b) {
221 logger('gpluspost_send: invoked for post '.$b['id']." ".$b['app']);
223 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
226 if(! strstr($b['postopts'],'gplus'))
229 if($b['parent'] != $b['id'])
232 // if post comes from Google+ don't send it back
233 if (!get_pconfig($b["uid"],'gpluspost','no_loop_prevention') and (($b['app'] == "Google+") OR ($b["extid"] == NETWORK_GPLUS)))
236 if (!gpluspost_nextscripts()) {
237 // Posting via RSS-Feed and Hootsuite
238 $itemlist = get_pconfig($b["uid"],'gpluspost','itemlist');
239 $items = explode(",", $itemlist);
242 $newitems = array($b['id']);
243 foreach ($items AS $item)
247 $itemlist = implode(",", $newitems);
249 logger('gpluspost_send: new itemlist: '.$itemlist." for uid ".$b["uid"]);
251 set_pconfig($b["uid"],'gpluspost','itemlist', $itemlist);
254 // Posting via NextScripts
255 $username = get_pconfig($b['uid'],'gpluspost','username');
256 $password = get_pconfig($b['uid'],'gpluspost','password');
257 $page = get_pconfig($b['uid'],'gpluspost','page');
261 if($username && $password) {
262 require_once("addon/gpluspost/postToGooglePlus.php");
263 require_once("include/plaintext.php");
267 // Markup for Google+
268 if ($item["title"] != "")
269 $item["title"] = "*".$item["title"]."*";
271 $item["body"] = preg_replace("(\[b\](.*?)\[\/b\])ism",'*$1*',$item["body"]);
272 $item["body"] = preg_replace("(\[i\](.*?)\[\/i\])ism",'_$1_',$item["body"]);
273 $item["body"] = preg_replace("(\[s\](.*?)\[\/s\])ism",'-$1-',$item["body"]);
275 $data = plaintext($a, $item, 0, false, 9);
277 logger('gpluspost_send: data: '.print_r($data, true), LOGGER_DEBUG);
279 $loginError = doConnectToGooglePlus2($username, $password);
281 if ($data["url"] != "")
282 $lnk = doGetGoogleUrlInfo2($data["url"]);
283 elseif ($data["image"] != "")
284 $lnk = array('img'=>$data["image"]);
288 // Send a special blank to identify the post through the "fromgplus" addon
289 $blank = html_entity_decode(" ", ENT_QUOTES, 'UTF-8');
291 doPostToGooglePlus2($data["text"].$blank, $lnk, $page);
295 logger('gpluspost_send: '.$b['uid'].' success', LOGGER_DEBUG);
297 logger('gpluspost_send: '.$b['uid'].' failed '.$loginError, LOGGER_DEBUG);
300 logger('gpluspost_send: requeueing '.$b['uid'], LOGGER_DEBUG);
302 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
304 $a->contact = $r[0]["id"];
306 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $data));
307 require_once('include/queue_fn.php');
308 add_to_queue($a->contact,NETWORK_GPLUS,$s);
309 notice(t('Google+ post failed. Queued for retry.').EOL);
312 logger('gpluspost_send: '.$b['uid'].' missing username or password', LOGGER_DEBUG);
317 function gpluspost_queue_hook(&$a,&$b) {
319 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
325 require_once('include/queue_fn.php');
328 if($x['network'] !== NETWORK_GPLUS)
331 logger('gpluspost_queue: run');
333 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
334 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
342 //logger('gpluspost_queue: fetching userdata '.print_r($userdata, true));
344 $username = get_pconfig($userdata['uid'],'gpluspost','username');
345 $password = get_pconfig($userdata['uid'],'gpluspost','password');
346 $page = get_pconfig($userdata['uid'],'gpluspost','page');
350 if($username && $password) {
351 require_once("addon/gpluspost/postToGooglePlus.php");
353 logger('gpluspost_queue: able to post for user '.$username);
355 $z = unserialize($x['content']);
360 logger('gpluspost_send: data: '.print_r($data, true), LOGGER_DATA);
362 $loginError = doConnectToGooglePlus2($username, $password);
364 if ($data["url"] != "")
365 $lnk = doGetGoogleUrlInfo2($data["url"]);
366 elseif ($data["image"] != "")
367 $lnk = array('img'=>$data["image"]);
371 // Send a special blank to identify the post through the "fromgplus" addon
372 $blank = html_entity_decode(" ", ENT_QUOTES, 'UTF-8');
374 doPostToGooglePlus2($data["text"].$blank, $lnk, $page);
376 logger('gpluspost_queue: send '.$userdata['uid'].' success', LOGGER_DEBUG);
380 remove_queue_item($x['id']);
382 logger('gpluspost_queue: send '.$userdata['uid'].' failed '.$loginError, LOGGER_DEBUG);
384 logger('gpluspost_queue: send '.$userdata['uid'].' missing username or password', LOGGER_DEBUG);
387 logger('gpluspost_queue: delayed');
388 update_queue_time($x['id']);
393 function gpluspost_module() {}
395 function gpluspost_init() {
400 if (isset($a->argv[1])) {
401 $uid = (int)$a->argv[1];
403 $contacts = q("SELECT `username`, `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1", dbesc($a->argv[1]));
405 $uid = $contacts[0]["uid"];
409 $contacts = q("SELECT `username` FROM `user` WHERE `uid`=%d LIMIT 1", intval($uid));
414 header("content-type: application/atom+xml");
415 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
416 echo '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
417 echo "\t".'<title type="html"><![CDATA['.$a->config['sitename'].']]></title>'."\n";
419 echo "\t".'<subtitle type="html"><![CDATA['.$contacts[0]["username"]."]]></subtitle>\n";
420 echo "\t".'<link rel="self" href="'.$a->get_baseurl().'/gpluspost/'.$nick.'"/>'."\n";
422 echo "\t".'<link rel="self" href="'.$a->get_baseurl().'/gpluspost"/>'."\n";
423 echo "\t<id>".$a->get_baseurl()."/</id>\n";
424 echo "\t".'<link rel="alternate" type="text/html" href="'.$a->get_baseurl().'"/>'."\n";
425 echo "\t<updated>".date("c")."</updated>\n"; // To-Do
426 // <rights>Copyright ... </rights>
427 echo "\t".'<generator uri="'.$a->get_baseurl().'">'.$a->config['sitename'].'</generator>'."\n";
430 $itemlist = get_pconfig($uid,'gpluspost','itemlist');
431 $items = explode(",", $itemlist);
433 foreach ($items AS $item)
434 gpluspost_feeditem($item, $uid);
436 $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");
437 foreach ($items AS $item)
438 gpluspost_feeditem($item["id"], $uid);
444 function gpluspost_feeditem($pid, $uid) {
447 require_once('include/api.php');
448 require_once('include/bbcode.php');
449 require_once("include/html2plain.php");
450 require_once("include/network.php");
452 $skipwithoutlink = get_pconfig($uid,'gpluspost','skip_without_link');
454 $items = q("SELECT `uri`, `plink`, `author-link`, `author-name`, `created`, `edited`, `id`, `title`, `body` from `item` WHERE id=%d", intval($pid));
455 foreach ($items AS $item) {
457 $item['body'] = bb_CleanPictureLinks($item['body']);
459 $item['body'] = bb_remove_share_information($item['body'], true);
461 if ($item["title"] != "")
462 $item['body'] = "*".$item["title"]."*\n\n".$item['body'];
464 // Looking for the first image
466 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$item['body'],$matches))
467 $image = $matches[3];
470 if(preg_match("/\[img\](.*?)\[\/img\]/is",$item['body'],$matches))
471 $image = $matches[1];
473 $multipleimages = (strpos($item['body'], "[img") != strrpos($item['body'], "[img"));
475 // When saved into the database the content is sent through htmlspecialchars
476 // That means that we have to decode all image-urls
477 $image = htmlspecialchars_decode($image);
480 // look for bookmark-bbcode and handle it with priority
481 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$item['body'],$matches))
484 $multiplelinks = (strpos($item['body'], "[bookmark") != strrpos($item['body'], "[bookmark"));
486 $body = $item['body'];
488 $body = preg_replace("(\[b\](.*?)\[\/b\])ism",'*$1*',$body);
489 $body = preg_replace("(\[i\](.*?)\[\/i\])ism",'_$1_',$body);
490 $body = preg_replace("(\[s\](.*?)\[\/s\])ism",'-$1-',$body);
492 // At first convert the text to html
493 $html = bbcode(api_clean_plain_items($body), false, false, 2);
495 // Then convert it to plain text
496 $msg = trim(html2plain($html, 0, true));
497 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
499 // If there is no bookmark element then take the first link
501 $links = collecturls($html);
502 if (sizeof($links) > 0) {
504 $link = current($links);
506 $multiplelinks = (sizeof($links) > 1);
508 if ($multiplelinks) {
509 $html2 = bbcode($msg, false, false);
510 $links2 = collecturls($html2);
511 if (sizeof($links2) > 0) {
513 $link = current($links2);
514 $multiplelinks = (sizeof($links2) > 1);
521 $msglink = $item["plink"];
522 else if ($link != "")
524 else if ($multipleimages)
525 $msglink = $item["plink"];
526 else if ($image != "")
529 if (($msglink == "") AND $skipwithoutlink)
531 else if ($msglink == "")
532 $msglink = $item["plink"];
534 // Fetching the title - or the first line
535 if ($item["title"] != "")
536 $title = $item["title"];
538 $lines = explode("\n", $msg);
542 //if ($image != $msglink)
543 // $html = trim(str_replace($msglink, "", $html));
545 $title = trim(str_replace($msglink, "", $title));
547 $msglink = original_url($msglink);
550 $title = $item["author-name"].": ".$title;
552 $msglink = htmlspecialchars(html_entity_decode($msglink));
554 if (strpos($msg, $msglink) == 0)
555 $msg .= "\n".$msglink;
559 $title = str_replace("&", "&", $title);
560 //$html = str_replace("&", "&", $html);
562 echo "\t".'<entry xmlns="http://www.w3.org/2005/Atom">'."\n";
563 echo "\t\t".'<title type="html" xml:space="preserve"><![CDATA['.$title."]]></title>\n";
564 echo "\t\t".'<link rel="alternate" type="text/html" href="'.$msglink.'" />'."\n";
565 // <link rel="enclosure" type="audio/mpeg" length="1337" href="http://example.org/audio/ph34r_my_podcast.mp3"/>
566 echo "\t\t<id>".$item["uri"]."</id>\n";
567 echo "\t\t<updated>".date("c", strtotime($item["edited"]))."</updated>\n";
568 echo "\t\t<published>".date("c", strtotime($item["created"]))."</published>\n";
569 echo "\t\t<author>\n\t\t\t<name><![CDATA[".$item["author-name"]."]]></name>\n";
570 echo "\t\t\t<uri>".$item["author-link"]."</uri>\n\t\t</author>\n";
571 //echo '<content type="image/png" src="http://media.example.org/the_beach.png"/>';
572 echo "\t\t".'<content type="html" xml:space="preserve" xml:base="'.$item["plink"].'"><![CDATA['.$msg."]]></content>\n";