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