<?php session_start();
//Export Excel
if(isset($_POST['export_excel'])){
// Include PEAR::Spreadsheet_Excel_Writer
require_once "Spreadsheet/Excel/Writer.php";
// Create an instance
$xls =& new Spreadsheet_Excel_Writer();
// Send HTTP headers to tell the browser what's coming
$xls->send("cmpg_booklibraray.xls");
// Add a worksheet to the file, returning an object to add data to
$sheet =& $xls->addWorksheet('Books CMPG Library');
//Prapre mySQL Connection
$connection=mysql_connect('webdb.zooblythii.unibe.ch:3309', 'cmpg', 'popgen');
mysql_select_db('booklibrary', $connection);
$error='';

//Write Legend
$sheet->write(0,0,'Label');
$sheet->write(0,1,'Title');
$sheet->write(0,2,'Authors');
$sheet->write(0,3,'Year');
$sheet->write(0,4,'Publisher');

//Write Books
    $i=0;
    foreach($_SESSION['booklist'] as $key=>$val){
        if(isset($_POST['export'.$key])){
            ++$i;
            $sql="select b.id, b.label, b.title, b.year, p.publisher
                  from book b, publisher p
                  WHERE b.publisher_id=p.id AND b.id=".$val;
            $query=mysql_query($sql,$connection);
            $book=mysql_fetch_object($query);
            $sheet->write($i,0,$book->label);
            $sheet->write($i,1,$book->title);
            $sql="SELECT * from author WHERE book_id=".$book->id." order by id asc";
            $query=mysql_query($sql,$connection);
            $text='';
            while($author=mysql_fetch_object($query)){
                $text=$text.$author->author.';';
            }
            $sheet->write($i,2,$text);
            $sheet->write($i,3,$book->year);
            $sheet->write($i,4,$book->publisher);
        }
    }

// Finish the spreadsheet, dumping it to the browser
$xls->close();
} else {
if(isset($_POST['export_endnote'])){
header("Content-Type: text/plain; charset=utf-8");
header("Content-Disposition: attachment; filename=cmpg_booklibraray.xml");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
header("Pragma: public");

//Prapre mySQL Connection
$connection=mysql_connect('webdb:3309', 'cluster', 'fromcluster');
mysql_select_db('booklibrary', $connection);

//Prpare string replacement
$char= array('&','ü','ä','ö', 'Ä','Ö','Ü','è','é','à','ç');
$char_ok=array('&amp;','Ã¼','Ã¤','Ã¶', 'Ã„', 'Ã–', 'Ãœ','Ã¨','Ã©','ï¿½','Ã§');

//Write Beginning
echo '<?xml version="1.0" encoding="UTF-8" ?><xml><records>';

//Write Books
    $i=0;
    foreach($_SESSION['booklist'] as $key=>$val){
        if(isset($_POST['export'.$key])){
            ++$i;
            $sql="select b.id, b.label, b.title, b.year, p.publisher
                  from book b, publisher p
                  WHERE b.publisher_id=p.id AND b.id=".$val;
            $query=mysql_query($sql,$connection);
            $book=mysql_fetch_object($query);
            echo '<record><database name="CMPG_Booklibrary.enl" path="CMPG_Booklibrary.enl">CMPG_Booklibrary.enl</database>';
            echo '<source-app name="EndNote" version="8.0">EndNote</source-app>';
            echo '<rec-number>'.$book->id.'</rec-number>';
            echo '<ref-type name="Book">6</ref-type>';
            echo '<contributors><authors>';
            $sql="SELECT * from author WHERE book_id=".$book->id." order by id asc";
            $query=mysql_query($sql,$connection);
            while($author=mysql_fetch_object($query)){
                echo '<author><style face="normal" font="default" size="100%">'.str_replace($char, $char_ok ,$author->author).'</style></author>';
            }
            echo '</authors></contributors>';
            echo '<titles><title><style face="normal" font="default" size="100%">'.str_replace($char, $char_ok, $book->title).'</style></title></titles>';
            echo '<dates><year><style face="normal" font="default" size="100%">'.str_replace('&', '&amp;',$book->year).'</style></year></dates>';
            echo '<publisher><style face="normal" font="default" size="100%">'.str_replace($char, $char_ok, $book->publisher).'</style></publisher>';
            echo '<label><style face="normal" font="default" size="100%">'.str_replace($char, $char_ok, $book->label).'</style></label>';
            echo '<urls></urls></record>';
        }
    }
echo '</records></xml>';
} else {
header("cache-control: private");





//insert into database
//------------------------------------------------------------------------------
function insert($sql){
   global $connection;
   $query=mysql_query($sql,$connection);
   if(mysql_affected_rows()==1) return mysql_insert_id();
}

//Display a red line
//------------------------------------------------------------------------------
function redline(){ ?>
       <tr>
            <td colspan='5' height='10' bgcolor="#ffffff"></td>
       </tr>
       <tr>
            <td colspan='5' height='2' bgcolor="#af0000"></td>
       </tr>
       <tr>
            <td colspan='5' height='10' bgcolor="#ffffff"></td>
       </tr>
<?php
}

//Display a red line
//------------------------------------------------------------------------------
function export_excel(){
    $text='"Label";"Title";"Author(s)";"Year";"Publisher"<br>';
    global $connection;
    foreach($_SESSION['booklist'] as $key=>$val){
        if(isset($_POST['export'.$key])){
            $sql="select b.id, b.label, b.title, b.year, p.publisher
                  from book b, publisher p
                  WHERE b.publisher_id=p.id AND b.id=".$val;
            $query=mysql_query($sql,$connection);
            $book=mysql_fetch_object($query);
            $text=$text.'"'.$book->label.'";"'.$book->title.'";"';
            $sql="SELECT * from author WHERE book_id=".$book->id." order by id asc";
            $query=mysql_query($sql,$connection);
            while($author=mysql_fetch_object($query)){
                $text=$text.$author->author.';';
            }
            $text=$text.'";"'.$book->year.'";"'.$book->publisher.'"<br>';
        }
    }
    return $text;
}


//colors for tables
//------------------------------------------------------------------------------
$bgcolor[1]='bgcolor=#ffffff';
$bgcolor[0]='bgcolor=#f3f3ff';

//read search
//------------------------------------------------------------------------------
if(isset($_POST['search_button']) && isset($_POST['combo_search']) && isset($_POST['search_text'])){
    if(isset($_SESSION['search_text'])) unset($_SESSION['search_text']);
    if(isset($_SESSION['combo_search'])) unset($_SESSION['combo_search']);
    if(isset($_SESSION['search'])) unset($_SESSION['search']);
    $char=array('"',';',"'");
    $search_text=str_replace($char, '', $_POST['search_text']);
    if($search_text!=''){
        $_SESSION['search']=1;
        $_SESSION['search_text']=$search_text;
        $_SESSION['combo_search']=$_POST['combo_search'];
    }
}
if(isset($_POST['show_all_button'])){
   if(isset($_SESSION['search_text'])) unset($_SESSION['search_text']);
   if(isset($_SESSION['search'])) unset($_SESSION['search']);
}

//check sort
//------------------------------------------------------------------------------
if(!isset($_SESSION['old_sort'])) $_SESSION['old_sort'] = 'title';

//check search direction
//------------------------------------------------------------------------------
if(isset($_SESSION['sort_direction']) && !isset($_POST['show_all_button'])){
    if(isset($_GET['sort']) &&  $_SESSION['old_sort']==$_GET['sort']){
         if($_SESSION['sort_direction']=='desc'){
             $_SESSION['sort_direction']='asc';
         } else {
             $_SESSION['sort_direction']='desc';
         }
    } else {
        if(isset($_GET['sort']) && ($_GET['sort']=='author' || $_GET['sort']=='label' || $_GET['sort']=='title' || $_GET['sort']=='year' || $_GET['sort']=='publisher')){
           $_SESSION['old_sort']=$_GET['sort'];
        }
    }
} else {
    if(!isset($_POST['show_all_button'])) $_SESSION['sort_direction']='asc';
}

//Write new book into database...
//------------------------------------------------------------------------------
if(isset($_POST['enter_new_book'])){
$char=array('"',';');
if(isset($_POST['new_label']) && str_replace($char, '', $_POST['new_label'])!='' && strlen(str_replace($char, '', $_POST['new_label']))=='5' &&
   isset($_POST['new_title']) && str_replace($char, '', $_POST['new_title'])!='' &&
   isset($_POST['new_year']) && $_POST['new_year']!=''  &&
   isset($_POST['new_publisher_combo']) && ($_POST['new_publisher_combo']!=0 || (isset($_POST['new_publisher']) && $_POST['new_publisher']!='')) &&
   isset($_POST['new_Author_1']) && str_replace($char, '', $_POST['new_Author_1'])!=''){
     $sql="SELECT count(*) as num from book WHERE label='".str_replace($char, '', $_POST['new_label'])."'";
     $query=mysql_query($sql,$connection);
     if(mysql_num_rows()==0){
       $pub_id=0;
       if($_POST['new_publisher_combo']==0){
           $pub_id=insert('INSERT into publisher (publisher) values("'.str_replace($char, '', $_POST['new_publisher']).'")');
       } else {
           $pub_id=$_POST['new_publisher_combo'];
       }
       if($pub_id > 0){
           $book_id=insert("INSERT into book (year, title, label, publisher_id, date) values(".str_replace($char, '', $_POST['new_year']).", '".str_replace($char, '', $_POST['new_title'])."', '".str_replace($char, '', $_POST['new_label'])."', ".$pub_id.", now())");
               if($book_id > 0){
                   $author_id=0;
                   for($i=1;$i<10;++$i){
                       if(isset($_POST['new_Author_'.$i]) && str_replace($char, '',$_POST['new_Author_'.$i])!=''){
                           $author_id=$author_id+insert("INSERT into author (author, book_id) values('".str_replace($char, '', $_POST['new_Author_'.$i])."', ".$book_id.")");
                       }
                   }
               } else {
                   $error=$error."Failed to insert new book!<br>";
               }
       } else {
           $error=$error."Failed to insert new publisher!<br>";
       }
     } else {
       $error=$error."Label exists!<br>";
     }
} else {
   $error=$error."Data missing or data not in the correct format!<br>";
}
}

   
   


// Head
//------------------------------------------------------------------------------
?>
<html>
<head>
<meta name="description" content="CMPG Booklibrary">
<meta name="keywords" content="">
<meta name="content-language" content="en">
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>CMPG Booklibrary</title>
<link rel="stylesheet" href="style.css" type="text/css">
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin

function uncheckAll(forwhat){
var j=0;
while(box = eval("document.exportform."+forwhat + j)){
if (box.checked == true) box.checked = false;
j++;
   }
}

function switchAll(forwhat) {
var j=0;
while(box = eval("document.exportform."+forwhat + j)){
box.checked = !box.checked;
j++;
   }
}
function checkAll(forwhat) {
var j=0;
while(box = eval("document.exportform."+forwhat + j)){
if (box.checked == false) box.checked = true;
j++;
   }
}

//  End -->
</script>
</head>

<body leftmargin='20'>
<p class='title'>CMPG Booklibrary</p>
<table valign='center' cellspacing='0' cellpadding='0'>

<?php
// search
//------------------------------------------------------------------------------
?>

       <tr>
           <td height='20'>
               <p class='subtitle'>Search:</p>
           </td>
           <form action="booklibrary.php?<?php if(isset($_GET['sort']) && ($_GET['sort']=='author' || $_GET['sort']=='label' || $_GET['sort']=='title' || $_GET['sort']=='year' || $_GET['sort']=='publisher')) echo 'sort='.$_GET['sort'].'&'; ?>" method='post' name='search_form'>
           <td>
               <input size='30' align='left' value='<?php if(isset($_SESSION['search_text'])) echo $_SESSION['search_text']; ?>' name='search_text' type='text'>
           </td>
           <td>
               <SELECT class='text' STYLE='width: 100px' name='combo_search'>
                  <option value="all" <?php if($_SESSION['combo_search']=="all") echo 'SELECTED';?>>everything</option>
                  <option value="title" <?php if($_SESSION['combo_search']=="title") echo 'SELECTED';?>>Title</option>
                  <option value="author" <?php if($_SESSION['combo_search']=="author") echo 'SELECTED';?>>Author</option>
                  <option value="publisher" <?php if($_SESSION['combo_search']=="publisher") echo 'SELECTED';?>>Publisher</option>
                  <option value="label" <?php if($_SESSION['combo_search']=="label") echo 'SELECTED';?>>Label</option>
                  <option value="year" <?php if($_SESSION['combo_search']=="year") echo 'SELECTED';?>>Year</option>
               </SELECT>
           </td>
           <td>
               <input align='center' name="search_button" value="Let's go!" type="submit" class='button'>
           </td>
           <td>
               <input align='center' name="show_all_button" value="Show all" type="submit" class='button'>
           </td>
           </form>
           <td width='300'></td>
      </tr>
<?php redline();

//Enter new Book!
//------------------------------------------------------------------------------
if((isset($_POST['show_all_button']) && isset($_POST['search_text']) && $_POST['search_text']=='***') || isset($_SESSION['enter_new_book'])){
$_SESSION['enter_new_book']=1;
?>
       <tr>
           <td>
               <p class='error'><?php echo $error; ?></p>
           </td>
       </tr>
       <tr>
           <td colspan='5'>
               <table width='800' align='center' cellspacing='0' cellpadding='0'border='0'>
               <form action="booklibrary.php" method='post' name='new_book'>
                   <tr>
                       <td height='30' width='65'>
                           <p class='subtitle'>Title:</p>
                       </td>
                       <td colspan='4'>
                           <input size='100' maxlength='255' align='left' name='new_title' type='text' value='<?php if(isset($_POST['new_title'])) echo $_POST['new_title']; ?>'>
                       </td>
                   </tr>
                   <tr>
                       <td height='5'></td>
                   </tr>
                   <tr>
                       <td height='20'>
                           <p class='subtitle'>Label:</p>
                       </td>
                       <td colspan='4'>
                           <input size='6' align='left' name='new_label' type='text' value='<?php if(isset($_POST['new_label'])) echo $_POST['new_label']; ?>'>
                       </td>
                   </tr>
                   <tr>
                       <td height='5'></td>
                   </tr>
                   <tr>
                       <td height='20'>
                           <p class='subtitle'>Year:</p>
                       </td>
                       <td colspan='4'>
                           <input size='6' align='left' name='new_year' type='text' value='<?php if(isset($_POST['new_year'])) echo $_POST['new_year']; ?>'>
                       </td>
                   </tr>
                   <tr>
                       <td height='5'></td>
                   </tr>
                   <tr>
                       <td height='20'>
                           <p class='subtitle'>Publisher:</p>
                       </td>
                       <td width='100'>
                           <SELECT class='text' STYLE='width: 400px' name='new_publisher_combo'>
                                          <option value='0'>-> new publisher to the right!</option>
                              <?php $sql="select * from publisher order by publisher asc";
                                    $query=mysql_query($sql,$connection);
                                    while($publisher=mysql_fetch_object($query)){
                                    if($publisher->id==$_POST['new_publisher_combo']) $z='SELECTED'; else $z='';
                                    echo "<option value='".$publisher->id."' ".$z.">".$publisher->publisher."</option>";
                                    } ?>
                           </SELECT>
                       </td>
                       <td width='5'></td>
                       <td>
                           <input size='30' align='left' name='new_publisher' type='text' value='<?php if(isset($_POST['new_publisher'])) echo $_POST['new_publisher']; ?>'>
                       </td>
                       <td></td>
                   </tr>
                   <?php for($i=1;$i<10;++$i){ ?>
                   <tr>
                       <td height='5'></td>
                   </tr>
                   <tr>
                       <td height='20'>
                           <p class='subtitle'>Author <?php echo $i; ?>:</p>
                       </td>
                       <td colspan='6'>
                           <input size='30' align='left' name='new_Author_<?php echo $i; ?>' type='text' value='<?php if(isset($_POST['new_Author_'.$i])) echo $_POST['new_Author_'.$i]; ?>'>
                       </td>
                   </tr>
                   <?php } ?>
                   <tr>
                       <td height='5'></td>
                   </tr>
                   <tr>
                       <td height='20'>
                       </td>
                       <td colspan='4'>
                           <input align='center' name="enter_new_book" value="enter a new book" type="submit" class='button'>
                       </td>
                   </tr>
               </form>
               </table>
           </td>
       </tr>
<?php    redline();
}

//Export
//------------------------------------------------------------------------------
?>
<form action="booklibrary.php" method='post' name='exportform'>
      <?php if(isset($_POST['export_ecxel']) || isset($_POST['export_endnote'])){
                  if(isset($_POST['export_ecxel'])) $text=export_excel();
                  if(isset($_POST['export_endnote'])) $text=export_endnote(); ?>
        
        <tr>
            <td colspan='6'>
              <?php $text=str_replace("<br>", chr(10), $text); ?>
              <textarea name='output' cols='80' rows='10' WRAP='off' readonly><?php echo $text; ?></textarea>
            </td>
        </tr>
        <tr>
            <td height='10'></td>
        </tr>
        <?php } ?>
        <tr>
           <td colspan='2'>
               <input class='button' type=button value="All" onClick="checkAll('export')"></input>
               <input class='button' type=button value="None" onClick="uncheckAll('export')"></input>
               <input class='button' type=button value="Switch" onClick="switchAll('export')"></input>
           </td>
           <td width='20'></td>
           
           <td>
               <input align='center' name="export_excel" value="export for EXCEL" type="submit" class='button'>
           </td>
           <td>
               <input align='center' name="export_endnote" value="export for ENDNOTE" type="submit" class='button'>
           </td>
        </tr>
        
<?php
redline();

// Table with books
//------------------------------------------------------------------------------
?>
      
                      <?php if(isset($_GET['sort']) && ($_GET['sort']=='author' || $_GET['sort']=='label' || $_GET['sort']=='title' || $_GET['sort']=='year' || $_GET['sort']=='publisher')){
                                 $z=$_GET['sort'];
                            } else {
                                 $z='label';
                            }
                            if(isset($_GET['desc']) && $_GET['desc']==1){
                                 $z=$z." desc";
                            } else {
                                 $z=$z." asc";
                            }
                           
                           $sql_num="select distinct b.label";
                           $sql_search="select b.id, b.label, b.title, b.year, a.author, p.publisher";
                           $sql=" from author a, book b, publisher p
                                 WHERE a.book_id=b.id AND b.publisher_id=p.id";
                           if(isset($_SESSION['search'])){
                               if($_SESSION['combo_search']=='all'){
                                   $sql=$sql." AND (b.label like '%".$_SESSION['search_text']."%' OR b.title like '%".$_SESSION['search_text']."%' or a.author like '%".$_SESSION['search_text']."%' or b.year like '%".$_SESSION['search_text']."%' or p.publisher like '%".$_SESSION['search_text']."%')";
                               }
                               if($_SESSION['combo_search']=='title'){
                                   $sql=$sql." AND b.title like '%".$_SESSION['search_text']."%'";
                               }
                               if($_SESSION['combo_search']=='year'){
                                   $sql=$sql." AND b.year like '%".$_SESSION['search_text']."%'";
                               }
                               if($_SESSION['combo_search']=='publisher'){
                                   $sql=$sql." AND p.publisher like '%".$_SESSION['search_text']."%'";
                               }
                               if($_SESSION['combo_search']=='author'){
                                   $sql=$sql." AND a.author like '%".$_SESSION['search_text']."%'";
                               }
                               if($_SESSION['combo_search']=='label'){
                                   $sql=$sql." AND b.label like '%".$_SESSION['search_text']."%'";
                               }
                           }
                           $sql_search=$sql_search.$sql." order by ".$_SESSION['old_sort']." ".$_SESSION['sort_direction'];
                           if($_SESSION['old_sort']!='author') $sql_search=$sql_search.", a.id asc";
                           $query=mysql_query($sql_search,$connection);
                           $sql_num=$sql_num.$sql;
                           $num=mysql_query($sql_num,$connection);
                           ?>
                           <tr align='left' colspan='5'>
                               <td>
                                   <p class='text'>Found <b><?php echo mysql_num_rows($num); ?></b> books!
                               </td>
                           </tr>
                           <tr>
           <td colspan='5'>
               <table width='800' align='center' cellspacing='0' cellpadding='0'border='0'>
               
                      <tr align='left' bgcolor='#d3d3ff'>
                          <td width='5'></td>
                          <td height='20' width='45'>
                              <a href='booklibrary.php?sort=label' class='subsubtitle'>Label<?php if(isset($_GET['sort']) && $_GET['sort']=='label'){ if($_SESSION['sort_direction']=='asc') echo " &darr;"; if($_SESSION['sort_direction']=='desc') echo " &uarr;"; } ?></a>
                          </td>
                          <td width='40'>
                              <a href='booklibrary.php?sort=title' class='subsubtitle'>Title<?php if(isset($_GET['sort']) && $_GET['sort']=='title'){ if($_SESSION['sort_direction']=='asc') echo " &darr;"; if($_SESSION['sort_direction']=='desc') echo " &uarr;"; } ?></a>
                          </td>
                          <td width='30'>
                              <a href='booklibrary.php?sort=author' class='subsubtitle'>Author<?php if(isset($_GET['sort']) && $_GET['sort']=='author'){ if($_SESSION['sort_direction']=='asc') echo " &darr;"; if($_SESSION['sort_direction']=='desc') echo " &uarr;"; } ?></a>
                          </td>
                          <td width='45'>
                              <a href='booklibrary.php?sort=year' class='subsubtitle'>Year<?php if(isset($_GET['sort']) && $_GET['sort']=='year'){ if($_SESSION['sort_direction']=='asc') echo " &uarr;"; if($_SESSION['sort_direction']=='desc') echo " &darr;"; } ?></a>
                          </td>
                          <td width='75'>
                              <a href='booklibrary.php?sort=publisher' class='subsubtitle'>Publisher<?php if(isset($_GET['sort']) && $_GET['sort']=='publisher'){ if($_SESSION['sort_direction']=='asc') echo " &darr;"; if($_SESSION['sort_direction']=='desc') echo " &uarr;"; } ?></a>
                          </td>
                      </tr>
                      <tr>
                          <td height='10'></td>
                      </tr>
                           <?php
                           $book_label='';
                           if(isset($_SESSION['booklist'])) unset($_SESSION['booklist']);
                           $i=-1;
                           while($book=mysql_fetch_object($query)){
                               if($book->label==$book_label){
                                     echo "<br>".$book->author;
                               } else {
                                   if($i>=0){
                                       echo "</p>" ?>
                                       </td>
                                       <td>
                                           <p class='text' align='center'><?php echo $old_year; ?></p>
                                       </td>
                                       <td>
                                           <p class='text'><?php echo $old_publisher; ?></p>
                                       </td>
                                   </tr>
                                   <?php } ?>
                                <tr align='left' <?php echo $bgcolor[$i-2*(floor($i/2))]; ++$i; ?>>
                                   <td>
                                       <INPUT type='checkbox' name='export<?php echo $i; $_SESSION['booklist'][$i]=$book->id; ?>'>
                                   </td>
                                   <td>
                                       <p class='text'><?php echo $book->label; $book_label=$book->label; ?></p>
                                   </td>
                                   <td >
                                       <p class='text'><?php echo $book->title; ?></p>
                                   </td>
                                   <td>
                                       <p class='text'><?php echo $book->author;
                                       $old_year=$book->year;
                                       $old_publisher=$book->publisher;
                               }
                           }
                           echo "</p>" ?>
                                       </td>
                                       <td>
                                           <p class='text' align='center'><?php echo $old_year; ?></p>
                                       </td>
                                       <td>
                                           <p class='text'><?php echo $old_publisher; ?></p>
                                       </td>
                                   </tr>
                           </form>
</table>
</html>
<?php } } //end export ?>
