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\Logger;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\Protocol;
18 use Friendica\Object\Image;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Model\Item;
23 require_once 'mod/share.php';
24 require_once 'mod/parse_url.php';
25 require_once 'include/text.php';
27 function fromgplus_install() {
28 Addon::registerHook('connector_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
29 Addon::registerHook('connector_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
30 Addon::registerHook('cron', 'addon/fromgplus/fromgplus.php', 'fromgplus_cron');
33 function fromgplus_uninstall() {
34 Addon::unregisterHook('connector_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
35 Addon::unregisterHook('connector_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
36 Addon::unregisterHook('cron', 'addon/fromgplus/fromgplus.php', 'fromgplus_cron');
39 Addon::unregisterHook('addon_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
40 Addon::unregisterHook('addon_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
43 function fromgplus_addon_settings(&$a,&$s) {
48 // If "gpluspost" is installed as well, then the settings are displayed there
49 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'gpluspost' AND `installed`");
50 if (count($result) > 0)
53 $enable_checked = (intval(PConfig::get(local_user(),'fromgplus','enable')) ? ' checked="checked"' : '');
54 $keywords_checked = (intval(PConfig::get(local_user(), 'fromgplus', 'keywords')) ? ' checked="checked"' : '');
55 $account = PConfig::get(local_user(),'fromgplus','account');
57 $s .= '<span id="settings_fromgplus_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_fromgplus_expanded\'); openClose(\'settings_fromgplus_inflated\');">';
58 $s .= '<img class="connector" src="images/googleplus.png" /><h3 class="connector">'. L10n::t('Google+ Mirror').'</h3>';
60 $s .= '<div id="settings_fromgplus_expanded" class="settings-block" style="display: none;">';
61 $s .= '<span class="fakelink" onclick="openClose(\'settings_fromgplus_expanded\'); openClose(\'settings_fromgplus_inflated\');">';
62 $s .= '<img class="connector" src="images/googleplus.png" /><h3 class="connector">'. L10n::t('Google+ Mirror').'</h3>';
65 $s .= '<div id="fromgplus-wrapper">';
67 $s .= '<label id="fromgplus-enable-label" for="fromgplus-enable">'.L10n::t('Enable Google+ Import').'</label>';
68 $s .= '<input id="fromgplus-enable" type="checkbox" name="fromgplus-enable" value="1"'.$enable_checked.' />';
69 $s .= '<div class="clear"></div>';
70 $s .= '<label id="fromgplus-label" for="fromgplus-account">'.L10n::t('Google Account ID').' </label>';
71 $s .= '<input id="fromgplus-account" type="text" name="fromgplus-account" value="'.$account.'" />';
72 $s .= '</div><div class="clear"></div>';
73 $s .= '<label id="fromgplus-keywords-label" for="fromgplus-keywords">'.L10n::t('Add keywords to post').'</label>';
74 $s .= '<input id="fromgplus-keywords" type="checkbox" name="fromgplus-keywords" value="1"'.$keywords_checked.' />';
75 $s .= '<div class="clear"></div>';
77 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fromgplus-submit" name="fromgplus-submit"
78 class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
84 function fromgplus_addon_settings_post(&$a,&$b) {
89 if (!empty($_POST['fromgplus-submit'])) {
90 PConfig::set(local_user(),'fromgplus','account',trim($_POST['fromgplus-account']));
91 $enable = (x($_POST,'fromgplus-enable') ? intval($_POST['fromgplus-enable']) : 0);
92 PConfig::set(local_user(),'fromgplus','enable', $enable);
93 $keywords = (x($_POST, 'fromgplus-keywords') ? intval($_POST['fromgplus-keywords']) : 0);
94 PConfig::set(local_user(),'fromgplus', 'keywords', $keywords);
97 PConfig::delete(local_user(),'fromgplus','lastdate');
99 info(L10n::t('Google+ Import Settings saved.') . EOL);
103 function fromgplus_addon_admin(&$a, &$o)
105 $t = get_markup_template("admin.tpl", "addon/fromgplus/");
107 $o = replace_macros($t, [
108 '$submit' => L10n::t('Save Settings'),
109 '$key' => ['key', L10n::t('Key'), trim(Config::get('fromgplus', 'key')), ''],
113 function fromgplus_addon_admin_post(&$a)
115 $key = ((x($_POST, 'key')) ? trim($_POST['key']) : '');
116 Config::set('fromgplus', 'key', $key);
117 info(L10n::t('Settings updated.'). EOL);
120 function fromgplus_cron($a,$b) {
121 $last = Config::get('fromgplus','last_poll');
123 $poll_interval = intval(Config::get('fromgplus','poll_interval'));
125 $poll_interval = FROMGPLUS_DEFAULT_POLL_INTERVAL;
128 $next = $last + ($poll_interval * 60);
130 Logger::log('fromgplus: poll intervall not reached');
135 Logger::log('fromgplus: cron_start');
137 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fromgplus' AND `k` = 'enable' AND `v` = '1' ORDER BY RAND() ");
140 $account = PConfig::get($rr['uid'],'fromgplus','account');
142 Logger::log('fromgplus: fetching for user '.$rr['uid']);
143 fromgplus_fetch($a, $rr['uid']);
148 Logger::log('fromgplus: cron_end');
150 Config::set('fromgplus','last_poll', time());
153 function fromgplus_post($a, $uid, $source, $body, $location, $coord, $id) {
157 // Don't know what it is. Maybe some trash from the mobile client
158 $trash = html_entity_decode("", ENT_QUOTES, 'UTF-8');
159 $body = str_replace($trash, "", $body);
163 if (substr($body, 0, 3) == "[b]") {
164 $pos = strpos($body, "[/b]");
165 $title = substr($body, 3, $pos-3);
166 $body = trim(substr($body, $pos+4));
170 $_SESSION['authenticated'] = true;
171 $_SESSION['uid'] = $uid;
174 $_REQUEST['api_source'] = true;
176 $_REQUEST['profile_uid'] = $uid;
177 $_REQUEST['source'] = $source;
178 $_REQUEST['extid'] = Protocol::GPLUS;
181 $_REQUEST['message_id'] = Item::newURI($uid, Protocol::GPLUS.':'.$id);
185 // $_REQUEST['parent']
186 // $_REQUEST['parent_uri']
188 $_REQUEST['title'] = $title;
189 $_REQUEST['body'] = $body;
190 $_REQUEST['location'] = $location;
191 $_REQUEST['coord'] = $coord;
193 if (($_REQUEST['title'] == "") && ($_REQUEST['body'] == "")) {
194 Logger::log('fromgplus: empty post for user '.$uid." ".print_r($_REQUEST, true));
198 require_once('mod/item.php');
199 //print_r($_REQUEST);
200 Logger::log('fromgplus: posting for user '.$uid." ".print_r($_REQUEST, true));
202 Logger::log('fromgplus: done for user '.$uid);
205 function fromgplus_html2bbcode($html) {
207 $bbcode = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
209 $bbcode = str_ireplace(["\n"], [""], $bbcode);
210 $bbcode = str_ireplace(["<b>", "</b>"], ["[b]", "[/b]"], $bbcode);
211 $bbcode = str_ireplace(["<i>", "</i>"], ["[i]", "[/i]"], $bbcode);
212 $bbcode = str_ireplace(["<s>", "</s>"], ["[s]", "[/s]"], $bbcode);
213 $bbcode = str_ireplace(["<br />"], ["\n"], $bbcode);
214 $bbcode = str_ireplace(["<br/>"], ["\n"], $bbcode);
215 $bbcode = str_ireplace(["<br>"], ["\n"], $bbcode);
217 $bbcode = trim(strip_tags($bbcode));
221 function fromgplus_parse_query($var)
224 * Use this function to parse out the query array element from
225 * the output of parse_url().
227 $var = parse_url($var, PHP_URL_QUERY);
228 $var = html_entity_decode($var);
229 $var = explode('&', $var);
232 foreach($var as $val) {
233 $x = explode('=', $val);
238 unset($val, $x, $var);
242 function fromgplus_cleanupgoogleproxy($fullImage, $image) {
243 //$preview = "/w".$fullImage->width."-h".$fullImage->height."/";
244 //$preview2 = "/w".$fullImage->width."-h".$fullImage->height."-p/";
245 //$fullImage = str_replace(array($preview, $preview2), array("/", "/"), $fullImage->url);
246 $fullImage = $fullImage->url;
248 //$preview = "/w".$image->width."-h".$image->height."/";
249 //$preview2 = "/w".$image->width."-h".$image->height."-p/";
250 //$image = str_replace(array($preview, $preview2), array("/", "/"), $image->url);
251 $image = $image->url;
255 $queryvar = fromgplus_parse_query($fullImage);
256 if (!empty($queryvar['url']))
257 $cleaned["full"] = urldecode($queryvar['url']);
259 $cleaned["full"] = $fullImage;
260 if (@exif_imagetype($cleaned["full"]) == 0)
261 $cleaned["full"] = "";
263 $queryvar = fromgplus_parse_query($image);
264 if (!empty($queryvar['url']))
265 $cleaned["preview"] = urldecode($queryvar['url']);
267 $cleaned["preview"] = $image;
268 if (@exif_imagetype($cleaned["preview"]) == 0)
269 $cleaned["preview"] = "";
271 if (empty($cleaned["full"])) {
272 $cleaned["full"] = $cleaned["preview"];
273 $cleaned["preview"] = "";
276 if (!empty($cleaned["full"]))
277 $infoFull = Image::getInfoFromURL($cleaned["full"]);
279 $infoFull = ["0" => 0, "1" => 0];
281 if (!empty($cleaned["preview"]))
282 $infoPreview = Image::getInfoFromURL($cleaned["preview"]);
284 $infoPreview = ["0" => 0, "1" => 0];
286 if (($infoPreview[0] >= $infoFull[0]) && ($infoPreview[1] >= $infoFull[1])) {
287 $temp = $cleaned["full"];
288 $cleaned["full"] = $cleaned["preview"];
289 $cleaned["preview"] = $temp;
292 if (($cleaned["full"] == $cleaned["preview"]) || (($infoPreview[0] == $infoFull[0]) && ($infoPreview[1] == $infoFull[1])))
293 $cleaned["preview"] = "";
295 if ($cleaned["full"] == "")
296 if (@exif_imagetype($fullImage) != 0)
297 $cleaned["full"] = $fullImage;
299 if ($cleaned["full"] == "")
300 if (@exif_imagetype($image) != 0)
301 $cleaned["full"] = $image;
303 // Could be changed in the future to a link to the album
304 $cleaned["page"] = $cleaned["full"];
309 function fromgplus_cleantext($text) {
311 // Don't know what it is. But it is added to the text.
312 $trash = html_entity_decode("", ENT_QUOTES, 'UTF-8');
314 $text = strip_tags($text);
315 $text = html_entity_decode($text, ENT_QUOTES);
317 $text = str_replace(["\n", "\r", " ", $trash], ["", "", "", ""], $text);
321 function fromgplus_handleattachments($a, $uid, $item, $displaytext, $shared) {
322 require_once 'include/items.php';
327 $pagedata["type"] = "";
329 foreach ($item->object->attachments as $attachment) {
330 switch($attachment->objectType) {
332 $pagedata["type"] = "video";
333 $pagedata["url"] = Network::finalUrl($attachment->url);
334 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
338 $pagedata["type"] = "link";
339 $pagedata["url"] = Network::finalUrl($attachment->url);
340 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
342 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
343 if ($images["full"] != "")
344 $pagedata["images"][0]["src"] = $images["full"];
346 if (!empty($attachment->content)) {
347 $quote = trim(fromgplus_html2bbcode($attachment->content));
350 if (!empty($quote)) {
351 $pagedata["text"] = $quote;
354 // Add Keywords to page link
355 $data = parseurl_getsiteinfo_cached($pagedata["url"], true);
356 if (isset($data["keywords"]) && PConfig::get($uid, 'fromgplus', 'keywords')) {
357 $pagedata["keywords"] = $data["keywords"];
362 // Don't store shared pictures in your wall photos (to prevent a possible violating of licenses)
364 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
366 if ($attachment->fullImage->url != "") {
367 $images = Image::storePhoto($a, $uid, "", $attachment->fullImage->url);
368 } elseif ($attachment->image->url != "") {
369 $images = Image::storePhoto($a, $uid, "", $attachment->image->url);
373 if (!empty($images["preview"])) {
374 $post .= "\n[url=".$images["page"]."][img]".$images["preview"]."[/img][/url]\n";
375 $pagedata["images"][0]["src"] = $images["preview"];
376 $pagedata["url"] = $images["page"];
377 } elseif (!empty($images["full"])) {
378 $post .= "\n[img]".$images["full"]."[/img]\n";
379 $pagedata["images"][0]["src"] = $images["full"];
381 if ($images["preview"] != "") {
382 $pagedata["images"][1]["src"] = $images["preview"];
386 if (($attachment->displayName != "") && (fromgplus_cleantext($attachment->displayName) != fromgplus_cleantext($displaytext))) {
387 $post .= fromgplus_html2bbcode($attachment->displayName)."\n";
388 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
393 $pagedata["url"] = Network::finalUrl($attachment->url);
394 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
395 $post .= "\n\n[bookmark=".$pagedata["url"]."]".$pagedata["title"]."[/bookmark]\n";
397 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
399 if ($images["preview"] != "") {
400 $post .= "\n[url=".$images["full"]."][img]".$images["preview"]."[/img][/url]\n";
401 $pagedata["images"][0]["src"] = $images["preview"];
402 $pagedata["url"] = $images["full"];
403 } elseif ($images["full"] != "") {
404 $post .= "\n[img]".$images["full"]."[/img]\n";
405 $pagedata["images"][0]["src"] = $images["full"];
407 if ($images["preview"] != "")
408 $pagedata["images"][1]["src"] = $images["preview"];
413 $pagedata["type"] = "link";
414 $pagedata["url"] = Network::finalUrl($attachment->url);
415 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
417 $thumb = $attachment->thumbnails[0];
418 $pagedata["images"][0]["src"] = $thumb->image->url;
420 $quote = trim(fromgplus_html2bbcode($thumb->description));
422 $pagedata["text"] = $quote;
427 $pagedata["url"] = Network::finalUrl($attachment->url);
428 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
429 $post .= "\n\n[bookmark=".$pagedata["url"]."]".$pagedata["title"]."[/bookmark]\n";
433 // die($attachment->objectType);
437 if ($pagedata["type"] != "")
438 return(add_page_info_data($pagedata));
440 return($post.$quote);
443 function fromgplus_fetch($a, $uid) {
446 // Special blank to identify postings from the googleplus connector
447 $blank = html_entity_decode(" ", ENT_QUOTES, 'UTF-8');
449 $account = PConfig::get($uid,'fromgplus','account');
450 $key = Config::get('fromgplus','key');
452 $result = Network::fetchUrl("https://www.googleapis.com/plus/v1/people/".$account."/activities/public?alt=json&pp=1&key=".$key."&maxResults=".$maxfetch);
453 //$result = file_get_contents("google.txt");
454 //file_put_contents("google.txt", $result);
456 $activities = json_decode($result);
458 $initiallastdate = PConfig::get($uid,'fromgplus','lastdate');
460 $first_time = ($initiallastdate == "");
464 if (empty($activities->items))
467 $reversed = array_reverse($activities->items);
469 foreach($reversed as $item) {
471 if (strtotime($item->published) <= $initiallastdate)
474 // Don't publish items that are too young
475 if (strtotime($item->published) > (time() - 3*60)) {
476 Logger::log('fromgplus_fetch: item too new '.$item->published);
480 if ($lastdate < strtotime($item->published))
481 $lastdate = strtotime($item->published);
483 PConfig::set($uid,'fromgplus','lastdate', $lastdate);
488 if ($item->access->description == "Public") {
490 // Loop prevention through the special blank from the googleplus connector
491 //if (strstr($item->object->content, $blank))
492 if (strrpos($item->object->content, $blank) >= strlen($item->object->content) - 5)
495 switch($item->object->objectType) {
497 $post = fromgplus_html2bbcode($item->object->content);
499 if (!empty($item->object->attachments)) {
500 $post .= fromgplus_handleattachments($a, $uid, $item, $item->object->content, false);
505 if (isset($item->location)) {
506 if (isset($item->location->address->formatted))
507 $location = $item->location->address->formatted;
509 if (isset($item->location->displayName))
510 $location = $item->location->displayName;
512 if (isset($item->location->position->latitude) &&
513 isset($item->location->position->longitude))
514 $coord = $item->location->position->latitude." ".$item->location->position->longitude;
516 } elseif (isset($item->address))
517 $location = $item->address;
519 fromgplus_post($a, $uid, $item->provider->title, $post, $location, $coord, $item->id);
524 $post = fromgplus_html2bbcode($item->annotation)."\n";
526 if (!intval(Config::get('system','old_share'))) {
528 if (function_exists("share_header"))
529 $post .= share_header($item->object->actor->displayName, $item->object->actor->url,
530 $item->object->actor->image->url, "",
531 DateTimeFormat::utc($item->published),$item->object->url);
533 $post .= "[share author='".str_replace("'", "'",$item->object->actor->displayName).
534 "' profile='".$item->object->actor->url.
535 "' avatar='".$item->object->actor->image->url.
536 "' posted='".DateTimeFormat::utc($item->published).
537 "' link='".$item->object->url."']";
539 $post .= fromgplus_html2bbcode($item->object->content);
541 if (is_array($item->object->attachments))
542 $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
546 $post .= fromgplus_html2bbcode("♲");
547 $post .= " [url=".$item->object->actor->url."]".$item->object->actor->displayName."[/url] \n";
548 $post .= fromgplus_html2bbcode($item->object->content);
550 if (is_array($item->object->attachments))
551 $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
556 if (isset($item->location)) {
557 if (isset($item->location->address->formatted))
558 $location = $item->location->address->formatted;
560 if (isset($item->location->displayName))
561 $location = $item->location->displayName;
563 if (isset($item->location->position->latitude) &&
564 isset($item->location->position->longitude))
565 $coord = $item->location->position->latitude." ".$item->location->position->longitude;
567 } elseif (isset($item->address))
568 $location = $item->address;
570 fromgplus_post($a, $uid, $item->provider->title, $post, $location, $coord, $item->id);
576 PConfig::set($uid,'fromgplus','lastdate', $lastdate);