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\Core\Renderer;
19 use Friendica\Object\Image;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Network;
22 use Friendica\Model\Item;
24 require_once 'mod/share.php';
25 require_once 'mod/parse_url.php';
26 require_once 'include/text.php';
28 function fromgplus_install() {
29 Addon::registerHook('connector_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
30 Addon::registerHook('connector_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
31 Addon::registerHook('cron', 'addon/fromgplus/fromgplus.php', 'fromgplus_cron');
34 function fromgplus_uninstall() {
35 Addon::unregisterHook('connector_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
36 Addon::unregisterHook('connector_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
37 Addon::unregisterHook('cron', 'addon/fromgplus/fromgplus.php', 'fromgplus_cron');
40 Addon::unregisterHook('addon_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
41 Addon::unregisterHook('addon_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
44 function fromgplus_addon_settings(&$a,&$s) {
49 // If "gpluspost" is installed as well, then the settings are displayed there
50 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'gpluspost' AND `installed`");
51 if (count($result) > 0)
54 $enable_checked = (intval(PConfig::get(local_user(),'fromgplus','enable')) ? ' checked="checked"' : '');
55 $keywords_checked = (intval(PConfig::get(local_user(), 'fromgplus', 'keywords')) ? ' checked="checked"' : '');
56 $account = PConfig::get(local_user(),'fromgplus','account');
58 $s .= '<span id="settings_fromgplus_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_fromgplus_expanded\'); openClose(\'settings_fromgplus_inflated\');">';
59 $s .= '<img class="connector" src="images/googleplus.png" /><h3 class="connector">'. L10n::t('Google+ Mirror').'</h3>';
61 $s .= '<div id="settings_fromgplus_expanded" class="settings-block" style="display: none;">';
62 $s .= '<span class="fakelink" onclick="openClose(\'settings_fromgplus_expanded\'); openClose(\'settings_fromgplus_inflated\');">';
63 $s .= '<img class="connector" src="images/googleplus.png" /><h3 class="connector">'. L10n::t('Google+ Mirror').'</h3>';
66 $s .= '<div id="fromgplus-wrapper">';
68 $s .= '<label id="fromgplus-enable-label" for="fromgplus-enable">'.L10n::t('Enable Google+ Import').'</label>';
69 $s .= '<input id="fromgplus-enable" type="checkbox" name="fromgplus-enable" value="1"'.$enable_checked.' />';
70 $s .= '<div class="clear"></div>';
71 $s .= '<label id="fromgplus-label" for="fromgplus-account">'.L10n::t('Google Account ID').' </label>';
72 $s .= '<input id="fromgplus-account" type="text" name="fromgplus-account" value="'.$account.'" />';
73 $s .= '</div><div class="clear"></div>';
74 $s .= '<label id="fromgplus-keywords-label" for="fromgplus-keywords">'.L10n::t('Add keywords to post').'</label>';
75 $s .= '<input id="fromgplus-keywords" type="checkbox" name="fromgplus-keywords" value="1"'.$keywords_checked.' />';
76 $s .= '<div class="clear"></div>';
78 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fromgplus-submit" name="fromgplus-submit"
79 class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
85 function fromgplus_addon_settings_post(&$a,&$b) {
90 if (!empty($_POST['fromgplus-submit'])) {
91 PConfig::set(local_user(),'fromgplus','account',trim($_POST['fromgplus-account']));
92 $enable = (x($_POST,'fromgplus-enable') ? intval($_POST['fromgplus-enable']) : 0);
93 PConfig::set(local_user(),'fromgplus','enable', $enable);
94 $keywords = (x($_POST, 'fromgplus-keywords') ? intval($_POST['fromgplus-keywords']) : 0);
95 PConfig::set(local_user(),'fromgplus', 'keywords', $keywords);
98 PConfig::delete(local_user(),'fromgplus','lastdate');
100 info(L10n::t('Google+ Import Settings saved.') . EOL);
104 function fromgplus_addon_admin(&$a, &$o)
106 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/fromgplus/");
108 $o = Renderer::replaceMacros($t, [
109 '$submit' => L10n::t('Save Settings'),
110 '$key' => ['key', L10n::t('Key'), trim(Config::get('fromgplus', 'key')), ''],
114 function fromgplus_addon_admin_post(&$a)
116 $key = ((x($_POST, 'key')) ? trim($_POST['key']) : '');
117 Config::set('fromgplus', 'key', $key);
118 info(L10n::t('Settings updated.'). EOL);
121 function fromgplus_cron($a,$b) {
122 $last = Config::get('fromgplus','last_poll');
124 $poll_interval = intval(Config::get('fromgplus','poll_interval'));
126 $poll_interval = FROMGPLUS_DEFAULT_POLL_INTERVAL;
129 $next = $last + ($poll_interval * 60);
131 Logger::log('fromgplus: poll intervall not reached');
136 Logger::log('fromgplus: cron_start');
138 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fromgplus' AND `k` = 'enable' AND `v` = '1' ORDER BY RAND() ");
141 $account = PConfig::get($rr['uid'],'fromgplus','account');
143 Logger::log('fromgplus: fetching for user '.$rr['uid']);
144 fromgplus_fetch($a, $rr['uid']);
149 Logger::log('fromgplus: cron_end');
151 Config::set('fromgplus','last_poll', time());
154 function fromgplus_post($a, $uid, $source, $body, $location, $coord, $id) {
158 // Don't know what it is. Maybe some trash from the mobile client
159 $trash = html_entity_decode("", ENT_QUOTES, 'UTF-8');
160 $body = str_replace($trash, "", $body);
164 if (substr($body, 0, 3) == "[b]") {
165 $pos = strpos($body, "[/b]");
166 $title = substr($body, 3, $pos-3);
167 $body = trim(substr($body, $pos+4));
171 $_SESSION['authenticated'] = true;
172 $_SESSION['uid'] = $uid;
175 $_REQUEST['api_source'] = true;
177 $_REQUEST['profile_uid'] = $uid;
178 $_REQUEST['source'] = $source;
179 $_REQUEST['extid'] = Protocol::GPLUS;
182 $_REQUEST['message_id'] = Item::newURI($uid, Protocol::GPLUS.':'.$id);
186 // $_REQUEST['parent']
187 // $_REQUEST['parent_uri']
189 $_REQUEST['title'] = $title;
190 $_REQUEST['body'] = $body;
191 $_REQUEST['location'] = $location;
192 $_REQUEST['coord'] = $coord;
194 if (($_REQUEST['title'] == "") && ($_REQUEST['body'] == "")) {
195 Logger::log('fromgplus: empty post for user '.$uid." ".print_r($_REQUEST, true));
199 require_once('mod/item.php');
200 //print_r($_REQUEST);
201 Logger::log('fromgplus: posting for user '.$uid." ".print_r($_REQUEST, true));
203 Logger::log('fromgplus: done for user '.$uid);
206 function fromgplus_html2bbcode($html) {
208 $bbcode = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
210 $bbcode = str_ireplace(["\n"], [""], $bbcode);
211 $bbcode = str_ireplace(["<b>", "</b>"], ["[b]", "[/b]"], $bbcode);
212 $bbcode = str_ireplace(["<i>", "</i>"], ["[i]", "[/i]"], $bbcode);
213 $bbcode = str_ireplace(["<s>", "</s>"], ["[s]", "[/s]"], $bbcode);
214 $bbcode = str_ireplace(["<br />"], ["\n"], $bbcode);
215 $bbcode = str_ireplace(["<br/>"], ["\n"], $bbcode);
216 $bbcode = str_ireplace(["<br>"], ["\n"], $bbcode);
218 $bbcode = trim(strip_tags($bbcode));
222 function fromgplus_parse_query($var)
225 * Use this function to parse out the query array element from
226 * the output of parse_url().
228 $var = parse_url($var, PHP_URL_QUERY);
229 $var = html_entity_decode($var);
230 $var = explode('&', $var);
233 foreach($var as $val) {
234 $x = explode('=', $val);
239 unset($val, $x, $var);
243 function fromgplus_cleanupgoogleproxy($fullImage, $image) {
244 //$preview = "/w".$fullImage->width."-h".$fullImage->height."/";
245 //$preview2 = "/w".$fullImage->width."-h".$fullImage->height."-p/";
246 //$fullImage = str_replace(array($preview, $preview2), array("/", "/"), $fullImage->url);
247 $fullImage = $fullImage->url;
249 //$preview = "/w".$image->width."-h".$image->height."/";
250 //$preview2 = "/w".$image->width."-h".$image->height."-p/";
251 //$image = str_replace(array($preview, $preview2), array("/", "/"), $image->url);
252 $image = $image->url;
256 $queryvar = fromgplus_parse_query($fullImage);
257 if (!empty($queryvar['url']))
258 $cleaned["full"] = urldecode($queryvar['url']);
260 $cleaned["full"] = $fullImage;
261 if (@exif_imagetype($cleaned["full"]) == 0)
262 $cleaned["full"] = "";
264 $queryvar = fromgplus_parse_query($image);
265 if (!empty($queryvar['url']))
266 $cleaned["preview"] = urldecode($queryvar['url']);
268 $cleaned["preview"] = $image;
269 if (@exif_imagetype($cleaned["preview"]) == 0)
270 $cleaned["preview"] = "";
272 if (empty($cleaned["full"])) {
273 $cleaned["full"] = $cleaned["preview"];
274 $cleaned["preview"] = "";
277 if (!empty($cleaned["full"]))
278 $infoFull = Image::getInfoFromURL($cleaned["full"]);
280 $infoFull = ["0" => 0, "1" => 0];
282 if (!empty($cleaned["preview"]))
283 $infoPreview = Image::getInfoFromURL($cleaned["preview"]);
285 $infoPreview = ["0" => 0, "1" => 0];
287 if (($infoPreview[0] >= $infoFull[0]) && ($infoPreview[1] >= $infoFull[1])) {
288 $temp = $cleaned["full"];
289 $cleaned["full"] = $cleaned["preview"];
290 $cleaned["preview"] = $temp;
293 if (($cleaned["full"] == $cleaned["preview"]) || (($infoPreview[0] == $infoFull[0]) && ($infoPreview[1] == $infoFull[1])))
294 $cleaned["preview"] = "";
296 if ($cleaned["full"] == "")
297 if (@exif_imagetype($fullImage) != 0)
298 $cleaned["full"] = $fullImage;
300 if ($cleaned["full"] == "")
301 if (@exif_imagetype($image) != 0)
302 $cleaned["full"] = $image;
304 // Could be changed in the future to a link to the album
305 $cleaned["page"] = $cleaned["full"];
310 function fromgplus_cleantext($text) {
312 // Don't know what it is. But it is added to the text.
313 $trash = html_entity_decode("", ENT_QUOTES, 'UTF-8');
315 $text = strip_tags($text);
316 $text = html_entity_decode($text, ENT_QUOTES);
318 $text = str_replace(["\n", "\r", " ", $trash], ["", "", "", ""], $text);
322 function fromgplus_handleattachments($a, $uid, $item, $displaytext, $shared) {
323 require_once 'include/items.php';
328 $pagedata["type"] = "";
330 foreach ($item->object->attachments as $attachment) {
331 switch($attachment->objectType) {
333 $pagedata["type"] = "video";
334 $pagedata["url"] = Network::finalUrl($attachment->url);
335 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
339 $pagedata["type"] = "link";
340 $pagedata["url"] = Network::finalUrl($attachment->url);
341 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
343 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
344 if ($images["full"] != "")
345 $pagedata["images"][0]["src"] = $images["full"];
347 if (!empty($attachment->content)) {
348 $quote = trim(fromgplus_html2bbcode($attachment->content));
351 if (!empty($quote)) {
352 $pagedata["text"] = $quote;
355 // Add Keywords to page link
356 $data = parseurl_getsiteinfo_cached($pagedata["url"], true);
357 if (isset($data["keywords"]) && PConfig::get($uid, 'fromgplus', 'keywords')) {
358 $pagedata["keywords"] = $data["keywords"];
363 // Don't store shared pictures in your wall photos (to prevent a possible violating of licenses)
365 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
367 if ($attachment->fullImage->url != "") {
368 $images = Image::storePhoto($a, $uid, "", $attachment->fullImage->url);
369 } elseif ($attachment->image->url != "") {
370 $images = Image::storePhoto($a, $uid, "", $attachment->image->url);
374 if (!empty($images["preview"])) {
375 $post .= "\n[url=".$images["page"]."][img]".$images["preview"]."[/img][/url]\n";
376 $pagedata["images"][0]["src"] = $images["preview"];
377 $pagedata["url"] = $images["page"];
378 } elseif (!empty($images["full"])) {
379 $post .= "\n[img]".$images["full"]."[/img]\n";
380 $pagedata["images"][0]["src"] = $images["full"];
382 if ($images["preview"] != "") {
383 $pagedata["images"][1]["src"] = $images["preview"];
387 if (($attachment->displayName != "") && (fromgplus_cleantext($attachment->displayName) != fromgplus_cleantext($displaytext))) {
388 $post .= fromgplus_html2bbcode($attachment->displayName)."\n";
389 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
394 $pagedata["url"] = Network::finalUrl($attachment->url);
395 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
396 $post .= "\n\n[bookmark=".$pagedata["url"]."]".$pagedata["title"]."[/bookmark]\n";
398 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
400 if ($images["preview"] != "") {
401 $post .= "\n[url=".$images["full"]."][img]".$images["preview"]."[/img][/url]\n";
402 $pagedata["images"][0]["src"] = $images["preview"];
403 $pagedata["url"] = $images["full"];
404 } elseif ($images["full"] != "") {
405 $post .= "\n[img]".$images["full"]."[/img]\n";
406 $pagedata["images"][0]["src"] = $images["full"];
408 if ($images["preview"] != "")
409 $pagedata["images"][1]["src"] = $images["preview"];
414 $pagedata["type"] = "link";
415 $pagedata["url"] = Network::finalUrl($attachment->url);
416 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
418 $thumb = $attachment->thumbnails[0];
419 $pagedata["images"][0]["src"] = $thumb->image->url;
421 $quote = trim(fromgplus_html2bbcode($thumb->description));
423 $pagedata["text"] = $quote;
428 $pagedata["url"] = Network::finalUrl($attachment->url);
429 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
430 $post .= "\n\n[bookmark=".$pagedata["url"]."]".$pagedata["title"]."[/bookmark]\n";
434 // die($attachment->objectType);
438 if ($pagedata["type"] != "")
439 return(add_page_info_data($pagedata));
441 return($post.$quote);
444 function fromgplus_fetch($a, $uid) {
447 // Special blank to identify postings from the googleplus connector
448 $blank = html_entity_decode(" ", ENT_QUOTES, 'UTF-8');
450 $account = PConfig::get($uid,'fromgplus','account');
451 $key = Config::get('fromgplus','key');
453 $result = Network::fetchUrl("https://www.googleapis.com/plus/v1/people/".$account."/activities/public?alt=json&pp=1&key=".$key."&maxResults=".$maxfetch);
454 //$result = file_get_contents("google.txt");
455 //file_put_contents("google.txt", $result);
457 $activities = json_decode($result);
459 $initiallastdate = PConfig::get($uid,'fromgplus','lastdate');
461 $first_time = ($initiallastdate == "");
465 if (empty($activities->items))
468 $reversed = array_reverse($activities->items);
470 foreach($reversed as $item) {
472 if (strtotime($item->published) <= $initiallastdate)
475 // Don't publish items that are too young
476 if (strtotime($item->published) > (time() - 3*60)) {
477 Logger::log('fromgplus_fetch: item too new '.$item->published);
481 if ($lastdate < strtotime($item->published))
482 $lastdate = strtotime($item->published);
484 PConfig::set($uid,'fromgplus','lastdate', $lastdate);
489 if ($item->access->description == "Public") {
491 // Loop prevention through the special blank from the googleplus connector
492 //if (strstr($item->object->content, $blank))
493 if (strrpos($item->object->content, $blank) >= strlen($item->object->content) - 5)
496 switch($item->object->objectType) {
498 $post = fromgplus_html2bbcode($item->object->content);
500 if (!empty($item->object->attachments)) {
501 $post .= fromgplus_handleattachments($a, $uid, $item, $item->object->content, false);
506 if (isset($item->location)) {
507 if (isset($item->location->address->formatted))
508 $location = $item->location->address->formatted;
510 if (isset($item->location->displayName))
511 $location = $item->location->displayName;
513 if (isset($item->location->position->latitude) &&
514 isset($item->location->position->longitude))
515 $coord = $item->location->position->latitude." ".$item->location->position->longitude;
517 } elseif (isset($item->address))
518 $location = $item->address;
520 fromgplus_post($a, $uid, $item->provider->title, $post, $location, $coord, $item->id);
525 $post = fromgplus_html2bbcode($item->annotation)."\n";
527 if (!intval(Config::get('system','old_share'))) {
529 if (function_exists("share_header"))
530 $post .= share_header($item->object->actor->displayName, $item->object->actor->url,
531 $item->object->actor->image->url, "",
532 DateTimeFormat::utc($item->published),$item->object->url);
534 $post .= "[share author='".str_replace("'", "'",$item->object->actor->displayName).
535 "' profile='".$item->object->actor->url.
536 "' avatar='".$item->object->actor->image->url.
537 "' posted='".DateTimeFormat::utc($item->published).
538 "' link='".$item->object->url."']";
540 $post .= fromgplus_html2bbcode($item->object->content);
542 if (is_array($item->object->attachments))
543 $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
547 $post .= fromgplus_html2bbcode("♲");
548 $post .= " [url=".$item->object->actor->url."]".$item->object->actor->displayName."[/url] \n";
549 $post .= fromgplus_html2bbcode($item->object->content);
551 if (is_array($item->object->attachments))
552 $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
557 if (isset($item->location)) {
558 if (isset($item->location->address->formatted))
559 $location = $item->location->address->formatted;
561 if (isset($item->location->displayName))
562 $location = $item->location->displayName;
564 if (isset($item->location->position->latitude) &&
565 isset($item->location->position->longitude))
566 $coord = $item->location->position->latitude." ".$item->location->position->longitude;
568 } elseif (isset($item->address))
569 $location = $item->address;
571 fromgplus_post($a, $uid, $item->provider->title, $post, $location, $coord, $item->id);
577 PConfig::set($uid,'fromgplus','lastdate', $lastdate);