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