<?php // $Id: glossary.php,v 1.17.2.7 2004/11/18 15:14:58 Exp $

//----------------------------------------------------------------------
// CLAROLINE 1.5.*
//----------------------------------------------------------------------
// Copyright (c) 2001-2004 Universite catholique de Louvain (UCL)
//----------------------------------------------------------------------
// This program is under the terms of the GENERAL PUBLIC LICENSE (GPL)
// as published by the FREE SOFTWARE FOUNDATION. The GPL is available
// through the world-wide-web at http://www.gnu.org/copyleft/gpl.html
//----------------------------------------------------------------------
// Authors: see 'credits' file
//----------------------------------------------------------------------

require '../../inc/claro_init_global.inc.php';
include_once('../../inc/lib/claro_main.lib.php');
if (file_exists($includePath . '/conf/CLHOME.conf.php'))
{
    require $includePath . '/conf/CLHOME.conf.php'; // conf file
}
else
{
    // Perhapas  it's better to add here a die("Upgrade your campus");
}

include('lang/' . $_course['language']. '/glossarie.inc.php');

if ( ! $_cid) claro_disp_select_course();
//if ( ! $is_courseAdmin) claro_disp_auth_form();

$htmlHeadXtra[] = 
"<link rel=\"stylesheet\" type=\"text/css\" href=\"../../css/ignozi.css\" />
<style type=\"text/css\">
<!--
.content {padding-left: 25px;}
-->
</style>
<style media=\"print\" type=\"text/css\">
<!--
th {border-bottom: thin dashed Gray;}
-->
</style>";

include($includePath."/lib/text.lib.php");

$nameTools = $langGlossaire;

include($includePath."/claro_init_header.inc.php");


//stats
include('../../inc/lib/events.lib.inc.php');
event_access_tool(TOOL_GLOSSARY);

$TABLECOURS= $mainDbName."`.`user";
$TABLECOURSUSER= $mainDbName."`.`cours_user";
$tbl_glossaire = $_course['dbNameGlu'].'glossary';
//$is_allowedToEdit   = $is_courseAdmin;
$is_allowedToEdit 	= api_is_allowed_to_edit();
$courseId = $_course['sysCode'];


// CHECK IF DATABASE EXIST...if not to create one ...
$sql='show tables from '.$mainDbName.' like \''.$tbl_glossaire.'\'';
$test = claro_sql_query_get_single_value($sql,'#');
if ($test==""){
   $sql="CREATE TABLE `".$tbl_glossaire."` (
        id int(11) NOT NULL auto_increment,
        mot varchar(40) NOT NULL default '',
        definition varchar(255) default '',
        PRIMARY KEY  (id))  ENGINE=MyISAM;";
   claro_sql_query($sql);
}
// END DATABASE CHECK


$cmd = $_REQUEST['cmd'];
unset($msg);

if     ($cmd == 'rqAdd' ) $subTitle = "<br>".$langAddGlossaire;
elseif ($cmd == 'rqEdit') $subTitle = "<br>".$langEditGlossaire;
else                 $subTitle = '';

echo (claro_disp_tool_title(array('mainTitle' => $nameTools, 'subTitle' => $subTitle))."\n");

if ($is_allowedToEdit)
{
    if ($cmd == 'exAdd')
    {
        $sql = "INSERT INTO `".$tbl_glossaire."` 
                SET   mot   = '".trim(addslashes($_REQUEST['mot']))."',
                      definition = '".trim(addslashes($_REQUEST['definition']))."'";

        if ( claro_sql_query($sql) != false)
        {
            $msg .= '<p>'.$langGlossaireAdded.'</p>';

        }
        else
        {
            $msg .= '<p>'.$langUnableToAdd.'</p>';
        }
    }

    if ($cmd == 'exEdit')
    {
        if ( $_REQUEST['id'] )
        {
            $sql = "UPDATE `".$tbl_glossaire."`
                SET   mot   = '".trim(addslashes($_REQUEST['mot']))."',
                      definition = '".trim(addslashes($_REQUEST['definition']))."'
                    WHERE id      ='".$_REQUEST['id']."'";

            if ( claro_sql_query($sql) !== false)
            {
                $msg .= '<p>'.$langGlossaireUpdated.'</p>';
            }
            else
            {
                $msg .= '<p>'.$langUnableToUpdate.'</p>';
            }
        }
    }

    if ($cmd == 'exDelete')
    {
        if ($_REQUEST['id'] == 'ALL')
        {
            $sql = "DELETE 
                    FROM `".$tbl_glossaire."`";
        }
        elseif ( (int) $_REQUEST['id'] != 0 )
        {
            $sql = "DELETE 
                    FROM `".$tbl_glossaire."`
                    WHERE id ='".$id."'";
        }

        if ( claro_sql_query($sql) !== false)
        {
            $msg .= '<p>'.$langGlossaireDeleted.'</p>';

        }
        else
        {
            $msg = '<p>'.$langUnableToDelete.'</p>';
        }
    }

    if ($cmd == 'rqEdit' || $cmd == 'rqAdd')
    {
        if ($cmd == 'rqEdit' && $_REQUEST['id'])
        {
            $sql = "SELECT id, mot, definition 
                    FROM `".$tbl_glossaire."` 
                    WHERE id='".$id."'";

            list($editedGlossaire) = claro_sql_query_fetch_all($sql);

            $nextCommand = 'exEdit';
        }
        else
        {
            $editedGlossaire['id'            ] = '';
            $editedGlossaire['mot'         ] = '';
            $editedGlossaire['definition'       ] = '';

            $nextCommand = 'exAdd';

        }

?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">

<input type="hidden" name="cmd" value="<?php echo $nextCommand       ?>"> 
<input type="hidden" name="id"  value="<?php echo $editedGlossaire['id'] ?>">

<table>


<?php 

      $mot   = $editedGlossaire['mot'];
      $definition = $editedGlossaire['definition'];
?>


<tr>
<td valign="top"><label for="mot"><?php echo $langMot ?> : </label></td>

<td> 
<input size="80" type="text" name="mot" id="mot" value="<?php  echo isset($mot) ? $mot : '' ?>">   
</td>
</tr>

<tr>
<td valign="top"><label for="definition"><?php echo $langDefinition ?> : </label></td>

<td>
<textarea name="definition" rows="4" cols="60" id="definition"><?php  echo isset($definition) ? $definition : '' ?></textarea>
</td>
</tr>

<tr> 

<td colspan="2"> 
<input class="claroButton" type="Submit" name="submitEvent" value="<?php echo $langOk ?>">
<?php  echo (claro_disp_button($_SERVER['PHP_SELF'], $langCancel)); ?>
</td>

</tr>

</table>

</form>
<?php

    } // end if cmd == 'rqEdit' && cmd == 'rqAdd'

    if (! empty($msg)) echo claro_disp_message_box($msg);


    if ($cmd != 'rqEdit' && $cmd != 'rqAdd') // display main commands only if we're not in the event form
    {
        echo '<p>';

         /*
         * Add event button
         */

        echo claro_disp_button($_SERVER['PHP_SELF'].'?cmd=rqAdd',
                       '<img src="'.$clarolineRepositoryWeb.'img/plus.gif" width="20" alt="">'
                      .$langAddGlossaire);

        /*
         * remove all event button
         */

        /*echo  claro_disp_button($_SERVER['PHP_SELF'].'?cmd=exDelete&id=ALL',
                          '<img src="'.$clarolineRepositoryWeb.'img/delete.gif" width="20" alt="">'
                          .$langClearList, $langClearList);*/
		echo '[&nbsp;<a href="'.$_SERVER['PHP_SELF'].'?cmd=exDelete&id=ALL" onClick="if (!confirm(\''.get_lang('DeleteAllConfirmation').'\')){ return false;}"><img src="'.$clarolineRepositoryWeb.'img/delete.gif" width="20" title="'.get_lang('ClearList').'">'.get_lang('ClearList').'</a>&nbsp;]';
        echo '</p>';
    } // end if diplayMainCommands
    
} // end id is_allowed to edit


echo "<table class=\"claroTable\" width=\"100%\" border=\"1\">\n";

if($is_courseAdmin) // check teacher status
{
   $sql = "SELECT id, mot, definition
        FROM `".$tbl_glossaire."`
        ORDER BY mot";
}
else
{

   //if ($_uid){   // anybody can view announcement
   $sql = "SELECT id, mot, definition
        FROM `".$tbl_glossaire."`
        ORDER BY mot";
   //}
}
#echo $sql;

$eventList = claro_sql_query_fetch_all($sql);


if (count($eventList) < 1)
{
	echo '<br><blockquote>'.$langNoFAQ.'</blockquote>';
}
/*if ($GLOBALS["HTTP_SESSION_VARS"]['_course']['language'] == 'greek') {
	$alphabet = array('á','Ü','â','ã','ä','å','Ý','æ','ç','Þ','è','é','ß','ê','ë','ì','í','î','ï','ü','ð','ñ','ó','ô','õ','ý','ö','÷','ø','ù','þ');
	foreach($eventList as $k => $v) {
		$ids[$k] = $v['id'];
		$mots[$k] = $v['mot'];
		$definitions[$k] = $v['definition'];
	}
	array_multisort($mots, SORT_ASC, SORT_STRING, $eventList);
}*/
reset($eventList);

$lettrePrec='';
echo "<tr class=\"headerX\" valign=\"top\">\n";
echo "<th align=\"left\">\n";
function utf8_substr($str,$from,$len){
  return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                       '$1',$str);
}

foreach($eventList as $thisGlossaire)
{
#echo $thisGlossaire['mot'];
#echo substr($thisGlossaire['mot'],0,1);
   if (strtoupper(utf8_substr($thisGlossaire['mot'],0,1))!=$lettrePrec)
   {
#echo "dans for";
	echo "&nbsp;&nbsp;&nbsp;";
	echo "<a href=#".strtoupper(utf8_substr($thisGlossaire['mot'],0,1))."><font size=6><b>".strtoupper(utf8_substr($thisGlossaire['mot'],0,1))."</b></font></a>";
	$lettrePrec=strtoupper(utf8_substr($thisGlossaire['mot'],0,1));
   }
}
echo "</th>\n";
echo "</tr>\n";

$lettrePrec='';
foreach($eventList as $thisGlossaire)
{


  /*
   * Display the glossaire content
   */



  echo "<tr class=\"headerX\" valign=\"top\">\n"
      ."<th align=\"left\">\n";
  if (strtoupper(utf8_substr($thisGlossaire['mot'],0,1))!=$lettrePrec)
  {
     echo "<a name=\"".strtoupper(utf8_substr($thisGlossaire['mot'],0,1))."\">&nbsp;</a>";
     $lettrePrec=strtoupper(utf8_substr($thisGlossaire['mot'],0,1));
  }


  echo ( empty($thisGlossaire['mot']  ) ? '' : '<strong>'.$thisGlossaire['mot'].'</strong>' )
	."</th>\n"
      ."</tr>\n"
      ."<td>\n"
      ."<div class=\"content\">\n"
      .( empty($thisGlossaire['definition']) ? '' :  claro_parse_user_text($thisGlossaire['definition']) )
      ."</div>\n";
  if ($is_allowedToEdit)
  {
    echo "<a href=\"".$_SERVER['PHP_SELF']."?cmd=rqEdit&id=".$thisGlossaire['id']."\">"
        ."<img src=\"".$clarolineRepositoryWeb."img/edit.gif\" border=\"O\" alt=\"".$langModify."\">"
        ."</a> "
         
        ."<a href=\"".$_SERVER['PHP_SELF']."?cmd=exDelete&id=".$thisGlossaire['id']."\" "
        ."onclick=\"javascript:if( ! confirm('"
        .addslashes (htmlspecialchars($langDelete.' '.$thisGlossaire['mot']." ?"))
        ."')) return false;\" >"
        ."<img src=\"".$clarolineRepositoryWeb."img/delete.gif\" border=\"0\" alt=\"".$langDelete."\">"
        ."</a>";
  }
  echo "</td>\n"
      ."</tr>\n";
}   // end while

echo "</table>";
for ($i=0;$i<28;$i++)
{
   echo "<br>";
}

include($includePath."/claro_init_footer.inc.php");

?>
