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