<?php
/* getpub
 * Author : Frédéric MAIRE
 * Parameters :
 *   idx : the pub index. if 0 then a rancom idx is get. 
 *     the max for the index is set in this script for performance : maxIdx
 *   ww : the width of banners we seek (ignored if idx!=0)
 *   hh : the height of banners we seek (ignored if idx!=0)
 * Return :
 *  javascript that produce html with an image of the pub with a link to the go_pub.php3 script
 */
require("inc_base.php3");

function jsprint($s) {
//  $s = ereg_replace( '"', '\"', $s);
  printf( "%s\n", "document.writeln('".$s."');" );
}

  // open database to find image ref and add a view
  mysql_Connect($hostname,$username,$password) or die("Could not connect on database server.");
  mysql_Select_Db($dbname) or die("erreur acces BD");

  $query = "SELECT idx,banner_url,banner_msg,banner_width,banner_height,view,special,weight FROM pub WHERE ";  
  if ($idx==0) {
    $query = $query . "weight>0 AND idx>2000"; // is_active=1
    if ($ww!=0) $query = $query . " AND banner_width=$ww"; 
    if ($hh!=0) $query = $query . " AND banner_height=$hh"; 
  } else {
    $query = $query . "idx=$idx";
  }
  $query_res = mysql_query($query); 
  $query_res_rows = mysql_num_rows($query_res);

  if ($query_res_rows!=0) {
  if ($idx == 0) {
    // compute the sum of weight
    $sw = 0;
    for ($i=0; $i<$query_res_rows; $i++) { $sw += mysql_result($query_res,$i,"weight"); }
    //
    srand((double)microtime()*1000000);
    if ($query_res_rows>1) $widx = rand(0,$sw-1)+1; else $cidx=0;
    $sw = 0; 
    for ($cidx=0; $cidx<$query_res_rows; $cidx++) { 
      $sw += mysql_result($query_res,$cidx,"weight"); 
      if ($sw>=$widx) break;
    }
    $idx = mysql_result($query_res,$cidx,"idx");
  } else {
    $cidx = 0;
  }
  $banner_url = mysql_result($query_res,$cidx,"banner_url");
  $banner_msg = mysql_result($query_res,$cidx,"banner_msg");
  $banner_width = mysql_result($query_res,$cidx,"banner_width");
  $banner_height = mysql_result($query_res,$cidx,"banner_height");
  $special = mysql_result($query_res,$cidx,"special");
  $view =  mysql_result($query_res,$cidx,"view");

  // update the view counter
  $view = $view + 1;
  $query = "UPDATE pub SET view=$view WHERE idx=".$idx;
  mysql_query($query);

  } else {
    $banner_url = "";
    $special = "";
  }

  mysql_Close();

  // produce code
  if ($banner_url != "") {
    jsprint( '<a target="_blank" href="http://www.interjeux.net/php/go_pub.php3?idx='.$idx.'">' .
             '<img src="'.$banner_url.'" alt="'.$banner_msg.'" border=0 width='.$banner_width.' height='.$banner_height.'></a>' );
    if ($special != "") { jsprint( $special ); }
  } else {
    if ($special != "") { jsprint( $special ); }
  }

?>