From 24bb2ca1d469e50f9cb8af7971ec6ab4f81ae43e Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 29 Apr 2008 21:13:49 +0000 Subject: [PATCH] Directory to store files follow same tree than tree of sections --- htdocs/admin/tools/purge.php | 176 +- htdocs/compta/clients.php | 4 +- htdocs/ecm/docmine.php | 104 +- htdocs/ecm/ecmdirectory.class.php | 57 +- htdocs/ecm/htmlecm.form.class.php | 73 +- htdocs/html.formfile.class.php | 3 +- htdocs/install/etape5.php | 6 +- htdocs/install/upgrade.php | 8 +- htdocs/install/upgrade2.php | 6 +- htdocs/langs/en_US/ecm.lang | 5 +- htdocs/langs/fr_FR/ecm.lang | 7 +- htdocs/lib/files.lib.php | 103 ++ htdocs/lib/functions.lib.php | 2873 ++++++++++++++--------------- htdocs/lib/security.lib.php | 247 +-- htdocs/master.inc.php | 6 +- 15 files changed, 1871 insertions(+), 1807 deletions(-) diff --git a/htdocs/admin/tools/purge.php b/htdocs/admin/tools/purge.php index 4f5b9d13a39..519f575d8b9 100644 --- a/htdocs/admin/tools/purge.php +++ b/htdocs/admin/tools/purge.php @@ -14,109 +14,107 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - * $Id$ - * $Source$ */ /** \file htdocs/admin/tools/purge.php \brief Page de purge des fichiers temporaires - \version $Revision$ -*/ - + \version $Id$ +*/ + require("./pre.inc.php"); -include_once $dolibarr_main_document_root."/lib/databases/".$conf->db->type.".lib.php"; +include_once(DOL_DOCUMENT_ROOT."/lib/databases/".$conf->db->type.".lib.php"); +include_once(DOL_DOCUMENT_ROOT.'/lib/files.lib.php'); $langs->load("admin"); if (! $user->admin) accessforbidden(); - -if ($_GET["msg"]) $message='
'.$_GET["msg"].'
'; - - -/* -* Actions -*/ -if ($_POST["action"]=='purge') -{ - $filesarray=array(); - - if ($_POST["choice"]=='tempfiles') - { - // Delete temporary files - if ($dolibarr_main_data_root) - { - $filesarray=dolibarr_dir_list($dolibarr_main_data_root,"directories",1,'temp'); - } - } - - if ($_POST["choice"]=='allfiles') - { - // Delete all files - if ($dolibarr_main_data_root) - { - $filesarray=dolibarr_dir_list($dolibarr_main_data_root,"all",0); - } - } - - $count=0; - if (sizeof($filesarray)) - { - foreach($filesarray as $key => $value) - { - //print "x ".$filesarray[$key]['fullname']."
\n"; - $count+=dol_delete_dir_recursive($filesarray[$key]['fullname']); - } - - } - - if ($count) $message=$langs->trans("PurgeNDirectoriesDeleted",$count); - else $message=$langs->trans("PurgeNothingToDelete"); - $message='
'.$message.'
'; -} - - -/* -* Affichage page -*/ +if ($_GET["msg"]) $message='
'.$_GET["msg"].'
'; + + + +/* +* Actions +*/ +if ($_POST["action"]=='purge') +{ + $filesarray=array(); + + if ($_POST["choice"]=='tempfiles') + { + // Delete temporary files + if ($dolibarr_main_data_root) + { + $filesarray=dol_dir_list($dolibarr_main_data_root,"directories",1,'temp'); + } + } + + if ($_POST["choice"]=='allfiles') + { + // Delete all files + if ($dolibarr_main_data_root) + { + $filesarray=dol_dir_list($dolibarr_main_data_root,"all",0); + } + } + + $count=0; + if (sizeof($filesarray)) + { + foreach($filesarray as $key => $value) + { + //print "x ".$filesarray[$key]['fullname']."
\n"; + $count+=dol_delete_dir_recursive($filesarray[$key]['fullname']); + } + + } + + if ($count) $message=$langs->trans("PurgeNDirectoriesDeleted",$count); + else $message=$langs->trans("PurgeNothingToDelete"); + $message='
'.$message.'
'; +} + + +/* +* Affichage page +*/ llxHeader(); -$html=new Form($db); - -print_fiche_titre($langs->trans("Purge"),'','setup'); -print '
'; - -print $langs->trans("PurgeAreaDesc",$dolibarr_main_data_root).'
'; -print '
'; - -if ($message) -{ - print $message.'
'; - print "\n"; -} - -print '
'; - -print ''; - -print '
'; -print ' '.$langs->trans("PurgeDeleteTemporaryFiles").'
'; -print ' '.$langs->trans("PurgeDeleteAllFilesInDocumentsDir",$dolibarr_main_data_root).'
'; -print '
'; - -print '
'; -print '
'; - - -print '
'; - +$html=new Form($db); + +print_fiche_titre($langs->trans("Purge"),'','setup'); +print '
'; + +print $langs->trans("PurgeAreaDesc",$dolibarr_main_data_root).'
'; +print '
'; + +if ($message) +{ + print $message.'
'; + print "\n"; +} + +print '
'; + +print ''; + +print '
'; +print ' '.$langs->trans("PurgeDeleteTemporaryFiles").'
'; +print ' '.$langs->trans("PurgeDeleteAllFilesInDocumentsDir",$dolibarr_main_data_root).'
'; +print '
'; + +print '
'; +print '
'; + + +print '
'; + llxFooter('$Date$ - $Revision$'); ?> \ No newline at end of file diff --git a/htdocs/compta/clients.php b/htdocs/compta/clients.php index 6314d104bf3..001e7e0f54b 100644 --- a/htdocs/compta/clients.php +++ b/htdocs/compta/clients.php @@ -15,15 +15,13 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - * $Id$ */ /** \file htdocs/compta/clients.php \ingroup compta \brief Page accueil des clients - \version $Revision$ + \version $Id$ */ require_once("./pre.inc.php"); diff --git a/htdocs/ecm/docmine.php b/htdocs/ecm/docmine.php index efff4eefd06..96d7215b631 100644 --- a/htdocs/ecm/docmine.php +++ b/htdocs/ecm/docmine.php @@ -16,6 +16,7 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + /** \file htdoc/ecm/docmine.php \ingroup ecm @@ -23,7 +24,6 @@ \version $Id$ \author Laurent Destailleur */ - require("./pre.inc.php"); require_once(DOL_DOCUMENT_ROOT."/html.formfile.class.php"); require_once(DOL_DOCUMENT_ROOT."/ecm/ecmdirectory.class.php"); @@ -39,16 +39,25 @@ $langs->load("other"); // Load permissions $user->getrights('ecm'); -// Get parameters -$socid = isset($_GET["socid"])?$_GET["socid"]:''; - -// Permissions +// Security check if ($user->societe_id > 0) { $action = ''; $socid = $user->societe_id; } +// Get parameters +$page=$_GET["page"]; +$sortorder=$_GET["sortorder"]; +$sortfield=$_GET["sortfield"]; + +if (! $sortorder) $sortorder="ASC"; +if (! $sortfield) $sortfield="name"; +if ($page == -1) { $page = 0 ; } +$offset = $conf->liste_limit * $page ; +$pageprev = $page - 1; +$pagenext = $page + 1; + $section=$_REQUEST["section"]; if (! $section) { @@ -56,18 +65,22 @@ if (! $section) exit; } -$ecmdir = new ECMDirectory($db); -if (! empty($_REQUEST["section"])) -{ - $result=$ecmdir->fetch($_REQUEST["section"]); - if (! $result > 0) - { - dolibarr_print_error($db,$ecmdir->error); - exit; - } -} -$upload_dir = $conf->ecm->dir_output.'/'.$ecmdir->label; +// Load ecm object +$ecmdir = new ECMDirectory($db); +if (empty($_REQUEST["section"])) +{ + dolibarr_print_error('','Error, section parameter missing'); + exit; +} +$result=$ecmdir->fetch($_REQUEST["section"]); +if (! $result > 0) +{ + dolibarr_print_error($db,$ecmdir->error); + exit; +} +$relativepath=$ecmdir->getRelativePath(); +$upload_dir = $conf->ecm->dir_output.'/'.$relativepath; /******************************************************************* @@ -132,33 +145,7 @@ $form=new Form($db); // Construit liste des fichiers -clearstatcache(); -$totalsize=0; -$filearray=array(); -$errorlevel=error_reporting(); -error_reporting(0); -$handle=opendir($upload_dir); -error_reporting($errorlevel); -if ($handle) -{ - $i=0; - while (($file = readdir($handle))!==false) - { - if (!is_dir($dir.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') - { - $filearray[$i]->name=$file; - $filearray[$i]->size=filesize($upload_dir."/".$file); - $filearray[$i]->date=filemtime($upload_dir."/".$file); - $totalsize+=$filearray[$i]->size; - $i++; - } - } - closedir($handle); -} -else -{ - // print '
'.$langs->trans("ErrorCanNotReadDir",$upload_dir).'
'; -} +$filearray=dol_dir_list($upload_dir,"files",0,'','\.meta$',$sortfield,(strtolower($sortorder)=='desc'?SORT_ASC:SORT_DESC),1); $head = ecm_prepare_head($ecmdir); @@ -173,9 +160,10 @@ $result = 1; while ($tmpecmdir && $result > 0) { $tmpecmdir->ref=$tmpecmdir->label; - $s=' -> '.$tmpecmdir->getNomUrl(1).$s; + $s=$tmpecmdir->getNomUrl(1).$s; if ($tmpecmdir->fk_parent) { + $s=' -> '.$s; $result=$tmpecmdir->fetch($tmpecmdir->fk_parent); } else @@ -183,7 +171,7 @@ while ($tmpecmdir && $result > 0) $tmpecmdir=0; } } -print img_picto('','object_dir').' '.$langs->trans("ECMRoot").''; +//print img_picto('','object_dir').' '.$langs->trans("ECMRoot").''; print $s; print ''; print ''.$langs->trans("Description").''; @@ -197,11 +185,20 @@ print ''; print ''.$langs->trans("ECMCreationDate").''; print dolibarr_print_date($ecmdir->date_c,'dayhour'); print ''; +print ''.$langs->trans("ECMDirectoryForFiles").''; +//print $conf->ecm->dir_output; +print '/ecm/'.$relativepath; +print ''; print ''.$langs->trans("ECMNbOfDocs").''; print sizeof($filearray); print ''; print ''.$langs->trans("TotalSizeOfAttachedFiles").''; -print $totalsize; +$totalsize=0; +foreach($filearray as $key => $file) +{ + $totalsize+=$file['size']; +} +print dol_print_size($totalsize); print ''; print ''; @@ -227,6 +224,7 @@ $formfile->form_attach_new_file(DOL_URL_ROOT.'/ecm/docmine.php','',0,$section); // Affiche liste des documents existant print_titre($langs->trans("AttachedFiles")); + /** * TODO Mettre cette section dans une zone AJAX */ @@ -234,28 +232,26 @@ $modulepart='ecm'; $url=$_SERVER["PHP_SELF"]; print ''; print ''; -$param='&socid='.$socid; +$param='&section='.$section; print_liste_field_titre($langs->trans("Document"),$_SERVER["PHP_SELF"],"name","",$param,'align="left"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Size"),$_SERVER["PHP_SELF"],"size","",$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"],"date","",$param,'align="center"',$sortfield,$sortorder); print ''; print ''; -usort($filearray,"dol_compare_file"); - $var=true; foreach($filearray as $key => $file) { - if (!is_dir($dir.$file->name) && substr($file->name, 0, 1) <> '.' && substr($file->name, 0, 3) <> 'CVS') + if (!is_dir($dir.$file['name']) && substr($file['name'], 0, 1) <> '.' && substr($file['name'], 0, 3) <> 'CVS') { $var=!$var; print "\n"; - print ''; - print ''; + print ''; + print ''; print '\n"; } } diff --git a/htdocs/ecm/ecmdirectory.class.php b/htdocs/ecm/ecmdirectory.class.php index b3fb3ff138c..0910c68f3cc 100644 --- a/htdocs/ecm/ecmdirectory.class.php +++ b/htdocs/ecm/ecmdirectory.class.php @@ -26,12 +26,6 @@ \remarks Initialy built by build_class_from_table on 2008-02-24 19:24 */ -// Put here all includes required by your class file -//require_once(DOL_DOCUMENT_ROOT."/commonobject.class.php"); -//require_once(DOL_DOCUMENT_ROOT."/societe.class.php"); -//require_once(DOL_DOCUMENT_ROOT."/product.class.php"); - - /** \class EcmDirectory \brief Class to manage ECM directories @@ -131,7 +125,7 @@ class EcmDirectory // extends CommonObject } } - /* + /** * \brief Update database * \param user User that modify * \param notrigger 0=no, 1=yes (no update trigger) @@ -186,7 +180,7 @@ class EcmDirectory // extends CommonObject } - /* + /** * \brief Update database * \sign '+' or '-' * \return int <0 if KO, >0 if OK @@ -214,7 +208,7 @@ class EcmDirectory // extends CommonObject } - /* + /** * \brief Load object in memory from database * \param id id object * \return int <0 if KO, >0 if OK @@ -268,7 +262,7 @@ class EcmDirectory // extends CommonObject } - /* + /** * \brief Delete object in database * \param user User that delete * \return int <0 if KO, >0 if OK @@ -317,12 +311,12 @@ class EcmDirectory // extends CommonObject } - /** + /** \brief Renvoie nom clicable (avec eventuellement le picto) \param withpicto 0=Pas de picto, 1=Inclut le picto dans le lien, 2=Picto seul \param option Sur quoi pointe le lien \return string Chaine avec URL - */ + */ function getNomUrl($withpicto=0,$option='') { global $langs; @@ -343,7 +337,44 @@ class EcmDirectory // extends CommonObject return $result; } - /** + /** + \brief Return relative path of a directory on disk + \return string Relative physical path + */ + function getRelativePath() + { + $this->get_full_arbo(); + + $ret=''; + $idtosearch=$this->id; + $i=0; + do { + // Get index cursor in this->cats for id_mere + $cursorindex=-1; + foreach ($this->cats as $key => $val) + { + if ($this->cats[$key]['id'] == $idtosearch) + { + $cursorindex=$key; + break; + } + } + //print "c=".$idtosearch."-".$cursorindex; + + if ($cursorindex >= 0) + { + $ret=$this->cats[$cursorindex]['label'].'/'.$ret; + + $idtosearch=$this->cats[$cursorindex]['id_mere']; + $i++; + } + } + while ($cursorindex >= 0 && ! empty($idtosearch) && $i < 100); // i avoid infinite loop + + return $ret; + } + + /** * \brief Load this->motherof array * \return int <0 if KO, >0 if OK */ diff --git a/htdocs/ecm/htmlecm.form.class.php b/htdocs/ecm/htmlecm.form.class.php index b47c9920f9c..d8e1ebb176a 100644 --- a/htdocs/ecm/htmlecm.form.class.php +++ b/htdocs/ecm/htmlecm.form.class.php @@ -1,14 +1,5 @@ - * Copyright (C) 2004-2008 Laurent Destailleur - * Copyright (C) 2004 Benoit Mortier - * Copyright (C) 2004 Sebastien Di Cintio - * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2005-2007 Regis Houssin - * Copyright (C) 2006 Andre Cianfarani - * Copyright (C) 2006 Marc Barilley/Ocebo - * Copyright (C) 2007 Franky Van Liedekerke - * Copyright (C) 2007 Patrick Raguin +/* Copyright (C) 2008 Laurent Destailleur * * 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 @@ -26,23 +17,23 @@ */ /** - \file htdocs/ecm/htmlecm.form.class.php - \brief Fichier de la classe des fonctions prédéfinie de composants html - \version $Id$ -*/ + * \file htdocs/ecm/htmlecm.form.class.php + * \brief Fichier de la classe des fonctions prédéfinie de composants html + * \version $Id$ + */ require_once(DOL_DOCUMENT_ROOT."/ecm/ecmdirectory.class.php"); /** - \class FormEcm - \brief Classe permettant la génération de composants html - \remarks Only common components must be here. -*/ + * \class FormEcm + * \brief Classe permettant la génération de composants html + * \remarks Only common components must be here. + */ class FormEcm { var $db; var $error; - + // Cache arrays var $cache_types_paiements=array(); var $cache_conditions_paiements=array(); @@ -50,28 +41,28 @@ class FormEcm var $tva_taux_value; var $tva_taux_libelle; - - /** - \brief Constructeur - \param DB handler d'accès base de donnée - */ - function FormEcm($DB) - { - $this->db = $DB; - - return 1; - } - - /** - * \brief Retourne la liste des catégories du type choisi - * \param selected Id categorie preselectionnee - * \param select_name Nom formulaire HTML - */ - function select_all_sections($selected='',$select_name='') - { - global $langs; - $langs->load("ecm"); + /** + * \brief Constructeur + * \param DB handler d'accès base de donnée + */ + function FormEcm($DB) + { + $this->db = $DB; + + return 1; + } + + + /** + * \brief Retourne la liste des catégories du type choisi + * \param selected Id categorie preselectionnee + * \param select_name Nom formulaire HTML + */ + function select_all_sections($selected='',$select_name='') + { + global $langs; + $langs->load("ecm"); if ($select_name=="") $select_name="catParent"; @@ -101,7 +92,7 @@ class FormEcm } $output.= ''; $output.= "\n"; - return $output; + return $output; } } diff --git a/htdocs/html.formfile.class.php b/htdocs/html.formfile.class.php index 09b2abb7152..4aafc32d536 100644 --- a/htdocs/html.formfile.class.php +++ b/htdocs/html.formfile.class.php @@ -125,6 +125,7 @@ class FormFile function show_documents($modulepart,$filename,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$modelliste=array(),$forcenomultilang=0,$iconPDF=0) { // filedir = conf->...dir_ouput."/".get_exdir(id) + include_once(DOL_DOCUMENT_ROOT.'/lib/files.lib.php'); global $langs,$bc,$conf; $var=true; @@ -289,7 +290,7 @@ class FormFile $png = '|\.png$'; $filter = $filename.'.pdf'; } - $file_list=dolibarr_dir_list($filedir,'files',0,$filter,'\.meta$'.$png,'date',SORT_DESC); + $file_list=dol_dir_list($filedir,'files',0,$filter,'\.meta$'.$png,'date',SORT_DESC); // Affiche en-tete tableau si non deja affiché if (sizeof($file_list) && ! $headershown && !$iconPDF) diff --git a/htdocs/install/etape5.php b/htdocs/install/etape5.php index 116b6d085be..78615923180 100644 --- a/htdocs/install/etape5.php +++ b/htdocs/install/etape5.php @@ -93,7 +93,11 @@ if ($_POST["action"] == "set" || $_POST["action"] == "upgrade") // on décode le mot de passe de la base si besoin require_once(DOL_DOCUMENT_ROOT ."/lib/functions.lib.php"); - if (isset($dolibarr_main_db_encrypted_pass) && $dolibarr_main_db_encrypted_pass) $dolibarr_main_db_pass = dolibarr_decode($dolibarr_main_db_encrypted_pass); + if (! empty($dolibarr_main_db_encrypted_pass)) + { + require_once(DOL_DOCUMENT_ROOT ."/lib/security.lib.php"); + $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } $conf->db->type = $dolibarr_main_db_type; $conf->db->host = $dolibarr_main_db_host; diff --git a/htdocs/install/upgrade.php b/htdocs/install/upgrade.php index 11f341baa83..9629e7bd3ee 100644 --- a/htdocs/install/upgrade.php +++ b/htdocs/install/upgrade.php @@ -77,8 +77,12 @@ if (! isset($_GET["action"]) || $_GET["action"] == "upgrade") print '
 
"; - echo ''.$file->name.''; + echo ''.$file['name'].''; print "'.$file->size.' '.$langs->trans("bytes").''.dolibarr_print_date($file->date,"dayhour").''.dol_print_size($file['size']).''.dolibarr_print_date($file['date'],"dayhour").''; - echo 'name).'">'.img_delete().''; + echo ''.img_delete().''; print "
'; $error=0; - // on d�code le mot de passe de la base si besoin - if (isset($dolibarr_main_db_encrypted_pass) && $dolibarr_main_db_encrypted_pass) $dolibarr_main_db_pass = dolibarr_decode($dolibarr_main_db_encrypted_pass); + // decode database pass if needed + if (! empty($dolibarr_main_db_encrypted_pass)) + { + require_once($dolibarr_main_document_root."/lib/security.lib.php"); + $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } // $conf is already instancied inside inc.php $conf->db->type = $dolibarr_main_db_type; diff --git a/htdocs/install/upgrade2.php b/htdocs/install/upgrade2.php index 3d0dc797520..ccd0fe7b7ee 100644 --- a/htdocs/install/upgrade2.php +++ b/htdocs/install/upgrade2.php @@ -75,7 +75,11 @@ if (isset($_POST['action']) && $_POST['action'] == 'upgrade') print '
'; // on decode le mot de passe de la base si besoin - if (isset($dolibarr_main_db_encrypted_pass) && $dolibarr_main_db_encrypted_pass) $dolibarr_main_db_pass = dolibarr_decode($dolibarr_main_db_encrypted_pass); + if (! empty($dolibarr_main_db_encrypted_pass)) + { + require_once($dolibarr_main_document_root."/lib/security.lib.php"); + $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } // $conf is already instancied inside inc.php $conf->db->type = $dolibarr_main_db_type; diff --git a/htdocs/langs/en_US/ecm.lang b/htdocs/langs/en_US/ecm.lang index 7f2045ec57a..6487b952739 100644 --- a/htdocs/langs/en_US/ecm.lang +++ b/htdocs/langs/en_US/ecm.lang @@ -20,8 +20,8 @@ ECMNewSection=New manual directory ECMNewDocument=New document ECMCreationDate=Creation date ECMCreationUser=Creator -ECMArea=Electronic Content Management area -ECMAreaDesc=The Electronic Content Management area allows you to save, share and search quickly documents in Dolibarr. +ECMArea=ECM area +ECMAreaDesc=The ECM (Electronic Content Management) area allows you to save, share and search quickly all kind of documents in Dolibarr. ECMAreaDesc2=* Automatic directories are filled automatically when adding documents from card of an element.
* Manual directories can be used to save documents not linked to a particular element. ECMSectionWasRemoved=Directory %s has been deleted. ECMDocumentsSection=Document of directory @@ -41,3 +41,4 @@ ECMNoDirecotyYet=No directory created ShowECMSection=Show directory DeleteSection=Remove directory ConfirmDeleteSection=Can you confirm you want to delete the directory %s ? +ECMDirectoryForFiles=Relative directory for files \ No newline at end of file diff --git a/htdocs/langs/fr_FR/ecm.lang b/htdocs/langs/fr_FR/ecm.lang index fdd1361cbe2..c42347da349 100644 --- a/htdocs/langs/fr_FR/ecm.lang +++ b/htdocs/langs/fr_FR/ecm.lang @@ -20,9 +20,9 @@ ECMNewSection=Nouvelle rubrique manuelle ECMNewDocument=Nouveau document ECMCreationDate=Date création ECMCreationUser=Créateur -ECMArea=Espace Gestion de documents -ECMAreaDesc=L'espace Gestion des documents vous permet de stocker et retrouver rapidement des documents dans Dolibarr. -ECMAreaDesc2=* Les rubriques automatiques sont alimentées automatiquement lors de l'ajout d'un document depuis une fiche objet.
* Les rubriques manuelles peuvent etre utilisées pour stocker des documents liés à aucun élément particulier. +ECMArea=Espace GED +ECMAreaDesc=L'espace GED (Gestion Electronique de Documents) vous permet de stocker dans Dolibarr et retrouver rapidement tout type de documents. +ECMAreaDesc2=* Les rubriques automatiques sont alimentées automatiquement lors de l'ajout d'un document depuis une fiche objet (propal, facture, commande...).
* Les rubriques manuelles peuvent etre utilisées pour stocker des documents divers, non liés à un objet particulier. ECMSectionWasRemoved=La rubrique %s a été effacée. ECMDocumentsSection=Document de la section ECMSearchByKeywords=Recherche par mots clés @@ -41,3 +41,4 @@ ECMNoDirecotyYet=Aucune rubrique cr ShowECMSection=Afficher rubrique DeleteSection=Suppression rubrique ConfirmDeleteSection=Confirmez-vous la suppression de la rubique %s ? +ECMDirectoryForFiles=Répertoire relatif pour les fichiers \ No newline at end of file diff --git a/htdocs/lib/files.lib.php b/htdocs/lib/files.lib.php index a46ef8d88bc..4a929e042d0 100644 --- a/htdocs/lib/files.lib.php +++ b/htdocs/lib/files.lib.php @@ -23,6 +23,109 @@ \version $Id$ */ +/** + \brief Scan a directory and return a list of files/directories + \param $path Starting path from which to search + \param $types Can be "directories", "files", or "all" + \param $recursive Determines whether subdirectories are searched + \param $filter Regex for filter + \param $exludefilter Regex for exclude filter (example: '\.meta$') + \param $sortcriteria Sort criteria ("name","date","size") + \param $sortorder Sort order (SORT_ASC, SORT_DESC) + \param $mode 0=Return array of key need, 1=Force all key to be loaded + \return array Array of array('name'=>xxx,'date'=>yyy,'size'=>zzz) + */ +function dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter="", $sortcriteria="name", $sortorder=SORT_ASC, $mode=0) +{ + dolibarr_syslog("files.lib.php::dol_dir_list $path"); + + $loaddate=$mode?true:false; + $loadsize=$mode?true:false; + + // Clean parameters + $path=eregi_replace('[\\/]+$','',$path); + + if (! is_dir($path)) return array(); + + if ($dir = opendir($path)) + { + $file_list = array(); + while (false !== ($file = readdir($dir))) + { + $qualified=1; + + // Check if file is qualified + if (eregi('^\.',$file)) $qualified=0; + if ($excludefilter && eregi($excludefilter,$file)) $qualified=0; + + if ($qualified) + { + // Check whether this is a file or directory and whether we're interested in that type + if (is_dir($path."/".$file) && (($types=="directories") || ($types=="all"))) + { + // Add entry into file_list array + if ($loaddate || $sortcriteria == 'date') $filedate=filemtime($path."/".$file); + if ($loadsize || $sortcriteria == 'size') $filesize=filesize($path."/".$file); + + if (! $filter || eregi($filter,$path.'/'.$file)) + { + $file_list[] = array( + "name" => $file, + "fullname" => $path.'/'.$file, + "date" => $filedate, + "size" => $filesize + ); + } + + // if we're in a directory and we want recursive behavior, call this function again + if ($recursive) + { + $file_list = array_merge($file_list, dol_dir_list($path."/".$file."/", $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder)); + } + } + else if (! is_dir($path."/".$file) && (($types == "files") || ($types == "all"))) + { + // Add file into file_list array + if ($loaddate || $sortcriteria == 'date') $filedate=filemtime($path."/".$file); + if ($loadsize || $sortcriteria == 'size') $filesize=filesize($path."/".$file); + if (! $filter || eregi($filter,$path.'/'.$file)) + { + $file_list[] = array( + "name" => $file, + "fullname" => $path.'/'.$file, + "date" => $filedate, + "size" => $filesize + ); + } + } + } + } + closedir($dir); + + // Obtain a list of columns + $myarray=array(); + foreach ($file_list as $key => $row) + { + $myarray[$key] = $row[$sortcriteria]; + } + // Sort the data + array_multisort($myarray, $sortorder, $file_list); + + return $file_list; + } + else + { + return false; + } +} + +/** + * \brief Compare 2 files + * + * @param unknown_type $a File 1 + * @param unknown_type $b File 2 + * @return int 1, 0, 1 + */ function dol_compare_file($a, $b) { global $sortorder; diff --git a/htdocs/lib/functions.lib.php b/htdocs/lib/functions.lib.php index 390cea511d8..654e9b3b7f9 100644 --- a/htdocs/lib/functions.lib.php +++ b/htdocs/lib/functions.lib.php @@ -24,10 +24,10 @@ */ /** - \file htdocs/lib/functions.lib.php - \brief Ensemble de fonctions de base de dolibarr sous forme d'include - \version $Id$ -*/ + \file htdocs/lib/functions.lib.php + \brief Ensemble de fonctions de base de dolibarr sous forme d'include + \version $Id$ + */ // Pour compatibilité lors de l'upgrade if (! defined('DOL_DOCUMENT_ROOT')) define('DOL_DOCUMENT_ROOT', '..'); @@ -36,48 +36,48 @@ if (! defined('ADODB_DATE_VERSION')) include_once(DOL_DOCUMENT_ROOT."/includes/a /** - \brief Renvoi vrai si l'email est syntaxiquement valide - \param address adresse email (Ex: "toto@titi.com", "John Do ") - \return boolean true si email valide, false sinon -*/ + \brief Renvoi vrai si l'email est syntaxiquement valide + \param address adresse email (Ex: "toto@titi.com", "John Do ") + \return boolean true si email valide, false sinon + */ function ValidEmail($address) { - if (ereg( ".*<(.+)>", $address, $regs)) { - $address = $regs[1]; - } - if (ereg( "^[^@ ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2}|coop|aero|biz|com|edu|gov|info|int|mil|name|net|org)\$",$address)) - { - return true; - } - else - { - return false; - } + if (ereg( ".*<(.+)>", $address, $regs)) { + $address = $regs[1]; + } + if (ereg( "^[^@ ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2}|coop|aero|biz|com|edu|gov|info|int|mil|name|net|org)\$",$address)) + { + return true; + } + else + { + return false; + } } /** - \brief Renvoi vrai si l'email a un nom de domaine qui résoud via dns - \param mail adresse email (Ex: "toto@titi.com", "John Do ") - \return boolean true si email valide, false sinon -*/ + \brief Renvoi vrai si l'email a un nom de domaine qui résoud via dns + \param mail adresse email (Ex: "toto@titi.com", "John Do ") + \return boolean true si email valide, false sinon + */ function check_mail ($mail) { - list($user, $domain) = split("@", $mail, 2); - if (checkdnsrr($domain, "MX")) - { - return true; - } - else - { - return false; - } + list($user, $domain) = split("@", $mail, 2); + if (checkdnsrr($domain, "MX")) + { + return true; + } + else + { + return false; + } } /** - \brief Nettoie chaine de caractere iso des accents - \param str Chaine a nettoyer - \return string Chaine nettoyee -*/ + \brief Nettoie chaine de caractere iso des accents + \param str Chaine a nettoyer + \return string Chaine nettoyee + */ function unaccent_isostring($str) { $translation = array( @@ -94,40 +94,40 @@ function unaccent_isostring($str) "\xF6" => "o", "\xFB" => "u", "\xFC" => "u" - ); + ); - return str_replace(array_keys($translation), array_values($translation), $str); + return str_replace(array_keys($translation), array_values($translation), $str); } /** - \brief Nettoie chaine de caractere de caracteres speciaux - \remarks Fonction appelee par exemple pour definir un nom de fichier depuis un identifiant chaine libre - \param str Chaine a nettoyer - \return string Chaine nettoyee (A-Z_) -*/ + \brief Nettoie chaine de caractere de caracteres speciaux + \remarks Fonction appelee par exemple pour definir un nom de fichier depuis un identifiant chaine libre + \param str Chaine a nettoyer + \return string Chaine nettoyee (A-Z_) + */ function sanitize_string($str) { - $forbidden_chars_to_underscore=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",",",";","="); - //$forbidden_chars_to_remove=array("(",")"); - $forbidden_chars_to_remove=array(); - return str_replace($forbidden_chars_to_underscore,"_",str_replace($forbidden_chars_to_remove,"",$str)); + $forbidden_chars_to_underscore=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",",",";","="); + //$forbidden_chars_to_remove=array("(",")"); + $forbidden_chars_to_remove=array(); + return str_replace($forbidden_chars_to_underscore,"_",str_replace($forbidden_chars_to_remove,"",$str)); } /** - \brief Envoi des messages dolibarr dans un fichier ou dans syslog - Pour fichier: fichier défini par SYSLOG_FILE - Pour syslog: facility défini par SYSLOG_FACILITY - \param message Message a tracer. Ne doit pas etre traduit si level = LOG_ERR - \param level Niveau de l'erreur - \remarks Cette fonction n'a un effet que si le module syslog est activé. - Warning, les fonctions syslog sont buggués sous Windows et générent des - fautes de protection mémoire. Pour résoudre, utiliser le loggage fichier, - au lieu du loggage syslog (configuration du module). - Si SYSLOG_FILE_NO_ERROR défini, on ne gére pas erreur ecriture log - \remarks On Windows LOG_ERR=4, LOG_WARNING=5, LOG_NOTICE=LOG_INFO=LOG_DEBUG=6 - On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7 -*/ + \brief Envoi des messages dolibarr dans un fichier ou dans syslog + Pour fichier: fichier défini par SYSLOG_FILE + Pour syslog: facility défini par SYSLOG_FACILITY + \param message Message a tracer. Ne doit pas etre traduit si level = LOG_ERR + \param level Niveau de l'erreur + \remarks Cette fonction n'a un effet que si le module syslog est activé. + Warning, les fonctions syslog sont buggués sous Windows et générent des + fautes de protection mémoire. Pour résoudre, utiliser le loggage fichier, + au lieu du loggage syslog (configuration du module). + Si SYSLOG_FILE_NO_ERROR défini, on ne gére pas erreur ecriture log + \remarks On Windows LOG_ERR=4, LOG_WARNING=5, LOG_NOTICE=LOG_INFO=LOG_DEBUG=6 + On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7 + */ function dolibarr_syslog($message, $level=LOG_INFO) { global $conf,$user,$langs; @@ -136,19 +136,19 @@ function dolibarr_syslog($message, $level=LOG_INFO) { //print $level.' - '.$conf->global->SYSLOG_LEVEL.' - '.$conf->syslog->enabled." \n"; if ($level > $conf->global->SYSLOG_LEVEL) return; - + // Traduction du message if ($level == LOG_ERR) { $langs->load("errors"); if ($message != $langs->trans($message)) $message = $langs->trans($message); } - + // Ajout user a la log $login='???'; if (is_object($user) && $user->id) $login=$user->login; $message=sprintf("%-8s",$login)." ".$message; - + if (defined("SYSLOG_FILE") && SYSLOG_FILE) { $filelog=SYSLOG_FILE; @@ -163,12 +163,12 @@ function dolibarr_syslog($message, $level=LOG_INFO) $liblevelarray=array(LOG_ERR=>'ERROR',LOG_WARNING=>'WARN',LOG_INFO=>'INFO',LOG_DEBUG=>'DEBUG'); $liblevel=$liblevelarray[$level]; if (! $liblevel) $liblevel='UNDEF'; - + $message=strftime("%Y-%m-%d %H:%M:%S",time())." ".sprintf("%-5s",$liblevel)." ".$ip." ".$message; - + fwrite($file,$message."\n"); fclose($file); - + // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments if (! empty($conf->global->MAIN_ENABLE_LOG_HTML) && ! empty($_GET["log"])) { @@ -199,9 +199,9 @@ function dolibarr_syslog($message, $level=LOG_INFO) { $facility = LOG_USER; } - + openlog("dolibarr", LOG_PID | LOG_PERROR, $facility); - + if (! $level) { syslog(LOG_ERR, $message); @@ -210,255 +210,255 @@ function dolibarr_syslog($message, $level=LOG_INFO) { syslog($level, $message); } - + closelog(); } } } /** - \brief Affiche le header d'une fiche - \param links Tableau de titre d'onglets - \param active 0=onglet non actif, 1=onglet actif - \param title Titre tabelau ("" par defaut) - \param notab 0=Add tab header, 1=no tab header -*/ + \brief Affiche le header d'une fiche + \param links Tableau de titre d'onglets + \param active 0=onglet non actif, 1=onglet actif + \param title Titre tabelau ("" par defaut) + \param notab 0=Add tab header, 1=no tab header + */ function dolibarr_fiche_head($links, $active='0', $title='', $notab=0) { - print "\n".'
'."\n"; + print "\n".'
'."\n"; - // Affichage titre - if ($title) - { - $limittitle=30; - print ''; - print - ((!defined('MAIN_USE_SHORT_TITLE')) || (defined('MAIN_USE_SHORT_TITLE') && MAIN_USE_SHORT_TITLE)) - ? dolibarr_trunc($title,$limittitle) - : $title; - print ''; - } + // Affichage titre + if ($title) + { + $limittitle=30; + print ''; + print + ((!defined('MAIN_USE_SHORT_TITLE')) || (defined('MAIN_USE_SHORT_TITLE') && MAIN_USE_SHORT_TITLE)) + ? dolibarr_trunc($title,$limittitle) + : $title; + print ''; + } - // Affichage onglets - for ($i = 0 ; $i < sizeof($links) ; $i++) - { - if ($links[$i][2] == 'image') - { - print ''.$links[$i][1].''."\n"; - } - else - { - //print "x $i $active ".$links[$i][2]." z"; - if ((is_numeric($active) && $i == $active) - || (! is_numeric($active) && $active == $links[$i][2])) - { - print ''.$links[$i][1].''."\n"; - } - else - { - print ''.$links[$i][1].''."\n"; - } - } - } + // Affichage onglets + for ($i = 0 ; $i < sizeof($links) ; $i++) + { + if ($links[$i][2] == 'image') + { + print ''.$links[$i][1].''."\n"; + } + else + { + //print "x $i $active ".$links[$i][2]." z"; + if ((is_numeric($active) && $i == $active) + || (! is_numeric($active) && $active == $links[$i][2])) + { + print ''.$links[$i][1].''."\n"; + } + else + { + print ''.$links[$i][1].''."\n"; + } + } + } - print "
\n"; + print "
\n"; - if (! $notab) print '
'."\n\n"; + if (! $notab) print '
'."\n\n"; } /** - \brief Sauvegarde parametrage personnel - \param db Handler d'accés base - \param user Objet utilisateur - \param url Si defini, on sauve parametre du tableau tab dont clé = (url avec sortfield, sortorder, begin et page) - Si non defini on sauve tous parametres du tableau tab - \param tab Tableau (clé=>valeur) des paramétres a sauvegarder - \return int <0 si ko, >0 si ok -*/ + \brief Sauvegarde parametrage personnel + \param db Handler d'accés base + \param user Objet utilisateur + \param url Si defini, on sauve parametre du tableau tab dont clé = (url avec sortfield, sortorder, begin et page) + Si non defini on sauve tous parametres du tableau tab + \param tab Tableau (clé=>valeur) des paramétres a sauvegarder + \return int <0 si ko, >0 si ok + */ function dolibarr_set_user_page_param($db, &$user, $url='', $tab) { - // Verification parametres - if (sizeof($tab) < 1) return -1; - - $db->begin(); + // Verification parametres + if (sizeof($tab) < 1) return -1; - // On efface anciens paramétres pour toutes les clé dans $tab - $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param"; - $sql.= " WHERE fk_user = ".$user->id; - if ($url) $sql.=" AND page='".$url."'"; - else $sql.=" AND page=''"; // Page ne peut etre null - $sql.= " AND param in ("; - $i=0; - foreach ($tab as $key => $value) - { + $db->begin(); + + // On efface anciens paramétres pour toutes les clé dans $tab + $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param"; + $sql.= " WHERE fk_user = ".$user->id; + if ($url) $sql.=" AND page='".$url."'"; + else $sql.=" AND page=''"; // Page ne peut etre null + $sql.= " AND param in ("; + $i=0; + foreach ($tab as $key => $value) + { if ($i > 0) $sql.=','; $sql.="'".$key."'"; $i++; } $sql.= ")"; - dolibarr_syslog("functions.lib.php::dolibarr_set_user_page_param $sql"); + dolibarr_syslog("functions.lib.php::dolibarr_set_user_page_param $sql"); - $resql=$db->query($sql); - if (! $resql) - { - dolibarr_print_error($db); - $db->rollback(); - exit; - } + $resql=$db->query($sql); + if (! $resql) + { + dolibarr_print_error($db); + $db->rollback(); + exit; + } - foreach ($tab as $key => $value) - { - // On positionne nouveaux paramétres - if ($value && (! $url || in_array($key,array('sortfield','sortorder','begin','page')))) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,page,param,value)"; - $sql.= " VALUES (".$user->id.","; - if ($url) $sql.= " '".urlencode($url)."',"; - else $sql.= " '',"; - $sql.= " '".$key."','".addslashes($value)."');"; - dolibarr_syslog("functions.lib.php::dolibarr_set_user_page_param $sql"); + foreach ($tab as $key => $value) + { + // On positionne nouveaux paramétres + if ($value && (! $url || in_array($key,array('sortfield','sortorder','begin','page')))) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,page,param,value)"; + $sql.= " VALUES (".$user->id.","; + if ($url) $sql.= " '".urlencode($url)."',"; + else $sql.= " '',"; + $sql.= " '".$key."','".addslashes($value)."');"; + dolibarr_syslog("functions.lib.php::dolibarr_set_user_page_param $sql"); - $result=$db->query($sql); - if (! $result) - { - dolibarr_print_error($db); - $db->rollback(); - exit; - } + $result=$db->query($sql); + if (! $result) + { + dolibarr_print_error($db); + $db->rollback(); + exit; + } - $user->page_param[$key] = $value; - } - } + $user->page_param[$key] = $value; + } + } - $db->commit(); - return 1; + $db->commit(); + return 1; } /** - \brief Formattage des nombres - \param ca valeur a formater - \return int valeur formatée -*/ + \brief Formattage des nombres + \param ca valeur a formater + \return int valeur formatée + */ function dolibarr_print_ca($ca) { - global $langs,$conf; + global $langs,$conf; - if ($ca > 1000) - { - $cat = round(($ca / 1000),2); - $cat = "$cat K".$langs->trans("Currency".$conf->monnaie); - } - else - { - $cat = round($ca,2); - $cat = "$cat ".$langs->trans("Currency".$conf->monnaie); - } + if ($ca > 1000) + { + $cat = round(($ca / 1000),2); + $cat = "$cat K".$langs->trans("Currency".$conf->monnaie); + } + else + { + $cat = round($ca,2); + $cat = "$cat ".$langs->trans("Currency".$conf->monnaie); + } - if ($ca > 1000000) - { - $cat = round(($ca / 1000000),2); - $cat = "$cat M".$langs->trans("Currency".$conf->monnaie); - } + if ($ca > 1000000) + { + $cat = round(($ca / 1000000),2); + $cat = "$cat M".$langs->trans("Currency".$conf->monnaie); + } - return $cat; + return $cat; } /** - \brief Effectue un décalage de date par rapport a une durée - \param time Date timestamp ou au format YYYY-MM-DD - \param duration_value Valeur de la durée a ajouter - \param duration_unit Unité de la durée a ajouter (d, m, y) - \return int Nouveau timestamp -*/ + \brief Effectue un décalage de date par rapport a une durée + \param time Date timestamp ou au format YYYY-MM-DD + \param duration_value Valeur de la durée a ajouter + \param duration_unit Unité de la durée a ajouter (d, m, y) + \return int Nouveau timestamp + */ function dolibarr_time_plus_duree($time,$duration_value,$duration_unit) { if ($duration_value == 0) return $time; if ($duration_value > 0) $deltastring="+".abs($duration_value); if ($duration_value < 0) $deltastring="-".abs($duration_value); - if ($duration_unit == 'd') { $deltastring.=" day"; } - if ($duration_unit == 'm') { $deltastring.=" month"; } - if ($duration_unit == 'y') { $deltastring.=" year"; } - return strtotime($deltastring,$time); + if ($duration_unit == 'd') { $deltastring.=" day"; } + if ($duration_unit == 'm') { $deltastring.=" month"; } + if ($duration_unit == 'y') { $deltastring.=" year"; } + return strtotime($deltastring,$time); } /** - \brief Formattage de la date en fonction de la langue $conf->langage - \param time Date 'timestamp' ou format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS' - \param format Format d'affichage de la date - "%d %b %Y", - "%d/%m/%Y %H:%M", - "%d/%m/%Y %H:%M:%S", - "day", "daytext", "dayhour", "dayhourldap", "dayhourtext" - \return string Date formatée ou '' si time null -*/ + \brief Formattage de la date en fonction de la langue $conf->langage + \param time Date 'timestamp' ou format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS' + \param format Format d'affichage de la date + "%d %b %Y", + "%d/%m/%Y %H:%M", + "%d/%m/%Y %H:%M:%S", + "day", "daytext", "dayhour", "dayhourldap", "dayhourtext" + \return string Date formatée ou '' si time null + */ function dolibarr_print_date($time,$format='') { - global $conf; + global $conf; - // Si format non défini, on prend $conf->format_date_text_short sinon %Y-%m-%d %H:%M:%S - if (! $format) $format=(isset($conf->format_date_text_short) ? $conf->format_date_text_short : '%Y-%m-%d %H:%M:%S'); + // Si format non défini, on prend $conf->format_date_text_short sinon %Y-%m-%d %H:%M:%S + if (! $format) $format=(isset($conf->format_date_text_short) ? $conf->format_date_text_short : '%Y-%m-%d %H:%M:%S'); - if ($format == 'day') $format=$conf->format_date_short; - if ($format == 'hour') $format=$conf->format_hour_short; - if ($format == 'daytext') $format=$conf->format_date_text_short; - if ($format == 'dayhour') $format=$conf->format_date_hour_short; - if ($format == 'dayhourtext') $format=$conf->format_date_hour_text_short; - if ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ'; - if ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ'; + if ($format == 'day') $format=$conf->format_date_short; + if ($format == 'hour') $format=$conf->format_hour_short; + if ($format == 'daytext') $format=$conf->format_date_text_short; + if ($format == 'dayhour') $format=$conf->format_date_hour_short; + if ($format == 'dayhourtext') $format=$conf->format_date_hour_text_short; + if ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ'; + if ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ'; - // Si date non definie, on renvoie '' - if ($time == '') return ''; // $time=0 permis car signifie 01/01/1970 00:00:00 + // Si date non definie, on renvoie '' + if ($time == '') return ''; // $time=0 permis car signifie 01/01/1970 00:00:00 - // Analyse de la date - if (eregi('^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?',$time,$reg)) - { - // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS' - $syear = $reg[1]; - $smonth = $reg[2]; - $sday = $reg[3]; - $shour = $reg[4]; - $smin = $reg[5]; - $ssec = $reg[6]; + // Analyse de la date + if (eregi('^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?',$time,$reg)) + { + // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS' + $syear = $reg[1]; + $smonth = $reg[2]; + $sday = $reg[3]; + $shour = $reg[4]; + $smin = $reg[5]; + $ssec = $reg[6]; - return adodb_strftime($format,dolibarr_mktime($shour,$smin,$ssec,$smonth,$sday,$syear)); - } - else - { - // Date est un timestamps - return adodb_strftime($format,$time); - } + return adodb_strftime($format,dolibarr_mktime($shour,$smin,$ssec,$smonth,$sday,$syear)); + } + else + { + // Date est un timestamps + return adodb_strftime($format,$time); + } } /** - \brief Retourne une date fabriquée depuis une chaine - \param string Date formatée en chaine - YYYYMMDD - YYYYMMDDHHMMSS - DD/MM/YY ou DD/MM/YYYY - DD/MM/YY HH:MM:SS ou DD/MM/YYYY HH:MM:SS - \return date Date -*/ + \brief Retourne une date fabriquée depuis une chaine + \param string Date formatée en chaine + YYYYMMDD + YYYYMMDDHHMMSS + DD/MM/YY ou DD/MM/YYYY + DD/MM/YY HH:MM:SS ou DD/MM/YYYY HH:MM:SS + \return date Date + */ function dolibarr_stringtotime($string) { - if (eregi('^([0-9]+)\/([0-9]+)\/([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?',$string,$reg)) - { - // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS' - // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS' - $sday = $reg[1]; - $smonth = $reg[2]; - $syear = $reg[3]; - $shour = $reg[4]; - $smin = $reg[5]; - $ssec = $reg[6]; + if (eregi('^([0-9]+)\/([0-9]+)\/([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?',$string,$reg)) + { + // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS' + // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS' + $sday = $reg[1]; + $smonth = $reg[2]; + $syear = $reg[3]; + $shour = $reg[4]; + $smin = $reg[5]; + $ssec = $reg[6]; if ($syear < 50) $syear+=1900; if ($syear >= 50 && $syear < 100) $syear+=2000; - $string=sprintf("%04d%02d%02d%02d%02d%02d",$syear,$smonth,$sday,$shour,$smin,$ssec); - } + $string=sprintf("%04d%02d%02d%02d%02d%02d",$syear,$smonth,$sday,$shour,$smin,$ssec); + } $string=eregi_replace('[^0-9]','',$string); $tmp=$string.'000000'; @@ -468,40 +468,40 @@ function dolibarr_stringtotime($string) /** - \brief Return an array with date info - \param timestamp Timestamp - \param fast Fast mode - \return array Array of informations - If no fast mode: - 'seconds' => $secs, - 'minutes' => $min, - 'hours' => $hour, - 'mday' => $day, - 'wday' => $dow, - 'mon' => $month, - 'year' => $year, - 'yday' => floor($secsInYear/$_day_power), - 'weekday' => gmdate('l',$_day_power*(3+$dow)), - 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)), - 0 => $origd - If fast mode: - 'seconds' => $secs, - 'minutes' => $min, - 'hours' => $hour, - 'mday' => $day, - 'mon' => $month, - 'year' => $year, - 'yday' => floor($secsInYear/$_day_power), - 'leap' => $leaf, - 'ndays' => $ndays - \remarks PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows -*/ + \brief Return an array with date info + \param timestamp Timestamp + \param fast Fast mode + \return array Array of informations + If no fast mode: + 'seconds' => $secs, + 'minutes' => $min, + 'hours' => $hour, + 'mday' => $day, + 'wday' => $dow, + 'mon' => $month, + 'year' => $year, + 'yday' => floor($secsInYear/$_day_power), + 'weekday' => gmdate('l',$_day_power*(3+$dow)), + 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)), + 0 => $origd + If fast mode: + 'seconds' => $secs, + 'minutes' => $min, + 'hours' => $hour, + 'mday' => $day, + 'mon' => $month, + 'year' => $year, + 'yday' => floor($secsInYear/$_day_power), + 'leap' => $leaf, + 'ndays' => $ndays + \remarks PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows + */ function dolibarr_getdate($timestamp,$fast=false) { $usealternatemethod=false; if ($timestamp <= 0) $usealternatemethod=true; // <= 1970 if ($timestamp >= 2145913200) $usealternatemethod=true; // >= 2038 - + if ($usealternatemethod) { $arrayinfo=adodb_getdate($timestamp,$fast); @@ -510,24 +510,24 @@ function dolibarr_getdate($timestamp,$fast=false) { $arrayinfo=getdate($timestamp); } - + return $arrayinfo; } /** - \brief Retourne une date fabriquée depuis infos. - Remplace la fonction mktime non implémentée sous Windows si année < 1970 - \param hour Heure - \param minute Minute - \param second Seconde - \param month Mois - \param day Jour - \param year Année - \param gm Time gm - \param check No check on parameters (Can use day 32, etc...) - \return timestamp Date en timestamp, '' if error - \remarks PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows -*/ + \brief Retourne une date fabriquée depuis infos. + Remplace la fonction mktime non implémentée sous Windows si année < 1970 + \param hour Heure + \param minute Minute + \param second Seconde + \param month Mois + \param day Jour + \param year Année + \param gm Time gm + \param check No check on parameters (Can use day 32, etc...) + \return timestamp Date en timestamp, '' if error + \remarks PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows + */ function dolibarr_mktime($hour,$minute,$second,$month,$day,$year,$gm=0,$check=1) { //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -"; @@ -542,26 +542,26 @@ function dolibarr_mktime($hour,$minute,$second,$month,$day,$year,$gm=0,$check=1) if ($hour < 0 || $hour > 24) return ''; if ($min < 0 || $min > 60) return ''; } - + $usealternatemethod=false; if ($year <= 1970) $usealternatemethod=true; // <= 1970 if ($year >= 2038) $usealternatemethod=true; // >= 2038 - + if ($usealternatemethod || $gm) // Si time gm, seule adodb peut convertir { /* - // On peut utiliser strtotime pour obtenir la traduction. - // strtotime is ok for range: Vendredi 13 Décembre 1901 20:45:54 GMT au Mardi 19 Janvier 2038 03:14:07 GMT. - $montharray=array(1=>'january',2=>'february',3=>'march',4=>'april',5=>'may',6=>'june', - 7=>'july',8=>'august',9=>'september',10=>'october',11=>'november',12=>'december'); - $string=$day." ".$montharray[0+$month]." ".$year." ".$hour.":".$minute.":".$second." GMT"; - $date=strtotime($string); - print "- ".$string." ".$date." -"; - */ + // On peut utiliser strtotime pour obtenir la traduction. + // strtotime is ok for range: Vendredi 13 Décembre 1901 20:45:54 GMT au Mardi 19 Janvier 2038 03:14:07 GMT. + $montharray=array(1=>'january',2=>'february',3=>'march',4=>'april',5=>'may',6=>'june', + 7=>'july',8=>'august',9=>'september',10=>'october',11=>'november',12=>'december'); + $string=$day." ".$montharray[0+$month]." ".$year." ".$hour.":".$minute.":".$second." GMT"; + $date=strtotime($string); + print "- ".$string." ".$date." -"; + */ $date=adodb_mktime($hour,$minute,$second,$month,$day,$year,0,$gm); } - else - { + else + { $date=mktime($hour,$minute,$second,$month,$day,$year); } return $date; @@ -570,18 +570,18 @@ function dolibarr_mktime($hour,$minute,$second,$month,$day,$year,$gm=0,$check=1) /** - \brief Returns formated date - \param fmt Format (Exemple: 'Y-m-d H:i:s') - \param timestamp Date. Exemple: Si timestamp=0 et gm=1, renvoi 01/01/1970 00:00:00 - \param gm 1 if timestamp was built with gmmktime, 0 if timestamp was build with mktime - \return string Formated date -*/ + \brief Returns formated date + \param fmt Format (Exemple: 'Y-m-d H:i:s') + \param timestamp Date. Exemple: Si timestamp=0 et gm=1, renvoi 01/01/1970 00:00:00 + \param gm 1 if timestamp was built with gmmktime, 0 if timestamp was build with mktime + \return string Formated date + */ function dolibarr_date($fmt, $timestamp, $gm=0) { $usealternatemethod=false; if ($timestamp <= 0) $usealternatemethod=true; if ($timestamp >= 2145913200) $usealternatemethod=true; - + if ($usealternatemethod || $gm) // Si time gm, seule adodb peut convertir { $string=adodb_date($fmt,$timestamp,$gm); @@ -596,84 +596,98 @@ function dolibarr_date($fmt, $timestamp, $gm=0) /** - \brief Affiche les informations d'un objet - \param object objet a afficher -*/ + \brief Affiche les informations d'un objet + \param object objet a afficher + */ function dolibarr_print_object_info($object) { - global $langs; + global $langs; $langs->load("other"); - if (isset($object->user_creation) && $object->user_creation->fullname) - print $langs->trans("CreatedBy")." : " . $object->user_creation->fullname . '
'; + if (isset($object->user_creation) && $object->user_creation->fullname) + print $langs->trans("CreatedBy")." : " . $object->user_creation->fullname . '
'; - if (isset($object->date_creation)) - print $langs->trans("DateCreation")." : " . dolibarr_print_date($object->date_creation,"dayhourtext") . '
'; + if (isset($object->date_creation)) + print $langs->trans("DateCreation")." : " . dolibarr_print_date($object->date_creation,"dayhourtext") . '
'; - if (isset($object->user_modification) && $object->user_modification->fullname) - print $langs->trans("ModifiedBy")." : " . $object->user_modification->fullname . '
'; + if (isset($object->user_modification) && $object->user_modification->fullname) + print $langs->trans("ModifiedBy")." : " . $object->user_modification->fullname . '
'; - if (isset($object->date_modification)) - print $langs->trans("DateLastModification")." : " . dolibarr_print_date($object->date_modification,"dayhourtext") . '
'; + if (isset($object->date_modification)) + print $langs->trans("DateLastModification")." : " . dolibarr_print_date($object->date_modification,"dayhourtext") . '
'; - if (isset($object->user_validation) && $object->user_validation->fullname) - print $langs->trans("ValidatedBy")." : " . $object->user_validation->fullname . '
'; + if (isset($object->user_validation) && $object->user_validation->fullname) + print $langs->trans("ValidatedBy")." : " . $object->user_validation->fullname . '
'; - if (isset($object->date_validation)) - print $langs->trans("DateValidation")." : " . dolibarr_print_date($object->date_validation,"dayhourtext") . '
'; + if (isset($object->date_validation)) + print $langs->trans("DateValidation")." : " . dolibarr_print_date($object->date_validation,"dayhourtext") . '
'; - if (isset($object->user_cloture) && $object->user_cloture->fullname ) - print $langs->trans("ClosedBy")." : " . $object->user_cloture->fullname . '
'; + if (isset($object->user_cloture) && $object->user_cloture->fullname ) + print $langs->trans("ClosedBy")." : " . $object->user_cloture->fullname . '
'; - if (isset($object->date_cloture)) - print $langs->trans("DateClosing")." : " . dolibarr_print_date($object->date_cloture,"dayhourtext") . '
'; + if (isset($object->date_cloture)) + print $langs->trans("DateClosing")." : " . dolibarr_print_date($object->date_cloture,"dayhourtext") . '
'; - if (isset($object->user_rappro) && $object->user_rappro->fullname ) - print $langs->trans("ConciliatedBy")." : " . $object->user_rappro->fullname . '
'; + if (isset($object->user_rappro) && $object->user_rappro->fullname ) + print $langs->trans("ConciliatedBy")." : " . $object->user_rappro->fullname . '
'; - if (isset($object->date_rappro)) - print $langs->trans("DateConciliating")." : " . dolibarr_print_date($object->date_rappro,"dayhourtext") . '
'; + if (isset($object->date_rappro)) + print $langs->trans("DateConciliating")." : " . dolibarr_print_date($object->date_rappro,"dayhourtext") . '
'; } /** - \brief Formatage des numéros de telephone en fonction du format d'un pays - \param phone Numéro de telephone a formater - \param country Pays selon lequel formatter - \return string Numéro de téléphone formaté -*/ + \brief Formatage des numéros de telephone en fonction du format d'un pays + \param phone Numéro de telephone a formater + \param country Pays selon lequel formatter + \return string Numéro de téléphone formaté + */ function dolibarr_print_phone($phone,$country="FR") { $phone=trim($phone); - if (! $phone) { return $phone; } - - if (strtoupper($country) == "FR") - { - // France - if (strlen($phone) == 10) { - return substr($phone,0,2)." ".substr($phone,2,2)." ".substr($phone,4,2)." ".substr($phone,6,2)." ".substr($phone,8,2); - } - elseif (strlen($phone) == 7) - { + if (! $phone) { return $phone; } - return substr($phone,0,3)." ".substr($phone,3,2)." ".substr($phone,5,2); - } - elseif (strlen($phone) == 9) - { - return substr($phone,0,2)." ".substr($phone,2,3)." ".substr($phone,5,2)." ".substr($phone,7,2); - } - elseif (strlen($phone) == 11) - { - return substr($phone,0,3)." ".substr($phone,3,2)." ".substr($phone,5,2)." ".substr($phone,7,2)." ".substr($phone,9,2); - } - elseif (strlen($phone) == 12) - { - return substr($phone,0,4)." ".substr($phone,4,2)." ".substr($phone,6,2)." ".substr($phone,8,2)." ".substr($phone,10,2); - } - } + if (strtoupper($country) == "FR") + { + // France + if (strlen($phone) == 10) { + return substr($phone,0,2)." ".substr($phone,2,2)." ".substr($phone,4,2)." ".substr($phone,6,2)." ".substr($phone,8,2); + } + elseif (strlen($phone) == 7) + { - return $phone; + return substr($phone,0,3)." ".substr($phone,3,2)." ".substr($phone,5,2); + } + elseif (strlen($phone) == 9) + { + return substr($phone,0,2)." ".substr($phone,2,3)." ".substr($phone,5,2)." ".substr($phone,7,2); + } + elseif (strlen($phone) == 11) + { + return substr($phone,0,3)." ".substr($phone,3,2)." ".substr($phone,5,2)." ".substr($phone,7,2)." ".substr($phone,9,2); + } + elseif (strlen($phone) == 12) + { + return substr($phone,0,4)." ".substr($phone,4,2)." ".substr($phone,6,2)." ".substr($phone,8,2)." ".substr($phone,10,2); + } + } + + return $phone; } + +/** + * \brief Return string with formated size + * \param size Size to print + * \return string Link + */ +function dol_print_size($size) +{ + global $langs; + + return $size.' '.$langs->trans("Bytes"); +} + + /** * \brief Show click to dial link * \param phone Phone to call @@ -683,28 +697,28 @@ function dolibarr_print_phone($phone,$country="FR") function dol_phone_link($phone,$option=0) { global $conf,$user; - + $link=''; //if (! empty($conf->global->CLICKTODIAL_URL)) if ($conf->clicktodial->enabled) { $phone=trim($phone); - $url = $conf->global->CLICKTODIAL_URL; - $url.= "?login=".urlencode($user->clicktodial_login)."&password=".urlencode($user->clicktodial_password); - $url.= "&caller=".urlencode($user->clicktodial_poste)."&called=".urlencode(trim($phone)); - $link.=''.img_phone("default",0).''; + $url = $conf->global->CLICKTODIAL_URL; + $url.= "?login=".urlencode($user->clicktodial_login)."&password=".urlencode($user->clicktodial_password); + $url.= "&caller=".urlencode($user->clicktodial_poste)."&called=".urlencode(trim($phone)); + $link.=''.img_phone("default",0).''; } return $link; } /** - \brief Tronque une chaine a une taille donnée en ajoutant les points de suspension si cela dépasse - \param string String to truncate - \param size Max string size. 0 for no limit. - \param trunc Where to trunc: right, left, middle - \return string Truncated string - \remarks USE_SHORT_TITLE=0 can disable all truncings -*/ + \brief Tronque une chaine a une taille donnée en ajoutant les points de suspension si cela dépasse + \param string String to truncate + \param size Max string size. 0 for no limit. + \param trunc Where to trunc: right, left, middle + \return string Truncated string + \remarks USE_SHORT_TITLE=0 can disable all truncings + */ function dolibarr_trunc($string,$size=40,$trunc='right') { if ($size==0) return $string; @@ -714,9 +728,9 @@ function dolibarr_trunc($string,$size=40,$trunc='right') if ($trunc == 'right') { if (strlen($string) > $size) - return substr($string,0,$size).'...'; + return substr($string,0,$size).'...'; else - return $string; + return $string; } if ($trunc == 'middle') { @@ -724,17 +738,17 @@ function dolibarr_trunc($string,$size=40,$trunc='right') { $size1=round($size/2); $size2=round($size/2); - return substr($string,0,$size1).'...'.substr($string,strlen($string) - $size2,$size2); + return substr($string,0,$size1).'...'.substr($string,strlen($string) - $size2,$size2); } else - return $string; + return $string; } if ($trunc == 'left') { if (strlen($string) > $size) - return '...'.substr($string,strlen($string) - $size,$size); + return '...'.substr($string,strlen($string) - $size,$size); else - return $string; + return $string; } } else @@ -744,13 +758,13 @@ function dolibarr_trunc($string,$size=40,$trunc='right') } /** - \brief Compléte une chaine a une taille donnée par des espaces - \param string Chaine a compléter - \param size Longueur de la chaine. - \param side 0=Complétion a droite, 1=Complétion a gauche - \param char Chaine de complétion - \return string Chaine complétée -*/ + \brief Compléte une chaine a une taille donnée par des espaces + \param string Chaine a compléter + \param size Longueur de la chaine. + \param side 0=Complétion a droite, 1=Complétion a gauche + \param char Chaine de complétion + \return string Chaine complétée + */ function dolibarr_pad($string,$size,$side,$char=' ') { $taille=sizeof($string); @@ -765,25 +779,25 @@ function dolibarr_pad($string,$size,$side,$char=' ') } /** - \brief Affiche picto propre a une notion/module (fonction générique) - \param alt Texte sur le alt de l'image - \param object Objet pour lequel il faut afficher le logo (exemple: user, group, action, bill, contract, propal, product, ...) - \return string Retourne tag img -*/ + \brief Affiche picto propre a une notion/module (fonction générique) + \param alt Texte sur le alt de l'image + \param object Objet pour lequel il faut afficher le logo (exemple: user, group, action, bill, contract, propal, product, ...) + \return string Retourne tag img + */ function img_object($alt, $object) { - global $conf,$langs; - return ''.$alt.''; + global $conf,$langs; + return ''.$alt.''; } /** - \brief Affiche picto (fonction générique) - \param alt Texte sur le alt de l'image - \param picto Nom de l'image a afficher (Si pas d'extension, on met '.png') - \param options Attribut supplémentaire a la balise img - \param pictoisfullpath If 1, image path is a full path - \return string Retourne tag img -*/ + \brief Affiche picto (fonction générique) + \param alt Texte sur le alt de l'image + \param picto Nom de l'image a afficher (Si pas d'extension, on met '.png') + \param options Attribut supplémentaire a la balise img + \param pictoisfullpath If 1, image path is a full path + \return string Retourne tag img + */ function img_picto($alt, $picto, $options='', $pictoisfullpath=0) { global $conf; @@ -793,167 +807,167 @@ function img_picto($alt, $picto, $options='', $pictoisfullpath=0) } /** - \brief Affiche logo action - \param alt Texte sur le alt de l'image - \param numaction Determine image action - \return string Retourne tag img -*/ + \brief Affiche logo action + \param alt Texte sur le alt de l'image + \param numaction Determine image action + \return string Retourne tag img + */ function img_action($alt = "default", $numaction) { - global $conf,$langs; - if ($alt=="default") { - if ($numaction == -1) $alt=$langs->trans("ChangeDoNotContact"); - if ($numaction == 0) $alt=$langs->trans("ChangeNeverContacted"); - if ($numaction == 1) $alt=$langs->trans("ChangeToContact"); - if ($numaction == 2) $alt=$langs->trans("ChangeContactInProcess"); - if ($numaction == 3) $alt=$langs->trans("ChangeContactDone"); - } - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") { + if ($numaction == -1) $alt=$langs->trans("ChangeDoNotContact"); + if ($numaction == 0) $alt=$langs->trans("ChangeNeverContacted"); + if ($numaction == 1) $alt=$langs->trans("ChangeToContact"); + if ($numaction == 2) $alt=$langs->trans("ChangeContactInProcess"); + if ($numaction == 3) $alt=$langs->trans("ChangeContactDone"); + } + return ''.$alt.''; } /** - \brief Affiche logo fichier - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo fichier + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_file($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Show"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Show"); + return ''.$alt.''; } /** - \brief Affiche logo refresh - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo refresh + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_refresh($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Refresh"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Refresh"); + return ''.$alt.''; } /** - \brief Affiche logo dossier - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo dossier + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_folder($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Dossier"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Dossier"); + return ''.$alt.''; } /** - \brief Affiche logo nouveau fichier - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo nouveau fichier + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_file_new($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Show"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Show"); + return ''.$alt.''; } /** - \brief Affiche logo pdf - \param alt Texte sur le alt de l'image - \param $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px - \return string Retourne tag img -*/ + \brief Affiche logo pdf + \param alt Texte sur le alt de l'image + \param $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px + \return string Retourne tag img + */ function img_pdf($alt = "default",$size=3) { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Show"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Show"); + return ''.$alt.''; } /** - \brief Affiche logo vcard - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo vcard + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_vcard($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("VCard"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("VCard"); + return ''.$alt.''; } /** - \brief Affiche logo + - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo + + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_edit_add($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Add"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Add"); + return ''.$alt.''; } /** - \brief Affiche logo - - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo - + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_edit_remove($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Remove"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Remove"); + return ''.$alt.''; } /** - \brief Affiche logo editer/modifier fiche - \param alt Texte sur le alt de l'image - \param float Si il faut y mettre le style "float: right" - \return string Retourne tag img -*/ + \brief Affiche logo editer/modifier fiche + \param alt Texte sur le alt de l'image + \param float Si il faut y mettre le style "float: right" + \return string Retourne tag img + */ function img_edit($alt = "default", $float=0, $other='') { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Modify"); - $img=''.$alt.'trans("Modify"); + $img=''.$alt.'trans("Delete"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Delete"); + return ''.$alt.''; } /** - \brief Affiche logo désactiver - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo désactiver + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_disable($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Disable"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Disable"); + return ''.$alt.''; } /** - \brief Affiche logo help avec curseur "?" - \return string Retourne tag img -*/ + \brief Affiche logo help avec curseur "?" + \return string Retourne tag img + */ function img_help($usehelpcursor=1,$usealttitle=1) { global $conf,$langs; @@ -966,217 +980,217 @@ function img_help($usehelpcursor=1,$usealttitle=1) } /** - \brief Affiche picto calendrier "?" - \return string Retourne tag img -*/ + \brief Affiche picto calendrier "?" + \return string Retourne tag img + */ function img_cal() { - global $conf,$langs; - return ''; + global $conf,$langs; + return ''; } /** - \brief Affiche logo info - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo info + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_info($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Informations"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Informations"); + return ''.$alt.''; } /** - \brief Affiche logo calculatrice - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo calculatrice + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_calc($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Calculate"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Calculate"); + return ''.$alt.''; } /** - \brief Affiche logo warning - \param alt Texte sur le alt de l'image - \param float Si il faut afficher le style "float: right" - \return string Retourne tag img -*/ + \brief Affiche logo warning + \param alt Texte sur le alt de l'image + \param float Si il faut afficher le style "float: right" + \return string Retourne tag img + */ function img_warning($alt = "default",$float=0) { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Warning"); - $img=''.$alt.'trans("Warning"); + $img=''.$alt.'trans("Error"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Error"); + return ''.$alt.''; } /** - \brief Affiche logo alerte - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo alerte + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_alerte($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Alert"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Alert"); + return ''.$alt.''; } /** - \brief Affiche logo téléphone - \param alt Texte sur le alt de l'image - \param option Choose of logo - \return string Retourne tag img -*/ + \brief Affiche logo téléphone + \param alt Texte sur le alt de l'image + \param option Choose of logo + \return string Retourne tag img + */ function img_phone($alt = "default",$option=0) { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Call"); - $img='call_out'; - if ($option == 1) $img='call'; - $img='object_commercial'; - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Call"); + $img='call_out'; + if ($option == 1) $img='call'; + $img='object_commercial'; + return ''.$alt.''; } /** - \brief Affiche logo suivant - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo suivant + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_next($alt = "default") { - global $conf,$langs; - if ($alt=="default") { - $alt=$langs->trans("Next"); - } - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") { + $alt=$langs->trans("Next"); + } + return ''.$alt.''; } /** - \brief Affiche logo précédent - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo précédent + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_previous($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Previous"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Previous"); + return ''.$alt.''; } /** - \brief Affiche logo bas - \param alt Texte sur le alt de l'image - \param selected Affiche version "selected" du logo - \return string Retourne tag img -*/ + \brief Affiche logo bas + \param alt Texte sur le alt de l'image + \param selected Affiche version "selected" du logo + \return string Retourne tag img + */ function img_down($alt = "default", $selected=0) { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Down"); - if ($selected) return ''.$alt.''; - else return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Down"); + if ($selected) return ''.$alt.''; + else return ''.$alt.''; } /** - \brief Affiche logo haut - \param alt Texte sur le alt de l'image - \param selected Affiche version "selected" du logo - \return string Retourne tag img -*/ + \brief Affiche logo haut + \param alt Texte sur le alt de l'image + \param selected Affiche version "selected" du logo + \return string Retourne tag img + */ function img_up($alt = "default", $selected=0) { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Up"); - if ($selected) return ''.$alt.''; - else return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Up"); + if ($selected) return ''.$alt.''; + else return ''.$alt.''; } /** - \brief Affiche logo gauche - \param alt Texte sur le alt de l'image - \param selected Affiche version "selected" du logo - \return string Retourne tag img -*/ + \brief Affiche logo gauche + \param alt Texte sur le alt de l'image + \param selected Affiche version "selected" du logo + \return string Retourne tag img + */ function img_left($alt = "default", $selected=0) { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Left"); - if ($selected) return ''.$alt.''; - else return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Left"); + if ($selected) return ''.$alt.''; + else return ''.$alt.''; } /** - \brief Affiche logo droite - \param alt Texte sur le alt de l'image - \param selected Affiche version "selected" du logo - \return string Retourne tag img -*/ + \brief Affiche logo droite + \param alt Texte sur le alt de l'image + \param selected Affiche version "selected" du logo + \return string Retourne tag img + */ function img_right($alt = "default", $selected=0) { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Right"); - if ($selected) return ''.$alt.''; - else return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Right"); + if ($selected) return ''.$alt.''; + else return ''.$alt.''; } /** - \brief Affiche logo tick - \param alt Texte sur le alt de l'image - \return string Retourne tag img -*/ + \brief Affiche logo tick + \param alt Texte sur le alt de l'image + \return string Retourne tag img + */ function img_tick($alt = "default") { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Active"); - return ''.$alt.''; + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Active"); + return ''.$alt.''; } /** - \brief Affiche le logo tick si allow - \param allow Authorise ou non - \return string Retourne tag img -*/ + \brief Affiche le logo tick si allow + \param allow Authorise ou non + \return string Retourne tag img + */ function img_allow($allow) { - global $conf,$langs; - if ($alt=="default") $alt=$langs->trans("Active"); + global $conf,$langs; + if ($alt=="default") $alt=$langs->trans("Active"); - if ($allow == 1) - { - return ''.$alt.''; - } - else - { - return "-"; - } + if ($allow == 1) + { + return ''.$alt.''; + } + else + { + return "-"; + } } /** - \brief Return if a filename is file name of a supported image format - \param file Filename - \return int -1=Not image filename, 0=Image filename but format not supported by PHP, 1=Image filename with format supported -*/ + \brief Return if a filename is file name of a supported image format + \param file Filename + \return int -1=Not image filename, 0=Image filename but format not supported by PHP, 1=Image filename with format supported + */ function image_format_supported($file) { // Case filename is not a format image @@ -1203,11 +1217,11 @@ function image_format_supported($file) } /** - \brief Affiche info admin - \param text Text info - \param infoonimgalt Info is shown on alt of star picto - \return string String with info text -*/ + \brief Affiche info admin + \param text Text info + \param infoonimgalt Info is shown on alt of star picto + \return string String with info text + */ function info_admin($texte,$infoonimgalt=0) { global $conf,$langs; @@ -1229,18 +1243,18 @@ function info_admin($texte,$infoonimgalt=0) /** - \brief Check permissions of a user to show a page and an object. - \param user User to check - \param feature Feature to check (in most cases, it's module name) - \param objectid Object ID if we want to check permission on on object (optionnal) - \param dbtable Table name where object is stored. Not used if objectid is null (optionnel) -*/ + \brief Check permissions of a user to show a page and an object. + \param user User to check + \param feature Feature to check (in most cases, it's module name) + \param objectid Object ID if we want to check permission on on object (optionnal) + \param dbtable Table name where object is stored. Not used if objectid is null (optionnel) + */ function restrictedArea($user, $feature='societe', $objectid=0, $dbtablename='') { global $db; - + //print "$user->id, $feature, $objectid, $dbtablename, $list ".$user->rights->societe->contact->lire; - + // Check read permission from module // TODO Replace "feature" param by permission for reading $readok=1; @@ -1299,7 +1313,7 @@ function restrictedArea($user, $feature='societe', $objectid=0, $dbtablename='') if (! $createok) accessforbidden(); //print "Write access is ok"; } - + // If we have a particular object to check permissions on if ($objectid) { @@ -1333,7 +1347,7 @@ function restrictedArea($user, $feature='societe', $objectid=0, $dbtablename='') else { if (!$dbtablename) $dbtablename = $feature; // Si dbtable non défini, meme nom que le module - + $sql = "SELECT sc.fk_soc"; $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = dbt.fk_soc"; @@ -1341,7 +1355,7 @@ function restrictedArea($user, $feature='societe', $objectid=0, $dbtablename='') $sql.= " AND IFNULL(sc.fk_user, ".$user->id.") = ".$user->id; } } - + //print $sql; if ($sql) { @@ -1357,17 +1371,17 @@ function restrictedArea($user, $feature='societe', $objectid=0, $dbtablename='') } } } - + return 1; } /** - \brief Affiche message erreur de type acces interdit et arrete le programme - \param message Force error message - \param printheader Affiche avant le header - \remarks L'appel a cette fonction termine le code. -*/ + \brief Affiche message erreur de type acces interdit et arrete le programme + \param message Force error message + \param printheader Affiche avant le header + \remarks L'appel a cette fonction termine le code. + */ function accessforbidden($message='',$printheader=1) { global $user, $langs; @@ -1399,105 +1413,105 @@ function accessforbidden($message='',$printheader=1) /** - \brief Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remontée des bugs. - On doit appeler cette fonction quand une erreur technique bloquante est rencontrée. - Toutefois, il faut essayer de ne l'appeler qu'au sein de pages php, les classes devant - renvoyer leur erreur par l'intermédiaire de leur propriété "error". - \param db Handler de base utilisé - \param error Chaine erreur ou tableau de chaines erreur complémentaires a afficher -*/ + \brief Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remontée des bugs. + On doit appeler cette fonction quand une erreur technique bloquante est rencontrée. + Toutefois, il faut essayer de ne l'appeler qu'au sein de pages php, les classes devant + renvoyer leur erreur par l'intermédiaire de leur propriété "error". + \param db Handler de base utilisé + \param error Chaine erreur ou tableau de chaines erreur complémentaires a afficher + */ function dolibarr_print_error($db='',$error='') { - global $conf,$langs,$argv; - $syslog = ''; + global $conf,$langs,$argv; + $syslog = ''; - // Si erreur intervenue avant chargement langue - if (! $langs) - { - require_once(DOL_DOCUMENT_ROOT ."/translate.class.php"); - $langs = new Translate("", $conf); - } - $langs->load("main"); + // Si erreur intervenue avant chargement langue + if (! $langs) + { + require_once(DOL_DOCUMENT_ROOT ."/translate.class.php"); + $langs = new Translate("", $conf); + } + $langs->load("main"); - if ($_SERVER['DOCUMENT_ROOT']) // Mode web - { - print $langs->trans("DolibarrHasDetectedError").".
\n"; - print $langs->trans("InformationToHelpDiagnose").":

\n"; + if ($_SERVER['DOCUMENT_ROOT']) // Mode web + { + print $langs->trans("DolibarrHasDetectedError").".
\n"; + print $langs->trans("InformationToHelpDiagnose").":

\n"; - print "".$langs->trans("Dolibarr").": ".DOL_VERSION."
\n";; - if (isset($conf->global->MAIN_FEATURES_LEVEL)) print "".$langs->trans("LevelOfFeature").": ".$conf->global->MAIN_FEATURES_LEVEL."
\n";; - print "".$langs->trans("Server").": ".$_SERVER["SERVER_SOFTWARE"]."
\n";; - print "".$langs->trans("RequestedUrl").": ".$_SERVER["REQUEST_URI"]."
\n";; - print "".$langs->trans("Referer").": ".$_SERVER["HTTP_REFERER"]."
\n";; - $syslog.="url=".$_SERVER["REQUEST_URI"]; - $syslog.=", query_string=".$_SERVER["QUERY_STRING"]; - } - else // Mode CLI - { - print $langs->transnoentities("ErrorInternalErrorDetected").": ".$argv[0]."\n"; - $syslog.="pid=".getmypid(); - } + print "".$langs->trans("Dolibarr").": ".DOL_VERSION."
\n";; + if (isset($conf->global->MAIN_FEATURES_LEVEL)) print "".$langs->trans("LevelOfFeature").": ".$conf->global->MAIN_FEATURES_LEVEL."
\n";; + print "".$langs->trans("Server").": ".$_SERVER["SERVER_SOFTWARE"]."
\n";; + print "".$langs->trans("RequestedUrl").": ".$_SERVER["REQUEST_URI"]."
\n";; + print "".$langs->trans("Referer").": ".$_SERVER["HTTP_REFERER"]."
\n";; + $syslog.="url=".$_SERVER["REQUEST_URI"]; + $syslog.=", query_string=".$_SERVER["QUERY_STRING"]; + } + else // Mode CLI + { + print $langs->transnoentities("ErrorInternalErrorDetected").": ".$argv[0]."\n"; + $syslog.="pid=".getmypid(); + } - if (is_object($db)) - { - if ($_SERVER['DOCUMENT_ROOT']) // Mode web - { - print "
\n"; - print "".$langs->trans("DatabaseTypeManager").": ".$db->type."
\n"; - print "".$langs->trans("RequestLastAccessInError").": ".($db->lastqueryerror()?$db->lastqueryerror():$langs->trans("ErrorNoRequestInError"))."
\n"; - print "".$langs->trans("ReturnCodeLastAccess").": ".$db->errno()."
\n"; - print "".$langs->trans("InformationLastAccess").": ".$db->error()."
\n"; - } - else // Mode CLI - { - print $langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n"; - print $langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->trans("ErrorNoRequestInError"))."\n"; - print $langs->transnoentities("ReturnCodeLastAccess").":\n".$db->errno()."\n"; - print $langs->transnoentities("InformationLastAccess").":\n".$db->error()."\n"; + if (is_object($db)) + { + if ($_SERVER['DOCUMENT_ROOT']) // Mode web + { + print "
\n"; + print "".$langs->trans("DatabaseTypeManager").": ".$db->type."
\n"; + print "".$langs->trans("RequestLastAccessInError").": ".($db->lastqueryerror()?$db->lastqueryerror():$langs->trans("ErrorNoRequestInError"))."
\n"; + print "".$langs->trans("ReturnCodeLastAccess").": ".$db->errno()."
\n"; + print "".$langs->trans("InformationLastAccess").": ".$db->error()."
\n"; + } + else // Mode CLI + { + print $langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n"; + print $langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->trans("ErrorNoRequestInError"))."\n"; + print $langs->transnoentities("ReturnCodeLastAccess").":\n".$db->errno()."\n"; + print $langs->transnoentities("InformationLastAccess").":\n".$db->error()."\n"; - } - $syslog.=", sql=".$db->lastquery(); - $syslog.=", db_error=".$db->error(); - } + } + $syslog.=", sql=".$db->lastquery(); + $syslog.=", db_error=".$db->error(); + } - if ($error) - { - $langs->load("errors"); - + if ($error) + { + $langs->load("errors"); + if (is_array($error)) $errors=$error; else $errors=array($error); - + foreach($errors as $msg) { $msg=$langs->trans($msg); - if ($_SERVER['DOCUMENT_ROOT']) // Mode web - { - print "".$langs->trans("Message").": ".$msg."
\n" ; - } - else // Mode CLI - { - print $langs->transnoentities("Message").":\n".$msg."\n" ; - } - $syslog.=", msg=".$msg; + if ($_SERVER['DOCUMENT_ROOT']) // Mode web + { + print "".$langs->trans("Message").": ".$msg."
\n" ; + } + else // Mode CLI + { + print $langs->transnoentities("Message").":\n".$msg."\n" ; + } + $syslog.=", msg=".$msg; } } - dolibarr_syslog("Error $syslog",LOG_ERROR); + dolibarr_syslog("Error $syslog",LOG_ERROR); } /** - \brief Deplacer les fichiers telechargés, apres quelques controles divers - \param src_file fichier source - \param dest_file fichier de destination - \return int true=Deplacement OK, false=Pas de deplacement ou KO -*/ + \brief Deplacer les fichiers telechargés, apres quelques controles divers + \param src_file fichier source + \param dest_file fichier de destination + \return int true=Deplacement OK, false=Pas de deplacement ou KO + */ function dol_move_uploaded_file($src_file, $dest_file) { global $conf; - + $file_name = $dest_file; - + if ($conf->global->MAIN_USE_AVSCAN) { $malware = dol_avscan_file($src_file); @@ -1514,7 +1528,7 @@ function dol_move_uploaded_file($src_file, $dest_file) } // Security: - // On interdit les remontées de repertoire ainsi que les pipe dans + // On interdit les remontées de repertoire ainsi que les pipe dans // les noms de fichiers. if (eregi('\.\.',$src_file) || eregi('[<>|]',$src_file)) { @@ -1523,7 +1537,7 @@ function dol_move_uploaded_file($src_file, $dest_file) } // Security: - // On interdit les remontées de repertoire ainsi que les pipe dans + // On interdit les remontées de repertoire ainsi que les pipe dans // les noms de fichiers. if (eregi('\.\.',$dest_file) || eregi('[<>|]',$dest_file)) { @@ -1532,108 +1546,108 @@ function dol_move_uploaded_file($src_file, $dest_file) } $return=move_uploaded_file($src_file, $file_name); - + return $return; } /** - \brief Show title line of an array - \param name libelle champ - \param file url pour clic sur tri - \param field champ de tri - \param begin ("" par defaut) - \param options ("" par defaut) - \param td options de l'attribut td ("" par defaut) - \param sortfield nom du champ sur lequel est effectué le tri du tableau - \param sortorder ordre du tri -*/ + \brief Show title line of an array + \param name libelle champ + \param file url pour clic sur tri + \param field champ de tri + \param begin ("" par defaut) + \param options ("" par defaut) + \param td options de l'attribut td ("" par defaut) + \param sortfield nom du champ sur lequel est effectué le tri du tableau + \param sortorder ordre du tri + */ function print_liste_field_titre($name, $file, $field, $begin="", $options="", $td="", $sortfield="", $sortorder="") { - global $conf; + global $conf; //print "$name, $file, $field, $begin, $options, $td, $sortfield, $sortorder
\n"; - // Le champ de tri est mis en évidence. - // Exemple si (sortfield,field)=("nom","xxx.nom") ou (sortfield,field)=("nom","nom") - if ($sortfield == $field || $sortfield == ereg_replace("^[^\.]+\.","",$field)) - { - print '
"; + print ""; } /** - \brief Affichage d'un titre - \param titre Le titre a afficher -*/ + \brief Affichage d'un titre + \param titre Le titre a afficher + */ function print_titre($titre) { - print '
'.$titre.'
'; + print '
'.$titre.'
'; } /** - \brief Affichage d'un titre d'une fiche, aligné a gauche - \param titre Le titre a afficher - \param mesg Message suplémentaire a afficher a droite - \param picto Picto pour ligne de titre - \param pictoisfullpath 1=Picto is a full absolute url of image -*/ + \brief Affichage d'un titre d'une fiche, aligné a gauche + \param titre Le titre a afficher + \param mesg Message suplémentaire a afficher a droite + \param picto Picto pour ligne de titre + \param pictoisfullpath 1=Picto is a full absolute url of image + */ function print_fiche_titre($titre, $mesg='', $picto='', $pictoisfullpath=0) { - print "\n"; - print '
'; - } - else - { - print ''; - } - print $name; - + // Le champ de tri est mis en évidence. + // Exemple si (sortfield,field)=("nom","xxx.nom") ou (sortfield,field)=("nom","nom") + if ($sortfield == $field || $sortfield == ereg_replace("^[^\.]+\.","",$field)) + { + print ''; + } + else + { + print ''; + } + print $name; + // If this is a sort field if ($field) { //print " "; - print ''; + print ''; if (! $sortorder) - { - print ''.img_down("A-Z",0).''; - print ''.img_up("Z-A",0).''; - } - else - { - if ($field != $sortfield) + { + print ''.img_down("A-Z",0).''; + print ''.img_up("Z-A",0).''; + } + else + { + if ($field != $sortfield) { - print ''.img_down("A-Z",0).''; - print ''.img_up("Z-A",0).''; - } - else { + print ''.img_down("A-Z",0).''; + print ''.img_up("Z-A",0).''; + } + else { $sortorder=strtoupper($sortorder); - if ($sortorder == 'DESC' ) { - print ''.img_down("A-Z",0).''; - print ''.img_up("Z-A",1).''; - } - if ($sortorder == 'ASC' ) { - print ''.img_down("A-Z",1).''; - print ''.img_up("Z-A",0).''; - } - } - } + if ($sortorder == 'DESC' ) { + print ''.img_down("A-Z",0).''; + print ''.img_up("Z-A",1).''; + } + if ($sortorder == 'ASC' ) { + print ''.img_down("A-Z",1).''; + print ''.img_up("Z-A",0).''; + } + } + } } - print "
'; + print "\n"; + print '
'; if ($picto) print ''; - print ''; - if (strlen($mesg)) - { - print ''; - } - print '
'.img_picto('',$picto, '', $pictoisfullpath).''; - print '
'.$titre.'
'; - print '
'.$mesg.'
'."\n"; + print ''; + print '
'.$titre.'
'; + print ''; + if (strlen($mesg)) + { + print ''.$mesg.''; + } + print ''."\n"; } /** - \brief Effacement d'un fichier - \param file Fichier a effacer ou masque de fichier a effacer - \param boolean true if file deleted, false if error -*/ + \brief Effacement d'un fichier + \param file Fichier a effacer ou masque de fichier a effacer + \param boolean true if file deleted, false if error + */ function dol_delete_file($file) { $ok=true; @@ -1647,20 +1661,20 @@ function dol_delete_file($file) } /** - \brief Effacement d'un répertoire - \param file Répertoire a effacer -*/ + \brief Effacement d'un répertoire + \param file Répertoire a effacer + */ function dol_delete_dir($dir) { return rmdir($dir); } /** - \brief Effacement d'un répertoire $dir et de son arborescence - \param file Répertoire a effacer - \param count Compteur pour comptage nb elements supprimés - \return int Nombre de fichier+repértoires supprimés -*/ + \brief Effacement d'un répertoire $dir et de son arborescence + \param file Répertoire a effacer + \param count Compteur pour comptage nb elements supprimés + \return int Nombre de fichier+repértoires supprimés + */ function dol_delete_dir_recursive($dir,$count=0) { if ($handle = opendir("$dir")) @@ -1692,69 +1706,69 @@ function dol_delete_dir_recursive($dir,$count=0) } /** - \brief Scan les fichiers avec un anti-virus - \param file Fichier a scanner - \return malware Nom du virus si infecté sinon retourne "null" -*/ + \brief Scan les fichiers avec un anti-virus + \param file Fichier a scanner + \return malware Nom du virus si infecté sinon retourne "null" + */ function dol_avscan_file($file) { $malware = ''; - + // Clamav if (function_exists("cl_scanfile")) { $maxreclevel = 5 ; // maximal recursion level - $maxfiles = 1000; // maximal number of files to be scanned within archive - $maxratio = 200; // maximal compression ratio - $archivememlim = 0; // limit memory usage for bzip2 (0/1) - $maxfilesize = 10485760; // archived files larger than this value (in bytes) will not be scanned - - cl_setlimits($maxreclevel, $maxfiles, $maxratio, $archivememlim, $maxfilesize); - $malware = cl_scanfile($file); - } + $maxfiles = 1000; // maximal number of files to be scanned within archive + $maxratio = 200; // maximal compression ratio + $archivememlim = 0; // limit memory usage for bzip2 (0/1) + $maxfilesize = 10485760; // archived files larger than this value (in bytes) will not be scanned + + cl_setlimits($maxreclevel, $maxfiles, $maxratio, $archivememlim, $maxfilesize); + $malware = cl_scanfile($file); + } return $malware; } /** - \brief Fonction print_barre_liste - \param titre Titre de la page - \param page numéro de la page - \param file lien - \param options parametres complementaires lien ('' par defaut) - \param sortfield champ de tri ('' par defaut) - \param sortorder ordre de tri ('' par defaut) - \param center chaine du centre ('' par defaut) - \param num number of records found by select with limit+1 - \param totalnboflines Total number of records/lines for all pages (if known) -*/ + \brief Fonction print_barre_liste + \param titre Titre de la page + \param page numéro de la page + \param file lien + \param options parametres complementaires lien ('' par defaut) + \param sortfield champ de tri ('' par defaut) + \param sortorder ordre de tri ('' par defaut) + \param center chaine du centre ('' par defaut) + \param num number of records found by select with limit+1 + \param totalnboflines Total number of records/lines for all pages (if known) + */ function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $center='', $num=-1, $totalnboflines=0) { - global $conf,$langs; + global $conf,$langs; - if ($num > $conf->liste_limit or $num == -1) - { - $nextpage = 1; - } - else - { - $nextpage = 0; - } + if ($num > $conf->liste_limit or $num == -1) + { + $nextpage = 1; + } + else + { + $nextpage = 0; + } - print ''; + print '
'; $pagelist = ''; if ($page > 0 || $num > $conf->liste_limit) - { + { if ($totalnboflines) { print ''; - + $maxnbofpage=10; - + $nbpages=ceil($totalnboflines/$conf->liste_limit); $cpt=($page-$maxnbofpage); if ($cpt < 0) { $cpt=0; } @@ -1778,48 +1792,48 @@ function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $so } while ($cpt < $nbpages && $cpt<=$page+$maxnbofpage); if ($cpt<$nbpages) - { + { if ($cpt<$nbpages-1) $pagelist.= ' ...'; $pagelist.= ' '.$nbpages.''; } } - else + else { print ''; } - } - else - { - print ''; - } + } + else + { + print ''; + } - if ($center) - { - print ''; - } + if ($center) + { + print ''; + } - print '
'; print '
'.$titre.'
'; print '
'; print '
'.$titre.'
'; $pagelist.= $langs->trans('Page').' '.($page+1); print '
'.$titre.'
'.$titre.'
'.$center.''.$center.''; + print ''; - if ($sortfield) $options .= "&sortfield=".$sortfield; - if ($sortorder) $options .= "&sortorder=".$sortorder; + if ($sortfield) $options .= "&sortfield=".$sortfield; + if ($sortorder) $options .= "&sortorder=".$sortorder; - // Affichage des fleches de navigation - print_fleche_navigation($page,$file,$options,$nextpage,$pagelist); + // Affichage des fleches de navigation + print_fleche_navigation($page,$file,$options,$nextpage,$pagelist); - print '
'; + print ''; } /** - \brief Fonction servant a afficher les fleches de navigation dans les pages de listes - \param page Numéro de la page - \param file Lien - \param options Autres parametres d'url a propager dans les liens ("" par defaut) - \param nextpage Faut-il une page suivante - \param betweenarraows HTML Content to show between arrows -*/ + \brief Fonction servant a afficher les fleches de navigation dans les pages de listes + \param page Numéro de la page + \param file Lien + \param options Autres parametres d'url a propager dans les liens ("" par defaut) + \param nextpage Faut-il une page suivante + \param betweenarraows HTML Content to show between arrows + */ function print_fleche_navigation($page,$file,$options='',$nextpage,$betweenarrows='') { global $conf, $langs; @@ -1836,13 +1850,13 @@ function print_fleche_navigation($page,$file,$options='',$nextpage,$betweenarrow /** -* \brief Fonction qui retourne un taux de tva formaté pour visualisation -* \remarks Fonction utilisée dans les pdf et les pages html -* \param rate Rate value to format (19.6 19,6 19.6% 19,6%,...) -* \param foundpercent Add a percent % sign in output -* \param info_bits Miscellanous information on vat -* \return string Chaine avec montant formaté (19,6 ou 19,6% ou 8.5% *) -*/ + * \brief Fonction qui retourne un taux de tva formaté pour visualisation + * \remarks Fonction utilisée dans les pdf et les pages html + * \param rate Rate value to format (19.6 19,6 19.6% 19,6%,...) + * \param foundpercent Add a percent % sign in output + * \param info_bits Miscellanous information on vat + * \return string Chaine avec montant formaté (19,6 ou 19,6% ou 8.5% *) + */ function vatrate($rate,$foundpercent=false,$info_bits=0) { // Test for compatibility @@ -1856,7 +1870,7 @@ function vatrate($rate,$foundpercent=false,$info_bits=0) $rate=eregi_replace('\*','',$rate); $info_bits |= 1; } - + $ret=price($rate,0,'',0,0).($foundpercent?'%':''); if ($info_bits & 1) $ret.=' '.MAIN_LABEL_MENTION_NPR; return $ret; @@ -1864,16 +1878,16 @@ function vatrate($rate,$foundpercent=false,$info_bits=0) /** -* \brief Fonction qui retourne un montant monétaire formaté pour visualisation -* \remarks Fonction utilisée dans les pdf et les pages html -* \param amount Montant a formater -* \param html Formatage html ou pas (0 par defaut) -* \param outlangs Objet langs pour formatage text -* \param trunc 1=Tronque affichage si trop de décimales,0=Force le non troncage -* \param nbdecimal Nbre decimals minimum. -* \return string Chaine avec montant formaté -* \seealso price2num Fonction inverse de price -*/ + * \brief Fonction qui retourne un montant monétaire formaté pour visualisation + * \remarks Fonction utilisée dans les pdf et les pages html + * \param amount Montant a formater + * \param html Formatage html ou pas (0 par defaut) + * \param outlangs Objet langs pour formatage text + * \param trunc 1=Tronque affichage si trop de décimales,0=Force le non troncage + * \param nbdecimal Nbre decimals minimum. + * \return string Chaine avec montant formaté + * \seealso price2num Fonction inverse de price + */ function price($amount, $html=0, $outlangs='', $trunc=1, $nbdecimal=2) { global $langs,$conf; @@ -1888,7 +1902,7 @@ function price($amount, $html=0, $outlangs='', $trunc=1, $nbdecimal=2) if ($outlangs->trans("SeparatorThousand")!= "SeparatorThousand") $thousand=$outlangs->trans("SeparatorThousand"); //print "amount=".$amount." html=".$html." trunc=".$trunc." nbdecimal=".$nbdecimal." dec=".$dec." thousand=".$thousand; - //print "amount=".$amount."-"; + //print "amount=".$amount."-"; $amount = ereg_replace(',','.',$amount); //print $amount."-"; $datas = split('\.',$amount); @@ -1900,7 +1914,7 @@ function price($amount, $html=0, $outlangs='', $trunc=1, $nbdecimal=2) // On augmente au besoin si il y a plus de 2 décimales if (strlen($decpart) > $nbdecimal) $nbdecimal=strlen($decpart); // Si on depasse max - if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) + if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) { $nbdecimal=$conf->global->MAIN_MAX_DECIMALS_SHOWN; if (eregi('\.\.\.',$conf->global->MAIN_MAX_DECIMALS_SHOWN)) @@ -1909,7 +1923,7 @@ function price($amount, $html=0, $outlangs='', $trunc=1, $nbdecimal=2) $end='...'; } } - + // Formate nombre if ($html) { @@ -1920,26 +1934,26 @@ function price($amount, $html=0, $outlangs='', $trunc=1, $nbdecimal=2) $output=number_format($amount, $nbdecimal, $dec, $thousand); } $output.=$end; - + return $output; } /** - \brief Fonction qui retourne un numérique conforme PHP et SQL, depuis un montant au - format utilisateur. - \remarks Fonction a appeler sur montants saisis avant un insert en base - \param amount Montant a formater - \param rounding 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT) - 'MT'=Round to Max with Tax (MAIN_MAX_DECIMALS_TOT) - 'MS'=Round to Max Shown (MAIN_MAX_DECIMALS_SHOWN) - ''=No rounding - \return string Montant au format numérique PHP et SQL (Exemple: '99.99999') - \seealso price Fonction inverse de price2num -*/ + \brief Fonction qui retourne un numérique conforme PHP et SQL, depuis un montant au + format utilisateur. + \remarks Fonction a appeler sur montants saisis avant un insert en base + \param amount Montant a formater + \param rounding 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT) + 'MT'=Round to Max with Tax (MAIN_MAX_DECIMALS_TOT) + 'MS'=Round to Max Shown (MAIN_MAX_DECIMALS_SHOWN) + ''=No rounding + \return string Montant au format numérique PHP et SQL (Exemple: '99.99999') + \seealso price Fonction inverse de price2num + */ function price2num($amount,$rounding='') { global $conf; - + // Round PHP function does not allow number like '1,234.5'. // Numbers must be '1234.5' $amount=ereg_replace(',','.',$amount); @@ -1958,15 +1972,15 @@ function price2num($amount,$rounding='') /** -* \brief Return vat rate of a product in a particular selling country -*/ + * \brief Return vat rate of a product in a particular selling country + */ function get_product_vat_for_country($idprod, $countrycode) { global $db; - + $product=new Product($db); $product->fetch($idprod); - + // \TODO Read rate according to countrycode // For the moment only one rate supported @@ -1975,18 +1989,18 @@ function get_product_vat_for_country($idprod, $countrycode) /** - \brief Fonction qui renvoie la tva d'une ligne (en fonction du vendeur, acheteur et taux du produit) - \remarks Si vendeur non assujeti a TVA, TVA par défaut=0. Fin de régle. - Si le (pays vendeur = pays acheteur) alors TVA par défaut=TVA du produit vendu. Fin de régle. - Si (vendeur et acheteur dans Communauté européenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par défaut=0 (La TVA doit étre payé par acheteur au centre d'impots de son pays et non au vendeur). Fin de régle. - Si (vendeur et acheteur dans Communauté européenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par défaut=TVA du produit vendu. Fin de régle. - Si (vendeur et acheteur dans Communauté européenne) et (acheteur = entreprise avec num TVA) intra alors TVA par défaut=0. Fin de régle. - Sinon TVA proposée par défaut=0. Fin de régle. - \param societe_vendeuse Objet société vendeuse - \param societe_acheteuse Objet société acheteuse - \param taux_produit Taux par defaut du produit vendu (old way to get product vat rate) - \param idprod Id product (new way to get product vat rate) - \return float Taux de tva a appliquer, -1 si ne peut etre déterminé + \brief Fonction qui renvoie la tva d'une ligne (en fonction du vendeur, acheteur et taux du produit) + \remarks Si vendeur non assujeti a TVA, TVA par défaut=0. Fin de régle. + Si le (pays vendeur = pays acheteur) alors TVA par défaut=TVA du produit vendu. Fin de régle. + Si (vendeur et acheteur dans Communauté européenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par défaut=0 (La TVA doit étre payé par acheteur au centre d'impots de son pays et non au vendeur). Fin de régle. + Si (vendeur et acheteur dans Communauté européenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par défaut=TVA du produit vendu. Fin de régle. + Si (vendeur et acheteur dans Communauté européenne) et (acheteur = entreprise avec num TVA) intra alors TVA par défaut=0. Fin de régle. + Sinon TVA proposée par défaut=0. Fin de régle. + \param societe_vendeuse Objet société vendeuse + \param societe_acheteuse Objet société acheteuse + \param taux_produit Taux par defaut du produit vendu (old way to get product vat rate) + \param idprod Id product (new way to get product vat rate) + \return float Taux de tva a appliquer, -1 si ne peut etre déterminé */ function get_default_tva($societe_vendeuse, $societe_acheteuse, $taux_produit, $idprod=0) { @@ -2004,7 +2018,7 @@ function get_default_tva($societe_vendeuse, $societe_acheteuse, $taux_produit, $ // Le test ci-dessus ne devrait pas etre necessaire. Me signaler l'exemple du cas juridique concercné si le test suivant n'est pas suffisant. if ($societe_vendeuse->pays_id == $societe_acheteuse->pays_id) { - if ($idprod) return get_product_vat_for_country($idprod,$societe_vendeuse->pays_code); + if ($idprod) return get_product_vat_for_country($idprod,$societe_vendeuse->pays_code); if (strlen($taux_produit) == 0) return -1; // Si taux produit = '', on ne peut déterminer taux tva return $taux_produit; } @@ -2012,38 +2026,38 @@ function get_default_tva($societe_vendeuse, $societe_acheteuse, $taux_produit, $ // Si (vendeur et acheteur dans Communauté européenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par défaut=0 (La TVA doit étre payé par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de régle. // Non géré - // Si (vendeur et acheteur dans Communauté européenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par défaut=TVA du produit vendu. Fin de régle. + // Si (vendeur et acheteur dans Communauté européenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par défaut=TVA du produit vendu. Fin de régle. if (($societe_vendeuse->isInEEC() && $societe_acheteuse->isInEEC()) && ! $societe_acheteuse->tva_intra) { - if ($idprod) return get_product_vat_for_country($idprod,$societe_vendeuse->pays_code); + if ($idprod) return get_product_vat_for_country($idprod,$societe_vendeuse->pays_code); if (strlen($taux_produit) == 0) return -1; // Si taux produit = '', on ne peut déterminer taux tva - return $taux_produit; + return $taux_produit; } - // Si (vendeur et acheteur dans Communauté européenne) et (acheteur = entreprise avec num TVA intra) alors TVA par défaut=0. Fin de régle. + // Si (vendeur et acheteur dans Communauté européenne) et (acheteur = entreprise avec num TVA intra) alors TVA par défaut=0. Fin de régle. if (($societe_vendeuse->isInEEC() && $societe_acheteuse->isInEEC()) && $societe_acheteuse->tva_intra) { - return 0; + return 0; } // Sinon la TVA proposée par défaut=0. Fin de régle. // Rem: Cela signifie qu'au moins un des 2 est hors Communauté européenne et que le pays différe - return 0; + return 0; } /** - \brief Fonction qui renvoie si tva doit etre tva percue récupérable - \remarks Si vendeur non assujeti a TVA, TVA par défaut=0. Fin de régle. - Si le (pays vendeur = pays acheteur) alors TVA par défaut=TVA du produit vendu. Fin de régle. - Si (vendeur et acheteur dans Communauté européenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par défaut=0 (La TVA doit étre payé par acheteur au centre d'impots de son pays et non au vendeur). Fin de régle. - Si (vendeur et acheteur dans Communauté européenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par défaut=TVA du produit vendu. Fin de régle. - Si (vendeur et acheteur dans Communauté européenne) et (acheteur = entreprise avec num TVA) intra alors TVA par défaut=0. Fin de régle. - Sinon TVA proposée par défaut=0. Fin de régle. - \param societe_vendeuse Objet société vendeuse - \param societe_acheteuse Objet société acheteuse - \param taux_produit Taux par defaut du produit vendu - \return float 0 or 1 + \brief Fonction qui renvoie si tva doit etre tva percue récupérable + \remarks Si vendeur non assujeti a TVA, TVA par défaut=0. Fin de régle. + Si le (pays vendeur = pays acheteur) alors TVA par défaut=TVA du produit vendu. Fin de régle. + Si (vendeur et acheteur dans Communauté européenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par défaut=0 (La TVA doit étre payé par acheteur au centre d'impots de son pays et non au vendeur). Fin de régle. + Si (vendeur et acheteur dans Communauté européenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par défaut=TVA du produit vendu. Fin de régle. + Si (vendeur et acheteur dans Communauté européenne) et (acheteur = entreprise avec num TVA) intra alors TVA par défaut=0. Fin de régle. + Sinon TVA proposée par défaut=0. Fin de régle. + \param societe_vendeuse Objet société vendeuse + \param societe_acheteuse Objet société acheteuse + \param taux_produit Taux par defaut du produit vendu + \return float 0 or 1 */ function get_default_npr($societe_vendeuse, $societe_acheteuse, $taux_produit) { @@ -2053,23 +2067,23 @@ function get_default_npr($societe_vendeuse, $societe_acheteuse, $taux_produit) /** - \brief Renvoie oui ou non dans la langue choisie - \param yesno Variable pour test si oui ou non - \param case 1=Yes/No, 0=yes/no - \param color 0=texte only, 1=Text is format with a color font style -*/ + \brief Renvoie oui ou non dans la langue choisie + \param yesno Variable pour test si oui ou non + \param case 1=Yes/No, 0=yes/no + \param color 0=texte only, 1=Text is format with a color font style + */ function yn($yesno, $case=1, $color=0) { - global $langs; + global $langs; $result='unknown'; - if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0 + if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0 { - $result=($case?$langs->trans("Yes"):$langs->trans("yes")); + $result=($case?$langs->trans("Yes"):$langs->trans("yes")); $class='ok'; } - elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') + elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') { - $result=($case?$langs->trans("No"):$langs->trans("no")); + $result=($case?$langs->trans("No"):$langs->trans("no")); $class='error'; } if ($color) return ''.$result.''; @@ -2078,43 +2092,43 @@ function yn($yesno, $case=1, $color=0) /** - \brief Fonction pour qui retourne le rowid d'un departement par son code - \param db handler d'accés base - \param code Code région - \param pays_id Id du pays -*/ + \brief Fonction pour qui retourne le rowid d'un departement par son code + \param db handler d'accés base + \param code Code région + \param pays_id Id du pays + */ function departement_rowid($db,$code, $pays_id) { - $sql = "SELECT c.rowid FROM ".MAIN_DB_PREFIX."c_departements as c,".MAIN_DB_PREFIX."c_regions as r"; - $sql .= " WHERE c.code_departement=". $code; - $sql .= " AND c.fk_region = r.code_region"; - $sql .= " AND r.fk_pays =".$pays_id; + $sql = "SELECT c.rowid FROM ".MAIN_DB_PREFIX."c_departements as c,".MAIN_DB_PREFIX."c_regions as r"; + $sql .= " WHERE c.code_departement=". $code; + $sql .= " AND c.fk_region = r.code_region"; + $sql .= " AND r.fk_pays =".$pays_id; - if ($db->query($sql)) - { - $num = $db->num_rows(); - if ($num) + if ($db->query($sql)) { + $num = $db->num_rows(); + if ($num) + { $obj = $db->fetch_object(); return $obj->rowid; - } - else - { + } + else + { return 0; + } + $db->free(); + } + else + { + return 0; } - $db->free(); - } - else - { - return 0; - } } /** - \brief Renvoi un chemin de classement répertoire en fonction d'un id - \remarks Examples: 1->"0/0/1/", 15->"0/1/5/" - \param $num Id a décomposer - \param $level Niveau de decoupage (1, 2 ou 3 niveaux) + \brief Renvoi un chemin de classement répertoire en fonction d'un id + \remarks Examples: 1->"0/0/1/", 15->"0/1/5/" + \param $num Id a décomposer + \param $level Niveau de decoupage (1, 2 ou 3 niveaux) */ function get_exdir($num,$level=3) { @@ -2127,312 +2141,224 @@ function get_exdir($num,$level=3) } /** - \brief Création de répertoire recursive - \param $dir Répertoire a créer - \return int < 0 si erreur, >= 0 si succés -*/ + \brief Création de répertoire recursive + \param $dir Répertoire a créer + \return int < 0 si erreur, >= 0 si succés + */ function create_exdir($dir) { - dolibarr_syslog("functions.lib.php::create_exdir: dir=$dir",LOG_INFO); + dolibarr_syslog("functions.lib.php::create_exdir: dir=$dir",LOG_INFO); - if (@is_dir($dir)) return 0; + if (@is_dir($dir)) return 0; - $nberr=0; - $nbcreated=0; + $nberr=0; + $nbcreated=0; - $ccdir = ''; - $cdir = explode("/",$dir); - for ($i = 0 ; $i < sizeof($cdir) ; $i++) - { - if ($i > 0) $ccdir .= '/'.$cdir[$i]; - else $ccdir = $cdir[$i]; - if (eregi("^.:$",$ccdir,$regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant + $ccdir = ''; + $cdir = explode("/",$dir); + for ($i = 0 ; $i < sizeof($cdir) ; $i++) + { + if ($i > 0) $ccdir .= '/'.$cdir[$i]; + else $ccdir = $cdir[$i]; + if (eregi("^.:$",$ccdir,$regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant // Attention, le is_dir() peut échouer bien que le rep existe. // (ex selon config de open_basedir) - if ($ccdir) - { - if (! @is_dir($ccdir)) - { + if ($ccdir) + { + if (! @is_dir($ccdir)) + { dolibarr_syslog("functions.lib.php::create_exdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.",LOG_DEBUG); umask(0); if (! @mkdir($ccdir, 0755)) - { - // Si le is_dir a renvoyé une fausse info, alors on passe ici. - dolibarr_syslog("functions.lib.php::create_exdir: Fails to create directory '".$ccdir."' or directory already exists.",LOG_WARNING); - $nberr++; - } - else - { - dolibarr_syslog("functions.lib.php::create_exdir: Directory '".$ccdir."' created",LOG_DEBUG); - $nberr=0; // On remet a zéro car si on arrive ici, cela veut dire que les échecs précédents peuvent etre ignorés - $nbcreated++; - } - } - else { - $nberr=0; // On remet a zéro car si on arrive ici, cela veut dire que les échecs précédents peuvent etre ignorés + // Si le is_dir a renvoyé une fausse info, alors on passe ici. + dolibarr_syslog("functions.lib.php::create_exdir: Fails to create directory '".$ccdir."' or directory already exists.",LOG_WARNING); + $nberr++; } - } - } - return ($nberr ? -$nberr : $nbcreated); -} - - -/** - \brief Scan a directory and return a list of files/directories - \param $path Starting path from which to search - \param $types Can be "directories", "files", or "all" - \param $recursive Determines whether subdirectories are searched - \param $filter Regex for filter - \param $exludefilter Regex for exclude filter - \param $sortcriteria Sort criteria ("name","date","size") - \param $sortorder Sort order (SORT_ASC, SORT_DESC) - \return array Array of array('name'=>xxx,'date'=>yyy,'size'=>zzz) - */ -function dolibarr_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter="", $sortcriteria="name", $sortorder=SORT_ASC) -{ - dolibarr_syslog("functions.lib.php::dolibarr_dir_list $path"); - - $loaddate=false; - $loadsize=false; - - if (! is_dir($path)) return array(); - - if ($dir = opendir($path)) - { - $file_list = array(); - while (false !== ($file = readdir($dir))) - { - $qualified=1; - - // Check if file is qualified - if (eregi('^\.',$file)) $qualified=0; - if ($excludefilter && eregi($excludefilter,$file)) $qualified=0; - - if ($qualified) + else + { + dolibarr_syslog("functions.lib.php::create_exdir: Directory '".$ccdir."' created",LOG_DEBUG); + $nberr=0; // On remet a zéro car si on arrive ici, cela veut dire que les échecs précédents peuvent etre ignorés + $nbcreated++; + } + } + else { - // Check whether this is a file or directory and whether we're interested in that type - if ((is_dir($path."/".$file)) && (($types=="directories") || ($types=="all"))) - { - // Add entry into file_list array - if ($loaddate || $sortcriteria == 'date') $filedate=filemtime($path."/".$file); - if ($loadsize || $sortcriteria == 'size') $filesize=filesize($path."/".$file); - - if (! $filter || eregi($filter,$path.'/'.$file)) - { - $file_list[] = array( - "name" => $file, - "fullname" => $path.'/'.$file, - "date" => $filedate, - "size" => $filesize - ); - } - - // if we're in a directory and we want recursive behavior, call this function again - if ($recursive) - { - $file_list = array_merge($file_list, dolibarr_dir_list($path."/".$file."/", $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder)); - } - } - else if (($types == "files") || ($types == "all")) - { - // Add file into file_list array - if ($loaddate || $sortcriteria == 'date') $filedate=filemtime($path."/".$file); - if ($loadsize || $sortcriteria == 'size') $filesize=filesize($path."/".$file); - if (! $filter || eregi($filter,$path.'/'.$file)) - { - $file_list[] = array( - "name" => $file, - "fullname" => $path.'/'.$file, - "date" => $filedate, - "size" => $filesize - ); - } - } + $nberr=0; // On remet a zéro car si on arrive ici, cela veut dire que les échecs précédents peuvent etre ignorés } } - closedir($dir); - - // Obtain a list of columns - $myarray=array(); - foreach ($file_list as $key => $row) - { - $myarray[$key] = $row[$sortcriteria]; - } - // Sort the data - array_multisort($myarray, $sortorder, $file_list); - - return $file_list; - } - else - { - return false; } + return ($nberr ? -$nberr : $nbcreated); } + + + /** - \brief Retourne le numéro de la semaine par rapport a une date - \param time Date au format 'timestamp' - \return int Numéro de semaine -*/ + \brief Retourne le numéro de la semaine par rapport a une date + \param time Date au format 'timestamp' + \return int Numéro de semaine + */ function numero_semaine($time) { - $stime = strftime( '%Y-%m-%d',$time); + $stime = strftime( '%Y-%m-%d',$time); - if (eregi('^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?',$stime,$reg)) - { - // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS' - $annee = $reg[1]; - $mois = $reg[2]; - $jour = $reg[3]; - } + if (eregi('^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?',$stime,$reg)) + { + // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS' + $annee = $reg[1]; + $mois = $reg[2]; + $jour = $reg[3]; + } - /* - * Norme ISO-8601: - * - La semaine 1 de toute année est celle qui contient le 4 janvier ou que la semaine 1 de toute année est celle qui contient le 1er jeudi de janvier. - * - La majorité des années ont 52 semaines mais les années qui commence un jeudi et les années bissextiles commenéant un mercredi en posséde 53. - * - Le 1er jour de la semaine est le Lundi - */ + /* + * Norme ISO-8601: + * - La semaine 1 de toute année est celle qui contient le 4 janvier ou que la semaine 1 de toute année est celle qui contient le 1er jeudi de janvier. + * - La majorité des années ont 52 semaines mais les années qui commence un jeudi et les années bissextiles commenéant un mercredi en posséde 53. + * - Le 1er jour de la semaine est le Lundi + */ - // Définition du Jeudi de la semaine - if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) // Dimanche - $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-3*24*60*60; - else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) // du Lundi au Mercredi - $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)+(4-date("w",mktime(12,0,0,$mois,$jour,$annee)))*24*60*60; - else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) // du Vendredi au Samedi - $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-(date("w",mktime(12,0,0,$mois,$jour,$annee))-4)*24*60*60; - else // Jeudi - $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee); + // Définition du Jeudi de la semaine + if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) // Dimanche + $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-3*24*60*60; + else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) // du Lundi au Mercredi + $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)+(4-date("w",mktime(12,0,0,$mois,$jour,$annee)))*24*60*60; + else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) // du Vendredi au Samedi + $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-(date("w",mktime(12,0,0,$mois,$jour,$annee))-4)*24*60*60; + else // Jeudi + $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee); - // Définition du premier Jeudi de l'année - if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) // Dimanche - { - $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+4*24*60*60; - } - else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) // du Lundi au Mercredi - { - $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(4-date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine))))*24*60*60; - } - else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) // du Vendredi au Samedi - { - $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(7-(date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))-4))*24*60*60; - } - else // Jeudi - { - $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine)); - } + // Définition du premier Jeudi de l'année + if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) // Dimanche + { + $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+4*24*60*60; + } + else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) // du Lundi au Mercredi + { + $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(4-date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine))))*24*60*60; + } + else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) // du Vendredi au Samedi + { + $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(7-(date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))-4))*24*60*60; + } + else // Jeudi + { + $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine)); + } - // Définition du numéro de semaine: nb de jours entre "premier Jeudi de l'année" et "Jeudi de la semaine"; - $numeroSemaine = ( - ( - date("z",mktime(12,0,0,date("m",$jeudiSemaine),date("d",$jeudiSemaine),date("Y",$jeudiSemaine))) - - - date("z",mktime(12,0,0,date("m",$premierJeudiAnnee),date("d",$premierJeudiAnnee),date("Y",$premierJeudiAnnee))) - ) / 7 - ) + 1; + // Définition du numéro de semaine: nb de jours entre "premier Jeudi de l'année" et "Jeudi de la semaine"; + $numeroSemaine = ( + ( + date("z",mktime(12,0,0,date("m",$jeudiSemaine),date("d",$jeudiSemaine),date("Y",$jeudiSemaine))) + - + date("z",mktime(12,0,0,date("m",$premierJeudiAnnee),date("d",$premierJeudiAnnee),date("Y",$premierJeudiAnnee))) + ) / 7 + ) + 1; - // Cas particulier de la semaine 53 - if ($numeroSemaine==53) - { - // Les années qui commence un Jeudi et les années bissextiles commenéant un Mercredi en posséde 53 - if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==4 || (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==3 && date("z",mktime(12,0,0,12,31,date("Y",$jeudiSemaine)))==365)) - { - $numeroSemaine = 53; - } - else - { - $numeroSemaine = 1; - } - } + // Cas particulier de la semaine 53 + if ($numeroSemaine==53) + { + // Les années qui commence un Jeudi et les années bissextiles commenéant un Mercredi en posséde 53 + if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==4 || (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==3 && date("z",mktime(12,0,0,12,31,date("Y",$jeudiSemaine)))==365)) + { + $numeroSemaine = 53; + } + else + { + $numeroSemaine = 1; + } + } - //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."
"; + //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."
"; - return sprintf("%02d",$numeroSemaine); + return sprintf("%02d",$numeroSemaine); } + + /** - \brief Retourne le picto champ obligatoire - \return string Chaine avec picto obligatoire -*/ + \brief Retourne le picto champ obligatoire + \return string Chaine avec picto obligatoire + */ function picto_required() { return '*'; } /** - \brief Convertit une masse d'une unite vers une autre unite - \param weight float Masse a convertir - \param from_unit int Unite originale en puissance de 10 - \param to_unit int Nouvelle unite en puissance de 10 - \return float Masse convertie -*/ + \brief Convertit une masse d'une unite vers une autre unite + \param weight float Masse a convertir + \param from_unit int Unite originale en puissance de 10 + \param to_unit int Nouvelle unite en puissance de 10 + \return float Masse convertie + */ function weight_convert($weight,&$from_unit,$to_unit) { - /* Pour convertire 320 gr en Kg appeler - * $f = -3 - * weigh_convert(320, $f, 0) retournera 0.32 - * - */ - while ($from_unit <> $to_unit) - { - if ($from_unit > $to_unit) + /* Pour convertire 320 gr en Kg appeler + * $f = -3 + * weigh_convert(320, $f, 0) retournera 0.32 + * + */ + while ($from_unit <> $to_unit) { + if ($from_unit > $to_unit) + { $weight = $weight * 10; $from_unit = $from_unit - 1; $weight = weight_convert($weight,$from_unit, $to_unit); - } - if ($from_unit < $to_unit) - { + } + if ($from_unit < $to_unit) + { $weight = $weight / 10; $from_unit = $from_unit + 1; $weight = weight_convert($weight,$from_unit, $to_unit); + } } - } - return $weight; + return $weight; } /** - \brief Renvoi le texte d'une unite - \param int Unit - \param measuring_style Le style de mesure : weight, volume,... - \return string Unite - \todo gerer les autres unités de mesure comme la livre, le gallon, le litre, ... -*/ + \brief Renvoi le texte d'une unite + \param int Unit + \param measuring_style Le style de mesure : weight, volume,... + \return string Unite + \todo gerer les autres unités de mesure comme la livre, le gallon, le litre, ... + */ function measuring_units_string($unit,$measuring_style='') { - /* Note Rodo aux dev :) - * Ne pas insérer dans la base de données ces valeurs - * cela surchagerait inutilement d'une requete supplémentaire - * pour quelque chose qui est somme toute peu variable - */ - - global $langs; - - if ($measuring_style == 'weight') - { - $measuring_units[3] = $langs->trans("WeightUnitton"); - $measuring_units[0] = $langs->trans("WeightUnitkg"); - $measuring_units[-3] = $langs->trans("WeightUnitg"); - $measuring_units[-6] = $langs->trans("WeightUnitmg"); - } - else if ($measuring_style == 'volume') - { - $measuring_units[0] = $langs->trans("VolumeUnitm3"); - $measuring_units[-3] = $langs->trans("VolumeUnitdm3"); - $measuring_units[-6] = $langs->trans("VolumeUnitcm3"); - $measuring_units[-9] = $langs->trans("VolumeUnitmm3"); - } + /* Note Rodo aux dev :) + * Ne pas insérer dans la base de données ces valeurs + * cela surchagerait inutilement d'une requete supplémentaire + * pour quelque chose qui est somme toute peu variable + */ + + global $langs; + + if ($measuring_style == 'weight') + { + $measuring_units[3] = $langs->trans("WeightUnitton"); + $measuring_units[0] = $langs->trans("WeightUnitkg"); + $measuring_units[-3] = $langs->trans("WeightUnitg"); + $measuring_units[-6] = $langs->trans("WeightUnitmg"); + } + else if ($measuring_style == 'volume') + { + $measuring_units[0] = $langs->trans("VolumeUnitm3"); + $measuring_units[-3] = $langs->trans("VolumeUnitdm3"); + $measuring_units[-6] = $langs->trans("VolumeUnitcm3"); + $measuring_units[-9] = $langs->trans("VolumeUnitmm3"); + } - return $measuring_units[$unit]; + return $measuring_units[$unit]; } /** - \brief Clean an url - \param url Url - \param http 1: keep http, 0: remove also http - \return string CleanUrl -*/ + \brief Clean an url + \param url Url + \param http 1: keep http, 0: remove also http + \return string CleanUrl + */ function clean_url($url,$http=1) { if (eregi('^(https?:[\\\/]+)?([0-9A-Z\-\.]+\.[A-Z]{2,4})(:[0-9]+)?',$url,$regs)) @@ -2460,12 +2386,14 @@ function clean_url($url,$http=1) } } + + /** - \brief Clean a string from all html tags - \param StringHtml String to clean - \param removelinefeed Replace also all lines feeds by a space - \return string String cleaned -*/ + \brief Clean a string from all html tags + \param StringHtml String to clean + \param removelinefeed Replace also all lines feeds by a space + \return string String cleaned + */ function clean_html($StringHtml,$removelinefeed=1) { $pattern = "<[^>]+>"; @@ -2485,63 +2413,63 @@ function clean_html($StringHtml,$removelinefeed=1) } /** - \brief Convert a binaray data to string that represent hexadecimal value - \param bin Value to convert - \param pad Add 0 - \param upper Convert to tupper - \return string x -*/ + \brief Convert a binaray data to string that represent hexadecimal value + \param bin Value to convert + \param pad Add 0 + \param upper Convert to tupper + \return string x + */ function binhex($bin, $pad=false, $upper=false){ - $last = strlen($bin)-1; - for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); } - $x = dechex($x); - if($pad){ while(strlen($x) < intval(strlen($bin))/4){ $x = "0$x"; } } - if($upper){ $x = strtoupper($x); } - return $x; + $last = strlen($bin)-1; + for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); } + $x = dechex($x); + if($pad){ while(strlen($x) < intval(strlen($bin))/4){ $x = "0$x"; } } + if($upper){ $x = strtoupper($x); } + return $x; } /** - \brief Convertir de l'héxadécimal en binaire - \param string hexa - \return string bin -*/ + \brief Convertir de l'héxadécimal en binaire + \param string hexa + \return string bin + */ function hexbin($hexa){ - $bin=''; - for($i=0;$i",$ret); + $ret=ereg_replace("\r","",$stringtoencode); + $ret=ereg_replace("\n","
",$ret); return $ret; } } /** -* \brief This function is called to encode a string into a HTML string -* \param stringtoencode String to encode -* \param nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example) -* \remarks For PDF usage, you can show text by 2 ways: -* - writeHTMLCell -> param must be encoded into HTML. -* - MultiCell -> param must not be encoded into HTML. -* Because writeHTMLCell convert also \n into
, if function -* is used to build PDF, nl2brmode must be 1. -*/ + * \brief This function is called to encode a string into a HTML string + * \param stringtoencode String to encode + * \param nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example) + * \remarks For PDF usage, you can show text by 2 ways: + * - writeHTMLCell -> param must be encoded into HTML. + * - MultiCell -> param must not be encoded into HTML. + * Because writeHTMLCell convert also \n into
, if function + * is used to build PDF, nl2brmode must be 1. + */ function dol_htmlentitiesbr($stringtoencode,$nl2brmode=0) { if (dol_textishtml($stringtoencode)) return $stringtoencode; @@ -2554,9 +2482,9 @@ function dol_htmlentitiesbr($stringtoencode,$nl2brmode=0) } /* -* \brief This function is called to decode a HTML string -* \param stringtodecode String to decode -*/ + * \brief This function is called to decode a HTML string + * \param stringtodecode String to decode + */ function dol_htmlentitiesbr_decode($stringtodecode) { $ret=html_entity_decode($stringtodecode); @@ -2568,10 +2496,10 @@ function dol_htmlentitiesbr_decode($stringtodecode) } /** - \brief Decode le code html - \param string StringHtml - \return string DecodeString -*/ + \brief Decode le code html + \param string StringHtml + \return string DecodeString + */ function dol_entity_decode($StringHtml) { $DecodeString = html_entity_decode($StringHtml); @@ -2579,12 +2507,12 @@ function dol_entity_decode($StringHtml) } /** - \brief Check if a string is a correct iso string - If not, it will we considered not HTML encoded even if it is by FPDF. - \remarks Example, if string contains euro symbol that has ascii code 128. - \param s String to check - \return int 0 if bad iso, 1 if good iso -*/ + \brief Check if a string is a correct iso string + If not, it will we considered not HTML encoded even if it is by FPDF. + \remarks Example, if string contains euro symbol that has ascii code 128. + \param s String to check + \return int 0 if bad iso, 1 if good iso + */ function dol_string_is_good_iso($s) { $len=strlen($s); @@ -2592,189 +2520,156 @@ function dol_string_is_good_iso($s) for($scursor=0;$scursor<$len;$scursor++) { $ordchar=ord($s{$scursor}); - //print $scursor.'-'.$ordchar.'
'; + //print $scursor.'-'.$ordchar.'
'; if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok=0; break; } if ($ordchar > 126 && $ordchar < 160) { $ok=0; break; } } return $ok; } -/** - \brief Encode une chaine de caractére - \param chain chaine de caractéres a encoder - \return string_coded chaine de caractéres encodée -*/ -function dolibarr_encode($chain) -{ - for($i=0;$itrans("Days"); - if ($inhour == 1 && $nbOpenDay <= 3) $nbOpenDay = $nbOpenDay*24 . $langs->trans("HourShort"); - return $nbOpenDay; + $nbOpenDay = num_between_day($timestampStart, $timestampEnd, $bit) - num_public_holiday($timestampStart, $timestampEnd); + $nbOpenDay.= " ".$langs->trans("Days"); + if ($inhour == 1 && $nbOpenDay <= 3) $nbOpenDay = $nbOpenDay*24 . $langs->trans("HourShort"); + return $nbOpenDay; } else { @@ -2783,13 +2678,13 @@ function num_open_day($timestampStart, $timestampEnd,$inhour=0,$lastday=0) } /** - \brief Fonction retournant le nombre de lignes dans un texte formaté - \param texte Texte - \return nblines Nombre de lignes -*/ + \brief Fonction retournant le nombre de lignes dans un texte formaté + \param texte Texte + \return nblines Nombre de lignes + */ function num_lines($texte) { - $repTable = array("\t" => " ", "\n" => "
", "\r" => " ", "\0" => " ", "\x0B" => " "); + $repTable = array("\t" => " ", "\n" => "
", "\r" => " ", "\0" => " ", "\x0B" => " "); $texte = strtr($texte, $repTable); $pattern = '/(<[^>]+>)/Uu'; $a = preg_split($pattern, $texte, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); @@ -2798,13 +2693,13 @@ function num_lines($texte) } /** -* \brief Fonction simple identique a microtime de PHP 5 mais compatible PHP 4 -* \return float Time en millisecondes avec decimal pour microsecondes -*/ + * \brief Fonction simple identique a microtime de PHP 5 mais compatible PHP 4 + * \return float Time en millisecondes avec decimal pour microsecondes + */ function dol_microtime_float() { - list($usec, $sec) = explode(" ", microtime()); - return ((float)$usec + (float)$sec); + list($usec, $sec) = explode(" ", microtime()); + return ((float)$usec + (float)$sec); } /* @@ -2857,7 +2752,7 @@ function make_substitutions($chaine,$substitutionarray) /* * \brief Formate l'affichage de date de début et de fin * \param date_start date de début - * \param date_end date de fin + * \param date_end date de fin */ function print_date_range($date_start,$date_end) { @@ -2879,7 +2774,7 @@ function print_date_range($date_start,$date_end) /* - * + * */ function make_alpha_from_numbers($number) { @@ -2897,40 +2792,40 @@ function make_alpha_from_numbers($number) /** - \brief Retourne un tableau des mois ou le mois sélectionné - \param selected Mois à sélectionner ou -1 - \return string or array Month string or array if selected < 0 -*/ + \brief Retourne un tableau des mois ou le mois sélectionné + \param selected Mois à sélectionner ou -1 + \return string or array Month string or array if selected < 0 + */ function monthArrayOrSelected($selected=0) { global $langs; - $langs->load("main"); - + $langs->load("main"); + $month = array (1 => $langs->trans("January"), - 2 => $langs->trans("February"), - 3 => $langs->trans("March"), - 4 => $langs->trans("April"), - 5 => $langs->trans("May"), - 6 => $langs->trans("June"), - 7 => $langs->trans("July"), - 8 => $langs->trans("August"), - 9 => $langs->trans("September"), - 10 => $langs->trans("October"), - 11 => $langs->trans("November"), - 12 => $langs->trans("December") - ); + 2 => $langs->trans("February"), + 3 => $langs->trans("March"), + 4 => $langs->trans("April"), + 5 => $langs->trans("May"), + 6 => $langs->trans("June"), + 7 => $langs->trans("July"), + 8 => $langs->trans("August"), + 9 => $langs->trans("September"), + 10 => $langs->trans("October"), + 11 => $langs->trans("November"), + 12 => $langs->trans("December") + ); if ($selected >=0) { $return=''; foreach ($month as $key => $val) - { - if ($selected == $key) - { - $return = $val; - } - } - return $return; + { + if ($selected == $key) + { + $return = $val; + } + } + return $return; } else { @@ -2939,17 +2834,17 @@ function monthArrayOrSelected($selected=0) } /** - \brief Returns formated reduction - \param reduction Reduction percentage - \return string Formated reduction -*/ + \brief Returns formated reduction + \param reduction Reduction percentage + \return string Formated reduction + */ function dolibarr_print_reduction($reduction=0) { global $langs; $langs->load("main"); - + $string = ''; - + if ($reduction == 100) { $string = $langs->trans("Offered"); @@ -2958,23 +2853,23 @@ function dolibarr_print_reduction($reduction=0) { $string = $reduction.'%'; } - + return $string; } /** - \brief Returns formated reduction - \param reduction Reduction percentage - \return int Return number of error messages shown -*/ + \brief Returns formated reduction + \param reduction Reduction percentage + \return int Return number of error messages shown + */ function dol_htmloutput_errors($mesgstring='',$mesgarray='') { global $langs; - + $ret = 0; $langs->load("errors"); - + if (is_array($mesgarray) && sizeof($mesgarray)) { print '
'; @@ -3009,16 +2904,16 @@ function stopwithmem() /** -* \brief Advanced sort array by second index function, which produces -* ascending (default) or descending output and uses optionally -* natural case insensitive sorting (which can be optionally case -* sensitive as well). -*/ + * \brief Advanced sort array by second index function, which produces + * ascending (default) or descending output and uses optionally + * natural case insensitive sorting (which can be optionally case + * sensitive as well). + */ function dol_sort_array($array, $index, $order='asc', $natsort, $case_sensitive) { // Clean parameters $order=strtolower($order); - + if (is_array($array) && count($array)>0) { foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index]; @@ -3033,5 +2928,5 @@ function dol_sort_array($array, $index, $order='asc', $natsort, $case_sensitive) } return $array; } - + ?> diff --git a/htdocs/lib/security.lib.php b/htdocs/lib/security.lib.php index 3c66bd4d29d..b657a2be838 100644 --- a/htdocs/lib/security.lib.php +++ b/htdocs/lib/security.lib.php @@ -1,108 +1,141 @@ - - * - * 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 2 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, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * or see http://www.gnu.org/ - */ - -/** - \file htdocs/lib/security.lib.php - \brief Ensemble de fonctions de securite de dolibarr sous forme de lib - \version $Id$ -*/ - - -/** - \brief Fonction pour initialiser un salt pour la fonction crypt - \param $type 2=>renvoi un salt pour cryptage DES - 12=>renvoi un salt pour cryptage MD5 - non defini=>renvoi un salt pour cryptage par defaut - \return string Chaine salt -*/ -function makesalt($type=CRYPT_SALT_LENGTH) -{ - dolibarr_syslog("security.lib.php::makesalt type=".$type); - switch($type) - { - case 12: // 8 + 4 - $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break; - case 8: // 8 + 4 (Pour compatibilite, ne devrait pas etre utilisé) - $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break; - case 2: // 2 - default: // by default, fall back on Standard DES (should work everywhere) - $saltlen=2; $saltprefix=''; $saltsuffix=''; break; - } - $salt=''; - while(strlen($salt) < $saltlen) $salt.=chr(rand(64,126)); - - $result=$saltprefix.$salt.$saltsuffix; - dolibarr_syslog("security.lib.php::makesalt return=".$result); - return $result; -} - -/** - \brief Encode\decode le mot de passe de la base de données dans le fichier de conf - \param level niveau d'encodage : 0 non encodé, 1 encodé -*/ -function encodedecode_dbpassconf($level=0) -{ - $config = ''; - - if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php','r')) - { - while(!feof($fp)) - { - $buffer = fgets($fp,4096); - - if (strstr($buffer,"\$dolibarr_main_db_encrypted_pass") && $level == 0) - { - $passwd = strstr($buffer,"$dolibarr_main_db_encrypted_pass="); - $passwd = substr(substr($passwd,2),0,-3); - $passwd = dolibarr_decode($passwd); - $config .= "\$dolibarr_main_db_pass=\"$passwd\";\n"; - } - else if (strstr($buffer,"\$dolibarr_main_db_pass") && $level == 1) - { - $passwd = strstr($buffer,"$dolibarr_main_db_pass="); - $passwd = substr(substr($passwd,2),0,-3); - $passwd = dolibarr_encode($passwd); - $config .= "\$dolibarr_main_db_encrypted_pass=\"$passwd\";\n"; - } - else - { - $config .= $buffer; - } - } - fclose($fp); - - if ($fp = @fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php','w')) - { - fputs($fp, $config, strlen($config)); - fclose($fp); - return 1; - } - else - { - return -1; - } - } - else - { - return -2; - } -} - - + + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * or see http://www.gnu.org/ + */ + +/** + \file htdocs/lib/security.lib.php + \brief Ensemble de fonctions de securite de dolibarr sous forme de lib + \version $Id$ +*/ + + +/** + \brief Fonction pour initialiser un salt pour la fonction crypt + \param $type 2=>renvoi un salt pour cryptage DES + 12=>renvoi un salt pour cryptage MD5 + non defini=>renvoi un salt pour cryptage par defaut + \return string Chaine salt +*/ +function makesalt($type=CRYPT_SALT_LENGTH) +{ + dolibarr_syslog("security.lib.php::makesalt type=".$type); + switch($type) + { + case 12: // 8 + 4 + $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break; + case 8: // 8 + 4 (Pour compatibilite, ne devrait pas etre utilisé) + $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break; + case 2: // 2 + default: // by default, fall back on Standard DES (should work everywhere) + $saltlen=2; $saltprefix=''; $saltsuffix=''; break; + } + $salt=''; + while(strlen($salt) < $saltlen) $salt.=chr(rand(64,126)); + + $result=$saltprefix.$salt.$saltsuffix; + dolibarr_syslog("security.lib.php::makesalt return=".$result); + return $result; +} + +/** + \brief Encode\decode database password in config file + \param level Encode level : 0 no enconding, 1 encoding +*/ +function encodedecode_dbpassconf($level=0) +{ + $config = ''; + + if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php','r')) + { + while(!feof($fp)) + { + $buffer = fgets($fp,4096); + + if (strstr($buffer,"\$dolibarr_main_db_encrypted_pass") && $level == 0) + { + $passwd = strstr($buffer,"$dolibarr_main_db_encrypted_pass="); + $passwd = substr(substr($passwd,2),0,-3); + $passwd = dol_decode($passwd); + $config .= "\$dolibarr_main_db_pass=\"$passwd\";\n"; + } + else if (strstr($buffer,"\$dolibarr_main_db_pass") && $level == 1) + { + $passwd = strstr($buffer,"$dolibarr_main_db_pass="); + $passwd = substr(substr($passwd,2),0,-3); + $passwd = dol_encode($passwd); + $config .= "\$dolibarr_main_db_encrypted_pass=\"$passwd\";\n"; + } + else + { + $config .= $buffer; + } + } + fclose($fp); + + if ($fp = @fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php','w')) + { + fputs($fp, $config, strlen($config)); + fclose($fp); + return 1; + } + else + { + return -1; + } + } + else + { + return -2; + } +} + +/** + \brief Encode une chaine de caractére + \param chain chaine de caractéres a encoder + \return string_coded chaine de caractéres encodée + */ +function dol_encode($chain) +{ + for($i=0;$i \ No newline at end of file diff --git a/htdocs/master.inc.php b/htdocs/master.inc.php index 6d260b9ae32..a041a5560ab 100644 --- a/htdocs/master.inc.php +++ b/htdocs/master.inc.php @@ -110,7 +110,11 @@ if (! file_exists(DOL_DOCUMENT_ROOT ."/lib/functions.lib.php")) // on décode le mot de passe de la base si besoin require_once(DOL_DOCUMENT_ROOT ."/lib/functions.lib.php"); // Need 970ko memory (1.1 in 2.2) -if (! empty($dolibarr_main_db_encrypted_pass)) $dolibarr_main_db_pass = dolibarr_decode($dolibarr_main_db_encrypted_pass); +if (! empty($dolibarr_main_db_encrypted_pass)) +{ + require_once(DOL_DOCUMENT_ROOT ."/lib/security.lib.php"); + $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); +} //print memory_get_usage(); require_once(DOL_DOCUMENT_ROOT."/conf/conf.class.php");