Advertisement
marongiuchristian93

Usare CSE al posto di GSS nel proprio sito

Jan 21st, 2018
689
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 10.17 KB | None | 0 0
  1. <?php
  2. # @author: Christian Marongiu
  3. # @version: v1.1.3
  4.  
  5. class SearchEngine {
  6.  public $cx=''; # CSE Engine ID
  7. public $apikey=''; # CSE API Key
  8. public $start=0; # CSE parameter to define which page to start from
  9. public $q=''; # Search query
  10. public $num=10; # Results per page
  11. public $url='';
  12.  public $json='';
  13.  public $results=[]; # Normal results
  14. public $promo=[]; # Promoted results
  15. public $multilang=FALSE;
  16.  public $data='';
  17.  public $selpage=1; # Selected results page
  18. public $message=''; # String of message to present the user about the success of his query
  19. public $strings=[]; # Array of translated strings
  20. public $totalResults=0; # Total of normal search results
  21. public $submit_name='send'; # Input submit name
  22. public $reqInfo=''; # Object containing general data about the request: data->queries
  23. public $searchInfo=''; # Object with more info about the research, like search time and total results;
  24. public $lang='it'; # Engine default language
  25.  
  26.  function __construct($cx,$apikey,$lang='it',$multilang=FALSE,$q='',$submit='send',$start=-1,$num=10) {
  27.   if($cx) $this->cx=$cx;
  28.   if($apikey) $this->apikey=$apikey;
  29.   if((int)$start>=0) $this->start=$start; else $this->start=(isSet($_GET['start'])?(int)$_GET['start']:0);
  30.   if($this->start<0) $this->start=0; elseif($this->start>90) $this->start=90; # Start maximum at 90 (10th page)
  31.  if($q!='') $this->q=trim($q); elseif($_GET['q']) $this->q=trim($_GET['q']); # Avoid XSS Injection
  32.  if((int)$num>=0) $this->num=$num; else $this->num=10;
  33.   if($this->num>50) $this->num=50; # Max 50 results per page
  34.  if($multilang) $this->multilang=TRUE;
  35.   if($lang!='') $this->lang=$lang;
  36.   if($this->q && $this->q!='') { # User sent a query
  37.   $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;
  38.    $this->selpage=(int)floor($this->start/10)+1;
  39.    $this->json=file_get_contents($this->url);
  40.    if($this->json) $this->data=json_decode($this->json); # JSON search results provided by Google Cloud Search API
  41.   if($this->data->queries) $this->reqInfo=$this->data->queries;
  42.    if($this->data->searchInformation) $this->searchInfo=$this->data->searchInformation;
  43.    if($this->data->items) $this->results=$this->data->items;
  44.    if($this->data->promotions) $this->promo=$this->data->promotions;
  45.    if((int)$this->searchInfo->totalResults>0) $this->totalResults=(int)$this->searchInfo->totalResults;
  46.    if(isSet($this->promo) && count($this->promo)>0) $this->totalResults+=count($this->promo); # Adding number of promo results to number of normal results
  47.   if($submit) $this->submit_name=$submit; else $this->submit_name='send';
  48.   }
  49.  }
  50.  
  51.  public function translate($id=0,$lang='') {
  52.   if($lang=='' && $this->lang!='') $lang=$this->lang;  # Set language if custom language is set by Class
  53.  $strings=[
  54.    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'=>'Ничего не найдено по Вашему запросу'],
  55.    2=>['it'=>'Altri risultati','en'=>'Other results','es'=>'Otros resultados','de'=>'Weitere Ergebnisse','fr'=>'Autres résultats','ru'=>'Другие результаты поиска'],
  56.    3=>['it'=>'Risultati trovati per','en'=>'Results found for'],
  57.    4=>['it'=>'risultato','en'=>'result'],
  58.    5=>['it'=>'risultati','en'=>'results'],
  59.    6=>['it'=>'Nessun risultato','en'=>'No results','es'=>'Ningún resultado','de'=>'Kein Ergebnis','fr'=>'Aucun résultat','ru'=>'Ничего не найдено'],
  60.    7=>['it'=>'Trova nel sito','en'=>'Search website','es'=>'Encontrar en la web','de'=>'Auf der Website suchen','fr'=>'Trouver dans le site','ru'=>'Найти на сайте'],
  61.    8=>['it'=>'Cerca','en'=>'Search','es'=>'Buscar','de'=>'Suchen','fr'=>'Rechercher','ru'=>'Поиск']
  62.   ];
  63.   if($id>0 && isSet($strings[$id][$lang])) return $strings[$id][$lang];
  64.   else return '';
  65.  }
  66.  
  67.  public function render_promoResults($class='result result-promo') {
  68.   $pprint=''; $ptot=0;
  69.   if(isSet($this->promo) && count($this->promo)>0) { # If there are promo results I build html
  70.  $ptot=count($this->promo); # Total number of promo results
  71.   foreach($this->promo as $pNum=>$pData) {
  72.     if(($pfoto=$pData->pagemap->cse_image[0]->src)!='') $pimg='<div class="rimg"><img src="'.$pfoto.'" /></div>'."\n";
  73.     else $pimg='';
  74.     $ptitle='<h3 class="rtitle">'.$pData->title."</h3>\n";
  75.     $plink='<a class="link" href="'.$pData->link.'">'.$pData->title."</a>\n";
  76.     $pwww='<a class="www" href="'.$pData->link.'">'.$pData->link."</a>\n";
  77.     if($pData->bodyLines[0]->title) $psnippet='<p class="rsnippet">'.$pData->bodyLines[0]->title."</p>\n"; # Promoted result description is not mandatory
  78.    else $psnippet='';
  79.     $pprint.='<div class="'.$class.'">'.$pimg.'<div class="rtext">'.$plink.$psnippet.$pwww."</div>\n</div>\n";
  80.    }
  81.   }
  82.   return $pprint;
  83.  }
  84.  
  85.  public function render_normalResults($class='result') {
  86.   $rprint='';
  87.   if(isSet($this->results)&&$this->totalResults>0) { # If there are normal results (not promoted)
  88.   foreach($this->results as $resNum=>$resData) {
  89.     if(($rphoto=$resData->pagemap->cse_image[0]->src)!='') $rimg='<div class="rimg"><img src="'.$rphoto.'" /></div>'."\n";
  90.     else $rimg='';
  91.     $rtitle='<h3 class="rtitle">'.$resData->title."</h3>\n";
  92.     $rlink='<a class="link" href="'.$resData->link.'">'.$resData->title."</a>\n";
  93.     $rwww='<a class="www" href="'.$resData->link.'">'.$resData->link."</a>\n";
  94.     $rsnippet='<p class="rsnippet">'.$resData->htmlSnippet."</p>\n";
  95.     $rprint.='<div class="'.$class.'">'.$rimg.'<div class="rtext">'.$rlink.$rsnippet.$rwww."</div>\n</div>\n";
  96.    }
  97.   }
  98.   return $rprint;
  99.  }
  100.  
  101.  public function render_pager() {
  102.   $pages='';
  103.   if($this->totalResults>10) $pagenum=(int)ceil($this->totalResults/10); else $pagenum=1;
  104.   if($pagenum>10) $pagenum=10; # Maximum 10 pages
  105.  if($pagenum>1) { # No need for pager with only 1 page
  106.   $pages='<div class="search-results-pager">'."\n";
  107.    $pages.='<p>'.$this->translate(2).":</p>\n";
  108.    for($p=1;$p<=$pagenum;$p++)
  109.     $pages.='<a href="'.$_SERVER['PHP_SELF'].'?q='.htmlspecialchars($this->q).'&amp;start='.($p==1?'':$p-1).'0&amp;send=Cerca"'.(($p==$this->selpage)?' class="selpage"':'').'>'.$p."</a>\n";
  110.    $pages.="</div>\n";
  111.   }
  112.   return $pages;
  113.  }
  114.  
  115.  public function render_form($id='form-search',$action='',$method='get') {
  116.   if($action=='') $action=$_SERVER['SCRIPT_NAME'];
  117.   $form='';
  118.   $form.='<form id="'.$id.'" action="'.$action.'" method="'.$method.'">'."\n";
  119.   $form.='<input type="text" name="q" placeholder="'.$this->translate(7).'"'.($this->q?' value="'.htmlspecialchars($this->q).'"':'').' />'."\n";
  120.   $form.='<input type="submit" name="'.$this->submit_name.'" value="'.$this->translate(8).'" />'."\n";
  121.   $form.="</form>\n";
  122.   return $form;
  123.  }
  124.  
  125.  public function initEngine() { return $this->html; } # If you want to use this instead of __toString, and then you print it with: $cse->initEngine();
  126.  
  127.  function __toString() { # Eventually change it with public function initEngine()
  128.  if(isSet($_REQUEST[$this->submit_name])) { # Form correctly submitted
  129.   $this->html.='<div class="search-results">'."\n";
  130.    if($this->q && $this->q!='') { # User sent a query
  131.    if($this->totalResults>0) {
  132.      $this->html.='<h2>'.$this->translate(3).': <em>'.htmlspecialchars($this->q).'</em></h2>';
  133.      $this->html.='<p class="rnum">'.($this->totalResults==1?'1 '.$this->translate(4):$this->totalResults.' '.$this->translate(5))."</p>\n";
  134.     } else $this->html.='<p class="rnum">'.$this->translate(6)."</p>\n";
  135.    } else $this->html.='<p class="rnum">'.$this->translate(1)."</p>\n"; # No search term specified
  136.   $this->html.=$this->render_promoResults();
  137.    $this->html.=$this->render_normalResults();
  138.    $this->html.=$this->render_pager();
  139.    $this->html.="</div>\n";
  140.    return $this->html;
  141.   }
  142.   return '';
  143.  }
  144. }
  145.  
  146. #$cx="xxx";
  147. #$apikey="yyy";
  148. #$cse=new SearchEngine($cx,$apikey);
  149. # To print form and results: echo $cse->render_form(); and echo $cse;
  150. ?>
  151.  
  152. <!DOCTYPE html>
  153. <html>
  154. <head>
  155.  <link rel="stylesheet" href="cse.css" />
  156.  <style type="text/css">
  157. .custom-search-engine { background-color:#FFF; }
  158.  #form-search { width:100%; }
  159.  #form-search input { max-width:100%; display:inline-block; }
  160.  #form-search input[type="text"] { border:1px solid #000; width:75%; height:42px; color:#000; padding:5px; font-size:15px; }
  161.  #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%; }
  162.  .result:before,.result:after { display:block; clear:both; content:""; }
  163.  .result { border-top:1px dotted #CCC; margin:10px 0; padding:10px 0; }
  164.  .result a { display:block; width:100%; margin-bottom:5px; font-weight:normal; color:#C12724; }
  165.  .result a.www { font-size:12px; display:block; text-overflow:ellipsis; overflow:hidden; white-space:nowrap; }
  166.  .result img { width:auto; max-width:100%; border:1px solid #000; }
  167.  .rsnippet { font-weight:normal; margin:0; }
  168.  .rsnippet br { display:none; }
  169.  .rnum { padding-bottom:10px; }
  170.  .rtext { width:100%; display:block; }
  171.  .rimg,.rimg+.rtext { display:inline-block; vertical-align:top; }
  172.  .rimg { width:10%; margin-right:10px; }
  173.  .rimg+.rtext { width:calc(85% - 10px); }
  174.  .result:first-child { border-top:none; margin-top:0; }
  175.  .search-results-pager { border-top:1px solid #000; width:100%; padding:10px 0; }
  176.  .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; }
  177.  .search-results-pager a:hover { background-color:#FFF; color:#000; transition:background-color .5s,color .5s; text-decoration:none; }
  178.  .search-results-pager .selpage { color:#000; background-color:#FFF; border:1px solid #C12724; font-weight:bold; }
  179.  </style>
  180. </head>
  181. <body>
  182. <?php require_once('cse.php') ?>
  183. <article class="custom-search-engine">
  184. <h1>CSE Search Engine</h1>
  185. <?php
  186. echo $cse->render_form();
  187. echo $cse;
  188. ?>
  189. </article>
  190. </body>
  191. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement