PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/wp-rss-poster/include/tools.php

https://bitbucket.org/silverlogic/dms
PHP | 474 lines | 309 code | 78 blank | 87 comment | 53 complexity | 3d31d48d07cb20e6e629527eca5c18b5 MD5 | raw file
Possible License(s): GPL-2.0, JSON, AGPL-1.0, LGPL-2.1
  1. <?php
  2. //get wrp data from database by jobid
  3. function wrp_get_data($jobid){
  4. global $wpdb;
  5. $wrp_table = $wpdb->prefix.'wrp';
  6. $query = "SELECT * FROM $wrp_table WHERE id=".$jobid;
  7. $data = $wpdb->get_row($query, ARRAY_A);
  8. return $data;
  9. }
  10. //DoJob
  11. function wrp_do_job($jobid) {
  12. global $wrp_dojob_message;
  13. if (empty($jobid))
  14. return false;
  15. require_once(dirname(__FILE__).'/wrp_dojob.php');
  16. $wrp_dojob= new wrp_dojob($jobid);
  17. unset($wrp_dojob);
  18. return $wrp_dojob_message;
  19. }
  20. function wrp_connect($service){
  21. $wrp_opts = get_option(WRP_OPTIONS);
  22. switch($service){
  23. case 'tw':
  24. if(!isset($_GET['resp'])){
  25. $tw = new TwitterOAuth("i8aDsTg4etTCDHrvyxTjg", "kZfkPAwQJc0nj97D77Bd0qZtEr5nMUgepIWy6MtMMlY");
  26. $twrt = $tw->getRequestToken(admin_url( 'admin.php?page=wrp-twitter&connect=tw&resp=1' ));
  27. $loginUrl = $tw->getAuthorizeURL($twrt);
  28. $wrp_opts['twrt'] = $twrt['oauth_token'];
  29. $wrp_opts['twrts'] = $twrt['oauth_token_secret'];;
  30. update_option(WRP_OPTIONS, $wrp_opts);
  31. wp_redirect($loginUrl);
  32. }else{
  33. $tw = new TwitterOAuth("i8aDsTg4etTCDHrvyxTjg", "kZfkPAwQJc0nj97D77Bd0qZtEr5nMUgepIWy6MtMMlY", $wrp_opts['twrt'], $wrp_opts['twrts']);
  34. $twrt = $tw->getAccessToken($_GET['oauth_verifier']);
  35. $_SESSION['access_token'] = $twrt; // saving access token to sessions
  36. $user = $tw->get('account/verify_credentials'); // get account details
  37. $wrp_opts['twat'] = $twrt['oauth_token'];
  38. $wrp_opts['twats'] = $twrt['oauth_token_secret'];
  39. $wrp_opts['tw_username'] = $user->screen_name;
  40. $wrp_opts['tw_profile'] = $user->profile_image_url;
  41. update_option(WRP_OPTIONS, $wrp_opts);
  42. //session_unset();
  43. $redirect = admin_url( 'admin.php?page=wrp-twitter' );
  44. wp_redirect($redirect);
  45. }
  46. break;
  47. case 'fb':
  48. if(isset($_GET['resp'])){
  49. $session_array = explode(",", stripslashes($_GET['session']));
  50. $fb_session = array();
  51. foreach($session_array as $session_value){
  52. list($key, $value) = explode(":", $session_value);
  53. $key = trim($key, '"');
  54. $value = trim($value, '"');
  55. if($key == 'uid' || $key == 'access_token'){
  56. $fb_session[$key] = $value;
  57. }
  58. }
  59. //print_r($fb_session);
  60. //$wrp_opts = get_option(WRP_OPTIONS);
  61. //var_dump($wrp_opts);
  62. $opts = array_merge($wrp_opts, $fb_session);
  63. update_option(WRP_OPTIONS, $opts);
  64. $redirect = admin_url( 'admin.php?page=wrp-facebook' );
  65. wp_redirect($redirect);
  66. }
  67. /*
  68. # Creating the facebook object
  69. $facebook = new Facebook(array(
  70. 'appId' => FB_APP_ID,
  71. 'secret' => FB_APP_SECRET,
  72. 'cookie' => true
  73. ));
  74. # Let's see if we have an active session
  75. $session = $facebook->getSession();
  76. if(!empty($session)) {
  77. # Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
  78. try{
  79. $uid = $facebook->getUser();
  80. $user = $facebook->api('/me');
  81. $wrp_opts['fb_userid'] = $user['id'];
  82. $wrp_opts['fb_name'] = $user['name'];
  83. $wrp_opts['fb_uid'] = $uid;
  84. $wrp_opts['fb_access_token'] = $session['access_token'];
  85. $redirect = admin_url( 'admin.php?page=wrp-facebook' );
  86. # req_perms is a comma separated list of the permissions needed
  87. $url = $facebook->getLoginUrl(array(
  88. 'req_perms' => 'publish_stream',
  89. 'next' => $redirect,
  90. 'cancel_url' => $redirect
  91. ));
  92. header("Location: {$url} ");
  93. } catch (Exception $e){}
  94. } else {
  95. # There's no active session, let's generate one
  96. $login_url = $facebook->getLoginUrl();
  97. header("Location: ".$login_url);
  98. }
  99. */
  100. break;
  101. }
  102. }
  103. function wrp_disconnect($service){
  104. $wrp_opts = get_option(WRP_OPTIONS);
  105. switch($service){
  106. case 'tw':
  107. unset($wrp_opts['twrt']);
  108. unset($wrp_opts['twrts']);
  109. unset($wrp_opts['twat']);
  110. unset($wrp_opts['twats']);
  111. unset($wrp_opts['tw_username']);
  112. unset($wrp_opts['tw_profile']);
  113. update_option(WRP_OPTIONS, $wrp_opts);
  114. wp_redirect(admin_url( 'admin.php?page=wrp-twitter' ));
  115. break;
  116. case 'fb':
  117. unset($wrp_opts['uid']);
  118. unset($wrp_opts['access_token']);
  119. update_option(WRP_OPTIONS, $wrp_opts);
  120. wp_redirect(admin_url( 'admin.php?page=wrp-facebook' ));
  121. break;
  122. }
  123. }
  124. //file size
  125. function wrp_formatBytes($bytes, $precision = 2) {
  126. $units = array('B', 'KB', 'MB', 'GB', 'TB');
  127. $bytes = max($bytes, 0);
  128. $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
  129. $pow = min($pow, count($units) - 1);
  130. $bytes /= pow(1024, $pow);
  131. return round($bytes, $precision) . ' ' . $units[$pow];
  132. }
  133. function wrp_get_file($url){
  134. if(ini_get('allow_url_fopen') != 1) {
  135. @ini_set('allow_url_fopen', '1');
  136. }
  137. if(ini_get('allow_url_fopen') != 1) {
  138. $ch = curl_init();
  139. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  140. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Set curl to return the data instead of printing it to the browser.
  141. curl_setopt($ch, CURLOPT_URL, $url);
  142. $data = curl_exec($ch);
  143. curl_close($ch);
  144. return $data;
  145. } else {
  146. return @file_get_contents($url);
  147. }
  148. return false;
  149. }
  150. //////////////////////////////////////////////
  151. // Convert $html to UTF8
  152. // (uses HTTP headers and HTML to find encoding)
  153. // adapted from http://stackoverflow.com/questions/910793/php-detect-encoding-and-make-everything-utf-8
  154. //////////////////////////////////////////////
  155. function wrp_convert_to_utf8($html, $header=null)
  156. {
  157. $accept = array(
  158. 'type' => array('application/rss+xml', 'application/xml', 'application/rdf+xml', 'text/xml', 'text/html'),
  159. 'charset' => array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'byte2be', 'byte2le', 'byte4be', 'byte4le', 'BASE64', 'UUENCODE', 'HTML-ENTITIES', 'Quoted-Printable', '7bit', '8bit'))
  160. );
  161. $encoding = null;
  162. if ($html || $header) {
  163. if (is_array($header)) $header = implode("\n", $header);
  164. if (!$header || !preg_match_all('/^Content-Type:\s+([^;]+)(?:;\s*charset=([^;"\'\n]*))?/im', $header, $match, PREG_SET_ORDER)) {
  165. // error parsing the response
  166. } else {
  167. $match = end($match); // get last matched element (in case of redirects)
  168. if (!in_array(strtolower($match[1]), $accept['type'])) {
  169. // type not accepted
  170. // TODO: avoid conversion
  171. }
  172. if (isset($match[2])) $encoding = trim($match[2], '"\'');
  173. }
  174. if (!$encoding) {
  175. if (preg_match('/^<\?xml\s+version=(?:"[^"]*"|\'[^\']*\')\s+encoding=("[^"]*"|\'[^\']*\')/s', $html, $match)) {
  176. $encoding = trim($match[1], '"\'');
  177. } elseif(preg_match('/<meta\s+http-equiv=["\']Content-Type["\'] content=["\'][^;]+;\s*charset=([^;"\'>]+)/i', $html, $match)) {
  178. if (isset($match[1])) $encoding = trim($match[1]);
  179. }
  180. }
  181. if (!$encoding) {
  182. $encoding = 'utf-8';
  183. } else {
  184. if (!in_array($encoding, array_map('strtolower', $accept['charset']))) {
  185. // encoding not accepted
  186. // TODO: avoid conversion
  187. }
  188. if (strtolower($encoding) != 'utf-8') {
  189. if (strtolower($encoding) == 'iso-8859-1') {
  190. // replace MS Word smart qutoes
  191. $trans = array();
  192. $trans[chr(130)] = '&sbquo;'; // Single Low-9 Quotation Mark
  193. $trans[chr(131)] = '&fnof;'; // Latin Small Letter F With Hook
  194. $trans[chr(132)] = '&bdquo;'; // Double Low-9 Quotation Mark
  195. $trans[chr(133)] = '&hellip;'; // Horizontal Ellipsis
  196. $trans[chr(134)] = '&dagger;'; // Dagger
  197. $trans[chr(135)] = '&Dagger;'; // Double Dagger
  198. $trans[chr(136)] = '&circ;'; // Modifier Letter Circumflex Accent
  199. $trans[chr(137)] = '&permil;'; // Per Mille Sign
  200. $trans[chr(138)] = '&Scaron;'; // Latin Capital Letter S With Caron
  201. $trans[chr(139)] = '&lsaquo;'; // Single Left-Pointing Angle Quotation Mark
  202. $trans[chr(140)] = '&OElig;'; // Latin Capital Ligature OE
  203. $trans[chr(145)] = '&lsquo;'; // Left Single Quotation Mark
  204. $trans[chr(146)] = '&rsquo;'; // Right Single Quotation Mark
  205. $trans[chr(147)] = '&ldquo;'; // Left Double Quotation Mark
  206. $trans[chr(148)] = '&rdquo;'; // Right Double Quotation Mark
  207. $trans[chr(149)] = '&bull;'; // Bullet
  208. $trans[chr(150)] = '&ndash;'; // En Dash
  209. $trans[chr(151)] = '&mdash;'; // Em Dash
  210. $trans[chr(152)] = '&tilde;'; // Small Tilde
  211. $trans[chr(153)] = '&trade;'; // Trade Mark Sign
  212. $trans[chr(154)] = '&scaron;'; // Latin Small Letter S With Caron
  213. $trans[chr(155)] = '&rsaquo;'; // Single Right-Pointing Angle Quotation Mark
  214. $trans[chr(156)] = '&oelig;'; // Latin Small Ligature OE
  215. $trans[chr(159)] = '&Yuml;'; // Latin Capital Letter Y With Diaeresis
  216. $html = strtr($html, $trans);
  217. }
  218. if(!class_exists('SimplePie_Misc'))
  219. require_once(RPFINC.'simplepie.class.php');
  220. $html = SimplePie_Misc::change_encoding($html, $encoding, 'utf-8');
  221. /*
  222. if (function_exists('iconv')) {
  223. // iconv appears to handle certain character encodings better than mb_convert_encoding
  224. $html = iconv($encoding, 'utf-8', $html);
  225. } else {
  226. $html = mb_convert_encoding($html, 'utf-8', $encoding);
  227. }
  228. */
  229. }
  230. }
  231. }
  232. return $html;
  233. }
  234. function wrp_full_feed($permalink, &$campagin, &$item){
  235. require_once('readability.php');
  236. if ($permalink && $html = wrp_get_file($permalink)) {
  237. $html = wrp_convert_to_utf8($html);
  238. $content = grabArticleHtml($html);
  239. }else
  240. return false;
  241. if( false !== stripos($content,'readability was unable to parse this page for content') )
  242. return false;
  243. if( false !== stripos($content, 'return go_back();') )
  244. return false;
  245. $origin_array = explode(",", $$campagin['origin']);
  246. $rewrite_array = explode(",", $$campagin['rewrite']);
  247. foreach($origin_array as $key => $value){
  248. $content = str_ireplace(trim($value), stripslashes(trim($rewrite_array[$key])), $content);
  249. }
  250. if($campagin['source_link'] == 'true'){
  251. $content .= '<br />Source Article from <a href="'.$permalink.'">'.$permalink.'</a>';
  252. }
  253. /*
  254. if($campaign['cache_image'] == 'true') {
  255. $content=wrp_content_fix($content);
  256. $content=wrp_parse_images($content,$item->get_base());
  257. }
  258. */
  259. return $content;
  260. }
  261. function wrp_content_fix($text){
  262. preg_match_all('@(<a.+?href=\".+?\">)(.*?</a>)@',$text,$m);
  263. $urls = $m[1];
  264. if(count($urls)){
  265. foreach($urls as $pos => $link){
  266. if(false === stripos($link,'http://') && false === stripos($link,'https://')){
  267. $text=str_replace($link,'',$text);
  268. $text=str_replace($m[2][$pos],str_replace('</a>','',$m[2][$pos]),$text);
  269. }
  270. }
  271. }
  272. $text=preg_replace("/[&|#|&#]+[a-z0-9]+;/i","",$text);
  273. $text=preg_replace('@<[dtrx][^>]*>@','',$text);
  274. $text=preg_replace('@</[dtrx][^>]*>@','',$text);
  275. return $text;
  276. }
  277. function wrp_parse_images($content,$link){
  278. preg_match_all('/<img(.+?)src=\"(.+?)\"(.*?)>/', $content, $images);
  279. $urls = $images[2];
  280. if(count($urls)){
  281. foreach($urls as $pos => $url){
  282. $oldurl=$url;
  283. $meta=parse_url($url);
  284. if(!isset($meta['host'])){
  285. $meta=parse_url($link);
  286. $url=$meta['scheme'].'://'.$meta['host'].'/'.$url;
  287. }
  288. $newurl = wrp_cache_image($url);
  289. if($newurl)
  290. $content = str_replace($oldurl, $newurl, $content);
  291. else
  292. $content = str_replace($images[0][$pos],'',$content);
  293. }
  294. }
  295. return $content;
  296. }
  297. function wrp_cache_image($url){
  298. if( strpos($url, "icon_") !== FALSE)
  299. return false;
  300. global $rpf_options;
  301. $contents = wrp_get_file($url);
  302. if( !$contents )
  303. return false;
  304. $basename = basename($url);
  305. $paresed_url = parse_url($basename);
  306. $filename = substr(md5(time()), 0, 5) . '_' . $paresed_url['path'];
  307. $pluginpath = WRP_URL;
  308. $real_cachepath=dirname(dirname(__FILE__)).'/cache';
  309. if(is_writable( $real_cachepath ) ){
  310. if($contents){
  311. file_put_contents($real_cachepath . $filename, $contents);
  312. $i=@exif_imagetype($real_cachepath . $filename);
  313. if($i)
  314. return $pluginpath . $cachepath . rawurlencode($filename);
  315. }
  316. }else{
  317. echo " directory is not writable";
  318. }
  319. return false;
  320. }
  321. function wrp_log($message){
  322. }
  323. //*********************************************************************************************************
  324. /**
  325. * Parses a feed with SimplePie
  326. *
  327. * @param boolean $stupidly_fast Set fast mode. Best for checks
  328. * @param integer $max Limit of items to fetch
  329. * @return SimplePie_Item Feed object
  330. **/
  331. function fetchFeed($url, $stupidly_fast = false, $max = 0) {
  332. # SimplePie
  333. if (!class_exists('SimplePie')) {
  334. if (is_file(trailingslashit(ABSPATH).'wp-admin/includes/class-simplepie.php'))
  335. include_once( trailingslashit(ABSPATH).'wp-admin/includes/class-simplepie.php' );
  336. else
  337. //include_once('class-simplepie.php');
  338. include_once('simplepie.class.php');
  339. }
  340. $feed = new SimplePie();
  341. $feed->enable_order_by_date(false);
  342. $feed->set_feed_url($url);
  343. $feed->set_item_limit($max);
  344. $feed->set_stupidly_fast(true);
  345. $feed->enable_cache(false);
  346. $feed->init();
  347. $feed->handle_content_type();
  348. return $feed;
  349. }
  350. function wrp_tweet($oauth_token, $oauth_token_secret, $message){
  351. $tw = new TwitterOAuth(TW_KEY, TW_SECRET, $oauth_token, $oauth_token_secret);
  352. $response = $tw->post('statuses/update', array('status' => $message));
  353. }
  354. //create bit.ly url
  355. function wrp_bitly($url)
  356. {
  357. //login information
  358. $login = 'darell'; //your bit.ly login
  359. $apikey = 'R_7edc48413e51301369ad7a52be587262'; //bit.ly apikey
  360. $format = 'json'; //choose between json or xml
  361. $version = '2.0.1';
  362. //create the URL
  363. $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
  364. //get the url
  365. //could also use cURL here
  366. $response = file_get_contents($bitly);
  367. //parse depending on desired format
  368. if(strtolower($format) == 'json')
  369. {
  370. $json = @json_decode($response,true);
  371. return $json['results'][$url]['shortUrl'];
  372. }
  373. else //xml
  374. {
  375. $xml = simplexml_load_string($response);
  376. return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
  377. }
  378. }
  379. function wrp_fb_post($title, $link, $content){
  380. $wrp_opts = get_option(WRP_OPTIONS);
  381. $fb = new Facebook(array(
  382. 'appId' => FB_APP_ID,
  383. 'secret' => FB_APP_SECRET
  384. ));
  385. $args['access_token'] = $wrp_opts['access_token'];
  386. //$args['message'] = 'The Message';
  387. $args['name'] = $title;
  388. //$args['caption'] = 'The caption';
  389. $args['link'] = $link;
  390. $fbpost = $fb->api('/me/feed/', 'post', $args);
  391. }
  392. ?>