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