]> git.mxchange.org Git - friendica-addons.git/blob - fromgplus/fromgplus.php
Merge pull request #226 from annando/1412-loop-prevention
[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         $_REQUEST['extid'] = NETWORK_GPLUS;
142
143         // $_REQUEST['verb']
144         // $_REQUEST['parent']
145         // $_REQUEST['parent_uri']
146
147         $_REQUEST['title'] = $title;
148         $_REQUEST['body'] = $body;
149         $_REQUEST['location'] = $location;
150
151         if (($_REQUEST['title'] == "") AND ($_REQUEST['body'] == "")) {
152                 logger('fromgplus: empty post for user '.$uid." ".print_r($_REQUEST, true));
153                 return;
154         }
155
156         require_once('mod/item.php');
157         //print_r($_REQUEST);
158         logger('fromgplus: posting for user '.$uid." ".print_r($_REQUEST, true));
159         item_post($a);
160         logger('fromgplus: done for user '.$uid);
161 }
162
163 function fromgplus_html2bbcode($html) {
164
165         $bbcode = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
166
167         $bbcode = str_ireplace(array("\n"), array(""), $bbcode);
168         $bbcode = str_ireplace(array("<b>", "</b>"), array("[b]", "[/b]"), $bbcode);
169         $bbcode = str_ireplace(array("<i>", "</i>"), array("[i]", "[/i]"), $bbcode);
170         $bbcode = str_ireplace(array("<s>", "</s>"), array("[s]", "[/s]"), $bbcode);
171         $bbcode = str_ireplace(array("<br />"), array("\n"), $bbcode);
172         $bbcode = str_ireplace(array("<br/>"), array("\n"), $bbcode);
173         $bbcode = str_ireplace(array("<br>"), array("\n"), $bbcode);
174
175         $bbcode = trim(strip_tags($bbcode));
176         return($bbcode);
177 }
178
179 function fromgplus_parse_query($var)
180  {
181         /**
182         *  Use this function to parse out the query array element from
183         *  the output of parse_url().
184         */
185         $var  = parse_url($var, PHP_URL_QUERY);
186         $var  = html_entity_decode($var);
187         $var  = explode('&', $var);
188         $arr  = array();
189
190         foreach($var as $val) {
191                 $x          = explode('=', $val);
192                 $arr[$x[0]] = $x[1];
193         }
194         unset($val, $x, $var);
195         return $arr;
196 }
197
198 function fromgplus_cleanupgoogleproxy($fullImage, $image) {
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         $fullImage = $fullImage->url;
203
204         //$preview = "/w".$image->width."-h".$image->height."/";
205         //$preview2 = "/w".$image->width."-h".$image->height."-p/";
206         //$image = str_replace(array($preview, $preview2), array("/", "/"), $image->url);
207         $image = $image->url;
208
209         $cleaned = array();
210
211         $queryvar = fromgplus_parse_query($fullImage);
212         if ($queryvar['url'] != "")
213                 $cleaned["full"] = urldecode($queryvar['url']);
214         else
215                 $cleaned["full"] = $fullImage;
216         if (@exif_imagetype($cleaned["full"]) == 0)
217                 $cleaned["full"] = "";
218
219         $queryvar = fromgplus_parse_query($image);
220         if ($queryvar['url'] != "")
221                 $cleaned["preview"] = urldecode($queryvar['url']);
222         else
223                 $cleaned["preview"] = $image;
224         if (@exif_imagetype($cleaned["preview"]) == 0)
225                 $cleaned["preview"] = "";
226
227         if ($cleaned["full"] == "") {
228                 $cleaned["full"] = $cleaned["preview"];
229                 $cleaned["preview"] = "";
230         }
231
232         if ($cleaned["full"] != "")
233                 $infoFull = get_photo_info($cleaned["full"]);
234         else
235                 $infoFull = array("0" => 0, "1" => 0);
236
237         if ($cleaned["preview"] != "")
238                 $infoPreview = get_photo_info($cleaned["preview"]);
239         else
240                 $infoFull = array("0" => 0, "1" => 0);
241
242         if (($infoPreview[0] >= $infoFull[0]) AND ($infoPreview[1] >= $infoFull[1])) {
243                 $temp = $cleaned["full"];
244                 $cleaned["full"] = $cleaned["preview"];
245                 $cleaned["preview"] = $temp;
246         }
247
248         if (($cleaned["full"] == $cleaned["preview"]) OR (($infoPreview[0] == $infoFull[0]) AND ($infoPreview[1] == $infoFull[1])))
249                 $cleaned["preview"] = "";
250
251         if ($cleaned["full"] == "")
252                 if (@exif_imagetype($fullImage) != 0)
253                         $cleaned["full"] = $fullImage;
254
255         if ($cleaned["full"] == "")
256                 if (@exif_imagetype($image) != 0)
257                         $cleaned["full"] = $image;
258
259         // Could be changed in the future to a link to the album
260         $cleaned["page"] = $cleaned["full"];
261
262         return($cleaned);
263 }
264
265 function fromgplus_cleantext($text) {
266
267         // Don't know what it is. But it is added to the text.
268         $trash = html_entity_decode("&#xFEFF;", ENT_QUOTES, 'UTF-8');
269
270         $text = strip_tags($text);
271         $text = html_entity_decode($text, ENT_QUOTES);
272         $text = trim($text);
273         $text = str_replace(array("\n", "\r", " ", $trash), array("", "", "", ""), $text);
274         return($text);
275 }
276
277 function fromgplus_handleattachments($a, $uid, $item, $displaytext, $shared) {
278         require_once("include/Photo.php");
279         require_once("include/items.php");
280         require_once("include/network.php");
281
282         $post = "";
283         $quote = "";
284         $pagedata = array();
285         $pagedata["type"] = "";
286
287         foreach ($item->object->attachments as $attachment) {
288                 switch($attachment->objectType) {
289                         case "video":
290                                 $pagedata["type"] = "video";
291                                 $pagedata["url"] = original_url($attachment->url);
292                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
293                                 break;
294
295                         case "article":
296                                 $pagedata["type"] = "link";
297                                 $pagedata["url"] = original_url($attachment->url);
298                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
299
300                                 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
301                                 if ($images["full"] != "")
302                                         $pagedata["images"][0]["src"] = $images["full"];
303
304                                 $quote = trim(fromgplus_html2bbcode($attachment->content));
305
306                                 if ($quote != "")
307                                         $pagedata["text"] = $quote;
308
309                                 break;
310
311                         case "photo":
312                                 // Don't store shared pictures in your wall photos (to prevent a possible violating of licenses)
313                                 if ($shared)
314                                         $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
315                                 else {
316                                         if ($attachment->fullImage->url != "")
317                                                 $images = store_photo($a, $uid, "", $attachment->fullImage->url);
318                                         elseif ($attachment->image->url != "")
319                                                 $images = store_photo($a, $uid, "", $attachment->image->url);
320                                 }
321
322                                 if ($images["preview"] != "") {
323                                         $post .= "\n[url=".$images["page"]."][img]".$images["preview"]."[/img][/url]\n";
324                                         $pagedata["images"][0]["src"] = $images["preview"];
325                                         $pagedata["url"] = $images["page"];
326                                 } elseif ($images["full"] != "") {
327                                         $post .= "\n[img]".$images["full"]."[/img]\n";
328                                         $pagedata["images"][0]["src"] = $images["full"];
329
330                                         if ($images["preview"] != "")
331                                                 $pagedata["images"][1]["src"] = $images["preview"];
332                                 }
333
334                                 if (($attachment->displayName != "") AND (fromgplus_cleantext($attachment->displayName) != fromgplus_cleantext($displaytext))) {
335                                         $post .= fromgplus_html2bbcode($attachment->displayName)."\n";
336                                         $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
337                                 }
338                                 break;
339
340                         case "photo-album":
341                                 $pagedata["url"] = original_url($attachment->url);
342                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
343                                 $post .= "\n\n[bookmark=".$pagedata["url"]."]".$pagedata["title"]."[/bookmark]\n";
344
345                                 $images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
346
347                                 if ($images["preview"] != "") {
348                                         $post .= "\n[url=".$images["full"]."][img]".$images["preview"]."[/img][/url]\n";
349                                         $pagedata["images"][0]["src"] = $images["preview"];
350                                         $pagedata["url"] = $images["full"];
351                                 } elseif ($images["full"] != "") {
352                                         $post .= "\n[img]".$images["full"]."[/img]\n";
353                                         $pagedata["images"][0]["src"] = $images["full"];
354
355                                         if ($images["preview"] != "")
356                                                 $pagedata["images"][1]["src"] = $images["preview"];
357                                 }
358                                 break;
359
360                         case "album":
361                                 $pagedata["type"] = "link";
362                                 $pagedata["url"] = original_url($attachment->url);
363                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
364
365                                 $thumb = $attachment->thumbnails[0];
366                                 $pagedata["images"][0]["src"] = $thumb->image->url;
367
368                                 $quote = trim(fromgplus_html2bbcode($thumb->description));
369                                 if ($quote != "")
370                                         $pagedata["text"] = $quote;
371
372                                 break;
373
374                         case "audio":
375                                 $pagedata["url"] = original_url($attachment->url);
376                                 $pagedata["title"] = fromgplus_html2bbcode($attachment->displayName);
377                                 $post .= "\n\n[bookmark=".$pagedata["url"]."]".$pagedata["title"]."[/bookmark]\n";
378                                 break;
379
380                         //default:
381                         //      die($attachment->objectType);
382                 }
383         }
384
385         if ($pagedata["type"] != "")
386                 return(add_page_info_data($pagedata));
387
388         return($post.$quote);
389 }
390
391 function fromgplus_fetch($a, $uid) {
392         $maxfetch = 20;
393
394         // Special blank to identify postings from the googleplus connector
395         $blank = html_entity_decode("&#x00A0;", ENT_QUOTES, 'UTF-8');
396
397         $account = get_pconfig($uid,'fromgplus','account');
398         $key = get_config('fromgplus','key');
399
400         $result = fetch_url("https://www.googleapis.com/plus/v1/people/".$account."/activities/public?alt=json&pp=1&key=".$key."&maxResults=".$maxfetch);
401         //$result = file_get_contents("google.txt");
402         //$result = file_get_contents("addon/fromgplus/album.txt");
403         //file_put_contents("google.txt", $result);
404
405         $activities = json_decode($result);
406
407         $initiallastdate = get_pconfig($uid,'fromgplus','lastdate');
408
409         $first_time = ($initiallastdate == "");
410
411         $lastdate = 0;
412
413         if (!is_array($activities->items))
414                 return;
415
416         $reversed = array_reverse($activities->items);
417
418         foreach($reversed as $item) {
419                 if (strtotime($item->published) <= $initiallastdate)
420                         continue;
421
422                 // Don't publish items that are too young
423                 if (strtotime($item->published) > (time() - 3*60)) {
424                         logger('fromgplus_fetch: item too new '.$item->published);
425                         continue;
426                 }
427
428                 if ($lastdate < strtotime($item->published))
429                         $lastdate = strtotime($item->published);
430
431                 if ($first_time)
432                         continue;
433
434                 if ($item->access->description == "Public")
435
436                         // Loop prevention - ignore postings from HootSuite
437                         if ($item->provider->title == "HootSuite")
438                                 continue;
439
440                         // Loop prevention through the special blank from the googleplus connector
441                         if (strstr($item->object->content, $blank))
442                                 continue;
443
444                         switch($item->object->objectType) {
445                                 case "note":
446                                         $post = fromgplus_html2bbcode($item->object->content);
447
448                                         if (is_array($item->object->attachments))
449                                                 $post .= fromgplus_handleattachments($a, $uid, $item, $item->object->content, false);
450
451                                         // geocode, placeName
452                                         if (isset($item->address))
453                                                 $location = $item->address;
454                                         else
455                                                 $location = "";
456
457                                         fromgplus_post($a, $uid, "Google+", $post, $location);
458                                         //fromgplus_post($a, $uid, $item->provider->title, $post, $location);
459
460                                         break;
461
462                                 case "activity":
463                                         $post = fromgplus_html2bbcode($item->annotation)."\n";
464
465                                         if (!intval(get_config('system','old_share'))) {
466                                                 $post .= "[share author='".str_replace("'", "&#039;",$item->object->actor->displayName).
467                                                                 "' profile='".$item->object->actor->url.
468                                                                 "' avatar='".$item->object->actor->image->url.
469                                                                 "' link='".$item->object->url."']";
470
471                                                 $post .= fromgplus_html2bbcode($item->object->content);
472
473                                                 if (is_array($item->object->attachments))
474                                                         $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
475
476                                                 $post .= "[/share]";
477                                         } else {
478                                                 $post .= fromgplus_html2bbcode("&#x2672;");
479                                                 $post .= " [url=".$item->object->actor->url."]".$item->object->actor->displayName."[/url] \n";
480                                                 $post .= fromgplus_html2bbcode($item->object->content);
481
482                                                 if (is_array($item->object->attachments))
483                                                         $post .= "\n".trim(fromgplus_handleattachments($a, $uid, $item, $item->object->content, true));
484                                         }
485
486                                         if (isset($item->address))
487                                                 $location = $item->address;
488                                         else
489                                                 $location = "";
490
491                                         fromgplus_post($a, $uid, "Google+", $post, $location);
492                                         //fromgplus_post($a, $uid, $item->provider->title, $post, $location);
493                                         break;
494                         }
495         }
496         if ($lastdate != 0)
497                 set_pconfig($uid,'fromgplus','lastdate', $lastdate);
498 }