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