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