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