<?php
# ObrEns     -  Fichero de administración de componente Mambo
# Version    :  1.0 
# By         :  2005 Rodax Software
# Web        :  www.rodax-software.com
# License    :  GNU GPL Public License

###################################################################################
#INICIO
###################################################################################
# Inicializamos
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
require($mosConfig_absolute_path."/components/com_obrens/version.php");

# Establecemos idioma
if (file_exists($mosConfig_absolute_path.'/components/com_obrens/lang/'.$mosConfig_lang.'.php')) {
  include($mosConfig_absolute_path.'/components/com_obrens/lang/'.$mosConfig_lang.'.php');
} else {
  include($mosConfig_absolute_path.'/components/com_obrens/lang/german.php');
}


###################################################################################
#CLASES
###################################################################################
# Clase de tabla mos_obrens
class mosartref extends mosDBTable {
  var $id=null;
  var $catid=null;
  var $titulo=null;
  var $autor=null;

  var $partituramus=null;
  var $partituramid=null;
  var $ncolfil=null;
  
  var $beschreibung=null;
  var $hits=null;
  var $ref_in=null;
  var $ref_out=null;
  var $published=null;
  var $ordering=null;
  var $checked_out=null;
  
  function mosartref( &$db ) {
    $this->mosDBTable( '#__obrens', 'id', $db );
  }
}

# Clase de tabla mos_obrens_cab_detalles
class mosenscabdet extends mosDBTable {
	var $id=null;
  var $ncol1=null;
  var $ncol2=null;    
  var $ncol3=null;
  var $ncol4=null;    
  var $ncol5=null;
  var $ncol6=null;    
  var $ncol7=null;
  var $ncol8=null;    

  //Como PHP4 no soporta sobrecarga los dos constructores que tendria la clase los hemos
  //hecho funciones.
  //Constructor 1
  function mosenscabdet1($POST, $id) {
  	$this->id = $id;    
  	$this->ncol1 = $POST['ncol1'];
  	$this->ncol2 = $POST['ncol2'];
  	$this->ncol3 = $POST['ncol3'];
  	$this->ncol4 = $POST['ncol4'];
  	$this->ncol5 = $POST['ncol5'];
  	$this->ncol6 = $POST['ncol6'];  	  	  	  	  	
  	$this->ncol7 = $POST['ncol7'];  	  	  	  	  	
  	$this->ncol8 = $POST['ncol8'];  	  
  	
		echo "<script> alert('Creamos la clase $this->ncol3');</script>\n";    		  	  	  	  	  	
  }

  //Constructor 2
  function mosenscabdet2(&$db, $id) {
  	$cadena = "SELECT * FROM #__obrens_cab_detalles "
						. "WHERE idobra = " . $id;

		$db->setQuery($cadena);
		$rows = $db->loadObjectList();
		foreach($rows as $row1) {
	  	$this->id = $id;    
	  	switch ($row1->id) {
  		case 0: $this->ncol1 = $row1->descripcion;
  						break;
  		case 1: $this->ncol2 = $row1->descripcion;
  						break;  		
  		case 2: $this->ncol3 = $row1->descripcion;
  						break;  		
  		case 3: $this->ncol4 = $row1->descripcion;
  						break;  		
  		case 4: $this->ncol5 = $row1->descripcion;
  						break;  		
  		case 5: $this->ncol6 = $row1->descripcion;
  						break;  		
  		case 6: $this->ncol7 = $row1->descripcion;  		  		  		  		
  						break;  		
  		case 7: $this->ncol8 = $row1->descripcion;  		  		  		  		  		
  						break; 
  		} 		
  	}
  }
  
	//Funcion que inserta una tupla en tabla
  function insert(&$db, $ncol, $valor) {
		$cadena = "INSERT INTO #__obrens_cab_detalles ( `idobra` , `id` , `descripcion` )"
						. "VALUES ( "
						. $this->id . ", " . $ncol . ", '" . $valor . "')";
		$db->setQuery($cadena);
    if (!$db->query()) {
      echo $db->getErrorMsg();
	    return false;
	  }
    return true;
	}
  	
  //Funcion que inserta todos los campos introducidos en backoffice	
  function insertdet(&$db) {
    //Borramos todo lo que hubiera
		$cadena = "DELETE FROM #__obrens_cab_detalles"
		          . " WHERE idobra =" . $this->id;
		$db->setQuery($cadena);
		$db->query();
#PENDIENTE
    if (!$db->query()) {
      echo $db->getErrorMsg();
	    return false;
	  }
		
		//Insertamos cada uno de los campos introducidos
    if ($this->ncol1 != "")
		   if (!$this->insert($db, 0, $this->ncol1))
			    return false;
			    	
		if ($this->ncol2 != "")			    
	     if (!$this->insert($db, 1, $this->ncol2))
	  			return false;	

		if ($this->ncol3 != "")	  			 
			 if (!$this->insert($db, 2, $this->ncol3))
			 		return false;
			 
		if ($this->ncol4 != "")			 			
			 if (!$this->insert($db, 3, $this->ncol4))
			 		return false;
			 
		if ($this->ncol5 != "")			 			
			 if (!$this->insert($db, 4, $this->ncol5))
			 		return false;	

		if ($this->ncol6 != "")			 			
			 if (!$this->insert($db, 5, $this->ncol6))
			 		return false;	

		if ($this->ncol7 != "")			 			
			 if (!$this->insert($db, 6, $this->ncol7))
			 		return false;	

		if ($this->ncol8 != "")			 			
			 if (!$this->insert($db, 7, $this->ncol8))
			 		return false;	
			 
	  return true;
	}  
}//Fin de clase


###################################################################################
#FUNCIONES
###################################################################################
# Dibujar Footer
function RefFooter($cuotas_version) {
  echo "<center><font face=\"Arial\" size=\"1\"><b><font color=\"#0000FF\">Área</font><font color=\"#FF0000\"><img border=\"0\" src=\"$mosConfig_live_site/components/com_obrens/images/tynimam.jpg\" width=\"12\" height=\"11\">Ensayo</font></b> $cuotas_version por <a href=\"http://www.rodax-software.com\" target=\"_blank\"><font face=\"Arial\" size=\"1\">Rodax Software S.L</font></a></center>";
  return;
}

# Editar obra
function editRef( $option, $uid ) {
  global $database, $my, $mosConfig_absolute_path, $mosConfig_live_site, $clist;

  //Creamos y cargamos nuestra clase con los datos detalle de la obra
  $row2 = new mosenscabdet($database);
  $row2->mosenscabdet2($database, $uid);

  //Tratamiento del resto de datos
  $row = new mosartref( $database );
  # Load the row from the db table
  $row->load( $uid );

  # Get list of categories
  $categories[] = mosHTML::makeOption( '0', ADM_ARTREF_WKat );
  $categories[] = mosHTML::makeOption( '-1', ADM_ARTREF_AKat );
  $database->setQuery( "SELECT id AS value, title AS text FROM #__categories"
    . "\nWHERE section='$option' ORDER BY ordering" );
  $categories = array_merge( $categories, $database->loadObjectList() );

  if (count( $categories ) < 1) {
    mosRedirect( "index2.php?option=categories&section=$option", ADM_ARTREF_ERROR_A );
  }

  $clist = mosHTML::selectList( $categories, 'catid', 'class="inputbox" size="1"',
    'value', 'text', intval( $row->catid ) );

  if (!$uid) {
    # Initialise new record
    $row->published = 0;
  }

  # Build the html select list for ordering
  $order = mosGetOrderingList( "SELECT ordering AS value, titulo AS text"
    . "\nFROM #__obrens"
    . "\nWHERE catid='$row->catid' ORDER BY ordering"
  );
  $olist = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"',
    'value', 'text', intval( $row->ordering ) );

  HTML_artref::editRef( $option, $row, $clist, $olist, $row2);
}

# Grabar obra (Alta/Modificacion)
function saveRef( $option ) {
  global $database, $my;

  //Grabamos la obra
  $row = new mosartref( $database );
  if (!$row->bind( $_POST )) {
    echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
    exit();
  }
  if (!$row->store()) {
    echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
    exit();
  }
  $row->updateOrder( "catid='$row->catid'" );

  //Grabamos los detalles
  $row2 = new mosenscabdet($database);  
  if (!$_POST['id']) {
	  //Sacamos el codigo de obra por si fuera un alta
		$database->setQuery( "SELECT max(id) as id FROM #__obrens");
		$row = NULL;
		$database->loadObject( $row );
		$lid = $row->id;
	}
	else $lid = $_POST['id'];
  //Creamos y grabamos detalles
  $row2->mosenscabdet1($_POST, $lid);  
  if ($row2->insertdet($database)) 
		 echo "<script> alert('No se ha podido grabar los detalles'); window.history.go(-1); </script>\n";  
		 
  mosRedirect( "index2.php?option=$option" );
}

# Listado de obras o categorias
function showRef($option) {
  global $database, $mainframe;
  global $mosConfig_absolute_path;
  require($mosConfig_absolute_path."/administrator/components/com_obrens/config.obrens.php");
  

  $catid = $mainframe->getUserStateFromRequest( "catid{$option}", 'catid', 0 );
  $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
  $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
  $search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
  $search = $database->getEscaped( trim( strtolower( $search ) ) );

  $where = array();

  if ($catid > 0) {
    $where[] = "a.catid='$catid'";
  }
  if ($search) {
    $where[] = "LOWER(a.name) LIKE '%$search%'";
  }

  # Get the total number of records
  $database->setQuery( "SELECT count(*) FROM #__obrens AS a"
    . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
  );
  $total = $database->loadResult();
  echo $database->getErrorMsg();

  include_once( "includes/pageNavigation.php" );
  $pageNav = new mosPageNav( $total, $limitstart, $limit  );

  $cadena = "SELECT a.*, cc.name AS category"
    . "\nFROM #__obrens AS a"
    . "\nLEFT JOIN #__categories AS cc ON cc.id = a.catid"
    . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
    . "\nORDER BY a.catid";    
    //Orden de la lista de obras
		switch ($obrens_ordenlista) {
	  case '1': $cadena .= ",a.titulo ";
	            break;
	  case '2': $cadena .= ",a.autor ";
	            break;  
	  case '3': $cadena .= ",a.id ";  
	            break;
	  }            
  $cadena .= ", a.ordering"
           . "\nLIMIT $pageNav->limitstart,$pageNav->limit";
    
  $database->setQuery($cadena);
  $rows = $database->loadObjectList();
  if ($database->getErrorNum()) {
    echo $database->stderr();
    return false;
  }

  # Get list of categories
  $categories[] = mosHTML::makeOption( '0', ADM_ARTREF_WKat );
  $categories[] = mosHTML::makeOption( '-1', ADM_ARTREF_AKat );
  $database->setQuery( "SELECT id AS value, title AS text FROM #__categories"
    . "\nWHERE section='com_obrens' ORDER BY ordering" );
  $categories = array_merge( $categories, $database->loadObjectList() );

  $clist = mosHTML::selectList( $categories, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"',
    'value', 'text', $catid );

  HTML_artref::showRef( $option, $rows, $clist, $search, $pageNav );
}


###################################################################################
#CUERPO
###################################################################################
require_once( $mainframe->getPath( 'admin_html' ) );

$cid = mosGetParam( $_POST, 'cid', array(0) );

switch ($act) {
  case "settings":
    $task = "settings";
    break;
  case "about":
    $task = "about";
    break;
}

switch ($task) {
  case "new":
    editRef( $option, 0 );
    break;

  case "edit":
    editRef( $option, $cid[0] );
    break;

  case "save":
    saveRef( $option );
    break;

  case "remove":
    removeRef( $cid, $option );
    break;

  case "publish":
    publishRef( $cid, 1, $option );
    break;

  case "unpublish":
    publishRef( $cid, 0, $option );
    break;

  case "cancel":
    cancelRef( $option );
    break;

  case "orderup":
    orderRef( $cid[0], -1, $option );
    break;

  case "orderdown":
    orderRef( $cid[0], 1, $option );
    break;

  case "settings":
    showConfig( $option );
    break;

  case "language":
    showLanguage($option);
    break;

  case "savelanguage":
    saveLanguage($file, $filecontent, $option);
    break;

  case "about":
    showAbout( $option );
    break;

  case "savesettings":
    saveConfig ($option, $obrens_verlista, $obrens_verfooter, $obrens_ordenlista);
    break;

  default:
    showRef($option);
    break;
}

# Footer
//Global $obrens_verfooter;
//if ($obrens_verfooter == "1")
	RefFooter($cuotas_version);


//Info Seite
function showAbout( $option ) {
Global $cuotas_version;
?>
<hr>
  <table cellpadding="4" cellspacing="0" border="0" width="80%">
  <tr>
    <td align="center" valign="middle" width="50%" class="sectionname">
        &nbsp;<img src="components/com_obrens/images/logo.png">
    </td>
	<td valign="center">
		<br>&nbsp;<br>&nbsp;<br>
		<b><? echo ADM_ARTREF_Name ?>: </b>ArtRef<br>
		<b><? echo ADM_ARTREF_Version ?> : </b><? echo $cuotas_version; ?><br>
		<b><? echo ADM_ARTREF_Von; ?> : </b>Andreas D.<br>
		&nbsp;&nbsp;&nbsp;&nbsp;<? echo ARTREF_WEBS; ?> : <a href="http://www.mamboart.de" target="_blank">Mamboart.de</a><br>
		&nbsp;&nbsp;&nbsp;&nbsp;<? echo LIT_NCOLFIL; ?> : <a href="mailto:webmaster@mamboart.de">webmaster@mamboart.de</a><br>
		<b>Dank :</b><br>
		&nbsp;&nbsp;&nbsp;&nbsp;<? echo ADM_ARTREF_CreditA; ?><br>
		&nbsp;&nbsp;&nbsp;&nbsp;<? echo ARTREF_WEBS; ?> : <a href="http://konze.de/" target="_blank">Arthur Konze</a><br>
		&nbsp;&nbsp;&nbsp;&nbsp;<? echo ADM_ARTREF_CreditB; ?> <br> 
		&nbsp;&nbsp;&nbsp;&nbsp;<? echo ARTREF_WEBS; ?> : <a href="http://www.mambooport.de" target="_blank">Mamboport.de</a><br>
		&nbsp;&nbsp;&nbsp;&nbsp;<? echo ADM_ARTREF_CreditC; ?> <br> 
		&nbsp;&nbsp;&nbsp;&nbsp;<? echo ARTREF_WEBS; ?> : <a href="http://www.webnetworx.de" target="_blank">Matthias Heymann</a><br>
	</td>
</tr>
  </table>
<br />
<hr>
<?
}

function removeRef( $cid, $option ) {
  global $database;
  if (!is_array( $cid ) || count( $cid ) < 1) {
    echo "<script> alert('".ADM_ARTREF_ERROR_B."'); window.history.go(-1);</script>\n";
    exit;
  }
  if (count( $cid )) {
    $cids = implode( ',', $cid );
    $database->setQuery( "DELETE FROM #__obrens WHERE id IN ($cids)" );
    if (!$database->query()) {
      echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
    }
  }
  mosRedirect( "index2.php?option=$option" );
}


function publishRef( $cid=null, $publish=1,  $option ) {
  global $database, $my;
  $catid = mosGetParam( $_POST, 'catid', array(0) );
  if (!is_array( $cid ) || count( $cid ) < 1) {
    $action = $publish ? 'publish' : 'unpublish';
    echo "<script> alert('".ADM_ARTREF_ERROR_C." $action'); window.history.go(-1);</script>\n";
    exit;
  }
  $cids = implode( ',', $cid );
  $database->setQuery( "UPDATE #__obrens SET published='$publish'WHERE id IN ($cids)" );
  if (!$database->query()) {
    echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
    exit();
  }
  mosRedirect( "index2.php?option=$option" );
}


function orderRef( $uid, $inc, $option ) {
  global $database;
  $row = new mosartref( $database );
  $row->load( $uid );
  $row->move( $inc, "published >= 0" );
  mosRedirect( "index2.php?option=$option" );
}


function cancelRef( $option ) {
  mosRedirect( "index2.php?option=$option" );
}

function saveConfig ($option, $obrens_verlista, $obrens_verfooter, $obrens_ordenlista) {
		
  $configfile = "components/com_obrens/config.obrens.php";
  @chmod ($configfile, 0766);
  $permission = is_writable($configfile);
  if (!$permission) {
    $mosmsg = ADM_ARTREF_ERROR_D;
    mosRedirect("index2.php?option=$option&act=settings",$mosmsg);
    break;
  }
  $config = "<?php\n";
  $config .= "\$obrens_ordenlista = \"$obrens_ordenlista\";\n";
  $config .= "\$obrens_verlista = \"$obrens_verlista\";\n";
  $config .= "\$obrens_verfooter = \"$obrens_verfooter\";\n";
  $config .= "?>";
  if ($fp = fopen("$configfile", "w")) {
    fputs($fp, $config, strlen($config));
    fclose ($fp);
  }
  mosRedirect("index2.php?option=$option&task=settings", ADM_ARTREF_GESPEICHERT);
}

function showConfig( $option ) {
  global $mosConfig_absolute_path;
  require($mosConfig_absolute_path."/administrator/components/com_obrens/config.obrens.php");

  $yesno[] = mosHTML::makeOption( '0', LIT_ADM_NO );
  $yesno[] = mosHTML::makeOption( '1', LIT_ADM_SI );
  $listdisp[] = mosHTML::makeOption( '1', LIT_ADM_LISTAS );
  $listdisp[] = mosHTML::makeOption( '2', LIT_ADM_CATEGORIAS );
  $listdisp2[] = mosHTML::makeOption( '1', LIT_TITULO );
  $listdisp2[] = mosHTML::makeOption( '2', LIT_AUTOR );
  $listdisp2[] = mosHTML::makeOption( '3', LIT_CODIGO );  

  
?>

  <script language="javascript" type="text/javascript">
  function submitbutton(pressbutton) {
    var form = document.adminForm;
    if (pressbutton == 'cancel') {
      submitform( pressbutton );
      return;
    }
    submitform( pressbutton );
  }
  </script>

  <form action="index2.php" method="POST" name="adminForm">
	<script language="javascript" src="js/dhtml.js"></script>
	<table cellpadding="3" cellspacing="0" border="0" width="90%">
	  <tr>
	    <td width="" class="tabpadding">&nbsp;</td>
	    <td id="tab1" onclick="dhtml.cycleTab(this.id)"></td>
	    <!--td id="tab2" class="offtab" onclick="dhtml.cycleTab(this.id)"><? echo ADM_ARTREF_Anzeige; ?></td-->
	    <td width="90%" class="tabpadding">&nbsp;</td>
	  </tr>
	</table>

  <div id="page1" class="pagetext">
  <table width="90%" border="0" cellpadding="4" cellspacing="2" class="adminForm">
    <TR>
      <td align="left" class="sectionname" colspan="3"><div align="left"><? echo LIT_ADM_CONFIGURACION; ?></div></td>
    </TR>

    <tr align="center" valign="middle">
      <td align="left" valign="top"><strong><?php echo ADM_ARTREF_bildZ ?></strong></td>
      <td align="left" valign="top">
      <?php
        $yn_artref_showpicture = mosHTML::selectList( $yesno, 'artref_showpicture', 'class="inputbox" size="2"', 'value', 'text');
        echo $yn_artref_showpicture;
      ?>
      </td>
      <td align="left" valign="top"><?php echo ADM_ARTREF_bildtextinf ?></td>
    </tr>

    <tr align="center" valign="middle">
      <td align="left" valign="top"><strong><?php echo LIT_ADM_VFOOTER ?></strong></td>
      <td align="left" valign="top">
      <?php
        $yn_obrens_verfooter = mosHTML::selectList( $yesno, 'obrens_verfooter', 'class="inputbox" size="2"', 'value', 'text', $obrens_verfooter );
        echo $yn_obrens_verfooter;
      ?>
      </td>
      <td align="left" valign="top"><?php echo LIT_ADM_VFOOTER_DET ?></td>
    </tr>
    
    <tr align="center" valign="middle">
      <td align="left" valign="top"><strong><?php echo LIT_ADM_VISTA ?></strong></td>
      <td align="left" valign="top">
      <?php
        $yn_obrens_verlista = mosHTML::selectList( $listdisp, 'obrens_verlista', 'class="inputbox" size="2"', 'value', 'text', $obrens_verlista );
        echo $yn_obrens_verlista;
      ?>
      </td>
      <td align="left" valign="top"><?php echo LIT_ADM_VISTA_DET ?></td>
    </tr>

    <tr align="center" valign="middle">
      <td align="left" valign="top"><strong><?php echo LIT_ADM_ORDEN ?></strong></td>
      <td align="left" valign="top">
      <?php
        $yn_obrens_ordenlista = mosHTML::selectList( $listdisp2, 'obrens_ordenlista', 'class="inputbox" size="3"', 'value', 'text', $obrens_ordenlista );
        echo $yn_obrens_ordenlista;
      ?>
      </td>
      <td align="left" valign="top"><?php echo LIT_ADM_ORDEN_DET ?></td>
    </tr>

    	
  </table>

  </div>

  <script language="javascript" type="text/javascript">dhtml.cycleTab('tab1');</script>
  <input type="hidden" name="option" value="<?php echo $option; ?>">
  <input type="hidden" name="task" value="">
</form>
<?php
}
############################################################################
############################################################################

function showLanguage($option) {

  global $mosConfig_absolute_path, $mosConfig_lang;

  if (file_exists($mosConfig_absolute_path.'/components/com_obrens/lang/'.$mosConfig_lang.'.php')) {
    $file = $mosConfig_absolute_path.'/components/com_obrens/lang/'.$mosConfig_lang.'.php';
  } else {
    $file = $mosConfig_absolute_path.'/components/com_obrens/lang/english.php';
  }
  @chmod ($file, 0766);
  $permission = is_writable($file);
  if (!$permission) {
    echo "<table width=\"100%\"><tr><td align=\"left\" valign=\"top\"><img src=\"components/com_obrens/images/logo.png\"></td><td>";
	echo "<center><h1><font color=red>".ADM_ARTREF_ERROR_J."</FONT></h1><BR>";
    echo "<B>Language file: ".$file.".</b><BR>";
    echo "<B>You need to chmod this to 766 in order for the config to be updated</B></center><BR><BR>";
    echo "</td></tr></table>";
  }else{
    echo "<table width=\"100%\"><tr><td align=\"left\" valign=\"top\"><img src=\"components/com_obrens/images/logo.png\"></td><td>";
	echo "<center><h1><font color=green>".ADM_ARTREF_ERROR_k."</FONT></h1>";
    echo "</td></tr></table>";
  }

  HTML_artref::showLanguage($file,$option);
}

function saveLanguage($file, $filecontent, $option) {

  @chmod ($file, 0766);
  $permission = is_writable($file);
  if (!$permission) {
    mosRedirect("index2.php?option=$option&task=language", "Language file not writeable!");
    break;
  }

  if ($fp = fopen( $file, "w")) {
    fputs($fp,stripslashes($filecontent));
    fclose($fp);
    mosRedirect( "index2.php?option=$option&task=language", "Language file saved" );
  }
}


?>
