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