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