Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- # @author: Christian Marongiu
- # @version: v1.1.3
- class SearchEngine {
- public $cx=''; # CSE Engine ID
- public $apikey=''; # CSE API Key
- public $start=0; # CSE parameter to define which page to start from
- public $q=''; # Search query
- public $num=10; # Results per page
- public $url='';
- public $json='';
- public $results=[]; # Normal results
- public $promo=[]; # Promoted results
- public $multilang=FALSE;
- public $data='';
- public $selpage=1; # Selected results page
- public $message=''; # String of message to present the user about the success of his query
- public $strings=[]; # Array of translated strings
- public $totalResults=0; # Total of normal search results
- public $submit_name='send'; # Input submit name
- public $reqInfo=''; # Object containing general data about the request: data->queries
- public $searchInfo=''; # Object with more info about the research, like search time and total results;
- public $lang='it'; # Engine default language
- function __construct($cx,$apikey,$lang='it',$multilang=FALSE,$q='',$submit='send',$start=-1,$num=10) {
- if($cx) $this->cx=$cx;
- if($apikey) $this->apikey=$apikey;
- if((int)$start>=0) $this->start=$start; else $this->start=(isSet($_GET['start'])?(int)$_GET['start']:0);
- if($this->start<0) $this->start=0; elseif($this->start>90) $this->start=90; # Start maximum at 90 (10th page)
- if($q!='') $this->q=trim($q); elseif($_GET['q']) $this->q=trim($_GET['q']); # Avoid XSS Injection
- if((int)$num>=0) $this->num=$num; else $this->num=10;
- if($this->num>50) $this->num=50; # Max 50 results per page
- if($multilang) $this->multilang=TRUE;
- if($lang!='') $this->lang=$lang;
- if($this->q && $this->q!='') { # User sent a query
- $this->url='https://www.googleapis.com/customsearch/v1?q='.urlencode($this->q).'&num='.$this->num.'&start='.($this->start?$this->start:1).'&cx='.$this->cx.'&key='.$this->apikey;
- $this->selpage=(int)floor($this->start/10)+1;
- $this->json=file_get_contents($this->url);
- if($this->json) $this->data=json_decode($this->json); # JSON search results provided by Google Cloud Search API
- if($this->data->queries) $this->reqInfo=$this->data->queries;
- if($this->data->searchInformation) $this->searchInfo=$this->data->searchInformation;
- if($this->data->items) $this->results=$this->data->items;
- if($this->data->promotions) $this->promo=$this->data->promotions;
- if((int)$this->searchInfo->totalResults>0) $this->totalResults=(int)$this->searchInfo->totalResults;
- if(isSet($this->promo) && count($this->promo)>0) $this->totalResults+=count($this->promo); # Adding number of promo results to number of normal results
- if($submit) $this->submit_name=$submit; else $this->submit_name='send';
- }
- }
- public function translate($id=0,$lang='') {
- if($lang=='' && $this->lang!='') $lang=$this->lang; # Set language if custom language is set by Class
- $strings=[
- 1=>['it'=>'Nessun termine di ricerca inserito','en'=>'No search term entered','es'=>'No se ha introducido ningún término de búsqueda','de'=>'Keinen Suchbegriff eingegeben','fr'=>'Aucun terme de recherche saisi','ru'=>'Ничего не найдено по Вашему запросу'],
- 2=>['it'=>'Altri risultati','en'=>'Other results','es'=>'Otros resultados','de'=>'Weitere Ergebnisse','fr'=>'Autres résultats','ru'=>'Другие результаты поиска'],
- 3=>['it'=>'Risultati trovati per','en'=>'Results found for'],
- 4=>['it'=>'risultato','en'=>'result'],
- 5=>['it'=>'risultati','en'=>'results'],
- 6=>['it'=>'Nessun risultato','en'=>'No results','es'=>'Ningún resultado','de'=>'Kein Ergebnis','fr'=>'Aucun résultat','ru'=>'Ничего не найдено'],
- 7=>['it'=>'Trova nel sito','en'=>'Search website','es'=>'Encontrar en la web','de'=>'Auf der Website suchen','fr'=>'Trouver dans le site','ru'=>'Найти на сайте'],
- 8=>['it'=>'Cerca','en'=>'Search','es'=>'Buscar','de'=>'Suchen','fr'=>'Rechercher','ru'=>'Поиск']
- ];
- if($id>0 && isSet($strings[$id][$lang])) return $strings[$id][$lang];
- else return '';
- }
- public function render_promoResults($class='result result-promo') {
- $pprint=''; $ptot=0;
- if(isSet($this->promo) && count($this->promo)>0) { # If there are promo results I build html
- $ptot=count($this->promo); # Total number of promo results
- foreach($this->promo as $pNum=>$pData) {
- if(($pfoto=$pData->pagemap->cse_image[0]->src)!='') $pimg='<div class="rimg"><img src="'.$pfoto.'" /></div>'."\n";
- else $pimg='';
- $ptitle='<h3 class="rtitle">'.$pData->title."</h3>\n";
- $plink='<a class="link" href="'.$pData->link.'">'.$pData->title."</a>\n";
- $pwww='<a class="www" href="'.$pData->link.'">'.$pData->link."</a>\n";
- if($pData->bodyLines[0]->title) $psnippet='<p class="rsnippet">'.$pData->bodyLines[0]->title."</p>\n"; # Promoted result description is not mandatory
- else $psnippet='';
- $pprint.='<div class="'.$class.'">'.$pimg.'<div class="rtext">'.$plink.$psnippet.$pwww."</div>\n</div>\n";
- }
- }
- return $pprint;
- }
- public function render_normalResults($class='result') {
- $rprint='';
- if(isSet($this->results)&&$this->totalResults>0) { # If there are normal results (not promoted)
- foreach($this->results as $resNum=>$resData) {
- if(($rphoto=$resData->pagemap->cse_image[0]->src)!='') $rimg='<div class="rimg"><img src="'.$rphoto.'" /></div>'."\n";
- else $rimg='';
- $rtitle='<h3 class="rtitle">'.$resData->title."</h3>\n";
- $rlink='<a class="link" href="'.$resData->link.'">'.$resData->title."</a>\n";
- $rwww='<a class="www" href="'.$resData->link.'">'.$resData->link."</a>\n";
- $rsnippet='<p class="rsnippet">'.$resData->htmlSnippet."</p>\n";
- $rprint.='<div class="'.$class.'">'.$rimg.'<div class="rtext">'.$rlink.$rsnippet.$rwww."</div>\n</div>\n";
- }
- }
- return $rprint;
- }
- public function render_pager() {
- $pages='';
- if($this->totalResults>10) $pagenum=(int)ceil($this->totalResults/10); else $pagenum=1;
- if($pagenum>10) $pagenum=10; # Maximum 10 pages
- if($pagenum>1) { # No need for pager with only 1 page
- $pages='<div class="search-results-pager">'."\n";
- $pages.='<p>'.$this->translate(2).":</p>\n";
- for($p=1;$p<=$pagenum;$p++)
- $pages.='<a href="'.$_SERVER['PHP_SELF'].'?q='.htmlspecialchars($this->q).'&start='.($p==1?'':$p-1).'0&send=Cerca"'.(($p==$this->selpage)?' class="selpage"':'').'>'.$p."</a>\n";
- $pages.="</div>\n";
- }
- return $pages;
- }
- public function render_form($id='form-search',$action='',$method='get') {
- if($action=='') $action=$_SERVER['SCRIPT_NAME'];
- $form='';
- $form.='<form id="'.$id.'" action="'.$action.'" method="'.$method.'">'."\n";
- $form.='<input type="text" name="q" placeholder="'.$this->translate(7).'"'.($this->q?' value="'.htmlspecialchars($this->q).'"':'').' />'."\n";
- $form.='<input type="submit" name="'.$this->submit_name.'" value="'.$this->translate(8).'" />'."\n";
- $form.="</form>\n";
- return $form;
- }
- public function initEngine() { return $this->html; } # If you want to use this instead of __toString, and then you print it with: $cse->initEngine();
- function __toString() { # Eventually change it with public function initEngine()
- if(isSet($_REQUEST[$this->submit_name])) { # Form correctly submitted
- $this->html.='<div class="search-results">'."\n";
- if($this->q && $this->q!='') { # User sent a query
- if($this->totalResults>0) {
- $this->html.='<h2>'.$this->translate(3).': <em>'.htmlspecialchars($this->q).'</em></h2>';
- $this->html.='<p class="rnum">'.($this->totalResults==1?'1 '.$this->translate(4):$this->totalResults.' '.$this->translate(5))."</p>\n";
- } else $this->html.='<p class="rnum">'.$this->translate(6)."</p>\n";
- } else $this->html.='<p class="rnum">'.$this->translate(1)."</p>\n"; # No search term specified
- $this->html.=$this->render_promoResults();
- $this->html.=$this->render_normalResults();
- $this->html.=$this->render_pager();
- $this->html.="</div>\n";
- return $this->html;
- }
- return '';
- }
- }
- #$cx="xxx";
- #$apikey="yyy";
- #$cse=new SearchEngine($cx,$apikey);
- # To print form and results: echo $cse->render_form(); and echo $cse;
- ?>
- <!DOCTYPE html>
- <html>
- <head>
- <link rel="stylesheet" href="cse.css" />
- <style type="text/css">
- .custom-search-engine { background-color:#FFF; }
- #form-search { width:100%; }
- #form-search input { max-width:100%; display:inline-block; }
- #form-search input[type="text"] { border:1px solid #000; width:75%; height:42px; color:#000; padding:5px; font-size:15px; }
- #form-search input[type="submit"] { border:1px solid #000; background-color:#C12724; color:#FFF; font-weight:bold; height:42px; padding:5px; font-size:15px; margin-left:-5px; width:25%; }
- .result:before,.result:after { display:block; clear:both; content:""; }
- .result { border-top:1px dotted #CCC; margin:10px 0; padding:10px 0; }
- .result a { display:block; width:100%; margin-bottom:5px; font-weight:normal; color:#C12724; }
- .result a.www { font-size:12px; display:block; text-overflow:ellipsis; overflow:hidden; white-space:nowrap; }
- .result img { width:auto; max-width:100%; border:1px solid #000; }
- .rsnippet { font-weight:normal; margin:0; }
- .rsnippet br { display:none; }
- .rnum { padding-bottom:10px; }
- .rtext { width:100%; display:block; }
- .rimg,.rimg+.rtext { display:inline-block; vertical-align:top; }
- .rimg { width:10%; margin-right:10px; }
- .rimg+.rtext { width:calc(85% - 10px); }
- .result:first-child { border-top:none; margin-top:0; }
- .search-results-pager { border-top:1px solid #000; width:100%; padding:10px 0; }
- .search-results-pager a { display:inline-block; margin:5px 3px; font-size:14px; font-weight:normal; color:#FFF; padding:10px; background-color:#C12724; border:1px solid #000; transition:background-color .5s,color .5s; text-decoration:none; }
- .search-results-pager a:hover { background-color:#FFF; color:#000; transition:background-color .5s,color .5s; text-decoration:none; }
- .search-results-pager .selpage { color:#000; background-color:#FFF; border:1px solid #C12724; font-weight:bold; }
- </style>
- </head>
- <body>
- <?php require_once('cse.php') ?>
- <article class="custom-search-engine">
- <h1>CSE Search Engine</h1>
- <?php
- echo $cse->render_form();
- echo $cse;
- ?>
- </article>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement