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