]> git.mxchange.org Git - friendica-addons.git/blob - fromgplus/fromgplus.php
EN US added twitter translation
[friendica-addons.git] / fromgplus / fromgplus.php
1 <?php
2 /**
3  * Name: From GPlus
4  * Description: Imports posts from a Google+ account and repeats them
5  * Version: 0.1
6  * Author: Michael Vogel <ike@piratenpartei.de>
7  *
8  */
9
10 define('FROMGPLUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
11
12 use Friendica\Core\Addon;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\PConfig;
16 use Friendica\Object\Image;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Network;
19 use Friendica\Model\Item;
20
21 require_once 'mod/share.php';
22 require_once 'mod/parse_url.php';
23 require_once 'include/text.php';
24
25 function fromgplus_install() {
26         Addon::registerHook('connector_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
27         Addon::registerHook('connector_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
28         Addon::registerHook('cron', 'addon/fromgplus/fromgplus.php', 'fromgplus_cron');
29 }
30
31 function fromgplus_uninstall() {
32         Addon::unregisterHook('connector_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
33         Addon::unregisterHook('connector_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
34         Addon::unregisterHook('cron', 'addon/fromgplus/fromgplus.php', 'fromgplus_cron');
35
36         // Old hooks
37         Addon::unregisterHook('addon_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
38         Addon::unregisterHook('addon_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
39 }
40
41 function fromgplus_addon_settings(&$a,&$s) {
42
43         if(! local_user())
44                 return;
45
46         // If "gpluspost" is installed as well, then the settings are displayed there
47         $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'gpluspost' AND `installed`");
48         if (count($result) > 0)
49                 return;
50
51         $enable_checked = (intval(PConfig::get(local_user(),'fromgplus','enable')) ? ' checked="checked"' : '');
52         $keywords_checked = (intval(PConfig::get(local_user(), 'fromgplus', 'keywords')) ? ' checked="checked"' : '');
53         $account = PConfig::get(local_user(),'fromgplus','account');
54
55         $s .= '<span id="settings_fromgplus_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_fromgplus_expanded\'); openClose(\'settings_fromgplus_inflated\');">';
56         $s .= '<img class="connector" src="images/googleplus.png" /><h3 class="connector">'. L10n::t('Google+ Mirror').'</h3>';
57         $s .= '</span>';
58         $s .= '<div id="settings_fromgplus_expanded" class="settings-block" style="display: none;">';
59         $s .= '<span class="fakelink" onclick="openClose(\'settings_fromgplus_expanded\'); openClose(\'settings_fromgplus_inflated\');">';
60         $s .= '<img class="connector" src="images/googleplus.png" /><h3 class="connector">'. L10n::t('Google+ Mirror').'</h3>';
61         $s .= '</span>';
62
63         $s .= '<div id="fromgplus-wrapper">';
64
65         $s .= '<label id="fromgplus-enable-label" for="fromgplus-enable">'.L10n::t('Enable Google+ Import').'</label>';
66         $s .= '<input id="fromgplus-enable" type="checkbox" name="fromgplus-enable" value="1"'.$enable_checked.' />';
67         $s .= '<div class="clear"></div>';
68         $s .= '<label id="fromgplus-label" for="fromgplus-account">'.L10n::t('Google Account ID').' </label>';
69         $s .= '<input id="fromgplus-account" type="text" name="fromgplus-account" value="'.$account.'" />';
70         $s .= '</div><div class="clear"></div>';
71         $s .= '<label id="fromgplus-keywords-label" for="fromgplus-keywords">'.L10n::t('Add keywords to post').'</label>';
72         $s .= '<input id="fromgplus-keywords" type="checkbox" name="fromgplus-keywords" value="1"'.$keywords_checked.' />';
73         $s .= '<div class="clear"></div>';
74
75         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fromgplus-submit" name="fromgplus-submit"
76 class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
77         $s .= '</div>';
78
79         return;
80 }
81
82 function fromgplus_addon_settings_post(&$a,&$b) {
83
84         if(! local_user())
85                 return;
86
87         if($_POST['fromgplus-submit']) {
88                 PConfig::set(local_user(),'fromgplus','account',trim($_POST['fromgplus-account']));
89                 $enable = ((x($_POST,'fromgplus-enable')) ? intval($_POST['fromgplus-enable']) : 0);
90                 PConfig::set(local_user(),'fromgplus','enable', $enable);
91                 $keywords = ((x($_POST, 'fromgplus-keywords')) ? intval($_POST['fromgplus-keywords']) : 0);
92                 PConfig::set(local_user(),'fromgplus', 'keywords', $keywords);
93
94                 if (!$enable)
95                         PConfig::delete(local_user(),'fromgplus','lastdate');
96
97                 info(L10n::t('Google+ Import Settings saved.') . EOL);
98         }
99 }
100
101 function fromgplus_addon_admin(&$a, &$o)
102 {
103         $t = get_markup_template("admin.tpl", "addon/fromgplus/");
104
105         $o = replace_macros($t, [
106                         '$submit' => L10n::t('Save Settings'),
107                         '$key' => ['key', L10n::t('Key'), trim(Config::get('fromgplus', 'key')), ''],
108         ]);
109 }
110
111 function fromgplus_addon_admin_post(&$a)
112 {
113         $key = ((x($_POST, 'key')) ? trim($_POST['key']) : '');
114         Config::set('fromgplus', 'key', $key);
115         info(L10n::t('Settings updated.'). EOL);
116 }
117
118 function fromgplus_cron($a,$b) {
119         $last = Config::get('fromgplus','last_poll');
120
121         $poll_interval = intval(Config::get('fromgplus','poll_interval'));
122         if(! $poll_interval)
123                 $poll_interval = FROMGPLUS_DEFAULT_POLL_INTERVAL;
124
125         if($last) {
126                 $next = $last + ($poll_interval * 60);
127                 if($next > time()) {
128                         logger('fromgplus: poll intervall not reached');
129                         return;
130                 }
131         }
132
133         logger('fromgplus: cron_start');
134
135         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fromgplus' AND `k` = 'enable' AND `v` = '1' ORDER BY RAND() ");
136         if(count($r)) {
137                 foreach($r as $rr) {
138                         $account = PConfig::get($rr['uid'],'fromgplus','account');
139                         if ($account) {
140                         logger('fromgplus: fetching for user '.$rr['uid']);
141                                 fromgplus_fetch($a, $rr['uid']);
142                         }
143                 }
144         }
145
146         logger('fromgplus: cron_end');
147
148         Config::set('fromgplus','last_poll', time());
149 }
150
151 function fromgplus_post($a, $uid, $source, $body, $location, $coord, $id) {
152
153         //$uid = 2;
154
155         // Don't know what it is. Maybe some trash from the mobile client
156         $trash = html_entity_decode("&#xFEFF;", ENT_QUOTES, 'UTF-8');
157         $body = str_replace($trash, "", $body);
158
159         $body = trim($body);
160
161         if (substr($body, 0, 3) == "[b]") {
162                 $pos = strpos($body, "[/b]");
163                 $title = substr($body, 3, $pos-3);
164                 $body = trim(substr($body, $pos+4));
165         } else
166                 $title = "";
167
168         $_SESSION['authenticated'] = true;
169         $_SESSION['uid'] = $uid;
170
171         unset($_REQUEST);
172         $_REQUEST['type'] = 'wall';
173         $_REQUEST['api_source'] = true;
174
175         $_REQUEST['profile_uid'] = $uid;
176         $_REQUEST['source'] = $source;
177         $_REQUEST['extid'] = NETWORK_GPLUS;
178
179         if (isset($id)) {
180                 $_REQUEST['message_id'] = Item::newURI($uid, NETWORK_GPLUS.':'.$id);
181         }
182
183         // $_REQUEST['verb']
184         // $_REQUEST['parent']
185         // $_REQUEST['parent_uri']
186
187         $_REQUEST['title'] = $title;
188         $_REQUEST['body'] = $body;
189         $_REQUEST['location'] = $location;
190         $_REQUEST['coord'] = $coord;
191
192         if (($_REQUEST['title'] == "") && ($_REQUEST['body'] == "")) {
193                 logger('fromgplus: empty post for user '.$uid." ".print_r($_REQUEST, true));
194                 return;
195         }
196
197         require_once('mod/item.php');
198         //print_r($_REQUEST);
199         logger('fromgplus: posting for user '.$uid." ".print_r($_REQUEST, true));
200         item_post($a);
201         logger('fromgplus: done for user '.$uid);
202 }
203
204 function fromgplus_html2bbcode($html) {
205
206         $bbcode = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
207
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);
215
216         $bbcode = trim(strip_tags($bbcode));
217         return($bbcode);
218 }
219
220 function fromgplus_parse_query($var)
221  {
222         /**
223         *  Use this function to parse out the query array element from
224         *  the output of parse_url().
225         */
226         $var  = parse_url($var, PHP_URL_QUERY);
227         $var  = html_entity_decode($var);
228         $var  = explode('&', $var);
229         $arr  = [];
230
231         foreach($var as $val) {
232                 $x          = explode('=', $val);
233                 $arr[$x[0]] = $x[1];
234         }
235         unset($val, $x, $var);
236         return $arr;
237 }
238
239 function fromgplus_cleanupgoogleproxy($fullImage, $image) {
240         //$preview = "/w".$fullImage->width."-h".$fullImage->height."/";
241         //$preview2 = "/w".$fullImage->width."-h".$fullImage->height."-p/";
242         //$fullImage = str_replace(array($preview, $preview2), array("/", "/"), $fullImage->url);
243         $fullImage = $fullImage->url;
244
245         //$preview = "/w".$image->width."-h".$image->height."/";
246         //$preview2 = "/w".$image->width."-h".$image->height."-p/";
247         //$image = str_replace(array($preview, $preview2), array("/", "/"), $image->url);
248         $image = $image->url;
249
250         $cleaned = [];
251
252         $queryvar = fromgplus_parse_query($fullImage);
253         if ($queryvar['url'] != "")
254                 $cleaned["full"] = urldecode($queryvar['url']);
255         else
256                 $cleaned["full"] = $fullImage;
257         if (@exif_imagetype($cleaned["full"]) == 0)
258                 $cleaned["full"] = "";
259
260         $queryvar = fromgplus_parse_query($image);
261         if ($queryvar['url'] != "")
262                 $cleaned["preview"] = urldecode($queryvar['url']);
263         else
264                 $cleaned["preview"] = $image;
265         if (@exif_imagetype($cleaned["preview"]) == 0)
266                 $cleaned["preview"] = "";
267
268         if ($cleaned["full"] == "") {
269                 $cleaned["full"] = $cleaned["preview"];
270                 $cleaned["preview"] = "";
271         }
272
273         if ($cleaned["full"] != "")
274                 $infoFull = Image::getInfoFromURL($cleaned["full"]);
275         else
276                 $infoFull = ["0" => 0, "1" => 0];
277
278         if ($cleaned["preview"] != "")
279                 $infoPreview = Image::getInfoFromURL($cleaned["preview"]);
280         else
281                 $infoFull = ["0" => 0, "1" => 0];
282
283         if (($infoPreview[0] >= $infoFull[0]) && ($infoPreview[1] >= $infoFull[1])) {
284                 $temp = $cleaned["full"];
285                 $cleaned["full"] = $cleaned["preview"];
286                 $cleaned["preview"] = $temp;
287         }
288
289         if (($cleaned["full"] == $cleaned["preview"]) || (($infoPreview[0] == $infoFull[0]) && ($infoPreview[1] == $infoFull[1])))
290                 $cleaned["preview"] = "";
291
292         if ($cleaned["full"] == "")
293                 if (@exif_imagetype($fullImage) != 0)
294                         $cleaned["full"] = $fullImage;
295
296         if ($cleaned["full"] == "")
297                 if (@exif_imagetype($image) != 0)
298                         $cleaned["full"] = $image;
299
300         // Could be changed in the future to a link to the album
301         $cleaned["page"] = $cleaned["full"];
302
303         return($cleaned);
304 }
305
306 function fromgplus_cleantext($text) {
307
308         // Don't know what it is. But it is added to the text.
309         $trash = html_entity_decode("&#xFEFF;", ENT_QUOTES, 'UTF-8');
310
311         $text = strip_tags($text);
312         $text = html_entity_decode($text, ENT_QUOTES);
313         $text = trim($text);
314         $text = str_replace(["\n", "\r", " ", $trash], ["", "", "", ""], $text);
315         return($text);
316 }
317
318 function fromgplus_handleattachments($a, $uid, $item, $displaytext, $shared) {
319         require_once 'include/items.php';
320
321         $post = "";
322         $quote = "";
323         $pagedata = [];
324         $pagedata["type"] = "";
325
326         foreach ($item->object->attachments as $attachment) {
327                 switch($attachment->objectType) {
328                         case "video":
329                                 $pagedata["type"] = "video";
330                                 $pagedata["url"] = Network::finalUrl($attachment->url);
331                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
332                                 break;
333
334                         case "article":
335                                 $pagedata["type"] = "link";
336                                 $pagedata["url"] = Network::finalUrl($attachment->url);
337                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
338
339                                 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
340                                 if ($images["full"] != "")
341                                         $pagedata["images"][0]["src"] = $images["full"];
342
343                                 $quote = trim(fromgplus_html2bbcode($attachment->content));
344
345                                 if ($quote != "")
346                                         $pagedata["text"] = $quote;
347
348                                 // Add Keywords to page link
349                                 $data = parseurl_getsiteinfo_cached($pagedata["url"], true);
350                                 if (isset($data["keywords"]) && PConfig::get($uid, 'fromgplus', 'keywords')) {
351                                         $pagedata["keywords"] = $data["keywords"];
352                                 }
353                                 break;
354
355                         case "photo":
356                                 // Don't store shared pictures in your wall photos (to prevent a possible violating of licenses)
357                                 if ($shared) {
358                                         $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
359                                 } else {
360                                         if ($attachment->fullImage->url != "") {
361                                                 $images = Image::storePhoto($a, $uid, "", $attachment->fullImage->url);
362                                         } elseif ($attachment->image->url != "") {
363                                                 $images = Image::storePhoto($a, $uid, "", $attachment->image->url);
364                                         }
365                                 }
366
367                                 if ($images["preview"] != "") {
368                                         $post .= "\n[url=".$images["page"]."][img]".$images["preview"]."[/img][/url]\n";
369                                         $pagedata["images"][0]["src"] = $images["preview"];
370                                         $pagedata["url"] = $images["page"];
371                                 } elseif ($images["full"] != "") {
372                                         $post .= "\n[img]".$images["full"]."[/img]\n";
373                                         $pagedata["images"][0]["src"] = $images["full"];
374
375                                         if ($images["preview"] != "") {
376                                                 $pagedata["images"][1]["src"] = $images["preview"];
377                                         }
378                                 }
379
380                                 if (($attachment->displayName != "") && (fromgplus_cleantext($attachment->displayName) != fromgplus_cleantext($displaytext))) {
381                                         $post .= fromgplus_html2bbcode($attachment->displayName)."\n";
382                                         $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
383                                 }
384                                 break;
385
386                         case "photo-album":
387                                 $pagedata["url"] = Network::finalUrl($attachment->url);
388                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
389                                 $post .= "\n\n[bookmark=".$pagedata["url"]."]".$pagedata["title"]."[/bookmark]\n";
390
391                                 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
392
393                                 if ($images["preview"] != "") {
394                                         $post .= "\n[url=".$images["full"]."][img]".$images["preview"]."[/img][/url]\n";
395                                         $pagedata["images"][0]["src"] = $images["preview"];
396                                         $pagedata["url"] = $images["full"];
397                                 } elseif ($images["full"] != "") {
398                                         $post .= "\n[img]".$images["full"]."[/img]\n";
399                                         $pagedata["images"][0]["src"] = $images["full"];
400
401                                         if ($images["preview"] != "")
402                                                 $pagedata["images"][1]["src"] = $images["preview"];
403                                 }
404                                 break;
405
406                         case "album":
407                                 $pagedata["type"] = "link";
408                                 $pagedata["url"] = Network::finalUrl($attachment->url);
409                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
410
411                                 $thumb = $attachment->thumbnails[0];
412                                 $pagedata["images"][0]["src"] = $thumb->image->url;
413
414                                 $quote = trim(fromgplus_html2bbcode($thumb->description));
415                                 if ($quote != "")
416                                         $pagedata["text"] = $quote;
417
418                                 break;
419
420                         case "audio":
421                                 $pagedata["url"] = Network::finalUrl($attachment->url);
422                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
423                                 $post .= "\n\n[bookmark=".$pagedata["url"]."]".$pagedata["title"]."[/bookmark]\n";
424                                 break;
425
426                         //default:
427                         //      die($attachment->objectType);
428                 }
429         }
430
431         if ($pagedata["type"] != "")
432                 return(add_page_info_data($pagedata));
433
434         return($post.$quote);
435 }
436
437 function fromgplus_fetch($a, $uid) {
438         $maxfetch = 20;
439
440         // Special blank to identify postings from the googleplus connector
441         $blank = html_entity_decode("&#x00A0;", ENT_QUOTES, 'UTF-8');
442
443         $account = PConfig::get($uid,'fromgplus','account');
444         $key = Config::get('fromgplus','key');
445
446         $result = Network::fetchUrl("https://www.googleapis.com/plus/v1/people/".$account."/activities/public?alt=json&pp=1&key=".$key."&maxResults=".$maxfetch);
447         //$result = file_get_contents("google.txt");
448         //file_put_contents("google.txt", $result);
449
450         $activities = json_decode($result);
451
452         $initiallastdate = PConfig::get($uid,'fromgplus','lastdate');
453
454         $first_time = ($initiallastdate == "");
455
456         $lastdate = 0;
457
458         if (!is_array($activities->items))
459                 return;
460
461         $reversed = array_reverse($activities->items);
462
463         foreach($reversed as $item) {
464
465                 if (strtotime($item->published) <= $initiallastdate)
466                         continue;
467
468                 // Don't publish items that are too young
469                 if (strtotime($item->published) > (time() - 3*60)) {
470                         logger('fromgplus_fetch: item too new '.$item->published);
471                         continue;
472                 }
473
474                 if ($lastdate < strtotime($item->published))
475                         $lastdate = strtotime($item->published);
476
477                 PConfig::set($uid,'fromgplus','lastdate', $lastdate);
478
479                 if ($first_time)
480                         continue;
481
482                 if ($item->access->description == "Public") {
483
484                         // Loop prevention through the special blank from the googleplus connector
485                         //if (strstr($item->object->content, $blank))
486                         if (strrpos($item->object->content, $blank) >= strlen($item->object->content) - 5)
487                                 continue;
488
489                         switch($item->object->objectType) {
490                                 case "note":
491                                         $post = fromgplus_html2bbcode($item->object->content);
492
493                                         if (is_array($item->object->attachments))
494                                                 $post .= fromgplus_handleattachments($a, $uid, $item, $item->object->content, false);
495
496                                         $coord = "";
497                                         $location = "";
498                                         if (isset($item->location)) {
499                                                 if (isset($item->location->address->formatted))
500                                                         $location = $item->location->address->formatted;
501
502                                                 if (isset($item->location->displayName))
503                                                         $location = $item->location->displayName;
504
505                                                 if (isset($item->location->position->latitude) &&
506                                                         isset($item->location->position->longitude))
507                                                         $coord = $item->location->position->latitude." ".$item->location->position->longitude;
508
509                                         } elseif (isset($item->address))
510                                                 $location = $item->address;
511
512                                         fromgplus_post($a, $uid, $item->provider->title, $post, $location, $coord, $item->id);
513
514                                         break;
515
516                                 case "activity":
517                                         $post = fromgplus_html2bbcode($item->annotation)."\n";
518
519                                         if (!intval(Config::get('system','old_share'))) {
520
521                                                 if (function_exists("share_header"))
522                                                         $post .= share_header($item->object->actor->displayName, $item->object->actor->url,
523                                                                                 $item->object->actor->image->url, "",
524                                                                                 DateTimeFormat::utc($item->object->published),$item->object->url);
525                                                 else
526                                                         $post .= "[share author='".str_replace("'", "&#039;",$item->object->actor->displayName).
527                                                                         "' profile='".$item->object->actor->url.
528                                                                         "' avatar='".$item->object->actor->image->url.
529                                                                         "' posted='".DateTimeFormat::utc($item->object->published).
530                                                                         "' link='".$item->object->url."']";
531
532                                                 $post .= fromgplus_html2bbcode($item->object->content);
533
534                                                 if (is_array($item->object->attachments))
535                                                         $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
536
537                                                 $post .= "[/share]";
538                                         } else {
539                                                 $post .= fromgplus_html2bbcode("&#x2672;");
540                                                 $post .= " [url=".$item->object->actor->url."]".$item->object->actor->displayName."[/url] \n";
541                                                 $post .= fromgplus_html2bbcode($item->object->content);
542
543                                                 if (is_array($item->object->attachments))
544                                                         $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
545                                         }
546
547                                         $coord = "";
548                                         $location = "";
549                                         if (isset($item->location)) {
550                                                 if (isset($item->location->address->formatted))
551                                                         $location = $item->location->address->formatted;
552
553                                                 if (isset($item->location->displayName))
554                                                         $location = $item->location->displayName;
555
556                                                 if (isset($item->location->position->latitude) &&
557                                                         isset($item->location->position->longitude))
558                                                         $coord = $item->location->position->latitude." ".$item->location->position->longitude;
559
560                                         } elseif (isset($item->address))
561                                                 $location = $item->address;
562
563                                         fromgplus_post($a, $uid, $item->provider->title, $post, $location, $coord, $item->id);
564                                         break;
565                         }
566                 }
567         }
568         if ($lastdate != 0)
569                 PConfig::set($uid,'fromgplus','lastdate', $lastdate);
570 }