4 * Description: Imports posts from a Google+ account and repeats them
6 * Author: Michael Vogel <ike@piratenpartei.de>
10 define('FROMGPLUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
12 use Friendica\Core\Addon;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\PConfig;
16 use Friendica\Core\Protocol;
17 use Friendica\Object\Image;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Network;
20 use Friendica\Model\Item;
22 require_once 'mod/share.php';
23 require_once 'mod/parse_url.php';
24 require_once 'include/text.php';
26 function fromgplus_install() {
27 Addon::registerHook('connector_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
28 Addon::registerHook('connector_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
29 Addon::registerHook('cron', 'addon/fromgplus/fromgplus.php', 'fromgplus_cron');
32 function fromgplus_uninstall() {
33 Addon::unregisterHook('connector_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
34 Addon::unregisterHook('connector_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
35 Addon::unregisterHook('cron', 'addon/fromgplus/fromgplus.php', 'fromgplus_cron');
38 Addon::unregisterHook('addon_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
39 Addon::unregisterHook('addon_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
42 function fromgplus_addon_settings(&$a,&$s) {
47 // If "gpluspost" is installed as well, then the settings are displayed there
48 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'gpluspost' AND `installed`");
49 if (count($result) > 0)
52 $enable_checked = (intval(PConfig::get(local_user(),'fromgplus','enable')) ? ' checked="checked"' : '');
53 $keywords_checked = (intval(PConfig::get(local_user(), 'fromgplus', 'keywords')) ? ' checked="checked"' : '');
54 $account = PConfig::get(local_user(),'fromgplus','account');
56 $s .= '<span id="settings_fromgplus_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_fromgplus_expanded\'); openClose(\'settings_fromgplus_inflated\');">';
57 $s .= '<img class="connector" src="images/googleplus.png" /><h3 class="connector">'. L10n::t('Google+ Mirror').'</h3>';
59 $s .= '<div id="settings_fromgplus_expanded" class="settings-block" style="display: none;">';
60 $s .= '<span class="fakelink" onclick="openClose(\'settings_fromgplus_expanded\'); openClose(\'settings_fromgplus_inflated\');">';
61 $s .= '<img class="connector" src="images/googleplus.png" /><h3 class="connector">'. L10n::t('Google+ Mirror').'</h3>';
64 $s .= '<div id="fromgplus-wrapper">';
66 $s .= '<label id="fromgplus-enable-label" for="fromgplus-enable">'.L10n::t('Enable Google+ Import').'</label>';
67 $s .= '<input id="fromgplus-enable" type="checkbox" name="fromgplus-enable" value="1"'.$enable_checked.' />';
68 $s .= '<div class="clear"></div>';
69 $s .= '<label id="fromgplus-label" for="fromgplus-account">'.L10n::t('Google Account ID').' </label>';
70 $s .= '<input id="fromgplus-account" type="text" name="fromgplus-account" value="'.$account.'" />';
71 $s .= '</div><div class="clear"></div>';
72 $s .= '<label id="fromgplus-keywords-label" for="fromgplus-keywords">'.L10n::t('Add keywords to post').'</label>';
73 $s .= '<input id="fromgplus-keywords" type="checkbox" name="fromgplus-keywords" value="1"'.$keywords_checked.' />';
74 $s .= '<div class="clear"></div>';
76 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fromgplus-submit" name="fromgplus-submit"
77 class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
83 function fromgplus_addon_settings_post(&$a,&$b) {
88 if (!empty($_POST['fromgplus-submit'])) {
89 PConfig::set(local_user(),'fromgplus','account',trim($_POST['fromgplus-account']));
90 $enable = (x($_POST,'fromgplus-enable') ? intval($_POST['fromgplus-enable']) : 0);
91 PConfig::set(local_user(),'fromgplus','enable', $enable);
92 $keywords = (x($_POST, 'fromgplus-keywords') ? intval($_POST['fromgplus-keywords']) : 0);
93 PConfig::set(local_user(),'fromgplus', 'keywords', $keywords);
96 PConfig::delete(local_user(),'fromgplus','lastdate');
98 info(L10n::t('Google+ Import Settings saved.') . EOL);
102 function fromgplus_addon_admin(&$a, &$o)
104 $t = get_markup_template("admin.tpl", "addon/fromgplus/");
106 $o = replace_macros($t, [
107 '$submit' => L10n::t('Save Settings'),
108 '$key' => ['key', L10n::t('Key'), trim(Config::get('fromgplus', 'key')), ''],
112 function fromgplus_addon_admin_post(&$a)
114 $key = ((x($_POST, 'key')) ? trim($_POST['key']) : '');
115 Config::set('fromgplus', 'key', $key);
116 info(L10n::t('Settings updated.'). EOL);
119 function fromgplus_cron($a,$b) {
120 $last = Config::get('fromgplus','last_poll');
122 $poll_interval = intval(Config::get('fromgplus','poll_interval'));
124 $poll_interval = FROMGPLUS_DEFAULT_POLL_INTERVAL;
127 $next = $last + ($poll_interval * 60);
129 logger('fromgplus: poll intervall not reached');
134 logger('fromgplus: cron_start');
136 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fromgplus' AND `k` = 'enable' AND `v` = '1' ORDER BY RAND() ");
139 $account = PConfig::get($rr['uid'],'fromgplus','account');
141 logger('fromgplus: fetching for user '.$rr['uid']);
142 fromgplus_fetch($a, $rr['uid']);
147 logger('fromgplus: cron_end');
149 Config::set('fromgplus','last_poll', time());
152 function fromgplus_post($a, $uid, $source, $body, $location, $coord, $id) {
156 // Don't know what it is. Maybe some trash from the mobile client
157 $trash = html_entity_decode("", ENT_QUOTES, 'UTF-8');
158 $body = str_replace($trash, "", $body);
162 if (substr($body, 0, 3) == "[b]") {
163 $pos = strpos($body, "[/b]");
164 $title = substr($body, 3, $pos-3);
165 $body = trim(substr($body, $pos+4));
169 $_SESSION['authenticated'] = true;
170 $_SESSION['uid'] = $uid;
173 $_REQUEST['api_source'] = true;
175 $_REQUEST['profile_uid'] = $uid;
176 $_REQUEST['source'] = $source;
177 $_REQUEST['extid'] = Protocol::GPLUS;
180 $_REQUEST['message_id'] = Item::newURI($uid, Protocol::GPLUS.':'.$id);
184 // $_REQUEST['parent']
185 // $_REQUEST['parent_uri']
187 $_REQUEST['title'] = $title;
188 $_REQUEST['body'] = $body;
189 $_REQUEST['location'] = $location;
190 $_REQUEST['coord'] = $coord;
192 if (($_REQUEST['title'] == "") && ($_REQUEST['body'] == "")) {
193 logger('fromgplus: empty post for user '.$uid." ".print_r($_REQUEST, true));
197 require_once('mod/item.php');
198 //print_r($_REQUEST);
199 logger('fromgplus: posting for user '.$uid." ".print_r($_REQUEST, true));
201 logger('fromgplus: done for user '.$uid);
204 function fromgplus_html2bbcode($html) {
206 $bbcode = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
208 $bbcode = str_ireplace(["\n"], [""], $bbcode);
209 $bbcode = str_ireplace(["<b>", "</b>"], ["[b]", "[/b]"], $bbcode);
210 $bbcode = str_ireplace(["<i>", "</i>"], ["[i]", "[/i]"], $bbcode);
211 $bbcode = str_ireplace(["<s>", "</s>"], ["[s]", "[/s]"], $bbcode);
212 $bbcode = str_ireplace(["<br />"], ["\n"], $bbcode);
213 $bbcode = str_ireplace(["<br/>"], ["\n"], $bbcode);
214 $bbcode = str_ireplace(["<br>"], ["\n"], $bbcode);
216 $bbcode = trim(strip_tags($bbcode));
220 function fromgplus_parse_query($var)
223 * Use this function to parse out the query array element from
224 * the output of parse_url().
226 $var = parse_url($var, PHP_URL_QUERY);
227 $var = html_entity_decode($var);
228 $var = explode('&', $var);
231 foreach($var as $val) {
232 $x = explode('=', $val);
237 unset($val, $x, $var);
241 function fromgplus_cleanupgoogleproxy($fullImage, $image) {
242 //$preview = "/w".$fullImage->width."-h".$fullImage->height."/";
243 //$preview2 = "/w".$fullImage->width."-h".$fullImage->height."-p/";
244 //$fullImage = str_replace(array($preview, $preview2), array("/", "/"), $fullImage->url);
245 $fullImage = $fullImage->url;
247 //$preview = "/w".$image->width."-h".$image->height."/";
248 //$preview2 = "/w".$image->width."-h".$image->height."-p/";
249 //$image = str_replace(array($preview, $preview2), array("/", "/"), $image->url);
250 $image = $image->url;
254 $queryvar = fromgplus_parse_query($fullImage);
255 if (!empty($queryvar['url']))
256 $cleaned["full"] = urldecode($queryvar['url']);
258 $cleaned["full"] = $fullImage;
259 if (@exif_imagetype($cleaned["full"]) == 0)
260 $cleaned["full"] = "";
262 $queryvar = fromgplus_parse_query($image);
263 if (!empty($queryvar['url']))
264 $cleaned["preview"] = urldecode($queryvar['url']);
266 $cleaned["preview"] = $image;
267 if (@exif_imagetype($cleaned["preview"]) == 0)
268 $cleaned["preview"] = "";
270 if (empty($cleaned["full"])) {
271 $cleaned["full"] = $cleaned["preview"];
272 $cleaned["preview"] = "";
275 if (!empty($cleaned["full"]))
276 $infoFull = Image::getInfoFromURL($cleaned["full"]);
278 $infoFull = ["0" => 0, "1" => 0];
280 if (!empty($cleaned["preview"]))
281 $infoPreview = Image::getInfoFromURL($cleaned["preview"]);
283 $infoPreview = ["0" => 0, "1" => 0];
285 if (($infoPreview[0] >= $infoFull[0]) && ($infoPreview[1] >= $infoFull[1])) {
286 $temp = $cleaned["full"];
287 $cleaned["full"] = $cleaned["preview"];
288 $cleaned["preview"] = $temp;
291 if (($cleaned["full"] == $cleaned["preview"]) || (($infoPreview[0] == $infoFull[0]) && ($infoPreview[1] == $infoFull[1])))
292 $cleaned["preview"] = "";
294 if ($cleaned["full"] == "")
295 if (@exif_imagetype($fullImage) != 0)
296 $cleaned["full"] = $fullImage;
298 if ($cleaned["full"] == "")
299 if (@exif_imagetype($image) != 0)
300 $cleaned["full"] = $image;
302 // Could be changed in the future to a link to the album
303 $cleaned["page"] = $cleaned["full"];
308 function fromgplus_cleantext($text) {
310 // Don't know what it is. But it is added to the text.
311 $trash = html_entity_decode("", ENT_QUOTES, 'UTF-8');
313 $text = strip_tags($text);
314 $text = html_entity_decode($text, ENT_QUOTES);
316 $text = str_replace(["\n", "\r", " ", $trash], ["", "", "", ""], $text);
320 function fromgplus_handleattachments($a, $uid, $item, $displaytext, $shared) {
321 require_once 'include/items.php';
326 $pagedata["type"] = "";
328 foreach ($item->object->attachments as $attachment) {
329 switch($attachment->objectType) {
331 $pagedata["type"] = "video";
332 $pagedata["url"] = Network::finalUrl($attachment->url);
333 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
337 $pagedata["type"] = "link";
338 $pagedata["url"] = Network::finalUrl($attachment->url);
339 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
341 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
342 if ($images["full"] != "")
343 $pagedata["images"][0]["src"] = $images["full"];
345 if (!empty($attachment->content)) {
346 $quote = trim(fromgplus_html2bbcode($attachment->content));
349 if (!empty($quote)) {
350 $pagedata["text"] = $quote;
353 // Add Keywords to page link
354 $data = parseurl_getsiteinfo_cached($pagedata["url"], true);
355 if (isset($data["keywords"]) && PConfig::get($uid, 'fromgplus', 'keywords')) {
356 $pagedata["keywords"] = $data["keywords"];
361 // Don't store shared pictures in your wall photos (to prevent a possible violating of licenses)
363 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
365 if ($attachment->fullImage->url != "") {
366 $images = Image::storePhoto($a, $uid, "", $attachment->fullImage->url);
367 } elseif ($attachment->image->url != "") {
368 $images = Image::storePhoto($a, $uid, "", $attachment->image->url);
372 if (!empty($images["preview"])) {
373 $post .= "\n[url=".$images["page"]."][img]".$images["preview"]."[/img][/url]\n";
374 $pagedata["images"][0]["src"] = $images["preview"];
375 $pagedata["url"] = $images["page"];
376 } elseif (!empty($images["full"])) {
377 $post .= "\n[img]".$images["full"]."[/img]\n";
378 $pagedata["images"][0]["src"] = $images["full"];
380 if ($images["preview"] != "") {
381 $pagedata["images"][1]["src"] = $images["preview"];
385 if (($attachment->displayName != "") && (fromgplus_cleantext($attachment->displayName) != fromgplus_cleantext($displaytext))) {
386 $post .= fromgplus_html2bbcode($attachment->displayName)."\n";
387 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
392 $pagedata["url"] = Network::finalUrl($attachment->url);
393 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
394 $post .= "\n\n[bookmark=".$pagedata["url"]."]".$pagedata["title"]."[/bookmark]\n";
396 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
398 if ($images["preview"] != "") {
399 $post .= "\n[url=".$images["full"]."][img]".$images["preview"]."[/img][/url]\n";
400 $pagedata["images"][0]["src"] = $images["preview"];
401 $pagedata["url"] = $images["full"];
402 } elseif ($images["full"] != "") {
403 $post .= "\n[img]".$images["full"]."[/img]\n";
404 $pagedata["images"][0]["src"] = $images["full"];
406 if ($images["preview"] != "")
407 $pagedata["images"][1]["src"] = $images["preview"];
412 $pagedata["type"] = "link";
413 $pagedata["url"] = Network::finalUrl($attachment->url);
414 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
416 $thumb = $attachment->thumbnails[0];
417 $pagedata["images"][0]["src"] = $thumb->image->url;
419 $quote = trim(fromgplus_html2bbcode($thumb->description));
421 $pagedata["text"] = $quote;
426 $pagedata["url"] = Network::finalUrl($attachment->url);
427 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
428 $post .= "\n\n[bookmark=".$pagedata["url"]."]".$pagedata["title"]."[/bookmark]\n";
432 // die($attachment->objectType);
436 if ($pagedata["type"] != "")
437 return(add_page_info_data($pagedata));
439 return($post.$quote);
442 function fromgplus_fetch($a, $uid) {
445 // Special blank to identify postings from the googleplus connector
446 $blank = html_entity_decode(" ", ENT_QUOTES, 'UTF-8');
448 $account = PConfig::get($uid,'fromgplus','account');
449 $key = Config::get('fromgplus','key');
451 $result = Network::fetchUrl("https://www.googleapis.com/plus/v1/people/".$account."/activities/public?alt=json&pp=1&key=".$key."&maxResults=".$maxfetch);
452 //$result = file_get_contents("google.txt");
453 //file_put_contents("google.txt", $result);
455 $activities = json_decode($result);
457 $initiallastdate = PConfig::get($uid,'fromgplus','lastdate');
459 $first_time = ($initiallastdate == "");
463 if (empty($activities->items))
466 $reversed = array_reverse($activities->items);
468 foreach($reversed as $item) {
470 if (strtotime($item->published) <= $initiallastdate)
473 // Don't publish items that are too young
474 if (strtotime($item->published) > (time() - 3*60)) {
475 logger('fromgplus_fetch: item too new '.$item->published);
479 if ($lastdate < strtotime($item->published))
480 $lastdate = strtotime($item->published);
482 PConfig::set($uid,'fromgplus','lastdate', $lastdate);
487 if ($item->access->description == "Public") {
489 // Loop prevention through the special blank from the googleplus connector
490 //if (strstr($item->object->content, $blank))
491 if (strrpos($item->object->content, $blank) >= strlen($item->object->content) - 5)
494 switch($item->object->objectType) {
496 $post = fromgplus_html2bbcode($item->object->content);
498 if (is_array($item->object->attachments))
499 $post .= fromgplus_handleattachments($a, $uid, $item, $item->object->content, false);
503 if (isset($item->location)) {
504 if (isset($item->location->address->formatted))
505 $location = $item->location->address->formatted;
507 if (isset($item->location->displayName))
508 $location = $item->location->displayName;
510 if (isset($item->location->position->latitude) &&
511 isset($item->location->position->longitude))
512 $coord = $item->location->position->latitude." ".$item->location->position->longitude;
514 } elseif (isset($item->address))
515 $location = $item->address;
517 fromgplus_post($a, $uid, $item->provider->title, $post, $location, $coord, $item->id);
522 $post = fromgplus_html2bbcode($item->annotation)."\n";
524 if (!intval(Config::get('system','old_share'))) {
526 if (function_exists("share_header"))
527 $post .= share_header($item->object->actor->displayName, $item->object->actor->url,
528 $item->object->actor->image->url, "",
529 DateTimeFormat::utc($item->object->published),$item->object->url);
531 $post .= "[share author='".str_replace("'", "'",$item->object->actor->displayName).
532 "' profile='".$item->object->actor->url.
533 "' avatar='".$item->object->actor->image->url.
534 "' posted='".DateTimeFormat::utc($item->object->published).
535 "' link='".$item->object->url."']";
537 $post .= fromgplus_html2bbcode($item->object->content);
539 if (is_array($item->object->attachments))
540 $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
544 $post .= fromgplus_html2bbcode("♲");
545 $post .= " [url=".$item->object->actor->url."]".$item->object->actor->displayName."[/url] \n";
546 $post .= fromgplus_html2bbcode($item->object->content);
548 if (is_array($item->object->attachments))
549 $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
554 if (isset($item->location)) {
555 if (isset($item->location->address->formatted))
556 $location = $item->location->address->formatted;
558 if (isset($item->location->displayName))
559 $location = $item->location->displayName;
561 if (isset($item->location->position->latitude) &&
562 isset($item->location->position->longitude))
563 $coord = $item->location->position->latitude." ".$item->location->position->longitude;
565 } elseif (isset($item->address))
566 $location = $item->address;
568 fromgplus_post($a, $uid, $item->provider->title, $post, $location, $coord, $item->id);
574 PConfig::set($uid,'fromgplus','lastdate', $lastdate);