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 .= '<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>';
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>';
67 /* provide a submit button */
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>';
78 function appnetpost_settings_post(&$a,&$b) {
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']));
86 function appnetpost_post_local(&$a,&$b) {
91 if((! local_user()) || (local_user() != $b['uid']))
94 if($b['private'] || $b['parent'])
97 $post = intval(get_pconfig(local_user(),'appnetpost','post'));
99 $enable = (($post && x($_REQUEST,'appnetpost_enable')) ? intval($_REQUEST['appnetpost_enable']) : 0);
101 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnetpost','post_by_default')))
107 if(strlen($b['postopts']))
108 $b['postopts'] .= ',';
110 $b['postopts'] .= 'gplus';
113 function appnetpost_send(&$a,&$b) {
115 logger('appnetpost_send: invoked for post '.$b['id']." ".$b['app']);
117 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
120 if(! strstr($b['postopts'],'gplus'))
123 if($b['parent'] != $b['id'])
126 $itemlist = get_pconfig($b["uid"],'appnetpost','itemlist');
127 $items = explode(",", $itemlist);
130 $newitems = array($b['id']);
131 foreach ($items AS $item)
135 $itemlist = implode(",", $newitems);
137 logger('appnetpost_send: new itemlist: '.$itemlist." for uid ".$b["uid"]);
139 set_pconfig($b["uid"],'appnetpost','itemlist', $itemlist);
142 function appnetpost_module() {}
144 function appnetpost_init() {
149 if (isset($a->argv[1])) {
150 $uid = (int)$a->argv[1];
152 $contacts = q("SELECT `username`, `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1", dbesc($a->argv[1]));
154 $uid = $contacts[0]["uid"];
158 $contacts = q("SELECT `username` FROM `user` WHERE `uid`=%d LIMIT 1", intval($uid));
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";
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";
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";
179 $itemlist = get_pconfig($uid,'appnetpost','itemlist');
180 $items = explode(",", $itemlist);
182 foreach ($items AS $item)
183 appnetpost_feeditem($item, $uid);
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);
193 function appnetpost_original_url($url, $depth=1) {
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');
207 $header = curl_exec($ch);
208 $curl_info = @curl_getinfo($ch);
209 $http_code = $curl_info['http_code'];
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));
217 return(appnetpost_original_url($curl_info['location'], ++$depth));
220 $pos = strpos($header, "\r\n\r\n");
223 $body = trim(substr($header, $pos));
227 $doc = new DOMDocument();
228 @$doc->loadHTML($body);
230 $xpath = new DomXPath($doc);
232 $list = $xpath->query("//meta[@content]");
233 foreach ($list as $node) {
235 if ($node->attributes->length)
236 foreach ($node->attributes as $attribute)
237 $attr[$attribute->name] = $attribute->value;
239 if (@$attr["http-equiv"] == 'refresh') {
240 $path = $attr["content"];
241 $pathinfo = explode(";", $path);
243 foreach ($pathinfo AS $value)
244 if (substr(strtolower($value), 0, 4) == "url=")
245 return(appnetpost_original_url(substr($value, 4), ++$depth));
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');
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() ) );
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() ) );
273 return $slinky->short();
276 function appnetpost_feeditem($pid, $uid) {
279 require_once('include/bbcode.php');
280 require_once("include/html2plain.php");
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) {
285 // Looking for the first image
287 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$item['body'],$matches))
288 $image = $matches[3];
291 if(preg_match("/\[img\](.*?)\[\/img\]/is",$item['body'],$matches))
292 $image = $matches[1];
294 $multipleimages = (strpos($item['body'], "[img") != strrpos($item['body'], "[img"));
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);
301 // look for bookmark-bbcode and handle it with priority
302 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$item['body'],$matches))
305 $multiplelinks = (strpos($item['body'], "[bookmark") != strrpos($item['body'], "[bookmark"));
307 $body = $item['body'];
309 // At first convert the text to html
310 $html = bbcode($body, false, false, 2);
312 // Then convert it to plain text
313 $msg = trim(html2plain($html, 0, true));
314 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
316 // If there is no bookmark element then take the first link
318 $links = collecturls($html);
319 if (sizeof($links) > 0) {
321 $link = current($links);
323 $multiplelinks = (sizeof($links) > 1);
325 if ($multiplelinks) {
326 $html2 = bbcode($msg, false, false);
327 $links2 = collecturls($html2);
328 if (sizeof($links2) > 0) {
330 $link = current($links2);
331 $multiplelinks = (sizeof($links2) > 1);
338 $msglink = $item["plink"];
339 else if ($link != "")
341 else if ($multipleimages)
342 $msglink = $item["plink"];
343 else if ($image != "")
346 // Fetching the title and add all lines
347 if ($item["title"] != "")
348 $title = $item["title"];
350 $lines = explode("\n", $msg);
351 foreach ($lines AS $line)
352 $title .= "\n".$line;
356 $origlink = $msglink;
358 if (strlen($msglink) > 20)
359 $msglink = short_link($msglink);
361 $title = trim(str_replace($origlink, $msglink, $title));
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");
369 $title = substr($title, 0, $pos);
370 else if ($lastchar != "\n")
371 $title = substr($title, 0, -3)."...";
374 if (($msglink != "") AND !strstr($title, $msglink))
375 $title = trim($title." ".$msglink);
377 $title = trim($title);
382 //$origlink = appnetpost_original_url($origlink);
384 $html = nl2br($title);
386 $origlink = $item["plink"];
387 $origlink = htmlspecialchars(html_entity_decode($origlink));
389 $title = str_replace("&", "&", $title);
390 //$html = str_replace("&", "&", $html);
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";