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