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