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