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