5 * Description: Posts to app.net with the help of ifttt.com
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
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');
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');
27 function appnetpost_jot_nets(&$a,&$b) {
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>';
40 function appnetpost_settings(&$a,&$s) {
45 /* Add our stylesheet to the page so we can make our settings look nice */
47 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/appnetpost/appnetpost.css' . '" media="all" />' . "\r\n";
49 $enabled = get_pconfig(local_user(),'appnetpost','post');
50 $checked = (($enabled) ? ' checked="checked" ' : '');
52 $def_enabled = get_pconfig(local_user(),'appnetpost','post_by_default');
53 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
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>';
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>';
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>';
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>';
73 /* provide a submit button */
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>';
84 function appnetpost_settings_post(&$a,&$b) {
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']));
92 function appnetpost_post_local(&$a,&$b) {
97 if((! local_user()) || (local_user() != $b['uid']))
100 if($b['private'] || $b['parent'])
103 $post = intval(get_pconfig(local_user(),'appnetpost','post'));
105 $enable = (($post && x($_REQUEST,'appnetpost_enable')) ? intval($_REQUEST['appnetpost_enable']) : 0);
107 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnetpost','post_by_default')))
113 if(strlen($b['postopts']))
114 $b['postopts'] .= ',';
116 $b['postopts'] .= 'gplus';
119 function appnetpost_send(&$a,&$b) {
121 logger('appnetpost_send: invoked for post '.$b['id']." ".$b['app']);
123 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
126 if(! strstr($b['postopts'],'gplus'))
129 if($b['parent'] != $b['id'])
132 $itemlist = get_pconfig($b["uid"],'appnetpost','itemlist');
133 $items = explode(",", $itemlist);
136 $newitems = array($b['id']);
137 foreach ($items AS $item)
141 $itemlist = implode(",", $newitems);
143 logger('appnetpost_send: new itemlist: '.$itemlist." for uid ".$b["uid"]);
145 set_pconfig($b["uid"],'appnetpost','itemlist', $itemlist);
148 function appnetpost_module() {}
150 function appnetpost_init() {
155 if (isset($a->argv[1])) {
156 $uid = (int)$a->argv[1];
158 $contacts = q("SELECT `username`, `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1", dbesc($a->argv[1]));
160 $uid = $contacts[0]["uid"];
164 $contacts = q("SELECT `username` FROM `user` WHERE `uid`=%d LIMIT 1", intval($uid));
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";
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";
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";
185 $itemlist = get_pconfig($uid,'appnetpost','itemlist');
186 $items = explode(",", $itemlist);
188 foreach ($items AS $item)
189 appnetpost_feeditem($item, $uid);
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);
199 function appnetpost_original_url($url, $depth=1) {
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');
213 $header = curl_exec($ch);
214 $curl_info = @curl_getinfo($ch);
215 $http_code = $curl_info['http_code'];
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));
223 return(appnetpost_original_url($curl_info['location'], ++$depth));
226 $pos = strpos($header, "\r\n\r\n");
229 $body = trim(substr($header, $pos));
233 $doc = new DOMDocument();
234 @$doc->loadHTML($body);
236 $xpath = new DomXPath($doc);
238 $list = $xpath->query("//meta[@content]");
239 foreach ($list as $node) {
241 if ($node->attributes->length)
242 foreach ($node->attributes as $attribute)
243 $attr[$attribute->name] = $attribute->value;
245 if (@$attr["http-equiv"] == 'refresh') {
246 $path = $attr["content"];
247 $pathinfo = explode(";", $path);
249 foreach ($pathinfo AS $value)
250 if (substr(strtolower($value), 0, 4) == "url=")
251 return(appnetpost_original_url(substr($value, 4), ++$depth));
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');
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() ) );
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() ) );
279 return $slinky->short();
282 function appnetpost_feeditem($pid, $uid) {
285 require_once('include/bbcode.php');
286 require_once("include/html2plain.php");
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) {
291 // Looking for the first image
293 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$item['body'],$matches))
294 $image = $matches[3];
297 if(preg_match("/\[img\](.*?)\[\/img\]/is",$item['body'],$matches))
298 $image = $matches[1];
300 $multipleimages = (strpos($item['body'], "[img") != strrpos($item['body'], "[img"));
302 // When saved into the database the content is sent through htmlspecialchars
303 // That means that we have to decode all image-urls
304 $image = htmlspecialchars_decode($image);
307 // look for bookmark-bbcode and handle it with priority
308 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$item['body'],$matches))
311 $multiplelinks = (strpos($item['body'], "[bookmark") != strrpos($item['body'], "[bookmark"));
313 $body = $item['body'];
315 // At first convert the text to html
316 $html = bbcode($body, false, false, 2);
318 // Then convert it to plain text
319 $msg = trim(html2plain($html, 0, true));
320 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
322 // If there is no bookmark element then take the first link
324 $links = collecturls($html);
325 if (sizeof($links) > 0) {
327 $link = current($links);
329 $multiplelinks = (sizeof($links) > 1);
331 if ($multiplelinks) {
332 $html2 = bbcode($msg, false, false);
333 $links2 = collecturls($html2);
334 if (sizeof($links2) > 0) {
336 $link = current($links2);
337 $multiplelinks = (sizeof($links2) > 1);
344 $msglink = $item["plink"];
345 else if ($link != "")
347 else if ($multipleimages)
348 $msglink = $item["plink"];
349 else if ($image != "")
352 // Fetching the title and add all lines
353 if ($item["title"] != "")
354 $title = $item["title"];
356 $lines = explode("\n", $msg);
357 foreach ($lines AS $line)
358 $title .= "\n".$line;
362 $origlink = $msglink;
364 if (strlen($msglink) > 20)
365 $msglink = short_link($msglink);
367 $title = trim(str_replace($origlink, $msglink, $title));
369 if (strlen(trim($title." ".$msglink)) > $max_char) {
370 $title = substr($title, 0, $max_char - (strlen($msglink)));
371 $lastchar = substr($title, -1);
372 $title = substr($title, 0, -1);
373 $pos = strrpos($title, "\n");
375 $title = substr($title, 0, $pos);
376 else if ($lastchar != "\n")
377 $title = substr($title, 0, -3)."...";
380 if (($msglink != "") AND !strstr($title, $msglink))
381 $title = trim($title." ".$msglink);
383 $title = trim($title);
388 //$origlink = appnetpost_original_url($origlink);
390 $html = nl2br($title);
392 $origlink = $item["plink"];
393 $origlink = htmlspecialchars(html_entity_decode($origlink));
395 $title = str_replace("&", "&", $title);
396 //$html = str_replace("&", "&", $html);
398 echo "\t".'<entry xmlns="http://www.w3.org/2005/Atom">'."\n";
399 echo "\t\t".'<title type="html" xml:space="preserve"><![CDATA['.$title."]]></title>\n";
400 echo "\t\t".'<link rel="alternate" type="text/html" href="'.$origlink.'" />'."\n";
401 // <link rel="enclosure" type="audio/mpeg" length="1337" href="http://example.org/audio/ph34r_my_podcast.mp3"/>
402 echo "\t\t<id>".$item["uri"]."</id>\n";
403 echo "\t\t<updated>".date("c", strtotime($item["edited"]))."</updated>\n";
404 echo "\t\t<published>".date("c", strtotime($item["created"]))."</published>\n";
405 echo "\t\t<author>\n\t\t\t<name><![CDATA[".$item["author-name"]."]]></name>\n";
406 echo "\t\t\t<uri>".$item["author-link"]."</uri>\n\t\t</author>\n";
407 //echo '<content type="image/png" src="http://media.example.org/the_beach.png"/>';
408 echo "\t\t".'<content type="html" xml:space="preserve" xml:base="'.$item["plink"].'"><![CDATA['.$html."]]></content>\n";