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