From 77ef046af462a5aa1a7837308ff46eb27c40856d Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Sun, 6 Sep 2015 12:30:41 +0200
Subject: [PATCH] Start to mutualize the builddoc and remove_file action.

---
 htdocs/core/actions_builddoc.inc.php          | 108 ++++++++++++++++++
 htdocs/core/actions_dellink.inc.php           |  37 ------
 htdocs/core/class/commonobject.class.php      |   1 -
 .../cheque/pdf/modules_chequereceipts.php     |   3 +-
 .../core/modules/facture/modules_facture.php  |   4 +-
 .../modules/societe/modules_societe.class.php |  27 ++++-
 .../tpl/document_actions_pre_headers.tpl.php  |   5 +
 .../install/mysql/migration/3.8.0-3.9.0.sql   |   3 +
 htdocs/install/mysql/tables/llx_societe.sql   |   1 +
 htdocs/livraison/class/livraison.class.php    |  16 +--
 htdocs/projet/class/task.class.php            |   3 +-
 htdocs/societe/class/societe.class.php        |  40 ++++++-
 htdocs/societe/soc.php                        |  57 +--------
 13 files changed, 199 insertions(+), 106 deletions(-)
 create mode 100644 htdocs/core/actions_builddoc.inc.php

diff --git a/htdocs/core/actions_builddoc.inc.php b/htdocs/core/actions_builddoc.inc.php
new file mode 100644
index 00000000000..27e5d8f602b
--- /dev/null
+++ b/htdocs/core/actions_builddoc.inc.php
@@ -0,0 +1,108 @@
+<?php
+/* Copyright (C) 2015 Laurent Destailleur  <eldy@users.sourceforge.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * or see http://www.gnu.org/
+ */
+
+/**
+ *	\file			htdocs/core/actions_builddoc.inc.php
+ *  \brief			Code for actions on building or deleting documents
+ */
+
+
+// $action must be defined
+// $id must be defined
+// $object must be defined and must have a method generateDocument.
+// $permissioncreate must be defined
+// $upload_dir must be defined (example $conf->projet->dir_output . "/";)
+// $hidedetails, $hidedesc and $hideref may have been set or not.
+
+
+// Build doc
+if ($action == 'builddoc' && $permissioncreate)
+{
+    if (is_numeric(GETPOST('model')))
+    {
+        $error=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Model"));
+    }
+    else
+    {
+        // Reload to get all modified line records and be ready for hooks
+        $ret = $object->fetch($id);
+        $ret = $object->fetch_thirdparty();
+        /*if (empty($object->id) || ! $object->id > 0)
+        {
+            dol_print_error('Object must have been loaded by a fetch');
+            exit;
+        }*/
+        
+        // Save last template used to generate document
+    	if (GETPOST('model')) $object->setDocModel($user, GETPOST('model','alpha'));
+    
+        // Special case for invoices
+        if (property_exists($object, 'fk_bank'))
+        {
+            if (GETPOST('fk_bank')) { // this field may come from an external module
+                $object->fk_bank = GETPOST('fk_bank');
+            } else {
+                $object->fk_bank = $object->fk_account;
+            }
+        }
+
+        $outputlangs = $langs;
+        $newlang='';
+        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id');
+        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->client->default_lang)) $newlang=$object->client->default_lang;  // for proposal, order, invoice, ...
+        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) $newlang=$object->default_lang;                  // for thirdparty
+        if (! empty($newlang))
+        {
+            $outputlangs = new Translate("",$conf);
+            $outputlangs->setDefaultLang($newlang);
+        }
+        
+        // To be sure vars is defined
+        if (empty($hidedetails)) $hidedetails=0;
+        if (empty($hidedesc)) $hidedesc=0;
+        if (empty($hideref)) $hideref=0;
+        
+        $result= $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+        if ($result <= 0)
+        {
+            setEventMessages($object->error, $object->errors, 'errors');
+            $action='';
+        }
+    }
+}
+
+// Delete file in doc form
+if ($action == 'remove_file' && $permissioncreate)
+{
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+    if (empty($object->id) || ! $object->id > 0)
+    {
+        // Reload to get all modified line records and be ready for hooks
+        $ret = $object->fetch($id);
+        $ret = $object->fetch_thirdparty();
+    }
+
+    $langs->load("other");
+    $filetodelete=GETPOST('file','alpha');
+    $file =	$upload_dir	. '/' .	$filetodelete;
+    $ret=dol_delete_file($file,0,0,0,$object);
+    if ($ret) setEventMessage($langs->trans("FileWasRemoved", $filetodelete));
+    else setEventMessage($langs->trans("ErrorFailToDeleteFile", $filetodelete), 'errors');
+}
+
diff --git a/htdocs/core/actions_dellink.inc.php b/htdocs/core/actions_dellink.inc.php
index 8f3d3c5f277..45fb8c5f9ec 100644
--- a/htdocs/core/actions_dellink.inc.php
+++ b/htdocs/core/actions_dellink.inc.php
@@ -36,41 +36,4 @@ if ($action == 'dellink' && ! empty($permissiondellink) && ! GETPOST('cancel') &
 	if ($result < 0) setEventMessages($object->error,$object->errors,'errors');
 }
 
-// Build doc
-/* TODO To mutualise code for builddoc and remove_file
-if ($action == 'builddoc' && $permissiondellink)
-{
-	// Save last template used to generate document
-	if (GETPOST('model')) $object->setDocModel($user, GETPOST('model','alpha'));
-
-    $outputlangs = $langs;
-    if (GETPOST('lang_id'))
-    {
-        $outputlangs = new Translate("",$conf);
-        $outputlangs->setDefaultLang(GETPOST('lang_id'));
-    }
-    $result= $object->generateDocument($object->modelpdf, $outputlangs);
-    if ($result <= 0)
-    {
-        setEventMessages($object->error, $object->errors, 'errors');
-        $action='';
-    }
-}
-
-// Delete file in doc form
-if ($action == 'remove_file' && $permissiondellink)
-{
-    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-
-    if ($object->id > 0)
-    {
-        $langs->load("other");
-        $urlfile=GETPOST('urlfile','alpha');
-        $file =	$upload_dir	. '/' .	$filetodelete;
-        $ret=dol_delete_file($file);
-        if ($ret) setEventMessage($langs->trans("FileWasRemoved", $urlfile));
-        else setEventMessage($langs->trans("ErrorFailToDeleteFile", $urlfile), 'errors');
-    }
-}
-*/
 
diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php
index a4136d880f0..42b8dba1da2 100644
--- a/htdocs/core/class/commonobject.class.php
+++ b/htdocs/core/class/commonobject.class.php
@@ -3432,7 +3432,6 @@ abstract class CommonObject
 			require_once $file;
 
 			$obj = new $classname($this->db);
-			//$obj->message = $message;
 
 			// If generator is ODT, we must have srctemplatepath defined, if not we set it.
 			if ($obj->type == 'odt' && empty($srctemplatepath))
diff --git a/htdocs/core/modules/cheque/pdf/modules_chequereceipts.php b/htdocs/core/modules/cheque/pdf/modules_chequereceipts.php
index 11ff9b509ad..e4d68c525fa 100644
--- a/htdocs/core/modules/cheque/pdf/modules_chequereceipts.php
+++ b/htdocs/core/modules/cheque/pdf/modules_chequereceipts.php
@@ -71,7 +71,7 @@ abstract class ModeleChequeReceipts extends CommonDocGenerator
  *	@param	string		$modele			Force le modele a utiliser ('' to not force)
  *	@param	Translate	$outputlangs	Object lang a utiliser pour traduction
  *	@return int        					<0 if KO, >0 if OK
- * 	TODO
+ * 	TODO Use commonDocGenerator
  */
 function chequereceipt_pdf_create($db, $id, $message, $modele, $outputlangs)
 {
@@ -103,7 +103,6 @@ function chequereceipt_pdf_create($db, $id, $message, $modele, $outputlangs)
 		require_once $dir.$file;
 
 		$obj = new $classname($db);
-		$obj->message = $message;
 
 		// We save charset_output to restore it because write_file can change it if needed for
 		// output format that does not support UTF8.
diff --git a/htdocs/core/modules/facture/modules_facture.php b/htdocs/core/modules/facture/modules_facture.php
index afae663b02b..23d55d0aa96 100644
--- a/htdocs/core/modules/facture/modules_facture.php
+++ b/htdocs/core/modules/facture/modules_facture.php
@@ -155,8 +155,8 @@ abstract class ModeleNumRefFactures
  *  @param  int			$hidedesc       Hide description
  *  @param  int			$hideref        Hide ref
  *	@return int        					<0 if KO, >0 if OK
- * @deprecated Use the new function generateDocument of Facture class
- * @see Facture::generateDocument()
+ *  @deprecated Use the new function generateDocument of Facture class
+ *  @see Facture::generateDocument()
  */
 function facture_pdf_create(DoliDB $db, Facture $object, $modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
 {
diff --git a/htdocs/core/modules/societe/modules_societe.class.php b/htdocs/core/modules/societe/modules_societe.class.php
index 72090a581ea..63208b1369c 100644
--- a/htdocs/core/modules/societe/modules_societe.class.php
+++ b/htdocs/core/modules/societe/modules_societe.class.php
@@ -363,6 +363,28 @@ abstract class ModeleAccountancyCode
 
 
 
+/**
+ *  Create a document onto disk according to template module.
+ *
+ *	@param	DoliDB		$db  			Database handler
+ *	@param  Facture		$object			Object invoice
+ *  @param  string      $message        Message (not used, deprecated)
+ *	@param	string		$modele			Force template to use ('' to not force)
+ *	@param	Translate	$outputlangs	objet lang a utiliser pour traduction
+ *  @param  int			$hidedetails    Hide details of lines
+ *  @param  int			$hidedesc       Hide description
+ *  @param  int			$hideref        Hide ref
+ *	@return int        					<0 if KO, >0 if OK
+ *  @deprecated Use the new function generateDocument of Facture class
+ *  @see Societe::generateDocument()
+ */
+function thirdparty_doc_create(DoliDB $db, Societe $object, $message, $modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
+{
+	dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
+
+	return $object->generateDocument($modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
+}
+
 
 /**
  *	Create a document for third party
@@ -374,7 +396,7 @@ abstract class ModeleAccountancyCode
  *	@param	Translate	$outputlangs	Object lang to use for translation
  *	@return int        					<0 if KO, >0 if OK
  */
-function thirdparty_doc_create($db, $object, $message, $modele, $outputlangs)
+/*function thirdparty_doc_create($db, $object, $message, $modele, $outputlangs)
 {
     global $conf,$langs,$user;
     $langs->load("bills");
@@ -413,7 +435,6 @@ function thirdparty_doc_create($db, $object, $message, $modele, $outputlangs)
         require_once $dir.'/'.$file;
 
         $obj = new $classname($db);
-        $obj->message = $message;
 
         // We save charset_output to restore it because write_file can change it if needed for
         // output format that does not support UTF8.
@@ -438,5 +459,5 @@ function thirdparty_doc_create($db, $object, $message, $modele, $outputlangs)
         return -1;
     }
 }
-
+*/
 
diff --git a/htdocs/core/tpl/document_actions_pre_headers.tpl.php b/htdocs/core/tpl/document_actions_pre_headers.tpl.php
index 1e4dbc7c5bb..2bb6d930b84 100644
--- a/htdocs/core/tpl/document_actions_pre_headers.tpl.php
+++ b/htdocs/core/tpl/document_actions_pre_headers.tpl.php
@@ -17,6 +17,11 @@
  * or see http://www.gnu.org/
  */
 
+
+// TODO This is an action include, not a presentation template.
+// Move this file into htdocs/core/actions_document.inc.php
+
+
 // Variable $upload_dir must be defined when entering here
 
 // Send file/link
diff --git a/htdocs/install/mysql/migration/3.8.0-3.9.0.sql b/htdocs/install/mysql/migration/3.8.0-3.9.0.sql
index 8b64acf2ce8..24d81f5f7e9 100644
--- a/htdocs/install/mysql/migration/3.8.0-3.9.0.sql
+++ b/htdocs/install/mysql/migration/3.8.0-3.9.0.sql
@@ -23,3 +23,6 @@ INSERT INTO llx_const (name, value, type, note, visible) values ('MAIN_DELAY_EXP
 
 ALTER TABLE llx_accounting_system MODIFY COLUMN pcg_version varchar(32);
 ALTER TABLE llx_accountingaccount MODIFY COLUMN fk_pcg_version varchar(32);
+
+ALTER TABLE llx_societe ADD COLUMN model_pdf varchar(255);
+
diff --git a/htdocs/install/mysql/tables/llx_societe.sql b/htdocs/install/mysql/tables/llx_societe.sql
index 4dc1b3fe750..0244b9ea757 100644
--- a/htdocs/install/mysql/tables/llx_societe.sql
+++ b/htdocs/install/mysql/tables/llx_societe.sql
@@ -67,6 +67,7 @@ create table llx_societe
   fk_stcomm                integer        DEFAULT 0 NOT NULL,      	-- commercial statut
   note_private             text,                                		--
   note_public              text,                                        --
+  model_pdf				   varchar(255),
   prefix_comm              varchar(5),                          		-- prefix commercial
   client                   tinyint        DEFAULT 0,            		-- client 0/1/2
   fournisseur              tinyint        DEFAULT 0,            		-- fournisseur 0/1
diff --git a/htdocs/livraison/class/livraison.class.php b/htdocs/livraison/class/livraison.class.php
index 3a1704f8d8d..c996c2a1bc5 100644
--- a/htdocs/livraison/class/livraison.class.php
+++ b/htdocs/livraison/class/livraison.class.php
@@ -35,8 +35,7 @@ if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande
 
 
 /**
- *  \class      Livraison
- *  \brief      Classe de gestion des bons de livraison
+ *  Class to manage receptions
  */
 class Livraison extends CommonObject
 {
@@ -967,11 +966,14 @@ class Livraison extends CommonObject
 	/**
 	 *	Create object on disk
 	 *
-	 *	@param	string		$modele			force le modele a utiliser ('' to not force)
-	 *	@param	Translate	$outputlangs	objet lang a utiliser pour traduction
-	 *  @return int         				0 if KO, 1 if OK
+	 *	@param     string		$modele			force le modele a utiliser ('' to not force)
+	 * 	@param     Translate	$outputlangs	Object langs to use for output
+	 *  @param     int			$hidedetails    Hide details of lines
+	 *  @param     int			$hidedesc       Hide description
+	 *  @param     int			$hideref        Hide ref
+	 *  @return    int             				0 if KO, 1 if OK
 	 */
-	public function generateDocument($modele, $outputlangs='')
+	public function generateDocument($modele, $outputlangs='',$hidedetails=0,$hidedesc=0,$hideref=0)
 	{
 		global $conf,$user,$langs;
 
@@ -992,7 +994,7 @@ class Livraison extends CommonObject
 
 		$modelpath = "core/modules/livraison/doc/";
 
-		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, 0, 0, 0);
+		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
 	}
 
 	/**
diff --git a/htdocs/projet/class/task.class.php b/htdocs/projet/class/task.class.php
index b938885adc9..a8dffb8c494 100644
--- a/htdocs/projet/class/task.class.php
+++ b/htdocs/projet/class/task.class.php
@@ -1486,10 +1486,9 @@ class Task extends CommonObject
 	 *  @param  int			$hidedetails    Hide details of lines
 	 *  @param  int			$hidedesc       Hide description
 	 *  @param  int			$hideref        Hide ref
-	 *  @param  HookManager	$hookmanager	Hook manager instance
 	 *  @return int         				0 if KO, 1 if OK
 	 */
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $hookmanager=false)
+	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
 	{
 		global $conf,$langs;
 
diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php
index 7de6fdec844..c3dfeb7b226 100644
--- a/htdocs/societe/class/societe.class.php
+++ b/htdocs/societe/class/societe.class.php
@@ -1012,7 +1012,7 @@ class Societe extends CommonObject
         $sql .= ', s.status';
         $sql .= ', s.price_level';
         $sql .= ', s.tms as date_modification';
-        $sql .= ', s.phone, s.fax, s.email, s.skype, s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
+        $sql .= ', s.phone, s.fax, s.email, s.skype, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
         $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
         $sql .= ', s.capital, s.tva_intra';
         $sql .= ', s.fk_typent as typent_id';
@@ -1154,6 +1154,7 @@ class Societe extends CommonObject
                 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
                 $this->note_private = $obj->note_private;
                 $this->note_public = $obj->note_public;
+                $this->modelpdf = $obj->model_pdf;
                 $this->default_lang = $obj->default_lang;
                 $this->logo = $obj->logo;
 
@@ -3342,6 +3343,43 @@ class Societe extends CommonObject
 
 	}
 
+	
+	/**
+	 *  Create a document onto disk according to template module.
+	 *
+	 *	@param	string		$modele			Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
+	 *	@param	Translate	$outputlangs	objet lang a utiliser pour traduction
+	 *  @param  int			$hidedetails    Hide details of lines
+	 *  @param  int			$hidedesc       Hide description
+	 *  @param  int			$hideref        Hide ref
+	 *	@return int        					<0 if KO, >0 if OK
+	 */
+	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
+	{
+		global $conf,$user,$langs;
+
+		// Positionne le modele sur le nom du modele a utiliser
+		if (! dol_strlen($modele))
+		{
+			if (! empty($conf->global->COMPANY_ADDON_PDF))
+			{
+				$modele = $conf->global->COMPANY_ADDON_PDF;
+			}
+			else
+			{
+				print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
+                return 0;
+			}
+		}
+
+		$modelpath = "core/modules/societe/doc/";
+
+		$result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
+
+		return $result;
+	}
+	
+	
 	/**
 	 * Function used to replace a thirdparty id with another one.
 	 * It must be used within a transaction to avoid trouble
diff --git a/htdocs/societe/soc.php b/htdocs/societe/soc.php
index b80f0f2c086..bc19fbe3fd6 100644
--- a/htdocs/societe/soc.php
+++ b/htdocs/societe/soc.php
@@ -702,56 +702,11 @@ if (empty($reshook))
     $mode='emailfromthirdparty';
     include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
 
-
-    /*
-     * Generate document
-     */
-    if ($action == 'builddoc')  // En get ou en post
-    {
-        if (is_numeric(GETPOST('model')))
-        {
-            $error=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Model"));
-        }
-        else
-        {
-            require_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
-
-            $object->fetch($socid);
-
-            // Define output language
-            $outputlangs = $langs;
-            $newlang='';
-            if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id');
-            if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$fac->client->default_lang;
-            if (! empty($newlang))
-            {
-                $outputlangs = new Translate("",$conf);
-                $outputlangs->setDefaultLang($newlang);
-            }
-            $result=thirdparty_doc_create($db, $object, '', GETPOST('model','alpha'), $outputlangs);
-            if ($result <= 0)
-            {
-                dol_print_error($db,$result);
-                exit;
-            }
-        }
-    }
-
-    // Remove file in doc form
-    else if ($action == 'remove_file')
-    {
-    	if ($object->fetch($socid))
-    	{
-    		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-
-    		$langs->load("other");
-    		$upload_dir = $conf->societe->dir_output;
-    		$file = $upload_dir . '/' . GETPOST('file');
-    		$ret=dol_delete_file($file,0,0,0,$object);
-    		if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile')));
-    		else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), 'errors');
-    	}
-    }
+    // Actions to build doc
+    $id = $socid;
+    $upload_dir = $conf->societe->dir_output;
+    $permissioncreate=$user->rights->societe->creer;
+    include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
 }
 
 
@@ -2556,7 +2511,7 @@ else
 
 	            $var=true;
 
-	            $somethingshown=$formfile->show_documents('company',$object->id,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,28,0,'',0,'',$object->default_lang);
+	            print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 0, 0, 0, 28, 0, '', 0, '', $object->default_lang);
 
 				print '</div><div class="fichehalfright"><div class="ficheaddleft">';
 
-- 
GitLab