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