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