From ee47cf17cf95b92a2fd4a2d7c6988668bd1360d8 Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@users.sourceforge.net>
Date: Wed, 24 Feb 2010 16:41:19 +0000
Subject: [PATCH] Qual: Uniformize code and remove useless function

---
 htdocs/admin/facture.php                      |   2 +-
 htdocs/admin/societe.php                      | 182 +++++++++++++++++-
 .../compta/export/ComptaJournalPdf.class.php  |  17 +-
 .../paiement/cheque/remisecheque.class.php    |   2 +-
 htdocs/compta/paiement/rapport.php            |   2 +-
 htdocs/facture.class.php                      |  53 +++--
 .../pdf/pdf_expedition_merou.modules.php      |  10 +-
 .../pdf/pdf_expedition_rouget.modules.php     |  20 +-
 htdocs/langs/en_US/admin.lang                 |   3 +
 htdocs/langs/fr_FR/admin.lang                 |   3 +
 10 files changed, 250 insertions(+), 44 deletions(-)

diff --git a/htdocs/admin/facture.php b/htdocs/admin/facture.php
index 0c639ffdcc9..5c35cadb9ff 100644
--- a/htdocs/admin/facture.php
+++ b/htdocs/admin/facture.php
@@ -190,7 +190,7 @@ if ($_GET["action"] == 'delete')
 
 
 /*
- * View page
+ * View
  */
 
 llxHeader("",$langs->trans("BillsSetup"),'EN:Invoice_Configuration|FR:Configuration_module_facture|ES:ConfiguracionFactura');
diff --git a/htdocs/admin/societe.php b/htdocs/admin/societe.php
index 8cac01bda5b..afc16719cb2 100644
--- a/htdocs/admin/societe.php
+++ b/htdocs/admin/societe.php
@@ -84,6 +84,45 @@ if ($_POST["action"] == 'updateMask')
 	dolibarr_set_const($db, "COMPANY_ELEPHANT_MASK_SUPPLIER",$_POST["masksupplier"],'chaine',0,'',$conf->entity);
 }
 
+if ($_GET["action"] == 'set')
+{
+	$type='company';
+	$sql = "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity) VALUES ('".$_GET["value"]."','".$type."',".$conf->entity.")";
+	if ($db->query($sql))
+	{
+
+	}
+}
+
+if ($_GET["action"] == 'setdoc')
+{
+	$db->begin();
+
+	if (dolibarr_set_const($db, "COMPANY_ADDON_PDF",$_GET["value"],'chaine',0,'',$conf->entity))
+	{
+		$conf->global->COMPANY_ADDON_PDF = $_GET["value"];
+	}
+
+	// On active le modele
+	$type='company';
+	$sql_del = "DELETE FROM ".MAIN_DB_PREFIX."document_model";
+	$sql_del.= " WHERE nom = '".$_GET["value"]."'";
+	$sql_del.= " AND type = '".$type."'";
+	$sql_del.= " AND entity = ".$conf->entity;
+	$result1=$db->query($sql_del);
+	$sql = "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom,type,entity) VALUES ('".$_GET["value"]."','".$type."',".$conf->entity.")";
+	$result2=$db->query($sql);
+	if ($result1 && $result2)
+	{
+		$db->commit();
+	}
+	else
+	{
+		$db->rollback();
+	}
+}
+
+
 
 /*
  * 	View
@@ -196,18 +235,18 @@ if ($handle)
 		if (substr($file, 0, 15) == 'mod_codecompta_' && substr($file, -3) == 'php')
 		{
 			$file = substr($file, 0, strlen($file)-4);
-			
+
 			require_once(DOL_DOCUMENT_ROOT ."/includes/modules/societe/".$file.".php");
-			
+
 			$modCodeCompta = new $file;
 			$var = !$var;
-			
+
 			print '<tr '.$bc[$var].'>';
 			print '<td width="140">'.$modCodeCompta->nom."</td><td>\n";
 			print $modCodeCompta->info($langs);
 			print '</td>';
 			print '<td nowrap="nowrap">'.$modCodeCompta->getExample($langs)."</td>\n";
-			
+
 			if ($conf->global->SOCIETE_CODECOMPTA_ADDON == "$file")
 			{
 				print '<td align="center">';
@@ -228,8 +267,143 @@ if ($handle)
 }
 print "</table>\n";
 
+
+//
+/*
+ *  Modeles de documents
+ */
 print '<br>';
+print_titre($langs->trans("ModelModules"));
+
+// Defini tableau def de modele invoice
+$def = array();
+$sql = "SELECT nom";
+$sql.= " FROM ".MAIN_DB_PREFIX."document_model";
+$sql.= " WHERE type = 'company'";
+$sql.= " AND entity = ".$conf->entity;
+$resql=$db->query($sql);
+if ($resql)
+{
+	$i = 0;
+	$num_rows=$db->num_rows($resql);
+	while ($i < $num_rows)
+	{
+		$array = $db->fetch_array($resql);
+		array_push($def, $array[0]);
+		$i++;
+	}
+}
+else
+{
+	dol_print_error($db);
+}
+
+print '<table class="noborder" width="100%">';
+print '<tr class="liste_titre">';
+print '<td>'.$langs->trans("Name").'</td>';
+print '<td>'.$langs->trans("Description").'</td>';
+print '<td align="center" width="60">'.$langs->trans("Activated").'</td>';
+print '<td align="center" width="60">'.$langs->trans("Default").'</td>';
+print '<td align="center" width="32" colspan="2">'.$langs->trans("Infos").'</td>';
+print "</tr>\n";
+
+clearstatcache();
+
 
+$var=true;
+foreach ($conf->file->dol_document_root as $dirroot)
+{
+	$dir = $dirroot . "/includes/modules/societe/doc";
+
+	if (is_dir($dir))
+	{
+		$handle=opendir($dir);
+		if ($handle)
+		{
+			while (($file = readdir($handle))!==false)
+			{
+				if (preg_match('/\.modules\.php$/i',$file))
+				{
+					$var = !$var;
+					$name = substr($file, 4, strlen($file) -16);
+					$classname = substr($file, 0, strlen($file) -12);
+
+					print '<tr '.$bc[$var].'><td width="100">';
+					echo "$name";
+					print "</td><td>\n";
+
+					require_once($dir.'/'.$file);
+					$module = new $classname($db);
+					print $module->description;
+					print '</td>';
+
+					// Active
+					if (in_array($name, $def))
+					{
+						print "<td align=\"center\">\n";
+						if ($conf->global->COMPANY_ADDON_PDF != "$name")
+						{
+							print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&amp;value='.$name.'">';
+							print img_tick($langs->trans("Disable"));
+							print '</a>';
+						}
+						else
+						{
+							print img_tick($langs->trans("Enabled"));
+						}
+						print "</td>";
+					}
+					else
+					{
+						print "<td align=\"center\">\n";
+						print '<a href="'.$_SERVER["PHP_SELF"].'?action=set&amp;value='.$name.'">'.$langs->trans("Activate").'</a>';
+						print "</td>";
+					}
+
+					// Defaut
+					print "<td align=\"center\">";
+					if ($conf->global->COMPANY_ADDON_PDF == "$name")
+					{
+						print img_tick($langs->trans("Default"));
+					}
+					else
+					{
+						print '<a href="'.$_SERVER["PHP_SELF"].'?action=setdoc&amp;value='.$name.'" alt="'.$langs->trans("Default").'">'.$langs->trans("Default").'</a>';
+					}
+					print '</td>';
+
+					// Info
+					$htmltooltip =    ''.$langs->trans("Name").': '.$module->name;
+					$htmltooltip.='<br>'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown"));
+					if ($modele->type == 'pdf')
+					{
+						$htmltooltip.='<br>'.$langs->trans("Height").'/'.$langs->trans("Width").': '.$module->page_hauteur.'/'.$module->page_largeur;
+					}
+					$htmltooltip.='<br><br><u>'.$langs->trans("FeaturesSupported").':</u>';
+					$htmltooltip.='<br>'.$langs->trans("WatermarkOnDraft").': '.yn($module->option_draft_watermark,1,1);
+
+
+					print '<td align="center">';
+					print $form->textwithpicto('',$htmltooltip,1,0);
+					print '</td>';
+					print '<td align="center">';
+					if ($modele->type == 'pdf')
+					{
+						print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'">'.img_object($langs->trans("Preview"),'bill').'</a>';
+					}
+					else print '&nbsp;';
+					print '</td>';
+
+					print "</tr>\n";
+				}
+			}
+			closedir($handle);
+		}
+	}
+}
+print '</table>';
+
+print '<br>';
 
 // Autres options
 $html=new Form($db);
diff --git a/htdocs/compta/export/ComptaJournalPdf.class.php b/htdocs/compta/export/ComptaJournalPdf.class.php
index e4935e03d92..96a0a3c2b14 100644
--- a/htdocs/compta/export/ComptaJournalPdf.class.php
+++ b/htdocs/compta/export/ComptaJournalPdf.class.php
@@ -20,20 +20,19 @@
  */
 
 /**
-        \file       htdocs/compta/export/ComptaJournalPdf.php
-        \ingroup    compta
-        \brief      Fichier de la classe export compta journal
-        \version    $Revision$
-*/
-
+ *       \file       htdocs/compta/export/ComptaJournalPdf.php
+ *       \ingroup    compta
+ *       \brief      Fichier de la classe export compta journal
+ *       \version    $Revision$
+ */
 require_once(DOL_DOCUMENT_ROOT.'/lib/pdf.lib.php');
 require_once(DOL_DOCUMENT_ROOT.'/includes/fpdf/fpdfi/fpdi_protection.php');
 
 
 /**
-        \class      ComptaJournalPdf
-        \brief      Classe export compta journal
-*/
+ *       \class      ComptaJournalPdf
+ *       \brief      Classe export compta journal
+ */
 class ComptaJournalPdf extends FPDF  {
 
   function Footer()
diff --git a/htdocs/compta/paiement/cheque/remisecheque.class.php b/htdocs/compta/paiement/cheque/remisecheque.class.php
index 1d60770dbab..8cd10a406af 100644
--- a/htdocs/compta/paiement/cheque/remisecheque.class.php
+++ b/htdocs/compta/paiement/cheque/remisecheque.class.php
@@ -516,7 +516,7 @@ class RemiseCheque extends CommonObject
 			{
 				$outputlangs->charset_output=$sav_charset_output;
 				dol_syslog("Error");
-				dol_print_error($db,$pdf->pdferror());
+				dol_print_error($db,$pdf->error);
 				return 0;
 			}
 		}
diff --git a/htdocs/compta/paiement/rapport.php b/htdocs/compta/paiement/rapport.php
index dab7e0c45f8..27efa83b1bf 100644
--- a/htdocs/compta/paiement/rapport.php
+++ b/htdocs/compta/paiement/rapport.php
@@ -72,7 +72,7 @@ if ($_POST["action"] == 'builddoc')
 	{
 		$outputlangs->charset_output=$sav_charset_output;
 		dol_syslog("Erreur dans commande_pdf_create");
-		dol_print_error($db,$obj->pdferror());
+		dol_print_error($db,$obj->error);
 	}
 
 	$year = $_POST["reyear"];
diff --git a/htdocs/facture.class.php b/htdocs/facture.class.php
index 00e7f55fdad..2fe47ed0935 100644
--- a/htdocs/facture.class.php
+++ b/htdocs/facture.class.php
@@ -1458,43 +1458,56 @@ class Facture extends CommonObject
 	{
 		global $conf,$langs;
 
-		if ($this->statut != 0)
+		$error=0;
+
+		if ($this->statut == 0)
 		{
-			$sql = "UPDATE ".MAIN_DB_PREFIX."facture";
-			$sql.= " SET fk_statut = 0";
-			$sql.= " WHERE rowid = ".$this->id;
+			dol_syslog("Facture::set_draft already draft status", LOG_WARNING);
+			return 0;
+		}
 
-			dol_syslog("Facture::set_draft sql=".$sql, LOG_DEBUG);
-			if ($this->db->query($sql))
+		$this->db->begin();
+
+		$sql = "UPDATE ".MAIN_DB_PREFIX."facture";
+		$sql.= " SET fk_statut = 0";
+		$sql.= " WHERE rowid = ".$this->id;
+
+		dol_syslog("Facture::set_draft sql=".$sql, LOG_DEBUG);
+		if ($this->db->query($sql))
+		{
+			// Si active on decremente le produit principal et ses composants a la validation de facture
+			if ($result >= 0 && $conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_BILL)
 			{
-				// Si active on decremente le produit principal et ses composants a la validation de facture
-				if ($result >= 0 && $conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_BILL)
-				{
-					require_once(DOL_DOCUMENT_ROOT."/product/stock/mouvementstock.class.php");
+				require_once(DOL_DOCUMENT_ROOT."/product/stock/mouvementstock.class.php");
 
-					for ($i = 0 ; $i < sizeof($this->lignes) ; $i++)
+				for ($i = 0 ; $i < sizeof($this->lignes) ; $i++)
+				{
+					if ($this->lignes[$i]->fk_product && $this->lignes[$i]->product_type == 0)
 					{
-						if ($this->lignes[$i]->fk_product && $this->lignes[$i]->product_type == 0)
-						{
-							$mouvP = new MouvementStock($this->db);
-							// We decrease stock for product
-							$entrepot_id = "1"; // TODO ajouter possibilite de choisir l'entrepot
-							$result=$mouvP->reception($user, $this->lignes[$i]->fk_product, $entrepot_id, $this->lignes[$i]->qty, $this->lignes[$i]->subprice);
-						}
+						$mouvP = new MouvementStock($this->db);
+						// We decrease stock for product
+						$entrepot_id = "1"; // TODO ajouter possibilite de choisir l'entrepot
+						$result=$mouvP->reception($user, $this->lignes[$i]->fk_product, $entrepot_id, $this->lignes[$i]->qty, $this->lignes[$i]->subprice);
 					}
 				}
+			}
 
+			if ($error == 0)
+			{
+				$this->db->commit();
 				return 1;
 			}
 			else
 			{
-				$this->error=$this->db->error();
+				$this->db->rollback();
 				return -1;
 			}
 		}
 		else
 		{
-			dol_syslog("Facture::set_draft Invoice already with draf status", LOG_WARNING);
+			$this->error=$this->db->error();
+			$this->db->rollback();
+			return -1;
 		}
 	}
 
diff --git a/htdocs/includes/modules/expedition/pdf/pdf_expedition_merou.modules.php b/htdocs/includes/modules/expedition/pdf/pdf_expedition_merou.modules.php
index e8680b9eb2b..41cc73b1a5e 100644
--- a/htdocs/includes/modules/expedition/pdf/pdf_expedition_merou.modules.php
+++ b/htdocs/includes/modules/expedition/pdf/pdf_expedition_merou.modules.php
@@ -22,7 +22,7 @@
 /**
  *	\file       htdocs/includes/modules/expedition/pdf/pdf_expedition_merou.modules.php
  *	\ingroup    expedition
- *	\brief      Fichier de la classe permettant de generer les bordereaux envoi au mod�le Merou
+ *	\brief      Fichier de la classe permettant de generer les bordereaux envoi au modele Merou
  *	\version    $Id$
  */
 
@@ -138,17 +138,19 @@ Class pdf_expedition_merou extends ModelePdfExpedition
 			//Si le dossier existe
 			if (file_exists($dir))
 			{
-				// Initialisation Bon vierge
-				$pdf = new FPDI_Protection('l','mm',$this->format);
-
 				// Protection et encryption du pdf
 				if ($conf->global->PDF_SECURITY_ENCRYPTION)
 				{
+					$pdf=new FPDI_Protection('l','mm',$this->format);
 					$pdfrights = array('print'); // Ne permet que l'impression du document
 					$pdfuserpass = ''; // Mot de passe pour l'utilisateur final
 					$pdfownerpass = NULL; // Mot de passe du proprietaire, cree aleatoirement si pas defini
 					$pdf->SetProtection($pdfrights,$pdfuserpass,$pdfownerpass);
 				}
+				else
+				{
+					$pdf=new FPDI('l','mm',$this->format);
+				}
 
 				$pdf->Open();
 				$pagenb=0;
diff --git a/htdocs/includes/modules/expedition/pdf/pdf_expedition_rouget.modules.php b/htdocs/includes/modules/expedition/pdf/pdf_expedition_rouget.modules.php
index 5732ba473a3..1eb52950361 100644
--- a/htdocs/includes/modules/expedition/pdf/pdf_expedition_rouget.modules.php
+++ b/htdocs/includes/modules/expedition/pdf/pdf_expedition_rouget.modules.php
@@ -21,7 +21,7 @@
 /**
  *	\file       htdocs/includes/modules/expedition/pdf/pdf_expedition_rouget.modules.php
  *	\ingroup    expedition
- *	\brief      Fichier de la classe permettant de generer les bordereaux envoi au mod�le Rouget
+ *	\brief      Fichier de la classe permettant de generer les bordereaux envoi au modele Rouget
  *	\version    $Id$
  */
 
@@ -40,8 +40,8 @@ Class pdf_expedition_rouget extends ModelePdfExpedition
 
 
 	/**
-	 \brief  Constructeur
-	 \param	db		Handler acc�s base de donn�e
+	 *	\brief  Constructeur
+	 *	\param	db		Database handler
 	 */
 	function pdf_expedition_rouget($db=0)
 	{
@@ -263,7 +263,19 @@ Class pdf_expedition_rouget extends ModelePdfExpedition
 
 			if (file_exists($dir))
 			{
-				$pdf=new ModelePdfExpedition();
+				// Protection et encryption du pdf
+				if ($conf->global->PDF_SECURITY_ENCRYPTION)
+				{
+					$pdf=new FPDI_Protection('P','mm',$this->format);
+					$pdfrights = array('print'); // Ne permet que l'impression du document
+					$pdfuserpass = ''; // Mot de passe pour l'utilisateur final
+					$pdfownerpass = NULL; // Mot de passe du proprietaire, cree aleatoirement si pas defini
+					$pdf->SetProtection($pdfrights,$pdfuserpass,$pdfownerpass);
+				}
+				else
+				{
+					$pdf=new FPDI('P','mm',$this->format);
+				}
 
 				$pdf->Open();
 				$pagenb=0;
diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang
index 60a92a127b8..6ef05a42e3e 100644
--- a/htdocs/langs/en_US/admin.lang
+++ b/htdocs/langs/en_US/admin.lang
@@ -779,6 +779,9 @@ ModuleCompanyCodePanicum=Return an empty accountancy code.
 ModuleCompanyCodeDigitaria=Accountancy code depends on third party code. The code is composed of the character "C" in the first position followed by the first 5 characters of the third party code.  
 UseNotifications=Use notifications
 NotificationsDesc=EMails notifications feature allows you to silently send automatic mail, for some Dolibarr events, to third parties (customers or suppliers) that are configured to. Choice of active notification and targets contacts is made one third party at time.
+ModelModules=Documents templates
+DocumentModelOdt=Generate documents from .ODT file format templates (OpenOffice...)
+WatermarkOnDraft=Watermark on draft document
 ##### Webcal setup #####
 WebCalSetup=Webcalendar link setup
 WebCalSyncro=Add Dolibarr events to WebCalendar
diff --git a/htdocs/langs/fr_FR/admin.lang b/htdocs/langs/fr_FR/admin.lang
index e3150821561..6441318e117 100644
--- a/htdocs/langs/fr_FR/admin.lang
+++ b/htdocs/langs/fr_FR/admin.lang
@@ -779,6 +779,9 @@ ModuleCompanyCodePanicum = Renvoie un code compta vide.
 ModuleCompanyCodeDigitaria = Renvoie un code compta composé suivant le code tiers. Le code est composé du caractère 'C' en première position suivi des 5 premiers caractères du code tiers.
 UseNotifications = Utiliser les notifications
 NotificationsDesc = La fonction des notifications par emails permet d'envoyer automatiquement un email, pour certains évênement Dolibarr, aux tiers (sociétés clients, prospects ou fournisseurs) configurés pour. Le choix des notifications et contacts destinataires se fait tiers par tiers.
+ModelModules=Modèle de documents
+DocumentModelOdt=Genérateur depuis des modèles au format .ODT (OpenOffice...)
+WatermarkOnDraft=Filigrame sur les documents brouillons
 ##### Webcal setup ##### = undefined
 WebCalSetup = Configuration du lien vers le calendrier Webcalendar
 WebCalSyncro = Intégrer les évênements Dolibarr dans WebCalendar
-- 
GitLab