]> git.mxchange.org Git - friendica-addons.git/blob - fromgplus/fromgplus.php
Merge pull request #778 from MrPetovan/task/move-config-to-php-array
[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\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;
23
24 require_once 'mod/share.php';
25 require_once 'mod/parse_url.php';
26 require_once 'include/text.php';
27
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');
32 }
33
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');
38
39         // Old hooks
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');
42 }
43
44 function fromgplus_addon_settings(&$a,&$s) {
45
46         if(! local_user())
47                 return;
48
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)
52                 return;
53
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');
57
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>';
60         $s .= '</span>';
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>';
64         $s .= '</span>';
65
66         $s .= '<div id="fromgplus-wrapper">';
67
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>';
77
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>';
80         $s .= '</div>';
81
82         return;
83 }
84
85 function fromgplus_addon_settings_post(&$a,&$b) {
86
87         if (!local_user())
88                 return;
89
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);
96
97                 if (!$enable)
98                         PConfig::delete(local_user(),'fromgplus','lastdate');
99
100                 info(L10n::t('Google+ Import Settings saved.') . EOL);
101         }
102 }
103
104 function fromgplus_addon_admin(&$a, &$o)
105 {
106         $t = Renderer::getMarkupTemplate("admin.tpl", "addon/fromgplus/");
107
108         $o = Renderer::replaceMacros($t, [
109                         '$submit' => L10n::t('Save Settings'),
110                         '$key' => ['key', L10n::t('Key'), trim(Config::get('fromgplus', 'key')), ''],
111         ]);
112 }
113
114 function fromgplus_addon_admin_post(&$a)
115 {
116         $key = ((x($_POST, 'key')) ? trim($_POST['key']) : '');
117         Config::set('fromgplus', 'key', $key);
118         info(L10n::t('Settings updated.'). EOL);
119 }
120
121 function fromgplus_cron($a,$b) {
122         $last = Config::get('fromgplus','last_poll');
123
124         $poll_interval = intval(Config::get('fromgplus','poll_interval'));
125         if(! $poll_interval)
126                 $poll_interval = FROMGPLUS_DEFAULT_POLL_INTERVAL;
127
128         if($last) {
129                 $next = $last + ($poll_interval * 60);
130                 if($next > time()) {
131                         Logger::log('fromgplus: poll intervall not reached');
132                         return;
133                 }
134         }
135
136         Logger::log('fromgplus: cron_start');
137
138         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fromgplus' AND `k` = 'enable' AND `v` = '1' ORDER BY RAND() ");
139         if(count($r)) {
140                 foreach($r as $rr) {
141                         $account = PConfig::get($rr['uid'],'fromgplus','account');
142                         if ($account) {
143                         Logger::log('fromgplus: fetching for user '.$rr['uid']);
144                                 fromgplus_fetch($a, $rr['uid']);
145                         }
146                 }
147         }
148
149         Logger::log('fromgplus: cron_end');
150
151         Config::set('fromgplus','last_poll', time());
152 }
153
154 function fromgplus_post($a, $uid, $source, $body, $location, $coord, $id) {
155
156         //$uid = 2;
157
158         // Don't know what it is. Maybe some trash from the mobile client
159         $trash = html_entity_decode("&#xFEFF;", ENT_QUOTES, 'UTF-8');
160         $body = str_replace($trash, "", $body);
161
162         $body = trim($body);
163
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));
168         } else
169                 $title = "";
170
171         $_SESSION['authenticated'] = true;
172         $_SESSION['uid'] = $uid;
173
174         unset($_REQUEST);
175         $_REQUEST['api_source'] = true;
176
177         $_REQUEST['profile_uid'] = $uid;
178         $_REQUEST['source'] = $source;
179         $_REQUEST['extid'] = Protocol::GPLUS;
180
181         if (isset($id)) {
182                 $_REQUEST['message_id'] = Item::newURI($uid, Protocol::GPLUS.':'.$id);
183         }
184
185         // $_REQUEST['verb']
186         // $_REQUEST['parent']
187         // $_REQUEST['parent_uri']
188
189         $_REQUEST['title'] = $title;
190         $_REQUEST['body'] = $body;
191         $_REQUEST['location'] = $location;
192         $_REQUEST['coord'] = $coord;
193
194         if (($_REQUEST['title'] == "") && ($_REQUEST['body'] == "")) {
195                 Logger::log('fromgplus: empty post for user '.$uid." ".print_r($_REQUEST, true));
196                 return;
197         }
198
199         require_once('mod/item.php');
200         //print_r($_REQUEST);
201         Logger::log('fromgplus: posting for user '.$uid." ".print_r($_REQUEST, true));
202         item_post($a);
203         Logger::log('fromgplus: done for user '.$uid);
204 }
205
206 function fromgplus_html2bbcode($html) {
207
208         $bbcode = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
209
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);
217
218         $bbcode = trim(strip_tags($bbcode));
219         return($bbcode);
220 }
221
222 function fromgplus_parse_query($var)
223  {
224         /**
225         *  Use this function to parse out the query array element from
226         *  the output of parse_url().
227         */
228         $var  = parse_url($var, PHP_URL_QUERY);
229         $var  = html_entity_decode($var);
230         $var  = explode('&', $var);
231         $arr  = [];
232
233         foreach($var as $val) {
234                 $x          = explode('=', $val);
235                 if (count($x) > 1) {
236                         $arr[$x[0]] = $x[1];
237                 }
238         }
239         unset($val, $x, $var);
240         return $arr;
241 }
242
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;
248
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;
253
254         $cleaned = [];
255
256         $queryvar = fromgplus_parse_query($fullImage);
257         if (!empty($queryvar['url']))
258                 $cleaned["full"] = urldecode($queryvar['url']);
259         else
260                 $cleaned["full"] = $fullImage;
261         if (@exif_imagetype($cleaned["full"]) == 0)
262                 $cleaned["full"] = "";
263
264         $queryvar = fromgplus_parse_query($image);
265         if (!empty($queryvar['url']))
266                 $cleaned["preview"] = urldecode($queryvar['url']);
267         else
268                 $cleaned["preview"] = $image;
269         if (@exif_imagetype($cleaned["preview"]) == 0)
270                 $cleaned["preview"] = "";
271
272         if (empty($cleaned["full"])) {
273                 $cleaned["full"] = $cleaned["preview"];
274                 $cleaned["preview"] = "";
275         }
276
277         if (!empty($cleaned["full"]))
278                 $infoFull = Image::getInfoFromURL($cleaned["full"]);
279         else
280                 $infoFull = ["0" => 0, "1" => 0];
281
282         if (!empty($cleaned["preview"]))
283                 $infoPreview = Image::getInfoFromURL($cleaned["preview"]);
284         else
285                 $infoPreview = ["0" => 0, "1" => 0];
286
287         if (($infoPreview[0] >= $infoFull[0]) && ($infoPreview[1] >= $infoFull[1])) {
288                 $temp = $cleaned["full"];
289                 $cleaned["full"] = $cleaned["preview"];
290                 $cleaned["preview"] = $temp;
291         }
292
293         if (($cleaned["full"] == $cleaned["preview"]) || (($infoPreview[0] == $infoFull[0]) && ($infoPreview[1] == $infoFull[1])))
294                 $cleaned["preview"] = "";
295
296         if ($cleaned["full"] == "")
297                 if (@exif_imagetype($fullImage) != 0)
298                         $cleaned["full"] = $fullImage;
299
300         if ($cleaned["full"] == "")
301                 if (@exif_imagetype($image) != 0)
302                         $cleaned["full"] = $image;
303
304         // Could be changed in the future to a link to the album
305         $cleaned["page"] = $cleaned["full"];
306
307         return($cleaned);
308 }
309
310 function fromgplus_cleantext($text) {
311
312         // Don't know what it is. But it is added to the text.
313         $trash = html_entity_decode("&#xFEFF;", ENT_QUOTES, 'UTF-8');
314
315         $text = strip_tags($text);
316         $text = html_entity_decode($text, ENT_QUOTES);
317         $text = trim($text);
318         $text = str_replace(["\n", "\r", " ", $trash], ["", "", "", ""], $text);
319         return($text);
320 }
321
322 function fromgplus_handleattachments($a, $uid, $item, $displaytext, $shared) {
323         require_once 'include/items.php';
324
325         $post = "";
326         $quote = "";
327         $pagedata = [];
328         $pagedata["type"] = "";
329
330         foreach ($item->object->attachments as $attachment) {
331                 switch($attachment->objectType) {
332                         case "video":
333                                 $pagedata["type"] = "video";
334                                 $pagedata["url"] = Network::finalUrl($attachment->url);
335                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
336                                 break;
337
338                         case "article":
339                                 $pagedata["type"] = "link";
340                                 $pagedata["url"] = Network::finalUrl($attachment->url);
341                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
342
343                                 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
344                                 if ($images["full"] != "")
345                                         $pagedata["images"][0]["src"] = $images["full"];
346
347                                 if (!empty($attachment->content)) {
348                                         $quote = trim(fromgplus_html2bbcode($attachment->content));
349                                 }
350
351                                 if (!empty($quote)) {
352                                         $pagedata["text"] = $quote;
353                                 }
354
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"];
359                                 }
360                                 break;
361
362                         case "photo":
363                                 // Don't store shared pictures in your wall photos (to prevent a possible violating of licenses)
364                                 if ($shared) {
365                                         $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
366                                 } else {
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);
371                                         }
372                                 }
373
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"];
381
382                                         if ($images["preview"] != "") {
383                                                 $pagedata["images"][1]["src"] = $images["preview"];
384                                         }
385                                 }
386
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);
390                                 }
391                                 break;
392
393                         case "photo-album":
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";
397
398                                 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
399
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"];
407
408                                         if ($images["preview"] != "")
409                                                 $pagedata["images"][1]["src"] = $images["preview"];
410                                 }
411                                 break;
412
413                         case "album":
414                                 $pagedata["type"] = "link";
415                                 $pagedata["url"] = Network::finalUrl($attachment->url);
416                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
417
418                                 $thumb = $attachment->thumbnails[0];
419                                 $pagedata["images"][0]["src"] = $thumb->image->url;
420
421                                 $quote = trim(fromgplus_html2bbcode($thumb->description));
422                                 if ($quote != "")
423                                         $pagedata["text"] = $quote;
424
425                                 break;
426
427                         case "audio":
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";
431                                 break;
432
433                         //default:
434                         //      die($attachment->objectType);
435                 }
436         }
437
438         if ($pagedata["type"] != "")
439                 return(add_page_info_data($pagedata));
440
441         return($post.$quote);
442 }
443
444 function fromgplus_fetch($a, $uid) {
445         $maxfetch = 20;
446
447         // Special blank to identify postings from the googleplus connector
448         $blank = html_entity_decode("&#x00A0;", ENT_QUOTES, 'UTF-8');
449
450         $account = PConfig::get($uid,'fromgplus','account');
451         $key = Config::get('fromgplus','key');
452
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);
456
457         $activities = json_decode($result);
458
459         $initiallastdate = PConfig::get($uid,'fromgplus','lastdate');
460
461         $first_time = ($initiallastdate == "");
462
463         $lastdate = 0;
464
465         if (empty($activities->items))
466                 return;
467
468         $reversed = array_reverse($activities->items);
469
470         foreach($reversed as $item) {
471
472                 if (strtotime($item->published) <= $initiallastdate)
473                         continue;
474
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);
478                         continue;
479                 }
480
481                 if ($lastdate < strtotime($item->published))
482                         $lastdate = strtotime($item->published);
483
484                 PConfig::set($uid,'fromgplus','lastdate', $lastdate);
485
486                 if ($first_time)
487                         continue;
488
489                 if ($item->access->description == "Public") {
490
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)
494                                 continue;
495
496                         switch($item->object->objectType) {
497                                 case "note":
498                                         $post = fromgplus_html2bbcode($item->object->content);
499
500                                         if (!empty($item->object->attachments)) {
501                                                 $post .= fromgplus_handleattachments($a, $uid, $item, $item->object->content, false);
502                                         }
503
504                                         $coord = "";
505                                         $location = "";
506                                         if (isset($item->location)) {
507                                                 if (isset($item->location->address->formatted))
508                                                         $location = $item->location->address->formatted;
509
510                                                 if (isset($item->location->displayName))
511                                                         $location = $item->location->displayName;
512
513                                                 if (isset($item->location->position->latitude) &&
514                                                         isset($item->location->position->longitude))
515                                                         $coord = $item->location->position->latitude." ".$item->location->position->longitude;
516
517                                         } elseif (isset($item->address))
518                                                 $location = $item->address;
519
520                                         fromgplus_post($a, $uid, $item->provider->title, $post, $location, $coord, $item->id);
521
522                                         break;
523
524                                 case "activity":
525                                         $post = fromgplus_html2bbcode($item->annotation)."\n";
526
527                                         if (!intval(Config::get('system','old_share'))) {
528
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);
533                                                 else
534                                                         $post .= "[share author='".str_replace("'", "&#039;",$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."']";
539
540                                                 $post .= fromgplus_html2bbcode($item->object->content);
541
542                                                 if (is_array($item->object->attachments))
543                                                         $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
544
545                                                 $post .= "[/share]";
546                                         } else {
547                                                 $post .= fromgplus_html2bbcode("&#x2672;");
548                                                 $post .= " [url=".$item->object->actor->url."]".$item->object->actor->displayName."[/url] \n";
549                                                 $post .= fromgplus_html2bbcode($item->object->content);
550
551                                                 if (is_array($item->object->attachments))
552                                                         $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
553                                         }
554
555                                         $coord = "";
556                                         $location = "";
557                                         if (isset($item->location)) {
558                                                 if (isset($item->location->address->formatted))
559                                                         $location = $item->location->address->formatted;
560
561                                                 if (isset($item->location->displayName))
562                                                         $location = $item->location->displayName;
563
564                                                 if (isset($item->location->position->latitude) &&
565                                                         isset($item->location->position->longitude))
566                                                         $coord = $item->location->position->latitude." ".$item->location->position->longitude;
567
568                                         } elseif (isset($item->address))
569                                                 $location = $item->address;
570
571                                         fromgplus_post($a, $uid, $item->provider->title, $post, $location, $coord, $item->id);
572                                         break;
573                         }
574                 }
575         }
576         if ($lastdate != 0)
577                 PConfig::set($uid,'fromgplus','lastdate', $lastdate);
578 }