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