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