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