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