PageRenderTime 87ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/inc/minibots.class.php

https://bitbucket.org/tamvominh/im-5r
PHP | 1134 lines | 880 code | 82 blank | 172 comment | 140 complexity | da82edcd052157a160e52813b6ae8353 MD5 | raw file
  1. <?
  2. /* ---------------------------------------------------------- */
  3. /* minibots.class.php Ver.1.9g */
  4. /* ---------------------------------------------------------- */
  5. /* Mini Bots class is a small php class that allows you to */
  6. /* use some free web seriveces online to retrive usefull data */
  7. /* and infos. This version includes: */
  8. /* smtp validation, check spelling, meteo, exchange rates, */
  9. /* shorten urls, and geo referencing with IP address and more */
  10. /* Feel free to use in your applications, but link my blog: */
  11. /* http://www.barattalo.it */
  12. /* Giulio Pons */
  13. /* ---------------------------------------------------------- */
  14. Class Minibots
  15. {
  16. private $file_size = 0;
  17. private $max_file_size = 5000;
  18. private $file_downloaded = "";
  19. public function __construct () {
  20. }
  21. public function getIP() {
  22. $ip="";
  23. if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP");
  24. else if(getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR");
  25. else if(getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR");
  26. else $ip = "";
  27. return $ip;
  28. }
  29. private function dayadd($days,$date=null , $format="d/m/Y"){
  30. // add days to a date
  31. return date($format,strtotime($days." days",strtotime( $date ? $date : date($format) )));
  32. }
  33. private function attr($s,$attrname) {
  34. //return html attribute
  35. preg_match_all('#\s*('.$attrname.')\s*=\s*["|\']([^"\']*)["|\']\s*#i', $s, $x);
  36. if (count($x)>=3) return isset($x[2][0]) ? $x[2][0] : "";
  37. return "";
  38. }
  39. private function makeabsolute($url,$link) {
  40. $p = parse_url($url);
  41. if (strpos( $link,"http://")===0 ) return $link;
  42. if($p['scheme']."://".$p['host']==$url && $link[0]!="/" && $link!=$url) return $p['scheme']."://".$p['host']."/".$link;
  43. if (strpos( $link, "/")===0) return "http://".$p['host'].$link;
  44. return str_replace(substr(strrchr($url, "/"), 1),"",$url).$link;
  45. }
  46. function on_curl_header($ch, $header) { // to handle file size check and prevent downloading too much
  47. $trimmed = rtrim($header);
  48. if (preg_match('/^Content-Length: (\d+)$/i', $trimmed, $matches)) {
  49. $file_size = (float)$matches[1];
  50. if ($file_size > $this->max_file_size) {
  51. // stop if bigger
  52. return -1;
  53. }
  54. }
  55. return strlen($header);
  56. }
  57. function on_curl_write($ch, $data) { // to handle file size check and prevent downloading too much
  58. $bytes = strlen($data);
  59. $this->file_size += $bytes;
  60. $this->file_downloaded .= $data;
  61. if ($this->file_size > $this->max_file_size) {
  62. // stop if bigger
  63. return -1;
  64. }
  65. return $bytes;
  66. }
  67. private function getRemoteFileSize($url) {
  68. if (substr($url,0,4)=='http') {
  69. $x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
  70. if ( strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { $x = $x['content-length'][1]; }
  71. else { $x = $x['content-length']; }
  72. }
  73. else { $x = @filesize($url); }
  74. return $x;
  75. }
  76. public function doSpelling($q) {
  77. // (thanks to google)
  78. // grab google page with search
  79. $web_page = file_get_contents( "http://www.google.it/search?q=" . urlencode($q) );
  80. // put anchors tag in an array
  81. preg_match_all('#<a([^>]*)?>(.*)</a>#Us', $web_page, $a_array);
  82. for($j=0;$j<count($a_array[0]);$j++) {
  83. // find link with spell suggestion and return it
  84. if(stristr($a_array[0][$j],"class=spell")) return strip_tags($a_array[0][$j]);
  85. }
  86. return $q; //if no results returns the q value
  87. }
  88. public function doExchangeRate($m,$d) {
  89. // (thanks to bank of italy)
  90. // grab exchange rates
  91. $dar = explode("-" , $this->dayadd(-1,$d,"Y-m-d") );
  92. $web_page = file_get_contents( "http://uif.bancaditalia.it/UICFEWebroot/QueryOneDateAllCur?lang=en&rate=0&initDay=".$dar[2]."&initMonth=".$dar[1]."&initYear=".$dar[0]."&refCur=euro&R1=csv");
  93. // parse csv results
  94. $lines = explode("\n",$web_page);
  95. for($j=0;$j<count($lines);$j++) {
  96. $fields = explode(",",$lines[$j]);
  97. if ($fields[2]==$m) return $fields[4];
  98. }
  99. return "";
  100. }
  101. public function doMeteo($q,$thedate="") {
  102. //(thanks to google)
  103. if (!$thedate) $date = date("Y-m-d"); //today
  104. else $date = $thedate;
  105. if ($date>$this->dayadd(3,date("Y-m-d"),"Y-m-d"))return "";
  106. // grab google page with meteo query
  107. $web_page = file_get_contents( "http://www.google.it/search?q=meteo+" . urlencode($q) );
  108. //parse to find data
  109. preg_match_all('#<div class=e>(.*)</table>#Us', $web_page, $m);
  110. if (count($m)>0) {
  111. $p = array();
  112. preg_match_all('#<img([^>]*)?>#Us', $m[0][0], $img);
  113. for ($i=0;$i<count($img[0]);$i++) {
  114. $tag = str_replace("src=\"/","src=\"http://www.google.it/",$img[0][$i]);
  115. $p[$i]["date"]=$this->dayadd($i,date("Y-m-d"),"Y-m-d");
  116. $p[$i]["title"] = $this->attr($tag,"title");
  117. $p[$i]["img"] = $this->attr($tag,"src");
  118. }
  119. preg_match_all('#<nobr>(.*)</nobr>#Uis', $m[0][0], $nobr);
  120. for ($i=0;$i<count($nobr[1]);$i++) {
  121. $temp= explode("|",$nobr[1][$i]);
  122. $p[$i]["min"] = trim($temp[1]) ;
  123. $p[$i]["max"] = trim($temp[0]) ;
  124. }
  125. return (!$thedate?$p:$p[$date]);
  126. }
  127. return array();
  128. }
  129. public function doShortURL($ToConvert) {
  130. //(thanks to tinyurl.com)
  131. $short_url= file_get_contents('http://tinyurl.com/api-create.php?url=' . $ToConvert);
  132. return $short_url;
  133. }
  134. public function doShortURLDecode($url) {
  135. if (!function_exists("curl_init")) die("doShortURLDecode needs CURL module, please install CURL on your php.");
  136. $ch = @curl_init($url);
  137. @curl_setopt($ch, CURLOPT_HEADER, TRUE);
  138. @curl_setopt($ch, CURLOPT_NOBODY, TRUE);
  139. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
  140. @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  141. $response = @curl_exec($ch);
  142. preg_match('/Location: (.*)\n/', $response, $a);
  143. if (!isset($a[1])) return $url;
  144. return $a[1];
  145. }
  146. public function checkMp3($url) {
  147. if (!function_exists("curl_init")) die("getHttpResponseCode needs CURL module, please install CURL on your php.");
  148. $a = parse_url($url);
  149. if(checkdnsrr(str_replace("www.","",$a['host']),"A") || checkdnsrr(str_replace("www.","",$a['host']))) {
  150. $ch = @curl_init();
  151. curl_setopt($ch, CURLOPT_URL, $url);
  152. curl_setopt($ch, CURLOPT_HEADER, 1);
  153. curl_setopt($ch, CURLOPT_NOBODY, 1);
  154. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  155. curl_setopt($ch, CURLOPT_TIMEOUT, 15);
  156. $results = explode("\n", trim(curl_exec($ch)));
  157. $mime = "";
  158. foreach($results as $line) {
  159. if (strtok($line, ':') == 'Content-Type') {
  160. $parts = explode(":", $line);
  161. $mime = trim($parts[1]);
  162. }
  163. }
  164. return $mime=="audio/mpeg";
  165. } else {
  166. return false;
  167. }
  168. }
  169. private function getHttpResponseCode($url) {
  170. if (!function_exists("curl_init")) die("getHttpResponseCode needs CURL module, please install CURL on your php.");
  171. // 404 not found, 403 forbidden...
  172. // for a full list: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  173. $ch = @curl_init($url);
  174. @curl_setopt($ch, CURLOPT_HEADER, TRUE);
  175. @curl_setopt($ch, CURLOPT_NOBODY, TRUE);
  176. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
  177. @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  178. $status = array();
  179. preg_match('/HTTP\/.* ([0-9]+) .*/', @curl_exec($ch) , $status);
  180. return isset($status[1]) ? $status[1] : null;
  181. }
  182. //like file_exists, but for remote urls.
  183. public function url_exists($url) {
  184. return ($this->getHttpResponseCode($url) == 200);
  185. }
  186. public function doGeoIp($ip="") {
  187. //(thanks to geoiptool)
  188. // -----------------------------------------------------------------------------------
  189. // better use this free api: http://ipinfodb.com/ip_query.php?ip=62.149.150.92
  190. // that returns clean xml code.
  191. if (!$ip) $ip = $this->getIP();
  192. $ar = array();
  193. $web_page = file_get_contents( "http://www.geoiptool.com/en/?IP=".$ip );
  194. preg_match_all('#<table([^>]*)tbl_style([^>]*)?>(.*)</table>#Us', $web_page, $t_array);
  195. for($j=0;$j<count($t_array[0]);$j++) {
  196. //find table with data
  197. if (stristr($t_array[0][$j],"IP Address")) {
  198. //parse data
  199. $table = $t_array[0][$j];
  200. preg_match_all('#<tr([^>]*)?>(.*)</tr>#Us', $table, $tr_array);
  201. for($i=0;$i<count($tr_array[0]);$i++) {
  202. $tar = explode(":", strip_tags ( $tr_array[0][$i] ) );
  203. $ar[ trim($tar[0]) ] = trim($tar[1]);
  204. }
  205. }
  206. }
  207. return $ar;
  208. }
  209. function doSMTPValidation($email, $probe_address="", $debug=false) {
  210. # --------------------------------
  211. # function to validate email address
  212. # through a smtp connection with the
  213. # mail server. returns an true when ok
  214. # or an array (msg, error code) when fails.
  215. # --------------------------------
  216. $output = "";
  217. # --------------------------------
  218. # Check syntax with regular expression
  219. # --------------------------------
  220. if (!$probe_address) $probe_address = $_SERVER["SERVER_ADMIN"];
  221. if (preg_match('/^([a-zA-Z0-9\._\+-]+)\@((\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,7}|[0-9]{1,3})(\]?))$/', $email, $matches)) {
  222. $user = $matches[1];
  223. $domain = $matches[2];
  224. # --------------------------------
  225. # Check availability of DNS MX records
  226. # --------------------------------
  227. if (function_exists('checkdnsrr')) {
  228. # --------------------------------
  229. # Construct array of available mailservers
  230. # --------------------------------
  231. if(getmxrr($domain, $mxhosts, $mxweight)) {
  232. for($i=0;$i<count($mxhosts);$i++){
  233. $mxs[$mxhosts[$i]] = $mxweight[$i];
  234. }
  235. asort($mxs);
  236. $mailers = array_keys($mxs);
  237. } elseif(checkdnsrr($domain, 'A')) {
  238. $mailers[0] = gethostbyname($domain);
  239. } else {
  240. $mailers=array();
  241. }
  242. $total = count($mailers);
  243. # --------------------------------
  244. # Query each mailserver
  245. # --------------------------------
  246. if($total > 0) {
  247. # --------------------------------
  248. # Check if mailers accept mail
  249. # --------------------------------
  250. for($n=0; $n < $total; $n++) {
  251. # --------------------------------
  252. # Check if socket can be opened
  253. # --------------------------------
  254. if($debug) { $output .= "Checking server $mailers[$n]...\n";}
  255. $connect_timeout = 2;
  256. $errno = 0;
  257. $errstr = 0;
  258. # --------------------------------
  259. # controllo probe address
  260. # --------------------------------
  261. if (preg_match('/^([a-zA-Z0-9\._\+-]+)\@((\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,7}|[0-9]{1,3})(\]?))$/', $probe_address,$fakematches)) {
  262. $probe_domain = str_replace("@","",strstr($probe_address, '@'));
  263. # --------------------------------
  264. # Try to open up socket
  265. # --------------------------------
  266. if($sock = @fsockopen($mailers[$n], 25, $errno , $errstr, $connect_timeout)) {
  267. $response = fgets($sock);
  268. if($debug) {$output .= "Opening up socket to $mailers[$n]... Success!\n";}
  269. stream_set_timeout($sock, 5);
  270. $meta = stream_get_meta_data($sock);
  271. if($debug) { $output .= "$mailers[$n] replied: $response\n";}
  272. # --------------------------------
  273. # Be sure to set this correctly!
  274. # --------------------------------
  275. $cmds = array(
  276. "HELO $probe_domain",
  277. "MAIL FROM: <$probe_address>",
  278. "RCPT TO: <$email>",
  279. "QUIT",
  280. );
  281. # --------------------------------
  282. # Hard error on connect -> break out
  283. # --------------------------------
  284. if(!$meta['timed_out'] && !preg_match('/^2\d\d[ -]/', $response)) {
  285. $codice = trim(substr(trim($response),0,3));
  286. if ($codice=="421") {
  287. //421 #4.4.5 Too many connections to this host.
  288. $error = $response;
  289. break;
  290. } else {
  291. if($response=="" || $codice=="") {
  292. //c'è stato un errore ma la situazione è poco chiara
  293. $codice = "0";
  294. }
  295. $error = "Error: $mailers[$n] said: $response\n";
  296. break;
  297. }
  298. break;
  299. }
  300. foreach($cmds as $cmd) {
  301. $before = microtime(true);
  302. fputs($sock, "$cmd\r\n");
  303. $response = fgets($sock, 4096);
  304. $t = 1000*(microtime(true)-$before);
  305. if($debug) {$output .= "$cmd\n$response" . "(" . sprintf('%.2f', $t) . " ms)\n";}
  306. if(!$meta['timed_out'] && preg_match('/^5\d\d[ -]/', $response)) {
  307. $codice = trim(substr(trim($response),0,3));
  308. if ($codice<>"552") {
  309. $error = "Unverified address: $mailers[$n] said: $response";
  310. break 2;
  311. } else {
  312. $error = $response;
  313. break 2;
  314. }
  315. # --------------------------------
  316. // il 554 e il 552 sono quota
  317. // 554 Recipient address rejected: mailbox overquota
  318. // 552 RCPT TO: Mailbox disk quota exceeded
  319. # --------------------------------
  320. }
  321. }
  322. fclose($sock);
  323. if($debug) { $output .= "Succesful communication with $mailers[$n], no hard errors, assuming OK\n";}
  324. break;
  325. } elseif($n == $total-1) {
  326. $error = "None of the mailservers listed for $domain could be contacted";
  327. $codice = "0";
  328. }
  329. } else {
  330. $error = "Il probe_address non è una mail valida.";
  331. }
  332. }
  333. } elseif($total <= 0) {
  334. $error = "No usable DNS records found for domain '$domain'";
  335. }
  336. }
  337. } else {
  338. $error = 'Address syntax not correct';
  339. }
  340. if($debug) {
  341. print nl2br(htmlentities($output));
  342. }
  343. if(!isset($codice)) {$codice="n.a.";}
  344. if(isset($error)) return array($error,$codice); else return true;
  345. }
  346. public function getUrlInfo($url,$maximages=5,$maxkbimg=10) {
  347. if (!function_exists("curl_init")) die("getUrlInfo needs CURL module, please install CURL on your php.");
  348. // this bot retrieves info about a url:
  349. // keywords, title, description,favicon and images
  350. //
  351. $url = $this->makeabsolute($url, $this->doShortURLDecode($url));
  352. $ch = curl_init();
  353. curl_setopt($ch, CURLOPT_URL, $url);
  354. curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
  355. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
  356. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
  357. curl_setopt($ch, CURLOPT_PORT, 80); //Set the port number
  358. curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
  359. if($maximages==0) {
  360. // if you don't want images from html
  361. // use only first 5 kb to reduce band used and time
  362. $this->max_file_size = 5000;
  363. curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'on_curl_header'));
  364. curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'on_curl_write'));
  365. }
  366. $web_page = curl_exec($ch);
  367. if(strlen($web_page) <= 1 && $maximages==0) {
  368. $web_page = $this->file_downloaded;
  369. }
  370. //$web_page = file_get_contents($url);
  371. $data['keywords']="";
  372. $data['description']="";
  373. $data['title']="";
  374. $data['favicon']="";
  375. $data['images']=array();
  376. $data['thumbsite']="http://open.thumbshots.org/image.pxf?url=".urlencode($url);
  377. //search title
  378. preg_match_all('#<title([^>]*)?>(.*)</title>#Uis', $web_page, $title_array);
  379. $data['title'] = $title_array[2][0];
  380. //search keywords and description
  381. preg_match_all('#<meta([^>]*)(.*)>#Uis', $web_page, $meta_array);
  382. //print_r($meta_array);
  383. for($i=0;$i<count($meta_array[0]);$i++) {
  384. if (strtolower($this->attr($meta_array[0][$i],"name"))=='description') $data['description'] = $this->attr($meta_array[0][$i],"content");
  385. if (strtolower($this->attr($meta_array[0][$i],"name"))=='keywords') $data['keywords'] = $this->attr($meta_array[0][$i],"content");
  386. }
  387. //search favicon
  388. preg_match_all('#<link([^>]*)(.*)>#Uis', $web_page, $link_array);
  389. for($i=0;$i<count($link_array[0]);$i++) {
  390. if (strtolower($this->attr($link_array[0][$i],"rel"))=='shortcut icon') $data['favicon'] = $this->makeabsolute($url,$this->attr($link_array[0][$i],"href"));
  391. }
  392. // search images big enough
  393. preg_match_all('#<img([^>]*)(.*)/?>#Uis', $web_page, $imgs_array);
  394. $imgs = array();
  395. for($i=0;$i<count($imgs_array[0]);$i++) {
  396. if ($src = $this->attr($imgs_array[0][$i],"src")) {
  397. $src = $this->makeabsolute($url,$src);
  398. if(!in_array($src,$imgs) && $this->getRemoteFileSize($src)>$maxkbimg*1000) array_push($imgs,$src);
  399. }
  400. if (count($imgs)>$maximages-1) break;
  401. }
  402. $data['images']=$imgs;
  403. return $data;
  404. }
  405. public function getUrlInfoFast($url,$maxbytes=4096) {
  406. if (!function_exists("curl_init")) die("getUrlInfo needs CURL module, please install CURL on your php.");
  407. $url = $this->makeabsolute($url, $this->doShortURLDecode($url));
  408. $ch = curl_init();
  409. curl_setopt($ch, CURLOPT_URL, $url);
  410. curl_setopt($ch, CURLOPT_FAILONERROR, 0); // Fail on errors
  411. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
  412. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
  413. curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
  414. $this->max_file_size = $maxbytes;
  415. //curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'on_curl_header'));
  416. curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'on_curl_write'));
  417. $web_page = curl_exec($ch);
  418. if(strlen($web_page) <= 1) $web_page = $this->file_downloaded;
  419. $data['d']="";
  420. $data['t']="";
  421. $data['f']="";
  422. $data['e']=""; // per mettere automaticamente embed di player video youtube e mp3
  423. $data['g']=""; // trigger per visualizzare embed
  424. //search title
  425. preg_match_all('#<title([^>]*)?>(.*)</title>#Uis', $web_page, $title_array);
  426. $data['t'] = isset($title_array[2][0]) ? trim(preg_replace('/ +/', ' ', $title_array[2][0])) : "senza titolo";
  427. //search keywords and description
  428. preg_match_all('#<meta([^>]*)(.*)>#Uis', $web_page, $meta_array);
  429. //print_r($meta_array);
  430. for($i=0;$i<count($meta_array[0]);$i++) if (strtolower($this->attr($meta_array[0][$i],"name"))=='description') $data['d'] = $this->attr($meta_array[0][$i],"content");
  431. //search favicon
  432. preg_match_all('#<link([^>]*)(.*)>#Uis', $web_page, $link_array);
  433. for($i=0;$i<count($link_array[0]);$i++) {
  434. if (strtolower($this->attr($link_array[0][$i],"rel"))=='shortcut icon') $data['f'] = $this->makeabsolute($url,$this->attr($link_array[0][$i],"href"));
  435. }
  436. $trigger = "<img src='http://open.thumbshots.org/image.pxf?url=".urlencode($url)."' />";
  437. $embed = "";
  438. //http://www.youtube.com/v/Md1E_Rg4MGQ&hl=en&fs=1&
  439. //http://www.youtube.com/watch?v=Md1E_Rg4MGQ&feature=aso
  440. preg_match_all('/^http:\/\/www.youtube.com\/(v\/|watch\?v=)([^&]*)(.*)$/', $url, $yarr);
  441. if(isset($yarr[2][0])) {
  442. $trigger = "<img src='http://img.youtube.com/vi/".$yarr[2][0]."/1.jpg'/>";
  443. $embed = $this->resizeEmbed(
  444. '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/'.$yarr[2][0].'?fs=1&amp;hl=it_IT"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'.$yarr[2][0].'?fs=1&amp;hl=it_IT" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>', 400);
  445. }
  446. //http://vimeo.com/17116744
  447. preg_match_all('/^http:\/\/vimeo.com\/([0-9]*)$/', $url, $varr);
  448. if(isset($varr[1][0])) {
  449. $trigger = "<img src='".$this->getVimeoInfo($varr[1][0],"thumbnail_small")."'/>";
  450. $embed = $this->resizeEmbed(
  451. '<iframe src="http://player.vimeo.com/video/'.$varr[1][0].'" width="400" height="225" frameborder="0"></iframe>' , 400);
  452. }
  453. $data["e"] = $embed;
  454. $data["g"] = $trigger;
  455. return $data;
  456. }
  457. //
  458. // copy remote file to server
  459. private function copyFile($url,$filename){
  460. $file = fopen ($url, "rb");
  461. if (!$file) return false; else {
  462. $fc = fopen($filename, "wb");
  463. while (!feof ($file)) {
  464. $line = fread ($file, 1028);
  465. fwrite($fc,$line);
  466. }
  467. fclose($fc);
  468. return true;
  469. }
  470. }
  471. //
  472. // save a url to a local pdf using pdfmyurl.com service
  473. public function url2pdf($url,$pdffilename) {
  474. return $this->copyFile("http://pdfmyurl.com?url=".urlencode( str_replace("http://","",$url) ), $pdffilename);
  475. }
  476. //
  477. // save a url to a local jpg thumb using open.thumbshots.com service
  478. public function url2thumb($url,$thumbfilename) {
  479. return $this->copyFile("http://open.thumbshots.org/image.pxf?url=".urlencode( $url ), $thumbfilename);
  480. }
  481. //
  482. // return text from a url
  483. // thanks to php.net
  484. public function webpage2txt($url) {
  485. if (!function_exists("curl_init")) die("webpage2txt needs CURL module, please install CURL on your php.");
  486. $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; it; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8";
  487. $ch = curl_init(); // initialize curl handle
  488. curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
  489. curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
  490. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
  491. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
  492. curl_setopt($ch, CURLOPT_PORT, 80); //Set the port number
  493. curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
  494. curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
  495. $document = curl_exec($ch);
  496. $search = array('@<script[^>]*?>.*?</script>@si', // Strip out javascript
  497. '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
  498. '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
  499. '@<![\s\S]*?–[ \t\n\r]*>@', // Strip multi-line comments including CDATA
  500. '/\s{2,}/',
  501. );
  502. $text = preg_replace($search, " ", html_entity_decode($document));
  503. $pat[0] = "/^\s+/";
  504. $pat[2] = "/\s+\$/";
  505. $rep[0] = "";
  506. $rep[2] = " ";
  507. $text = preg_replace($pat, $rep, trim($text));
  508. return $text;
  509. }
  510. function remove_html_tags($str) {
  511. $str = preg_replace(
  512. array(// Remove invisible content
  513. '@<head[^>]*?>.*?</head>@siu',
  514. '@<script[^>]*?>.*?</script>@siu',
  515. '@<noscript[^>]*?.*?</noscript>@siu',
  516. ),
  517. "", //replace above with nothing
  518. $str );
  519. return $str;
  520. }
  521. // OK
  522. public function twitterSetStatus($user, $pwd, $status, $proxy_obj) {
  523. if (!function_exists("curl_init")) die("twitterSetStatus needs CURL module, please install CURL on your php.");
  524. $ch = curl_init();
  525. // -------------------------------------------------------
  526. // get login form and parse it
  527. $cookie_file = "." . DIRECTORY_SEPARATOR . "cookies" . DIRECTORY_SEPARATOR . "my_cookies.txt";
  528. if (file_exists($cookie_file)) {
  529. unlink($cookie_file);
  530. }
  531. curl_setopt($ch, CURLOPT_URL, "https://mobile.twitter.com/session/new");
  532. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  533. curl_setopt($ch, CURLOPT_FAILONERROR, 1);
  534. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  535. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  536. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  537. curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
  538. curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
  539. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3 ");
  540. if ($proxy_obj) {
  541. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
  542. curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  543. curl_setopt($ch, CURLOPT_PROXY, $proxy_obj['proxy']);
  544. curl_setopt($ch, CURLOPT_PROXYPORT, $proxy_obj['port']);
  545. }
  546. $page = curl_exec($ch);
  547. $page = $this->remove_html_tags($page);
  548. // echo "Login page: $page <br/>";
  549. // $page = stristr($page, "<div id>");
  550. preg_match("/form action=\"(.*?)\"/", $page, $action);
  551. $regex = "/<input.+?name=\"authenticity_token\".+?value=\"(\w+)\"/";
  552. preg_match($regex, $page, $authenticity_token);
  553. // echo "Auth token: $authenticity_token[1]";
  554. // -------------------------------------------------------
  555. // make login and get home page
  556. $strpost = "authenticity_token=".urlencode($authenticity_token[1])."&username=".urlencode($user)."&password=".urlencode($pwd);
  557. curl_setopt($ch, CURLOPT_URL, $action[1]);
  558. curl_setopt($ch, CURLOPT_POSTFIELDS, $strpost);
  559. $page = curl_exec($ch);
  560. $page = $this->remove_html_tags($page);
  561. // echo "home page: $page";
  562. // check if login was ok
  563. curl_setopt($ch, CURLOPT_URL, "https://mobile.twitter.com/compose/tweet");
  564. // curl_setopt($ch, CURLOPT_POSTFIELDS, $strpost);
  565. $page = curl_exec($ch);
  566. $page = $this->remove_html_tags($page);
  567. // echo $page;
  568. preg_match("/\<div class=\"warning\"\>(.*?)\<\/div\>/", $page, $warning);
  569. if (isset($warning[1])) {
  570. echo $warning[1];
  571. return false;
  572. }
  573. // $page = stristr($page,'<table class="tweettable">');
  574. preg_match("/form action=\"(.*?)\"/", $page, $action);
  575. preg_match($regex, $page, $authenticity_token);
  576. // -------------------------------------------------------
  577. // send status update
  578. $strpost = "authenticity_token=".urlencode($authenticity_token[1]);
  579. $tweet['display_coordinates']='';
  580. $tweet['in_reply_to_status_id']='';
  581. $tweet['lat']='';
  582. $tweet['long']='';
  583. $tweet['place_id']='';
  584. $tweet['text']=$status;
  585. $ar = array("authenticity_token" => $authenticity_token[1], "tweet"=>$tweet);
  586. $data = http_build_query($ar);
  587. curl_setopt($ch, CURLOPT_URL, "https://mobile.twitter.com/");
  588. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  589. $page = curl_exec($ch);
  590. $page = $this->remove_html_tags($page);
  591. // echo $page;
  592. // return $page;
  593. if (Util::http_code($ch) == 200) {
  594. return true;
  595. } else {
  596. return false;
  597. }
  598. }
  599. //
  600. // get twitter infos from nickname
  601. // and get avatar url, parse data from page
  602. public function twitterInfo($nick) {
  603. if (!function_exists("curl_init")) die("twitterInfo needs CURL module, please install CURL on your php.");
  604. $ch = curl_init(); // initialize curl handle
  605. curl_setopt($ch, CURLOPT_URL, "http://twitter.com/$nick"); // set url to post to
  606. curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
  607. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
  608. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
  609. curl_setopt($ch, CURLOPT_PORT, 80); // Set the port number
  610. curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
  611. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
  612. $document = curl_exec($ch);
  613. preg_match_all('#<div class="stats">(.*)</div>#Uis', $document, $stats);
  614. preg_match_all('#<span[^>]*?>(.*)</span>#Uis', $stats[1][0], $spans);
  615. $o = array();
  616. for ($i=0;$i<count($spans[0]);$i++) {
  617. if ($this->attr($spans[0][$i],"id")=="following_count") $o['following'] = $spans[1][$i];
  618. if ($this->attr($spans[0][$i],"id")=="follower_count") $o['follower'] = $spans[1][$i];
  619. if ($this->attr($spans[0][$i],"id")=="lists_count") $o['lists'] = $spans[1][$i];
  620. }
  621. $o['avatar'] = "";
  622. preg_match_all('#<img [^>]*?>#Uis', $document, $t);
  623. for ($i=0;$i<count($t[0]);$i++) if ($this->attr($t[0][$i],"id")=="profile-image") $o['avatar'] = $this->attr($t[0][$i],"src");
  624. return $o;
  625. }
  626. //
  627. // get twitter infos from nickname
  628. // and get avatar url, parse data from api xml response
  629. // OK
  630. public function twitterInfoApi($nick) {
  631. if (!function_exists("curl_init")) die("twitterInfoApi needs CURL module, please install CURL on your php.");
  632. $ch = curl_init(); // initialize curl handle
  633. curl_setopt($ch, CURLOPT_URL, "http://api.twitter.com/1/users/show.xml?screen_name=$nick"); // set url to post to
  634. curl_setopt($ch, CURLOPT_FAILONERROR, 1);
  635. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  636. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  637. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  638. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
  639. $obj = simplexml_load_string( curl_exec($ch) );
  640. // echo "<pre>";
  641. // var_dump($obj);
  642. // echo "</pre>";
  643. if(is_object($obj)) {
  644. return array(
  645. "id" => (string)$obj->id,
  646. "name" => (string)$obj->name,
  647. "screen_name" => (string)$obj->screen_name,
  648. "description" => (string)$obj->description,
  649. "avatar" => (string)$obj->profile_image_url,
  650. "followers" => (string)$obj->followers_count,
  651. "following" => (string)$obj->friends_count,
  652. "favourites_count" => (string)$obj->favourites_count,
  653. "statuses_count" => (string)$obj->statuses_count,
  654. "status" => date("Y-m-d H:i:s", strtotime( (string)$obj->status->created_at ))." - ".(string)$obj->status->text
  655. );
  656. } else {
  657. return null;
  658. }
  659. }
  660. //
  661. // update twitter status (old function, no longer valid, with basic authentication)
  662. private function twitterSetStatus__OLD__($user,$pwd,$status) {
  663. if (!function_exists("curl_init")) die("twitterSetStatus needs CURL module, please install CURL on your php.");
  664. $ch = curl_init();
  665. curl_setopt($ch, CURLOPT_URL, "http://api.twitter.com/1/statuses/update.xml");
  666. curl_setopt($ch, CURLOPT_FAILONERROR, 1);
  667. curl_setopt($ch, CURLOPT_POSTFIELDS, 'status=' . urlencode($status));
  668. curl_setopt($ch, CURLOPT_USERPWD, "$user:$pwd");
  669. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  670. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  671. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  672. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
  673. $document = curl_exec($ch);
  674. if ($document) return true; else return false;
  675. }
  676. //
  677. // elenco aggiornamenti di status
  678. public function twitterGetStatusList($nick) {
  679. if (!function_exists("curl_init")) die("twitterGetStatusList needs CURL module, please install CURL on your php.");
  680. $ch = curl_init();
  681. curl_setopt($ch, CURLOPT_URL, "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=$nick");
  682. curl_setopt($ch, CURLOPT_FAILONERROR, 1);
  683. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  684. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  685. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  686. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
  687. $obj = simplexml_load_string( curl_exec($ch) );
  688. $a= array();
  689. if ($obj) {
  690. for ($i=0;$i<count($obj->status);$i++) {
  691. $s = date("Y-m-d H:i:s", strtotime( (string)$obj->status[$i]->created_at ))." - ".(string)$obj->status[$i]->text;
  692. array_push($a,$s);
  693. }
  694. }
  695. return $a;
  696. }
  697. //
  698. // change Facebook status with curl
  699. // Thanks to Alste (curl stuff inspired by nexdot.net/blog)
  700. // This function executes the status update if $pagina == "home.php".
  701. // If you provide a different fan page url, this function will post
  702. // on the page wall (if the user can).
  703. private function setFacebookStatusOrPostToWall($status, $login_email, $login_pass, $pagina = "home.php", $debug=false) {
  704. if (!function_exists("curl_init")) die("setFacebookStatusOrPostToWall needs CURL module, please install CURL on your php.");
  705. //CURL stuff
  706. //This executes the login procedure
  707. $ch = curl_init();
  708. curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php?m&amp;next=http%3A%2F%2Fm.facebook.com%2Fhome.php');
  709. curl_setopt($ch, CURLOPT_POSTFIELDS, 'email=' . urlencode($login_email) . '&pass=' . urlencode($login_pass) . '&login=' . urlencode("Log in"));
  710. curl_setopt($ch, CURLOPT_POST, 1);
  711. curl_setopt($ch, CURLOPT_HEADER, 0);
  712. //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  713. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  714. curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
  715. curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
  716. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  717. //make sure you put a popular web browser here (signature for your web browser can be retrieved with 'echo $_SERVER['HTTP_USER_AGENT'];'
  718. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12");
  719. curl_exec($ch);
  720. // post status or on a fan page
  721. curl_setopt($ch, CURLOPT_POST, 0);
  722. curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/'.$pagina);
  723. //echo 'http://m.facebook.com/'.$pagina;
  724. //die;
  725. $page = curl_exec($ch);
  726. if($pagina == "home.php" ) {
  727. // update status
  728. if ($debug) {
  729. //show information regarding the request
  730. print_r(curl_getinfo($ch));
  731. echo curl_errno($ch) . '-' . curl_error($ch);
  732. echo "<hr>";
  733. echo (htmlspecialchars($page));
  734. echo "<br><br>Your Facebook status seems to have been updated.";
  735. }
  736. curl_setopt($ch, CURLOPT_POST, 1);
  737. //this gets the post_form_id value
  738. preg_match("/input type=\"hidden\" name=\"post_form_id\" value=\"(.*?)\"/", $page, $form_id);
  739. preg_match("/input type=\"hidden\" name=\"fb_dtsg\" value=\"(.*?)\"/", $page, $fb_dtsg);
  740. preg_match("/input type=\"hidden\" name=\"charset_test\" value=\"(.*?)\"/", $page, $charset_test);
  741. preg_match("/input type=\"submit\" class=\"button\" name=\"update\" value=\"(.*?)\"/", $page, $update);
  742. //we'll also need the exact name of the form processor page
  743. //preg_match("/form action=\"(.*?)\"/", $page, $form_num);
  744. //sometimes doesn't work so we search the correct form action to use
  745. //since there could be more than one form in the page.
  746. preg_match_all("#<form([^>]*)>(.*)</form>#Ui", $page, $form_ar);
  747. for($i=0;$i<count($form_ar[0]);$i++) if(stristr($form_ar[0][$i],"post_form_id")) preg_match("/form action=\"(.*?)\"/", $page, $form_num);
  748. $strpost = 'post_form_id=' . $form_id[1] . '&status=' . urlencode($status) . '&update=' . urlencode($update[1]) . '&charset_test=' . urlencode($charset_test[1]) . '&fb_dtsg=' . urlencode($fb_dtsg[1]);
  749. if($debug) {
  750. echo "Parameters sent: ".$strpost."<hr>";
  751. }
  752. curl_setopt($ch, CURLOPT_POSTFIELDS, $strpost );
  753. //set url to form processor page
  754. curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com' . $form_num[1]);
  755. curl_exec($ch);
  756. if ($debug) {
  757. //show information regarding the request
  758. print_r(curl_getinfo($ch));
  759. echo curl_errno($ch) . '-' . curl_error($ch);
  760. echo "<br><br>Your Facebook status seems to have been updated.";
  761. }
  762. //close the connection
  763. curl_close($ch);
  764. } else {
  765. // post on facebook page
  766. if ($debug) {
  767. //show information regarding the request
  768. print_r(curl_getinfo($ch));
  769. echo curl_errno($ch) . '-' . curl_error($ch);
  770. echo "<hr>";
  771. echo (htmlspecialchars($page));
  772. }
  773. curl_setopt($ch, CURLOPT_POST, 1);
  774. //this gets the post_form_id value
  775. preg_match("/form action=\"(.*?)\" method=\"post\"/", $page, $action);
  776. preg_match("/input type=\"hidden\" name=\"post_form_id\" value=\"(.*?)\"/", $page, $form_id);
  777. preg_match("/input type=\"hidden\" name=\"fb_dtsg\" value=\"(.*?)\"/", $page, $fb_dtsg);
  778. preg_match("/input type=\"hidden\" name=\"charset_test\" value=\"(.*?)\"/", $page, $charset_test);
  779. preg_match("/input type=\"submit\" class=\"button\" name=\"post\" value=\"(.*?)\"/", $page, $post);
  780. //we'll also need the exact name of the form processor page
  781. preg_match("/form action=\"(.*?)\"/", $page, $form_num);
  782. $strpost = 'post_form_id=' . $form_id[1] . '&message=' . urlencode($status) . '&post=' . urlencode($post[1]) . '&charset_test=' . urlencode($charset_test[1]) . '&fb_dtsg=' . urlencode($fb_dtsg[1]);
  783. if($debug) {
  784. echo "Parameters sent: ".$strpost."<hr>";
  785. }
  786. curl_setopt($ch, CURLOPT_POSTFIELDS, $strpost );
  787. //set url to form processor page
  788. curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com' . $action[1]);
  789. curl_exec($ch);
  790. if ($debug) {
  791. //show information regarding the request
  792. print_r(curl_getinfo($ch));
  793. echo curl_errno($ch) . '-' . curl_error($ch);
  794. echo "<br><br>Your Facebook page wall have been updated.";
  795. }
  796. //close the connection
  797. curl_close($ch);
  798. }
  799. }
  800. public function setFacebookStatus($status, $login_email, $login_pass, $debug=false) {
  801. if (!function_exists("curl_init")) die("setFacebookStatus needs CURL module, please install CURL on your php.");
  802. $this->setFacebookStatusOrPostToWall($status, $login_email, $login_pass, "home.php", $debug);
  803. }
  804. public function postToFacebookPage($msg, $pagina, $login_email, $login_pass, $debug=false) {
  805. if (!function_exists("curl_init")) die("postToFacebookPage needs CURL module, please install CURL on your php.");
  806. //http://www.facebook.com/#!/pages/Favignana/38995680998?ref=ts
  807. // $pagina = "/pages/Favignana/38995680998";
  808. $this->setFacebookStatusOrPostToWall($msg, $login_email, $login_pass, $pagina, $debug);
  809. }
  810. //
  811. // get list of images from google images
  812. public function googleGetImages($k) {
  813. $url = "http://images.google.it/images?as_q=##query##&hl=it&imgtbs=z&btnG=Cerca+con+Google&as_epq=&as_oq=&as_eq=&imgtype=&imgsz=m&imgw=&imgh=&imgar=&as_filetype=&imgc=&as_sitesearch=&as_rights=&safe=images&as_st=y";
  814. $web_page = file_get_contents( str_replace("##query##",urlencode($k), $url ));
  815. $tieni = stristr($web_page,"dyn.setResults(");
  816. $tieni = str_replace( "dyn.setResults(","", str_replace(stristr($tieni,");"),"",$tieni) );
  817. $tieni = str_replace("[]","",$tieni);
  818. $m = preg_split("/[\[\]]/",$tieni);
  819. $x = array();
  820. for($i=0;$i<count($m);$i++) {
  821. $m[$i] = str_replace("/imgres?imgurl\\x3d","",$m[$i]);
  822. $m[$i] = str_replace(stristr($m[$i],"\\x26imgrefurl"),"",$m[$i]);
  823. $m[$i] = preg_replace("/^\"/i","",$m[$i]);
  824. $m[$i] = preg_replace("/^,/i","",$m[$i]);
  825. if ($m[$i]!="") array_push($x,$m[$i]);
  826. }
  827. return $x;
  828. }
  829. //
  830. // get users video from youtube
  831. public function youtubeGetVideos($user) {
  832. // you can retrieve thumbs from here: http://www.reelseo.com/youtube-thumbnail-image/
  833. // youtube thumbs here: http://img.youtube.com/vi/####VIDEOID#####/1.jpg
  834. $web_page = file_get_contents( "http://m.youtube.com/".urlencode($user) );
  835. preg_match_all('#<a (.*)</a>#Uis', $web_page, $links);
  836. $x = array();
  837. for ($i=0;$i<count($links[1]);$i++) {
  838. if (stristr($links[1][$i],"/watch")) {
  839. $m = preg_split("/[&=\?]/", str_replace("&amp;", "&", $this->attr($links[1][$i],"href")));
  840. for ($j=0;$j<count($m);$j++) if ($m[$j]=="v") { array_push($x,$m[$j+1]); break; }
  841. }
  842. }
  843. return $x;
  844. }
  845. private function decodeFlickrUsername($n) {
  846. $s = @file_get_contents("http://www.flickr.com/photos/".$n);
  847. preg_match_all('#<a([^>]*)?>(.*)</a>#Us', $s, $a_array);
  848. for($i=0;$i<count($a_array[0]);$i++) {
  849. //echo htmlspecialchars($a_array[0][$i])."<hr>";
  850. if(stristr($a_array[0][$i],"http://api.flickr.com/services/feeds")) {
  851. $m = preg_split("/[&=\?]/", $this->attr($a_array[0][$i],"href"));
  852. for ($j=0;$j<count($m);$j++) if ($m[$j]=="id") return $m[$j+1];
  853. }
  854. }
  855. return "";
  856. }
  857. public function parseFlickrFeed($user,$n) {
  858. $id = $this->decodeFlickrUsername($user);
  859. if(!$id) return array();
  860. // $id = 16664181@N00
  861. $url = "http://api.flickr.com/services/feeds/photos_public.gne?id={$id}&lang=it-it&format=rss_200";
  862. $s = file_get_contents($url);
  863. preg_match_all('#<item>(.*)</item>#Us', $s, $items);
  864. $ar = array();
  865. for($i=0;$i<count($items[1]);$i++) {
  866. if($i>=$n) return $out;
  867. $item = $items[1][$i];
  868. preg_match_all('#<link>(.*)</link>#Us', $item, $temp);
  869. $link = $temp[1][0];
  870. preg_match_all('#<title>(.*)</title>#Us', $item, $temp);
  871. $title = $temp[1][0];
  872. preg_match_all('#<media:thumbnail([^>]*)>#Us', $item, $temp);
  873. $thumb = $this->attr($temp[0][0],"url");
  874. $ar['images'][$i] = $thumb;
  875. $ar['link'][$i] = $link;
  876. $ar['title'][$i] = $title;
  877. }
  878. return $ar;
  879. }
  880. public function pushMeTo($widgeturl,$text,$signature) {
  881. if (!function_exists("curl_init")) die("pushMeTo needs CURL module, please install CURL on your php.");
  882. //$widgeturl = "http://pushme.to/q/widget/export/?hash=51ff0b6e3c1ce3a7a7e473198e1b6d9a";
  883. $ch = curl_init();
  884. curl_setopt($ch, CURLOPT_URL, $widgeturl);
  885. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  886. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12");
  887. $page = curl_exec($ch);
  888. //this gets the post_form_id value
  889. preg_match("/form action=\"(.*?)\"/", $page, $form_action);
  890. preg_match("/textarea name=\"(.*?)\"/", $page, $message_field);
  891. preg_match("/input type=\"text\" name=\"(.*?)\"/", $page, $signature_field);
  892. $ch = curl_init();
  893. $strpost = $message_field[1].'=' . urlencode($text) . '&'.$signature_field[1].'=' . urlencode($signature);
  894. curl_setopt($ch, CURLOPT_POSTFIELDS, $strpost );
  895. curl_setopt($ch, CURLOPT_URL, $form_action[1]);
  896. curl_setopt($ch, CURLOPT_POST, 1);
  897. curl_setopt($ch, CURLOPT_HEADER, 0);
  898. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  899. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12");
  900. $page = curl_exec($ch);
  901. }
  902. public function googleSuggestKeywords($k) {
  903. if (!function_exists("curl_init")) die("googleSuggestKeywords needs CURL module, please install CURL on your php.");
  904. // Get all the related keywords from Google Suggest (JUST ONE WORD ALLOWED)
  905. // http://www.labnol.org/internet/tutorial-create-bot-for-gtalk-yahoo-messenger/4354/
  906. $k = explode(" ",$k); $k = $k[0];
  907. $u = "http://google.com/complete/search?output=toolbar&q=" . $k;
  908. $ch = curl_init();
  909. curl_setopt($ch, CURLOPT_URL, $u);
  910. curl_setopt($ch, CURLOPT_HEADER, 0);
  911. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  912. $xml = simplexml_load_string(curl_exec($ch));
  913. curl_close($ch);
  914. // Parse the keywords
  915. $result = $xml->xpath('//@data');
  916. $ar = array();
  917. while (list($key, $value) = each($result)) $ar[] = (string)$value;
  918. return $ar;
  919. }
  920. // from an address to a couple (lat,long) coordinates
  921. public function getLatLong($address){
  922. if (!is_string($address))die("All Addresses must be passed as a string");
  923. $_url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address));
  924. $_result = false;
  925. if($_result = file_get_contents($_url)) {
  926. if(strpos($_result,'errortips') > 1 || strpos($_result,'Did you mean:') !== false) return false;
  927. preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
  928. $_coords['lat'] = $_match[1];
  929. $_coords['long'] = $_match[2];
  930. }
  931. return $_coords;
  932. }
  933. public function wikiDefinition($s) {
  934. //http://it.wikipedia.org/w/api.php?action=opensearch&search=subsonica&format=xml&limit=1
  935. $url = "http://en.wikipedia.org/w/api.php?action=opensearch&search=".urlencode($s)."&format=xml&limit=1";
  936. $ch = curl_init($url);
  937. curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
  938. curl_setopt($ch, CURLOPT_POST, FALSE);
  939. curl_setopt($ch, CURLOPT_HEADER, false); // Include head as needed
  940. curl_setopt($ch, CURLOPT_NOBODY, FALSE); // Return body
  941. curl_setopt($ch, CURLOPT_VERBOSE, FALSE); // Minimize logs
  942. curl_setopt($ch, CURLOPT_REFERER, ""); // Referer value
  943. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // No certificate
  944. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects
  945. curl_setopt($ch, CURLOPT_MAXREDIRS, 4); // Limit redirections to four
  946. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return in string
  947. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8"); // Webbot name
  948. $page = curl_exec($ch);
  949. $xml = simplexml_load_string($page);
  950. if((string)$xml->Section->Item->Description) {
  951. return array((string)$xml->Section->Item->Text, (string)$xml->Section->Item->Description, (string)$xml->Section->Item->Url);
  952. } else {
  953. return "";
  954. }
  955. }
  956. public function myspaceConcerts($user) {
  957. $ch = curl_init("http://www.myspace.com/".$user."/shows");
  958. curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
  959. curl_setopt($ch, CURLOPT_POST, FALSE);
  960. curl_setopt($ch, CURLOPT_HEADER, false); // Include head as needed
  961. curl_setopt($ch, CURLOPT_NOBODY, FALSE); // Return body
  962. curl_setopt($ch, CURLOPT_VERBOSE, FALSE); // Minimize logs
  963. curl_setopt($ch, CURLOPT_REFERER, ""); // Referer value
  964. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // No certificate
  965. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects
  966. curl_setopt($ch, CURLOPT_MAXREDIRS, 4); // Limit redirections to four
  967. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return in string
  968. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");
  969. $page = curl_exec($ch);
  970. preg_match_all("#<a class=\"userLink\" href=\"/".$user."\">(.*)</a>#Us", $page, $a);
  971. $band = trim(strip_tags($a[1][0]));
  972. // months array is in italian because of from my web servers pages returns in italian
  973. // probably you have to change this array
  974. $months = array("gen"=>"01","feb"=>"02","mar"=>"03","apr"=>"04","mag"=>"05","giu"=>"06","lug"=>"07","ago"=>"08","set"=>"09","ott"=>"10","nov"=>"11","dic"=>"12");
  975. $out = array();
  976. $c=0;
  977. $li = preg_split("/<li class=\"moduleItem event( odd| even)?( first| last)? vevent\" ?>/i",$page);
  978. for($i=0;$i<count($li);$i++) {
  979. if(stristr($li[$i],"<div class=\"entryDate\">")) {
  980. //echo strip_tags($li[$i])."<hr>";
  981. //<span class="month"> ott</span>
  982. preg_match_all("#<span class=\"month\">(.*)</span>#Us", $li[$i], $temp);
  983. $month = $months[strip_tags(trim($temp[1][0]))];
  984. preg_match_all("#<span class=\"day\">(.*)</span>#Us", $li[$i], $temp);
  985. $day = str_pad( strip_tags(trim($temp[1][0])), 2, "0", STR_PAD_LEFT);
  986. $year = date("Y");
  987. $data = $year."-".$month."-".$day;
  988. if($data<date("Y-m-d")) { $data = (date("Y")+1)."-".$month."-".$day; }
  989. preg_match_all("#<h4>(.*)</h4>#Us", $li[$i], $temp);
  990. $posto = strip_tags(trim($temp[1][0]));
  991. preg_match_all("#<span class=\"locality\">(.*)</span>#Us", $li[$i], $temp);
  992. $citta = strip_tags(trim($temp[1][0]));
  993. preg_match_all("#<span class=\"region\">(.*)</span>#Us", $li[$i], $temp);
  994. $region = strip_tags(trim($temp[1][0]));
  995. preg_match_all("#<span class=\"country-name\">(.*)</span>#Us", $li[$i], $temp);
  996. $stato = strip_tags(trim($temp[1][0]));
  997. $out[$c]["band"] = $band;
  998. $out[$c]["date"] = $data;
  999. //$out[$c]["time"] = ""; not parsed
  1000. $out[$c]["venue"] = $posto;
  1001. //$out[$c]["url"] = ""; not parsed
  1002. $out[$c]["where"] = $citta.",".$region.",".$stato;
  1003. $c++;
  1004. }
  1005. }
  1006. return $out;
  1007. }
  1008. public function getVimeoInfo($id, $info = 'thumbnail_medium') {
  1009. // http://www.soapboxdave.com/2010/04/getting-the-vimeo-thumbnail/
  1010. if (!function_exists('curl_init')) die('CURL is not installed!');
  1011. $ch = curl_init();
  1012. curl_setopt($ch, CURLOPT_URL, "http://vimeo.com/api/v2/video/$id.php");
  1013. curl_setopt($ch, CURLOPT_HEADER, 0);
  1014. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1015. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  1016. $output = unserialize(curl_exec($ch));
  1017. $output = $output[0][$info];
  1018. curl_close($ch);
  1019. return $output;
  1020. }
  1021. // resize video embed and iframes
  1022. public function resizeEmbed($video,$new_width='') {
  1023. preg_match("/width=\"([^\"]*)\"/i",$video,$w); $w = (integer)$w[1];
  1024. preg_match("/height=\"([^\"]*)\"/i",$video,$h); $h = (integer)$h[1];
  1025. if (!$new_width) $new_width = $w;
  1026. $w2 = $new_width;
  1027. $ratio = (float)($w2/$w);
  1028. $h2 = (integer)($h * $ratio);
  1029. $video = str_replace("width=\"$w\"","width=\"$w2\"",$video);
  1030. $video = str_replace("height=\"$h\"","height=\"$h2\"",$video);
  1031. //return array("embed"=>$video,"w"=>$w2,"h"=>$h2,"w0"=>$w,"h0"=>$h);
  1032. return $video;
  1033. }
  1034. }
  1035. ?>