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