]> git.mxchange.org Git - friendica-addons.git/blob - gpluspost/gpluspost.php
Merge pull request #137 from annando/master
[friendica-addons.git] / gpluspost / gpluspost.php
1 <?php
2
3 /**
4  * Name: G+ Post
5  * Description: Posts to a Google+ page with the help of Hootsuite
6  * Version: 0.1
7  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8  */
9
10 function gpluspost_install() {
11         register_hook('post_local',           'addon/gpluspost/gpluspost.php', 'gpluspost_post_local');
12         register_hook('notifier_normal',      'addon/gpluspost/gpluspost.php', 'gpluspost_send');
13         register_hook('jot_networks',         'addon/gpluspost/gpluspost.php', 'gpluspost_jot_nets');
14         register_hook('connector_settings',      'addon/gpluspost/gpluspost.php', 'gpluspost_settings');
15         register_hook('connector_settings_post', 'addon/gpluspost/gpluspost.php', 'gpluspost_settings_post');
16 }
17
18
19 function gpluspost_uninstall() {
20         unregister_hook('post_local',       'addon/gpluspost/gpluspost.php', 'gpluspost_post_local');
21         unregister_hook('notifier_normal',  'addon/gpluspost/gpluspost.php', 'gpluspost_send');
22         unregister_hook('jot_networks',     'addon/gpluspost/gpluspost.php', 'gpluspost_jot_nets');
23         unregister_hook('connector_settings',      'addon/gpluspost/gpluspost.php', 'gpluspost_settings');
24         unregister_hook('connector_settings_post', 'addon/gpluspost/gpluspost.php', 'gpluspost_settings_post');
25 }
26
27 function gpluspost_jot_nets(&$a,&$b) {
28         if(! local_user())
29                 return;
30
31         $post = get_pconfig(local_user(),'gpluspost','post');
32         if(intval($post) == 1) {
33                 $defpost = get_pconfig(local_user(),'gpluspost','post_by_default');
34                 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
35                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="gpluspost_enable"' . $selected . ' value="1" /> '
36                         . t('Post to Google+') . '</div>';
37     }
38 }
39
40 function gpluspost_settings(&$a,&$s) {
41
42         if(! local_user())
43                 return;
44
45         $enabled = get_pconfig(local_user(),'gpluspost','post');
46         $checked = (($enabled) ? ' checked="checked" ' : '');
47
48         $def_enabled = get_pconfig(local_user(),'gpluspost','post_by_default');
49         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
50
51         $noloop_enabled = get_pconfig(local_user(),'gpluspost','no_loop_prevention');
52         $noloop_checked = (($noloop_enabled) ? ' checked="checked" ' : '');
53
54         $skip_enabled = get_pconfig(local_user(),'gpluspost','skip_without_link');
55         $skip_checked = (($skip_enabled) ? ' checked="checked" ' : '');
56
57         $s .= '<div class="settings-block">';
58         $s .= '<h3>' . t('Google+ Post Settings') . '</h3>';
59         $s .= '<div id="gpluspost-enable-wrapper">';
60         $s .= '<label id="gpluspost-enable-label" for="gpluspost-checkbox">' . t('Enable Google+ Post Plugin') . '</label>';
61         $s .= '<input id="gpluspost-checkbox" type="checkbox" name="gpluspost" value="1" ' . $checked . '/>';
62         $s .= '</div><div class="clear"></div>';
63
64         $s .= '<div id="gpluspost-bydefault-wrapper">';
65         $s .= '<label id="gpluspost-bydefault-label" for="gpluspost-bydefault">' . t('Post to Google+ by default') . '</label>';
66         $s .= '<input id="gpluspost-bydefault" type="checkbox" name="gpluspost_bydefault" value="1" ' . $def_checked . '/>';
67         $s .= '</div><div class="clear"></div>';
68
69         $s .= '<div id="gpluspost-noloopprevention-wrapper">';
70         $s .= '<label id="gpluspost-noloopprevention-label" for="gpluspost-noloopprevention">' . t('Do not prevent posting loops') . '</label>';
71         $s .= '<input id="gpluspost-noloopprevention" type="checkbox" name="gpluspost_noloopprevention" value="1" ' . $noloop_checked . '/>';
72         $s .= '</div><div class="clear"></div>';
73
74         $s .= '<div id="gpluspost-skipwithoutlink-wrapper">';
75         $s .= '<label id="gpluspost-skipwithoutlink-label" for="gpluspost-skipwithoutlink">' . t('Skip messages without links') . '</label>';
76         $s .= '<input id="gpluspost-skipwithoutlink" type="checkbox" name="gpluspost_skipwithoutlink" value="1" ' . $skip_checked . '/>';
77         $s .= '</div><div class="clear"></div>';
78
79         /* provide a submit button */
80
81         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="gpluspost-submit" name="gpluspost-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
82         $s .= 'Register an account at <a href="https://hootsuite.com">Hootsuite</a>, add your G+ page and add the feed-url there.<br />';
83         $s .= 'Feed-url: '.$a->get_baseurl().'/gpluspost/'.urlencode($a->user["nickname"]).'</div>';
84 }
85
86 function gpluspost_settings_post(&$a,&$b) {
87
88         if(x($_POST,'gpluspost-submit')) {
89                 set_pconfig(local_user(),'gpluspost','post',intval($_POST['gpluspost']));
90                 set_pconfig(local_user(),'gpluspost','post_by_default',intval($_POST['gpluspost_bydefault']));
91                 set_pconfig(local_user(),'gpluspost','no_loop_prevention',intval($_POST['gpluspost_noloopprevention']));
92                 set_pconfig(local_user(),'gpluspost','skip_without_link',intval($_POST['gpluspost_skipwithoutlink']));
93         }
94 }
95
96 function gpluspost_post_local(&$a,&$b) {
97
98         if($b['edit'])
99                 return;
100
101         if((! local_user()) || (local_user() != $b['uid']))
102                 return;
103
104         if($b['private'] || $b['parent'])
105                 return;
106
107         $post   = intval(get_pconfig(local_user(),'gpluspost','post'));
108
109         $enable = (($post && x($_REQUEST,'gpluspost_enable')) ? intval($_REQUEST['gpluspost_enable']) : 0);
110
111         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'gpluspost','post_by_default')))
112                 $enable = 1;
113
114         if(!$enable)
115                 return;
116
117         if(strlen($b['postopts']))
118                 $b['postopts'] .= ',';
119
120         $b['postopts'] .= 'gplus';
121 }
122
123 function gpluspost_send(&$a,&$b) {
124
125         logger('gpluspost_send: invoked for post '.$b['id']." ".$b['app']);
126
127         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
128                 return;
129
130         if(! strstr($b['postopts'],'gplus'))
131                 return;
132
133         if($b['parent'] != $b['id'])
134                 return;
135
136         // if post comes from Google+ don't send it back
137         if (!get_pconfig($b["uid"],'gpluspost','no_loop_prevention') and ($b['app'] == "Google+"))
138                 return;
139
140         $itemlist = get_pconfig($b["uid"],'gpluspost','itemlist');
141         $items = explode(",", $itemlist);
142
143         $i = 0;
144         $newitems = array($b['id']);
145         foreach ($items AS $item)
146                 if ($i++ < 9)
147                         $newitems[] = $item;
148
149         $itemlist = implode(",", $newitems);
150
151         logger('gpluspost_send: new itemlist: '.$itemlist." for uid ".$b["uid"]);
152
153         set_pconfig($b["uid"],'gpluspost','itemlist', $itemlist);
154 }
155
156 function gpluspost_module() {}
157
158 function gpluspost_init() {
159         global $a, $_SERVER;
160
161         $uid = 0;
162
163         if (isset($a->argv[1])) {
164                 $uid = (int)$a->argv[1];
165                 if ($uid == 0) {
166                         $contacts = q("SELECT `username`, `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1", dbesc($a->argv[1]));
167                         if ($contacts) {
168                                 $uid = $contacts[0]["uid"];
169                                 $nick = $a->argv[1];
170                         }
171                 } else {
172                         $contacts = q("SELECT `username` FROM `user` WHERE `uid`=%d LIMIT 1", intval($uid));
173                         $nick = $uid;
174                 }
175         }
176
177         header("content-type: application/atom+xml");
178         echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
179         echo '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
180         echo "\t".'<title type="html"><![CDATA['.$a->config['sitename'].']]></title>'."\n";
181         if ($uid != 0) {
182                 echo "\t".'<subtitle type="html"><![CDATA['.$contacts[0]["username"]."]]></subtitle>\n";
183                 echo "\t".'<link rel="self" href="'.$a->get_baseurl().'/gpluspost/'.$nick.'"/>'."\n";
184         } else
185                 echo "\t".'<link rel="self" href="'.$a->get_baseurl().'/gpluspost"/>'."\n";
186         echo "\t<id>".$a->get_baseurl()."/</id>\n";
187         echo "\t".'<link rel="alternate" type="text/html" href="'.$a->get_baseurl().'"/>'."\n";
188         echo "\t<updated>".date("c")."</updated>\n"; // To-Do
189         // <rights>Copyright ... </rights>
190         echo "\t".'<generator uri="'.$a->get_baseurl().'">'.$a->config['sitename'].'</generator>'."\n";
191
192         if ($uid != 0) {
193                 $itemlist = get_pconfig($uid,'gpluspost','itemlist');
194                 $items = explode(",", $itemlist);
195
196                 foreach ($items AS $item)
197                         gpluspost_feeditem($item, $uid);
198         } else {
199                 $items = q("SELECT `id` FROM `item` FORCE INDEX (`received`) WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0 AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `item`.`id` = `item`.`parent` ORDER BY `received` DESC LIMIT 10");
200                 foreach ($items AS $item)
201                         gpluspost_feeditem($item["id"], $uid);
202         }
203         echo "</feed>\n";
204         killme();
205 }
206
207 function gpluspost_original_url($url, $depth=1) {
208
209         if ($depth > 10)
210                 return($url);
211
212         $siteinfo = array();
213         $ch = curl_init();
214         curl_setopt($ch, CURLOPT_URL, $url);
215         curl_setopt($ch, CURLOPT_HEADER, 1);
216         curl_setopt($ch, CURLOPT_NOBODY, 0);
217         curl_setopt($ch, CURLOPT_TIMEOUT, 3);
218         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
219         curl_setopt($ch,CURLOPT_USERAGENT,'Opera/9.64(Windows NT 5.1; U; de) Presto/2.1.1');
220
221         $header = curl_exec($ch);
222         $curl_info = @curl_getinfo($ch);
223         $http_code = $curl_info['http_code'];
224         curl_close($ch);
225
226         if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
227                 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
228                 if ($curl_info['redirect_url'] != "")
229                         return(gpluspost_original_url($curl_info['redirect_url'], ++$depth));
230                 else
231                         return(gpluspost_original_url($curl_info['location'], ++$depth));
232         }
233
234         $pos = strpos($header, "\r\n\r\n");
235
236         if ($pos)
237                 $body = trim(substr($header, $pos));
238         else
239                 $body = $header;
240
241         $doc = new DOMDocument();
242         @$doc->loadHTML($body);
243
244         $xpath = new DomXPath($doc);
245
246         $list = $xpath->query("//meta[@content]");
247         foreach ($list as $node) {
248                 $attr = array();
249                 if ($node->attributes->length)
250                         foreach ($node->attributes as $attribute)
251                                 $attr[$attribute->name] = $attribute->value;
252
253                 if (@$attr["http-equiv"] == 'refresh') {
254                         $path = $attr["content"];
255                         $pathinfo = explode(";", $path);
256                         $content = "";
257                         foreach ($pathinfo AS $value)
258                                 if (substr(strtolower($value), 0, 4) == "url=")
259                                         return(gpluspost_original_url(substr($value, 4), ++$depth));
260                 }
261         }
262
263         return($url);
264 }
265
266 function gpluspost_ShareAttributes($match) {
267
268         $attributes = $match[1];
269
270         $author = "";
271         preg_match("/author='(.*?)'/ism", $attributes, $matches);
272         if ($matches[1] != "")
273                 $author = $matches[1];
274
275         preg_match('/author="(.*?)"/ism', $attributes, $matches);
276         if ($matches[1] != "")
277                 $author = $matches[1];
278
279         $headline = '<div class="shared_header">';
280
281         $headline .= sprintf(t('%s:'), $author);
282
283         $headline .= "</div>";
284
285         //$text = "<br />".$headline."</strong><blockquote>".$match[2]."</blockquote>";
286         //$text = "\n\t".$match[2].":\t";
287         $text = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').$author.": ".$match[2];
288
289         return($text);
290 }
291
292 function gpluspost_feeditem($pid, $uid) {
293         global $a;
294
295         require_once('include/bbcode.php');
296         require_once("include/html2plain.php");
297
298         $skipwithoutlink = get_pconfig($uid,'gpluspost','skip_without_link');
299
300         $items = q("SELECT `uri`, `plink`, `author-link`, `author-name`, `created`, `edited`, `id`, `title`, `body` from `item` WHERE id=%d", intval($pid));
301         foreach ($items AS $item) {
302
303                 // Looking for the first image
304                 $image = '';
305                 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$item['body'],$matches))
306                         $image = $matches[3];
307
308                 if ($image == '')
309                         if(preg_match("/\[img\](.*?)\[\/img\]/is",$item['body'],$matches))
310                                 $image = $matches[1];
311
312                 $multipleimages = (strpos($item['body'], "[img") != strrpos($item['body'], "[img"));
313
314                 // When saved into the database the content is sent through htmlspecialchars
315                 // That means that we have to decode all image-urls
316                 $image = htmlspecialchars_decode($image);
317
318                 $link = '';
319                 // look for bookmark-bbcode and handle it with priority
320                 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$item['body'],$matches))
321                         $link = $matches[1];
322
323                 $multiplelinks = (strpos($item['body'], "[bookmark") != strrpos($item['body'], "[bookmark"));
324
325                 $body = $item['body'];
326                 $body = preg_replace_callback("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]/ism","gpluspost_ShareAttributes", $body);
327
328                 $html = bbcode($body, false, false);
329                 $msg = trim(html2plain($html, 0, true));
330
331                 // If there is no bookmark element then take the first link
332                 if ($link == '') {
333                         $links = collecturls($html);
334                         if (sizeof($links) > 0) {
335                                 reset($links);
336                                 $link = current($links);
337                         }
338                         $multiplelinks = (sizeof($links) > 1);
339
340                         if ($multiplelinks) {
341                                 $html2 = bbcode($msg, false, false);
342                                 $links2 = collecturls($html2);
343                                 if (sizeof($links2) > 0) {
344                                         reset($links2);
345                                         $link = current($links2);
346                                         $multiplelinks = (sizeof($links2) > 1);
347                                 }
348                         }
349                 }
350
351                 $msglink = "";
352                 if ($multiplelinks)
353                         $msglink = $item["plink"];
354                 else if ($link != "")
355                         $msglink = $link;
356                 else if ($multipleimages)
357                         $msglink = $item["plink"];
358                 else if ($image != "")
359                         $msglink = $image;
360
361                 if (($msglink == "") AND $skipwithoutlink)
362                         continue;
363                 else if ($msglink == "")
364                         $msglink = $item["plink"];
365
366                 // Fetching the title - or the first line
367                 if ($item["title"] != "")
368                         $title = $item["title"];
369                 else {
370                         $lines = explode("\n", $msg);
371                         $title = $lines[0];
372                 }
373
374                 //if ($image != $msglink)
375                 //      $html = trim(str_replace($msglink, "", $html));
376
377                 $title = trim(str_replace($msglink, "", $title));
378
379                 $msglink = gpluspost_original_url($msglink);
380
381                 if ($uid == 0)
382                         $title = $item["author-name"].": ".$title;
383
384                 $msglink = htmlspecialchars(html_entity_decode($msglink));
385
386                 $title = str_replace("&", "&amp;", $title);
387                 //$html = str_replace("&", "&amp;", $html);
388
389                 echo "\t".'<entry xmlns="http://www.w3.org/2005/Atom">'."\n";
390                 echo "\t\t".'<title type="html" xml:space="preserve"><![CDATA['.$title."]]></title>\n";
391                 echo "\t\t".'<link rel="alternate" type="text/html" href="'.$msglink.'" />'."\n";
392                 // <link rel="enclosure" type="audio/mpeg" length="1337" href="http://example.org/audio/ph34r_my_podcast.mp3"/>
393                 echo "\t\t<id>".$item["uri"]."</id>\n";
394                 echo "\t\t<updated>".date("c", strtotime($item["edited"]))."</updated>\n";
395                 echo "\t\t<published>".date("c", strtotime($item["created"]))."</published>\n";
396                 echo "\t\t<author>\n\t\t\t<name><![CDATA[".$item["author-name"]."]]></name>\n";
397                 echo "\t\t\t<uri>".$item["author-link"]."</uri>\n\t\t</author>\n";
398                 //echo '<content type="image/png" src="http://media.example.org/the_beach.png"/>';
399                 echo "\t\t".'<content type="html" xml:space="preserve" xml:base="'.$item["plink"].'"><![CDATA['.$html."]]></content>\n";
400                 echo "\t</entry>\n";
401         }
402 }