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