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