Location: PHPKode > projects > Simple Way to Usenet > swun/libs/swun/search/search_nbrid.class.php
<?php
/**
 *  
 * @author  Benjamin Gillissen <hide@address.com>
 * 
 *	**************************************************************

	Copyright (C) 2009  Benjamin Gillissen
	
	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details at:
	http://www.gnu.org/copyleft/gpl.html

 *	**************************************************************
 */
class search_nbrid {
	
	const base_url 	= 'https://v3.newzbin.com/';
	private static $uris = Array ( 	0 => Array(	0 => 'search/query/?q=%_SEARCH_%&area=-1&fpn=p&searchaction=Go&areadone=-1&feed=rss',
												1 => 'search/query/?area=-1&fpn=p&searchaction=Go&areadone=-1&feed=rss'),
									2 => Array(	0 => 'search/query/?q=%_SEARCH_%&fpn=p&area=c.%_ID_%&searchaction=Go&category=%_ID_%&areadone=c.%_ID_%&feed=rss',
												1 => 'search/query/?area=c.%_ID_%&fpn=p&searchaction=Go&category=%_ID_%&areadone=c.%_ID_%&feed=rss'),
									3 => Array(	0 => 'search/query/?q=%_SEARCH_%&searchaction=Go&grouplist=%_ID_%&feed=rss',
												1 => 'browse/grouplist/p/%_ID_%/?feed=rss'),
									4 => 'browse/category/p/%_MAIN_%/?ps_rb_%_ATTR_%=%_ID_%&feed=rss',
									5 => Array(	0 => 'search/?q=%_SEARCH_%&searchaction=Search&fpn=p&group=%GROUPS%&category=-1&sort=ps_edit_date&order=desc&feed=rss&areadone=-1',
												1 => 'search/?searchaction=Search&fpn=p&group=%GROUPS%&category=-1&sort=ps_edit_date&order=desc&feed=rss&areadone=-1')
								);
	public $engine = 'nbrid';
	private static $_CACHE;		//nb_cache_xxx object
	private static $types = Array('all', 'adv', 'bycats', 'bygl', 'bysubcats', 'bygrp');	//the search types
	private $url;				//once send, used to fetch, FIXME resupport crossed search call/fetch with hash arg ;)
	
	public function __construct(){
		if ( isset(self::$_CACHE) ){ return; }
		$cachetype = configs::get('newzbinv2', 'cachetype');
		$class = 'nb_cache_'.$cachetype;
		self::$_CACHE = new $class();	
	}
	
	public function arg_rewrite($type, $cat, $filter){
		$o['type'] = $type;
		$o['cat'] = $cat;
		$o['filter'] = $filter;
		if ( $type == '1' ) {
			if ( $cat == '0' ){ 
				if ( !isset($_POST['search_filter']) ){ $o['filter'] = sessions::read('last_advfilter', 'profile'); }
			} elseif ( !isset($_POST['search_filter']) ){
				$prof = new profile('site_profile');
				$adv = $prof->read('savedadv');
				if ( isset($adv[$cat]) ){
					$o['filter'] = $adv[$cat]['filter']; 
				}
				unset($prof, $adv);
			}
		} elseif ($type == 3 OR $type == 4 ){
			 $o['filter'] = '';
		}
		return $o;
	}
	
	public function get_types(){ return self::$types; }
	
	public function get_default_type(){ return 0; }
	
	public function type_isvalid($type){ return isset(self::$types[$type]); }
	
	public function type_use_filter($type){
		//not for grouplist and subcats
		return ( $type != 3 AND $type != 4 ); 
	}

	public function type_got_cats($type){ return ($type != 0); }
	
	/* ORDERED feature....
	public function type_use_order($type){ return ($type != 0); }
	
	public function get_orders($type){ return ($type != 0); }
	
	public function order_isvalid($type, $order){ return ($type != 0); }
	*/
	
	public function get_cats($type){
		switch($type){
			case 1 : $o[0] = 'Last';
					 $prof = new profile('site_profile');
					 $tmp = $prof->read('savedadv');
					 //$tmp = sessions::read('savedadv', 'profile');
					 break;
			case 2 : $tmp = configs::get('newzbinv2', 'cats');
					 //foreach($tmp as $k => &$cat){ $cat['name'] = langs::dico_translate("cat_".$cat['name'], NULL, "search"); }
					 break;
			case 3 : $tmp = configs::get('newzbinv2', 'grouplist');
					 break;
			case 4 : $tmp = configs::get('newzbinv2', 'subcats');
					 break; 
			case 5 : $prof = new profile('site_profile');
					 $tmp = $prof->read('savedgrp');
					 unset($prof);
					 break;
		}
		if ( !is_array($tmp) ){
			if ( isset($o) ){ return $o; } 
			return FALSE; 
		}
		foreach($tmp as $k => &$cat){ $o[$k] = $cat['name']; }
		if ( isset($o) ){ return $o; }
		return FALSE; 
	}
	
	public function get_default_cat($type){ return 0; }
	
	public function cat_isvalid($type, $cat){ 	
		switch($type){
			case 1 : //is user saved advsearch ?
					 break;
			case 2 : return (FALSE !== configs::get('newzbinv2', 'cats', $cat) );
					 break;
			case 3 : return (FALSE !== configs::get('newzbinv2', 'grouplist', $cat) );
					 break;
			case 4 : //is sub cat valid ?
					 break;
			case 5 : //is user savedgrp ?
					 break; 
					 
		}
		return TRUE;
	}
	
	public function cat_use_filter($type, $cat){ 
		return ($type != 4); 
	}
	
	
	
	private function buildadvurl($vars, $filter=FALSE){
		$url = 'search/';
		if ( $filter ){ $url .= '?q=%_SEARCH_%'; }
		$c=0;
		foreach($vars as $k => $val){
			if ( !empty($val) ){
				if ( !$filter AND $c == 0 ){ $pre = '?'; } else { $pre='&'; }
				if ( !is_array($val) ){
					$url .= $pre.$k.'='.urlencode($val);
				} else {
					$sum=0;
					foreach($val as $ids){ $sum += $ids; }
					$url .= $pre.$k.'='.$sum;
				}
				$c++;
			}
		}
		return $url.'&feed=rss&areadone=-1';
	}
		
	private function buildurl($str, $type, $cat){
		switch($type){
			//set url base, and var to insert
			case 0 : $url = self::$uris[0][empty($str)]; 
					 break;
			case 1 : $filter = !empty($str);
					 if ( $cat === '0' ){
						//last, so posted or in sess, or default
						if ( isset($_POST['nbadvsearch']) ){
							//build url from posted vars
							unset($_POST['nbadvsearch'], $_POST['saveadvas'], $_POST['advname'], $_POST['search_filter'], $_POST['savedadv']);
							//errors::raise('Posted advsearch vars : '.print_r($_POST, TRUE), CORE_LOG_NOTICE, 'SEARCH');
							$vars = $_POST;
							sessions::set('last_advsearch', $vars, 'profile');
							sessions::set('last_advfilter', $str, 'profile');
						} elseif ( sessions::isdefined('last_advsearch', 'profile') ){
							//build session or default vars.
							$vars = sessions::read('last_advsearch', 'profile');
							//errors::raise('Last advsearch vars : '.print_r($vars, TRUE), CORE_LOG_NOTICE, 'SEARCH');
							sessions::set('last_advfilter', $str, 'profile');
						} else {
							pagegen::add_event('First, you must send an advanced search before getting results ;)');
							errors::raise('NBRID avanced default search is not working yet ', CORE_LOG_ERROR, 'NB');
							return FALSE;
						}
					 } else {
					 	//errors::raise('NBRID : Saved advsearch '.$cat, CORE_LOG_NOTICE, 'NB');
					 	$prof = new profile('site_profile');
					 	$adv = $prof->read('savedadv');
					 	if ( !isset($adv[$cat]) ){ return FALSE; }
					 	$vars = $adv[$cat]['vars'];
					 	unset($prof);
					 }
					 $url = $this->buildadvurl($vars, $filter);
					 sessions::set('last_advsearch', $vars, 'profile');
					 sessions::set('last_advfilter', $str, 'profile');
					 break;
			case 2 : $data['ID'] = configs::get('newzbinv2', 'cats', Array($cat, 'arg'));
					 if ( FALSE === $data['ID'] ){ return FALSE; }
					 $url = self::$uris[2][empty($str)];
					 break;
			case 3 : $data['ID'] = configs::get('newzbinv2', 'grouplist', Array($cat, 'arg'));
					 if ( FALSE === $data['ID'] ){ return FALSE; }
					 $url = self::$uris[3][1];//fixe no filter 
					 break;
			case 4 : $data = configs::get('newzbinv2', 'subcats', Array($cat, 'arg'));
					 if ( FALSE === $data ){ return FALSE; }
					 $url = self::$uris[4];
					 break; 
		    case 5 : $prof = new profile('site_profile');
					 $tmp = $prof->read('savedgrp');
					 unset($prof);
					 if ( !isset($tmp[$cat]) ){ return FALSE; }
					 $buf = split("\n", $tmp[$cat]['grp']);
					 unset($tmp);
					 foreach($buf as $k => &$v){ $v = trim($v); }
					 $buf = implode(',', $buf);
					 $url = self::$uris[5][empty($str)];
					 $url = str_replace('%GROUPS%', rawurlencode($buf), $url);
					 break;
		}
		if ( !isset($url) ){ return FALSE; }
		//replace vars into url, return url
		if (isset($data) ){
			foreach($data as $k => &$val ){ $url = str_replace('%_'.$k.'_%', $val, $url); }
		}
		if ( !empty($str) ){ 
			$url = str_replace('%_SEARCH_%', rawurlencode($str), $url); 
		}
		$url = self::base_url.$url;
		errors::raise('NBRID Search is using url: '.$url, CORE_LOG_NOTICE, 'NB');
		//QUICKFIX since 21/07/2009 rss feed require http digest auth, curl is taking care of that ;)
		$user = configs::get('newzbinv2', 'user');
		$pass = configs::get('newzbinv2', 'pass');
		return str_replace('https://', "https://$user:$pass@", $url);
	}
	
	
	
	public function send($search, $type, $cat){
		$url = $this->buildurl($search, $type, $cat);
		if ( FALSE === $url ){
			errors::raise('Newzbin Search URL Could not be build !', CORE_LOG_ERROR, 'SEARCH'); 
			return FALSE; 
		}
		if ( self::$_CACHE->isexpired('search', $url) ){
			$file = nb_fetch::request($url, TRUE);	//return tmp filepath
			if ( FALSE === $file ){ return FALSE; }
			$rss = new nb_rssv2($file);
			$c=0;	//# search item
			$r=0;	//# report updated
			$a=0;
			self::$_CACHE->drop_results($url);
			while( FALSE !== ($report = $rss->fetch_items(FALSE)) ){
				if ( self::$_CACHE->import_result($url, $report['id']) ){
					if ( self::$_CACHE->iscached('report', $report['id']) ){ self::$_CACHE->drop_report($report['id']);$r++; }
					if ( self::$_CACHE->import_report($report['id'], $report) ){ $a++; }
				}
				$c++;
			}
			errors::raise('Newzbin Search is expired : '.$r. ' items updated,'.$a.' added, on '.$c.' found', CORE_LOG_DEBUG, 'NB');
			unset($rss);
			unlink($file);
		} else {
			errors::raise('Newzbin Search is cached', CORE_LOG_DEBUG, 'NB');
		}
		$this->url = $url;
		return TRUE;
	}
	
	public function count($hash){
		if ( !isset($this->url) ){ return 0; }
		return self::$_CACHE->count_results($this->url);
	}
	
	public function fetch($hash, $start, $end){
		if ( !isset($this->url) ){ return FALSE; }
		$nbrid = self::$_CACHE->fetch_results($this->url, $start, $end);
		if ( FALSE === $nbrid ){ return FALSE; }
		return $this->get_details($nbrid);
	}
	
	public function get_details($nbrid){
		$out = self::$_CACHE->get_report($nbrid);
		if ( FALSE === $out ){ return Array('id'=>$nbrid, 'gotdetails'=>FALSE);	}
		if ( isset($out['size']) ){ 
			$s = CORE::Byteconvert($out['size']);
			$out['size'] = langs::number($s[0], $s[2]).'&nbsp;'.$s[1]; 
		}
		return $out;
	}
		
	public function get_nfo($reportid){
		if ( self::$_CACHE->isexpired('nfo', $reportid) ){
			$details = self::$_CACHE->get_report($reportid);
			if ( FALSE === $details ){ 
				errors::raise('Newzbin Report is not cached or do not have nfo key defined', CORE_LOG_ALERT, 'NB');
				return FALSE; 
			}
			$nfo = nb_fetch::getnfo($details['nfoid'], '');
			if ( FALSE === $nfo ){ return FALSE; }
			if ( ! self::$_CACHE->import_nfo($reportid, $nfo) ){ 
				errors::raise('NFO could not be imported to cache', CORE_LOG_WARNING, 'NB');
			}
			return $nfo;
		}
		return self::$_CACHE->read_nfo($reportid, $file);
	}
}
return TRUE;
Return current item: Simple Way to Usenet