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