From 998eea09bd2f43ba3508d7cb7ba1c43128d8a39a Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Mon, 18 Sep 2017 16:48:13 +0100 Subject: [PATCH 001/413] Added new option MAIN_SHOW_STATE_CODE (on/off; 1/0) to show state code in select fields options and values. Changed option MAIN_SHOW_REGION_IN_STATE to on/off - 1/0 and to mix with the new MAIN_SHOW_STATE_CODE (can show region name and state code) --- htdocs/core/class/html.formcompany.class.php | 21 +++++++++---- htdocs/core/lib/company.lib.php | 32 ++++++++++++++------ 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/htdocs/core/class/html.formcompany.class.php b/htdocs/core/class/html.formcompany.class.php index 6389733f72c..6dde7cccd98 100644 --- a/htdocs/core/class/html.formcompany.class.php +++ b/htdocs/core/class/html.formcompany.class.php @@ -265,16 +265,25 @@ class FormCompany { $out.= ''; } $i++; diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index 159e7a6435a..27f2f152ea3 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -390,14 +390,17 @@ function getCountry($searchkey,$withcode='',$dbtouse=0,$outputlangs='',$entconv= * @param DoliDB $dbtouse Database handler (using in global way may fail because of conflicts with some autoload features) * @return string String with state code or state name (Return value is always utf8 encoded and without entities) */ -function getState($id,$withcode='',$dbtouse=0) +function getState($id,$dbtouse=0) { - global $db,$langs; + global $db,$langs,$conf; if (! is_object($dbtouse)) $dbtouse=$db; - $sql = "SELECT rowid, code_departement as code, nom as label FROM ".MAIN_DB_PREFIX."c_departements"; - $sql.= " WHERE rowid=".$id; + $sql = "SELECT d.rowid, d.code_departement as code, d.nom as name, d.active, c.label as country, c.code as country_code, r.nom as region_name FROM"; + $sql .= " ".MAIN_DB_PREFIX ."c_departements as d, ".MAIN_DB_PREFIX."c_regions as r,".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE d.fk_region=r.code_region and r.fk_pays=c.rowid and d.rowid=".$id; + $sql .= " AND d.active = 1 AND r.active = 1 AND c.active = 1"; + $sql .= " ORDER BY c.code, d.code_departement"; dol_syslog("Company.lib::getState", LOG_DEBUG); $resql=$dbtouse->query($sql); @@ -406,11 +409,22 @@ function getState($id,$withcode='',$dbtouse=0) $obj = $dbtouse->fetch_object($resql); if ($obj) { - $label=$obj->label; - if ($withcode == '1') return $label=$obj->code?"$obj->code":"$obj->code - $label"; - else if ($withcode == '2') return $label=$obj->code; - else if ($withcode == 'all') return array('id'=>$obj->rowid,'code'=>$obj->code,'label'=>$label); - else return $label; + if(!empty($conf->global->MAIN_SHOW_STATE_CODE) && $conf->global->MAIN_SHOW_STATE_CODE == 1) { + if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE) && $conf->global->MAIN_SHOW_REGION_IN_STATE == 1) { + return $label = $obj->region_name . ' - ' . $obj->code . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); + } + else { + return $label = $obj->code . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); + } + } + else { + if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE) && $conf->global->MAIN_SHOW_REGION_IN_STATE == 1) { + return $label = $obj->region_name . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); + } + else { + return $label = ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); + } + } } else { From 76a2513c76a11651bb8546b032af53ba4549736a Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Mon, 18 Sep 2017 17:49:31 +0100 Subject: [PATCH 002/413] Added self to contributors list --- htdocs/core/lib/company.lib.php | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index 27f2f152ea3..2f830a24549 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -9,6 +9,7 @@ * Copyright (C) 2013 Alexandre Spangaro * Copyright (C) 2015 Frederic France * Copyright (C) 2015 Raphaël Doursenaud + * Copyright (C) 2017 Rui Strecht * * 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 From f1126b65bf69883c849ce79d5363c567c823ccb2 Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Wed, 20 Sep 2017 12:06:35 +0100 Subject: [PATCH 003/413] Updated method to fetch state name, code and id to match method used with country Reverted some previous changes to allow backwards compatibility Extended MAIN_SHOW_REGION_IN_STATE to include showing region in thirdparty card --- htdocs/admin/company.php | 20 +++++++-- htdocs/core/class/commonobject.class.php | 54 +++++++++++++++++++++--- htdocs/core/lib/company.lib.php | 33 ++++++++++++--- htdocs/societe/class/societe.class.php | 31 ++++++++++---- 4 files changed, 112 insertions(+), 26 deletions(-) diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index bd84c1d6339..3b52fb5b875 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -67,7 +67,19 @@ if ( ($action == 'update' && ! GETPOST("cancel",'alpha')) dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ADDRESS", GETPOST("address",'nohtml'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_TOWN", GETPOST("town",'nohtml'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ZIP", GETPOST("zipcode",'alpha'),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_INFO_SOCIETE_STATE", GETPOST("state_id",'alpha'),'chaine',0,'',$conf->entity); + + //dolibarr_set_const($db, "MAIN_INFO_SOCIETE_STATE", GETPOST("state_id",'alpha'),'chaine',0,'',$conf->entity); + $tmparray=getState(GETPOST('state_id','int'),'all','',$db,$langs,0); + if (! empty($tmparray['id'])) + { + $mysoc->state_id =$tmparray['id']; + $mysoc->state_code =$tmparray['code']; + $mysoc->state_label=$tmparray['label']; + + $s=$mysoc->state_id.':'.$mysoc->state_code.':'.$mysoc->state_label; + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_STATE", $s,'chaine',0,'',$conf->entity); + } + dolibarr_set_const($db, "MAIN_MONNAIE", GETPOST("currency",'alpha'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_TEL", GETPOST("tel",'alpha'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_FAX", GETPOST("fax",'alpha'),'chaine',0,'',$conf->entity); @@ -336,7 +348,7 @@ if ($action == 'edit' || $action == 'updateedit') print ''; - $formcompany->select_departement($conf->global->MAIN_INFO_SOCIETE_STATE,$mysoc->country_code,'state_id'); + $formcompany->select_departement($mysoc->state_id,$mysoc->country_code,'state_id'); print ''."\n"; @@ -721,7 +733,9 @@ else print ''.$langs->trans("State").''; - if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) print getState($conf->global->MAIN_INFO_SOCIETE_STATE); + if ($mysoc->state_id) { + print getState($mysoc->state_id,$conf->global->MAIN_SHOW_STATE_CODE,0,$conf->global->MAIN_SHOW_REGION_IN_STATE); + } else print ' '; print ''; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 54a907a3c0f..6a5d841684e 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -186,7 +186,7 @@ abstract class CommonObject * @var string * @see getFullAddress() */ - public $country; + public $country; /** * @var int * @see getFullAddress(), country @@ -196,7 +196,32 @@ abstract class CommonObject * @var string * @see getFullAddress(), isInEEC(), country */ - public $country_code; + public $country_code; + /** + * @var string + * @see getFullAddress() + */ + public $state; + /** + * @var int + * @see getFullAddress(), state + */ + public $state_id; + /** + * @var string + * @see getFullAddress(), state + */ + public $state_code; + /** + * @var string + * @see getFullAddress(), region + */ + public $region; + /** + * @var string + * @see getFullAddress(), region + */ + public $region_code; /** * @var int @@ -418,15 +443,25 @@ abstract class CommonObject * @param string $sep Separator to use to build string * @return string Full address string */ - function getFullAddress($withcountry=0,$sep="\n") + function getFullAddress($withcountry=0,$sep="\n",$withregion=0) { if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) { require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; $tmparray=getCountry($this->country_id,'all'); $this->country_code=$tmparray['code']; - $this->country =$tmparray['label']; - } + $this->country =$tmparray['label']; + } + + if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde))) + { + require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; + $tmparray=getState($this->state_id,'all',0,1); + $this->state_code =$tmparray['code']; + $this->state =$tmparray['label']; + $this->region_code =$tmparray['region_code']; + $this->region =$tmparray['region']; + } return dol_format_address($this, $withcountry, $sep); } @@ -465,7 +500,7 @@ abstract class CommonObject $out=''; $outdone=0; - $coords = $this->getFullAddress(1,', '); + $coords = $this->getFullAddress(1,', ',$conf->global->MAIN_SHOW_REGION_IN_STATE); if ($coords) { if (! empty($conf->use_javascript_ajax)) @@ -483,7 +518,12 @@ abstract class CommonObject if (! in_array($this->country_code,$countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) { - $out.=($outdone?' - ':'').$this->state; + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE) && $conf->global->MAIN_SHOW_REGION_IN_STATE == 1 && $this->region) { + $out.=($outdone?' - ':'').$this->region.' - '.$this->state; + } + else { + $out.=($outdone?' - ':'').$this->state; + } $outdone++; } diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index 2f830a24549..5a6a1bf6944 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -391,13 +391,13 @@ function getCountry($searchkey,$withcode='',$dbtouse=0,$outputlangs='',$entconv= * @param DoliDB $dbtouse Database handler (using in global way may fail because of conflicts with some autoload features) * @return string String with state code or state name (Return value is always utf8 encoded and without entities) */ -function getState($id,$dbtouse=0) +function getState($id,$withcode='',$dbtouse=0,$withregion='',$outputlangs='',$entconv=1,$searchlabel='') { - global $db,$langs,$conf; + global $db,$langs; if (! is_object($dbtouse)) $dbtouse=$db; - $sql = "SELECT d.rowid, d.code_departement as code, d.nom as name, d.active, c.label as country, c.code as country_code, r.nom as region_name FROM"; + $sql = "SELECT d.rowid as id, d.code_departement as code, d.nom as name, d.active, c.label as country, c.code as country_code, r.code_region as region_code, r.nom as region_name FROM"; $sql .= " ".MAIN_DB_PREFIX ."c_departements as d, ".MAIN_DB_PREFIX."c_regions as r,".MAIN_DB_PREFIX."c_country as c"; $sql .= " WHERE d.fk_region=r.code_region and r.fk_pays=c.rowid and d.rowid=".$id; $sql .= " AND d.active = 1 AND r.active = 1 AND c.active = 1"; @@ -410,22 +410,41 @@ function getState($id,$dbtouse=0) $obj = $dbtouse->fetch_object($resql); if ($obj) { - if(!empty($conf->global->MAIN_SHOW_STATE_CODE) && $conf->global->MAIN_SHOW_STATE_CODE == 1) { - if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE) && $conf->global->MAIN_SHOW_REGION_IN_STATE == 1) { + $label=((! empty($obj->name) && $obj->name!='-')?$obj->name:''); + if (is_object($outputlangs)) + { + $outputlangs->load("dict"); + if ($entconv) $label=($obj->code && ($outputlangs->trans("State".$obj->code)!="State".$obj->code))?$outputlangs->trans("State".$obj->code):$label; + else $label=($obj->code && ($outputlangs->transnoentitiesnoconv("State".$obj->code)!="State".$obj->code))?$outputlangs->transnoentitiesnoconv("State".$obj->code):$label; + } + + if ($withcode == 1) { + if ($withregion == 1) { return $label = $obj->region_name . ' - ' . $obj->code . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); } else { return $label = $obj->code . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); } } - else { - if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE) && $conf->global->MAIN_SHOW_REGION_IN_STATE == 1) { + else if ($withcode == 2) { + if ($withregion == 1) { return $label = $obj->region_name . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); } else { return $label = ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); } } + else if ($withcode === 'all') { + if ($withregion == 1) { + return array('id'=>$obj->id,'code'=>$obj->code,'label'=>$label,'region_code'=>$obj->region_code,'region'=>$obj->region_name); + } + else { + return array('id'=>$obj->id,'code'=>$obj->code,'label'=>$label); + } + } + else { + return $label; + } } else { diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 55a328e2538..91b5ef3205c 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -3050,16 +3050,29 @@ class Societe extends CommonObject $this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS; $this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP; $this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN; - $this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE; - /* Disabled: we don't want any SQL request into method setMySoc. This method set object from env only. - If we need label, label must be loaded by output that need it from id (label depends on output language) - require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; - if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) { - $this->state_id= $conf->global->MAIN_INFO_SOCIETE_STATE; - $this->state = getState($this->state_id); - } - */ + // We define state_id, state_code and state + $state_id=$state_code=$state_label=''; + if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) + { + $tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_STATE); + $state_id=$tmp[0]; + if (! empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label" or "id:code:label:region_code:region" + { + $state_code=$tmp[1]; + $state_label=$tmp[2]; + } + else // For backward compatibility + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + $state_code=getState($state_id,2,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore + $state_label=getState($state_id,0,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore + } + } + $this->state_id=$state_id; + $this->state_code=$state_code; + $this->state=$state_label; + if (is_object($langs)) $this->state=($langs->trans('State'.$state_code)!='State'.$state_code)?$langs->trans('State'.$state_code):$state_label; $this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE; From 24f8ea003a2b42401bd9d213505d237acce65fae Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Wed, 20 Sep 2017 12:30:59 +0100 Subject: [PATCH 004/413] Added self to contributors list --- htdocs/admin/company.php | 1 + htdocs/core/class/commonobject.class.php | 1 + htdocs/societe/class/societe.class.php | 1 + 3 files changed, 3 insertions(+) diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index 3b52fb5b875..e41cf19715a 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -5,6 +5,7 @@ * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2011-2017 Philippe Grand * Copyright (C) 2015 Alexandre Spangaro + * Copyright (C) 2017 Rui Strecht * * 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 diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 6a5d841684e..994c7654614 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -12,6 +12,7 @@ * Copyright (C) 2015 Alexandre Spangaro * Copyright (C) 2016 Bahfir abbes * Copyright (C) 2017 ATM Consulting + * Copyright (C) 2017 Rui Strecht * * 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 diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 91b5ef3205c..53ea9870eed 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -12,6 +12,7 @@ * Copyright (C) 2013 Peter Fontaine * Copyright (C) 2014-2015 Marcos García * Copyright (C) 2015 Raphaël Doursenaud + * Copyright (C) 2017 Rui Strecht * * 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 From 395100ca70f91bb953908ba1625d8d88564aae44 Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Wed, 20 Sep 2017 12:45:18 +0100 Subject: [PATCH 005/413] Added missing comments for new function parameters, removed unused parameter $searchlabel --- htdocs/core/class/commonobject.class.php | 1 + htdocs/core/lib/company.lib.php | 10 +++++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 994c7654614..c194a5abb40 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -442,6 +442,7 @@ abstract class CommonObject * * @param int $withcountry 1=Add country into address string * @param string $sep Separator to use to build string + * @param int $withregion 1=Add region into address string * @return string Full address string */ function getFullAddress($withcountry=0,$sep="\n",$withregion=0) diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index 5a6a1bf6944..e041e489499 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -383,15 +383,19 @@ function getCountry($searchkey,$withcode='',$dbtouse=0,$outputlangs='',$entconv= /** * Return state translated from an id. Return value is always utf8 encoded and without entities. * - * @param int $id id of state (province/departement) + * @param int $id id of state (province/departement) * @param int $withcode '0'=Return label, * '1'=Return string code + label, * '2'=Return code, * 'all'=return array('id'=>,'code'=>,'label'=>) + * @param int $withregion '0'=Ignores region, + * '1'=Add region name/code/id as needed to output, * @param DoliDB $dbtouse Database handler (using in global way may fail because of conflicts with some autoload features) - * @return string String with state code or state name (Return value is always utf8 encoded and without entities) + * @param Translate $outputlangs Langs object for output translation, not fully implemented yet + * @param int $entconv 0=Return value without entities and not converted to output charset, 1=Ready for html output + * @return mixed String with state code or state name or Array('id','code','label')/Array('id','code','label','region_code','region') */ -function getState($id,$withcode='',$dbtouse=0,$withregion='',$outputlangs='',$entconv=1,$searchlabel='') +function getState($id,$withcode='',$dbtouse=0,$withregion='',$outputlangs='',$entconv=1) { global $db,$langs; From 9fc8012663bd2b8d1fcbfa62dc23ac1f9309fd10 Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Wed, 20 Sep 2017 14:30:53 +0100 Subject: [PATCH 006/413] Tiny fix to php doc variables --- htdocs/core/lib/company.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index e041e489499..5f8fc1f8ae2 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -388,9 +388,9 @@ function getCountry($searchkey,$withcode='',$dbtouse=0,$outputlangs='',$entconv= * '1'=Return string code + label, * '2'=Return code, * 'all'=return array('id'=>,'code'=>,'label'=>) + * @param DoliDB $dbtouse Database handler (using in global way may fail because of conflicts with some autoload features) * @param int $withregion '0'=Ignores region, * '1'=Add region name/code/id as needed to output, - * @param DoliDB $dbtouse Database handler (using in global way may fail because of conflicts with some autoload features) * @param Translate $outputlangs Langs object for output translation, not fully implemented yet * @param int $entconv 0=Return value without entities and not converted to output charset, 1=Ready for html output * @return mixed String with state code or state name or Array('id','code','label')/Array('id','code','label','region_code','region') From 6c0cb31c088bdccea116aad41732562edf837d37 Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Mon, 9 Oct 2017 11:44:10 +0100 Subject: [PATCH 007/413] Fixed issue with merge error --- htdocs/core/class/commonobject.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 60d0f17f6c5..4e47d24c1dd 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -452,7 +452,7 @@ abstract class CommonObject * @param int $withregion 1=Add region into address string * @return string Full address string */ - function getFullAddress($withcountry=0,$sep="\n",$withregion=0)function getFullAddress($withcountry=0,$sep="\n",$withregion=0) + function getFullAddress($withcountry=0,$sep="\n",$withregion=0) { if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) { From f45c3e8231ad5a0fabb253500280b0c51e20e80c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcos=20Garc=C3=ADa?= Date: Sun, 17 Dec 2017 23:42:50 +0100 Subject: [PATCH 008/413] FIX #6980 FormMail::getEmailTemplate returns an array instead of a ModelMail object Close #6980 --- htdocs/core/class/html.formmail.class.php | 67 ++++++++++++----------- 1 file changed, 36 insertions(+), 31 deletions(-) diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index a3a37c86e8c..94222c6c5df 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -2,7 +2,7 @@ /* Copyright (C) 2005-2012 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2010-2011 Juanjo Menent - * Copyright (C) 2015 Marcos García + * Copyright (C) 2015-2017 Marcos García * * 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 @@ -283,7 +283,7 @@ class FormMail extends Form } // Get message template for $this->param["models"] into c_email_templates - $arraydefaultmessage=array(); + $arraydefaultmessage = -1; if ($this->param['models'] != 'none') { $model_id=0; @@ -291,12 +291,10 @@ class FormMail extends Form { $model_id=$this->param["models_id"]; } - $arraydefaultmessage=$this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, ($model_id ? $model_id : -1)); // we set -1 if model_id empty - } - //var_dump($this->param["models"]); - //var_dump($model_id); - //var_dump($arraydefaultmessage); + // we set -1 if model_id empty + $arraydefaultmessage = $this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, ($model_id ? $model_id : -1)); + } // Define list of attached files $listofpaths=array(); @@ -307,7 +305,7 @@ class FormMail extends Form if (GETPOST('mode','alpha') == 'init' || (GETPOST('modelmailselected','alpha') && GETPOST('modelmailselected','alpha') != '-1')) { $this->clear_attached_files(); - if (! empty($arraydefaultmessage['joinfiles']) && is_array($this->param['fileinit'])) + if (! empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit'])) { foreach($this->param['fileinit'] as $file) { @@ -755,8 +753,11 @@ class FormMail extends Form $defaulttopic=GETPOST('subject','none'); if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1') { - if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['topic']) $defaulttopic=$arraydefaultmessage['topic']; - elseif (! is_numeric($this->withtopic)) $defaulttopic=$this->withtopic; + if ($arraydefaultmessage && $arraydefaultmessage->topic) { + $defaulttopic = $arraydefaultmessage->topic; + } elseif (! is_numeric($this->withtopic)) { + $defaulttopic = $this->withtopic; + } } $defaulttopic=make_substitutions($defaulttopic,$this->substit); @@ -847,8 +848,11 @@ class FormMail extends Form $defaultmessage=GETPOST('message','none'); if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1') { - if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['content']) $defaultmessage=$arraydefaultmessage['content']; - elseif (! is_numeric($this->withbody)) $defaultmessage=$this->withbody; + if ($arraydefaultmessage && $arraydefaultmessage->content) { + $defaultmessage = $arraydefaultmessage['content']; + } elseif (! is_numeric($this->withbody)) { + $defaultmessage = $this->withbody; + } } // Complete substitution array @@ -874,7 +878,7 @@ class FormMail extends Form //Add lines substitution key from each line $lines = ''; - $defaultlines = $arraydefaultmessage['content_lines']; + $defaultlines = $arraydefaultmessage->content_lines; if (isset($defaultlines)) { foreach ($this->substit_lines as $substit_line) @@ -984,11 +988,11 @@ class FormMail extends Form * @param Translate $outputlangs Output lang object * @param int $id Id of template to find, or -1 for first found with position = 0, or 0 for all * @param int $active 1=Only active template, 0=Only disabled, -1=All - * @return array array('topic'=>,'content'=>,..) + * @return ModelMail */ public function getEMailTemplate($db, $type_template, $user, $outputlangs, $id=0, $active=1) { - $ret=array(); + $ret = new ModelMail(); $sql = "SELECT label, topic, joinfiles, content, content_lines, lang"; $sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates'; @@ -1001,20 +1005,20 @@ class FormMail extends Form if ($id == -1) $sql.= " AND position=0"; $sql.= $db->order("position,lang,label","ASC"); if ($id == -1) $sql.= $db->plimit(1); - //print $sql; $resql = $db->query($sql); if ($resql) { - $obj = $db->fetch_object($resql); // Get first found - if ($obj) - { - $ret['label']=$obj->label; - $ret['lang']=$obj->lang; - $ret['topic']=$obj->topic; - $ret['joinfiles']=$obj->joinfiles; - $ret['content']=$obj->content; - $ret['content_lines']=$obj->content_lines; + // Get first found + $obj = $db->fetch_object($resql); + + if ($obj) { + $ret->label = $obj->label; + $ret->lang = $obj->lang; + $ret->topic = $obj->topic; + $ret->content = $obj->content; + $ret->content_lines = $obj->content_lines; + $ret->joinfiles = $obj->joinfiles; } else // If there is no template at all { @@ -1031,12 +1035,12 @@ class FormMail extends Form elseif ($type_template=='thirdparty') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentThirdparty"); } elseif ($type_template=='user') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentUser"); } - $ret['label']='default'; - $ret['lang']=$outputlangs->defaultlang; - $ret['topic']=''; - $ret['joinfiles']=1; - $ret['content']=$defaultmessage; - $ret['content_lines']=''; + $ret->label = 'default'; + $ret->lang = $outputlangs->defaultlang; + $ret->topic = ''; + $ret->joinfiles = 1; + $ret->content = $defaultmessage; + $ret->content_lines =''; } $db->free($resql); @@ -1297,4 +1301,5 @@ class ModelMail public $content; public $content_lines; public $lang; + public $joinfiles; } From a34b99f3ec86ae472d6c3701d870f71ac9efab5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Sun, 21 Jan 2018 15:55:56 +0100 Subject: [PATCH 009/413] swiftmailer --- htdocs/core/class/CMailFile.class.php | 48 +- htdocs/core/class/notify.class.php | 51 ++- .../EmailValidator/EmailLexer.php | 221 +++++++++ .../EmailValidator/EmailParser.php | 104 +++++ .../EmailValidator/EmailValidator.php | 67 +++ .../Exception/AtextAfterCFWS.php | 9 + .../EmailValidator/Exception/CRLFAtTheEnd.php | 9 + .../EmailValidator/Exception/CRLFX2.php | 9 + .../EmailValidator/Exception/CRNoLF.php | 9 + .../Exception/CharNotAllowed.php | 9 + .../Exception/CommaInDomain.php | 9 + .../Exception/ConsecutiveAt.php | 9 + .../Exception/ConsecutiveDot.php | 9 + .../Exception/DomainHyphened.php | 9 + .../EmailValidator/Exception/DotAtEnd.php | 9 + .../EmailValidator/Exception/DotAtStart.php | 9 + .../EmailValidator/Exception/ExpectingAT.php | 9 + .../Exception/ExpectingATEXT.php | 9 + .../Exception/ExpectingCTEXT.php | 9 + .../Exception/ExpectingDTEXT.php | 9 + .../Exception/ExpectingDomainLiteralClose.php | 9 + .../Exception/ExpectingQPair.php | 9 + .../EmailValidator/Exception/InvalidEmail.php | 14 + .../EmailValidator/Exception/NoDNSRecord.php | 11 + .../EmailValidator/Exception/NoDomainPart.php | 9 + .../EmailValidator/Exception/NoLocalPart.php | 9 + .../Exception/UnclosedComment.php | 9 + .../Exception/UnclosedQuotedString.php | 9 + .../Exception/UnopenedComment.php | 9 + .../EmailValidator/Parser/DomainPart.php | 368 +++++++++++++++ .../EmailValidator/Parser/LocalPart.php | 138 ++++++ .../EmailValidator/Parser/Parser.php | 215 +++++++++ .../Validation/DNSCheckValidation.php | 61 +++ .../Validation/EmailValidation.php | 34 ++ .../Validation/Error/RFCWarnings.php | 11 + .../Validation/Error/SpoofEmail.php | 11 + .../Exception/EmptyValidationList.php | 13 + .../Validation/MultipleErrors.php | 26 ++ .../Validation/MultipleValidationWithAnd.php | 110 +++++ .../Validation/NoRFCWarningsValidation.php | 41 ++ .../Validation/RFCValidation.php | 49 ++ .../Validation/SpoofCheckValidation.php | 45 ++ .../EmailValidator/Warning/AddressLiteral.php | 14 + .../EmailValidator/Warning/CFWSNearAt.php | 13 + .../EmailValidator/Warning/CFWSWithFWS.php | 13 + .../EmailValidator/Warning/Comment.php | 13 + .../Warning/DeprecatedComment.php | 13 + .../EmailValidator/Warning/DomainLiteral.php | 14 + .../EmailValidator/Warning/DomainTooLong.php | 14 + .../EmailValidator/Warning/EmailTooLong.php | 15 + .../EmailValidator/Warning/IPV6BadChar.php | 14 + .../EmailValidator/Warning/IPV6ColonEnd.php | 14 + .../EmailValidator/Warning/IPV6ColonStart.php | 14 + .../EmailValidator/Warning/IPV6Deprecated.php | 14 + .../Warning/IPV6DoubleColon.php | 14 + .../EmailValidator/Warning/IPV6GroupCount.php | 14 + .../EmailValidator/Warning/IPV6MaxGroups.php | 14 + .../EmailValidator/Warning/LabelTooLong.php | 14 + .../EmailValidator/Warning/LocalTooLong.php | 15 + .../EmailValidator/Warning/NoDNSMXRecord.php | 14 + .../EmailValidator/Warning/ObsoleteDTEXT.php | 14 + .../EmailValidator/Warning/QuotedPart.php | 13 + .../EmailValidator/Warning/QuotedString.php | 13 + .../EmailValidator/Warning/TLD.php | 13 + .../EmailValidator/Warning/Warning.php | 30 ++ .../includes/egulias/email-validator/LICENSE | 19 + .../egulias/email-validator/README.md | 79 ++++ htdocs/includes/lexer/LICENSE | 19 + htdocs/includes/lexer/README.md | 5 + htdocs/includes/lexer/composer.json | 24 + .../Doctrine/Common/Lexer/AbstractLexer.php | 327 ++++++++++++++ .../swiftmailer/lib/classes/Swift.php | 5 +- .../lib/classes/Swift/Attachment.php | 20 +- .../AbstractFilterableInputStream.php | 58 +-- .../Swift/ByteStream/ArrayByteStream.php | 52 +-- .../Swift/ByteStream/FileByteStream.php | 131 +++--- .../lib/classes/Swift/CharacterReader.php | 4 +- .../GenericFixedWidthReader.php | 20 +- .../Swift/CharacterReader/Utf8Reader.php | 32 +- .../SimpleCharacterReaderFactory.php | 46 +- .../CharacterStream/ArrayCharacterStream.php | 114 ++--- .../CharacterStream/NgCharacterStream.php | 104 ++--- .../lib/classes/Swift/ConfigurableSpool.php | 12 +- .../lib/classes/Swift/DependencyContainer.php | 110 ++--- .../lib/classes/Swift/EmbeddedFile.php | 18 +- .../lib/classes/Swift/Encoder/QpEncoder.php | 76 ++-- .../classes/Swift/Encoder/Rfc2231Encoder.php | 14 +- .../lib/classes/Swift/Encoding.php | 64 --- .../lib/classes/Swift/Events/CommandEvent.php | 16 +- .../classes/Swift/Events/EventDispatcher.php | 4 +- .../lib/classes/Swift/Events/EventObject.php | 12 +- .../classes/Swift/Events/ResponseEvent.php | 12 +- .../lib/classes/Swift/Events/SendEvent.php | 30 +- .../Swift/Events/SimpleEventDispatcher.php | 38 +- .../Swift/Events/TransportExceptionEvent.php | 6 +- .../lib/classes/Swift/FailoverTransport.php | 12 - .../lib/classes/Swift/FileSpool.php | 32 +- .../lib/classes/Swift/IdGenerator.php | 22 + .../swiftmailer/lib/classes/Swift/Image.php | 22 +- .../classes/Swift/KeyCache/ArrayKeyCache.php | 42 +- .../classes/Swift/KeyCache/DiskKeyCache.php | 105 ++--- .../KeyCache/SimpleKeyCacheInputStream.php | 28 +- .../classes/Swift/LoadBalancedTransport.php | 12 - .../lib/classes/Swift/MailTransport.php | 45 -- .../swiftmailer/lib/classes/Swift/Mailer.php | 34 +- .../Swift/Mailer/ArrayRecipientIterator.php | 8 +- .../lib/classes/Swift/MemorySpool.php | 34 +- .../swiftmailer/lib/classes/Swift/Message.php | 35 +- .../lib/classes/Swift/Mime/Attachment.php | 44 +- .../ContentEncoder/NativeQpContentEncoder.php | 4 +- .../ContentEncoder/PlainContentEncoder.php | 26 +- .../Mime/ContentEncoder/QpContentEncoder.php | 34 +- .../lib/classes/Swift/Mime/EmbeddedFile.php | 14 +- .../lib/classes/Swift/Mime/Grammar.php | 176 -------- .../Mime/HeaderEncoder/QpHeaderEncoder.php | 2 +- .../lib/classes/Swift/Mime/HeaderFactory.php | 78 ---- .../lib/classes/Swift/Mime/HeaderSet.php | 169 ------- .../Swift/Mime/Headers/AbstractHeader.php | 146 +++--- .../classes/Swift/Mime/Headers/DateHeader.php | 62 ++- .../Mime/Headers/IdentificationHeader.php | 46 +- .../Swift/Mime/Headers/MailboxHeader.php | 65 +-- .../Swift/Mime/Headers/OpenDKIMHeader.php | 22 +- .../Mime/Headers/ParameterizedHeader.php | 53 ++- .../classes/Swift/Mime/Headers/PathHeader.php | 43 +- .../Swift/Mime/Headers/UnstructuredHeader.php | 14 +- .../lib/classes/Swift/Mime/IdGenerator.php | 53 +++ .../lib/classes/Swift/Mime/Message.php | 223 ---------- .../lib/classes/Swift/Mime/MimeEntity.php | 117 ----- .../lib/classes/Swift/Mime/MimePart.php | 82 ++-- .../Swift/Mime/ParameterizedHeader.php | 34 -- .../Swift/Mime/SimpleHeaderFactory.php | 84 ++-- .../classes/Swift/Mime/SimpleHeaderSet.php | 156 ++++--- .../lib/classes/Swift/Mime/SimpleMessage.php | 162 +++---- .../classes/Swift/Mime/SimpleMimeEntity.php | 418 +++++++++--------- .../lib/classes/Swift/MimePart.php | 14 - .../lib/classes/Swift/NullTransport.php | 13 - .../classes/Swift/Plugins/AntiFloodPlugin.php | 32 +- .../Swift/Plugins/BandwidthMonitorPlugin.php | 30 +- .../classes/Swift/Plugins/DecoratorPlugin.php | 62 +-- .../Swift/Plugins/ImpersonatePlugin.php | 8 +- .../classes/Swift/Plugins/LoggerPlugin.php | 28 +- .../Swift/Plugins/Loggers/ArrayLogger.php | 16 +- .../Swift/Plugins/Loggers/EchoLogger.php | 6 +- .../classes/Swift/Plugins/MessageLogger.php | 4 +- .../Swift/Plugins/PopBeforeSmtpPlugin.php | 112 ++--- .../Swift/Plugins/RedirectingPlugin.php | 48 +- .../lib/classes/Swift/Plugins/Reporter.php | 8 +- .../classes/Swift/Plugins/ReporterPlugin.php | 10 +- .../Swift/Plugins/Reporters/HitReporter.php | 22 +- .../Swift/Plugins/Reporters/HtmlReporter.php | 8 +- .../classes/Swift/Plugins/ThrottlerPlugin.php | 64 +-- .../lib/classes/Swift/Preferences.php | 27 +- .../lib/classes/Swift/SendmailTransport.php | 12 - .../lib/classes/Swift/SignedMessage.php | 23 - .../lib/classes/Swift/Signers/BodySigner.php | 2 +- .../lib/classes/Swift/Signers/DKIMSigner.php | 364 ++++++++------- .../classes/Swift/Signers/DomainKeySigner.php | 239 +++++----- .../classes/Swift/Signers/HeaderSigner.php | 16 +- .../classes/Swift/Signers/OpenDKIMSigner.php | 77 ++-- .../lib/classes/Swift/Signers/SMimeSigner.php | 41 +- .../lib/classes/Swift/SmtpTransport.php | 16 +- .../swiftmailer/lib/classes/Swift/Spool.php | 4 +- .../lib/classes/Swift/SpoolTransport.php | 12 - .../ByteArrayReplacementFilter.php | 61 +-- .../StreamFilters/StringReplacementFilter.php | 16 +- .../StringReplacementFilterFactory.php | 16 +- .../lib/classes/Swift/Transport.php | 27 +- .../Swift/Transport/AbstractSmtpTransport.php | 233 +++++----- .../Esmtp/Auth/CramMd5Authenticator.php | 4 +- .../Esmtp/Auth/NTLMAuthenticator.php | 94 ++-- .../Esmtp/Auth/XOAuth2Authenticator.php | 2 +- .../Swift/Transport/Esmtp/AuthHandler.php | 46 +- .../Swift/Transport/EsmtpTransport.php | 133 +++--- .../Swift/Transport/FailoverTransport.php | 56 ++- .../Swift/Transport/LoadBalancedTransport.php | 69 +-- .../classes/Swift/Transport/MailInvoker.php | 32 -- .../classes/Swift/Transport/MailTransport.php | 239 ---------- .../classes/Swift/Transport/NullTransport.php | 24 +- .../Swift/Transport/SendmailTransport.php | 33 +- .../Swift/Transport/SimpleMailInvoker.php | 39 -- .../Swift/Transport/SpoolTransport.php | 36 +- .../classes/Swift/Transport/StreamBuffer.php | 167 +++---- .../lib/classes/Swift/Validate.php | 43 -- .../lib/dependency_maps/mime_deps.php | 35 +- .../lib/dependency_maps/transport_deps.php | 15 +- .../includes/swiftmailer/lib/mime_types.php | 2 +- .../includes/swiftmailer/lib/preferences.php | 6 - .../includes/swiftmailer/lib/swift_init.php | 28 -- .../swiftmailer/lib/swift_required.php | 28 +- .../swiftmailer/lib/swift_required_pear.php | 30 -- .../lib/swiftmailer_generate_mimes_config.php | 8 +- 191 files changed, 5164 insertions(+), 4074 deletions(-) create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFX2.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRNoLF.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtStart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Parser/DomainPart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php create mode 100644 htdocs/includes/egulias/email-validator/LICENSE create mode 100644 htdocs/includes/egulias/email-validator/README.md create mode 100644 htdocs/includes/lexer/LICENSE create mode 100644 htdocs/includes/lexer/README.md create mode 100644 htdocs/includes/lexer/composer.json create mode 100644 htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Encoding.php create mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/IdGenerator.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/MailTransport.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Grammar.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderSet.php create mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Message.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/SignedMessage.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Transport/MailTransport.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Validate.php delete mode 100644 htdocs/includes/swiftmailer/lib/swift_init.php delete mode 100644 htdocs/includes/swiftmailer/lib/swift_required_pear.php mode change 100644 => 100755 htdocs/includes/swiftmailer/lib/swiftmailer_generate_mimes_config.php diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 86a6cb008d3..25988fd801d 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -80,14 +80,16 @@ class CMailFile var $atleastoneimage=0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used). var $html_images=array(); var $images_encoded=array(); - var $image_types = array('gif' => 'image/gif', - 'jpg' => 'image/jpeg', - 'jpeg' => 'image/jpeg', - 'jpe' => 'image/jpeg', - 'bmp' => 'image/bmp', - 'png' => 'image/png', - 'tif' => 'image/tiff', - 'tiff' => 'image/tiff'); + var $image_types = array( + 'gif' => 'image/gif', + 'jpg' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'bmp' => 'image/bmp', + 'png' => 'image/png', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + ); /** @@ -395,9 +397,21 @@ class CMailFile $host = dol_getprefix('email'); + require_once DOL_DOCUMENT_ROOT.'/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailParser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/Warning.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/Parser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/DomainPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailLexer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailValidator.php'; require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; // Create the message - $this->message = Swift_Message::newInstance(); + //$this->message = Swift_Message::newInstance(); + $this->message = new Swift_Message(); // Adding a trackid header to a message $headers = $this->message->getHeaders(); @@ -449,11 +463,11 @@ class CMailFile if ($this->msgishtml) { $this->message->setBody($msg,'text/html'); // And optionally an alternative body - //$this->message->addPart('Here is the message itself', 'text/plain'); + $this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain'); } else { $this->message->setBody($msg,'text/plain'); // And optionally an alternative body - //$this->message->addPart('Here is the message itself', 'text/html'); + $this->message->addPart($msg, 'text/html'); } if ($this->atleastonefile) @@ -491,7 +505,7 @@ class CMailFile global $conf,$db,$langs; $errorlevel=error_reporting(); - error_reporting($errorlevel ^ E_WARNING); // Desactive warnings + //error_reporting($errorlevel ^ E_WARNING); // Desactive warnings $res=false; @@ -721,19 +735,19 @@ class CMailFile if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport=ini_get('smtp_port'); // If we use SSL/TLS - $server=$conf->global->$keyforsmtpserver; - $secure=''; + $server = $conf->global->$keyforsmtpserver; + $secure = ''; if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl'; if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls'; - $this->transport = Swift_SmtpTransport::newInstance($server, $conf->global->$keyforsmtpport, $secure); + $this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure); if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid); if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw); //$smtps->_msgReplyTo = 'reply@web.com'; // Create the Mailer using your created Transport - $this->mailer = Swift_Mailer::newInstance($this->transport); + $this->mailer = new Swift_Mailer($this->transport); if (! empty($conf->global->MAIN_MAIL_DEBUG)) { // To use the ArrayLogger @@ -751,7 +765,7 @@ class CMailFile if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); $res = true; - if (! empty($this->error) && ! $result) { + if (! empty($this->error) || ! $result) { dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res=false; } else { diff --git a/htdocs/core/class/notify.class.php b/htdocs/core/class/notify.class.php index d40fcadc17c..2cd919db296 100644 --- a/htdocs/core/class/notify.class.php +++ b/htdocs/core/class/notify.class.php @@ -460,7 +460,7 @@ class Notify $message.= $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n"; $message.= "\n"; $message.= $mesg; - if ($link) $message=dol_concatdesc($message,$urlwithroot.$link); + if ($link) $message.= "\n" . $urlwithroot . $link; $parameters=array('notifcode'=>$notifcode, 'sendto'=>$sendto, 'replyto'=>$replyto, 'file'=>$file, 'mimefile'=>$mimefile, 'filename'=>$filename); $reshook=$hookmanager->executeHooks('formatNotificationMessage',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -555,77 +555,77 @@ class Notify switch ($notifcode) { case 'BILL_VALIDATE': - $link='/compta/facture/card.php?facid='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->facture->dir_output; $object_type = 'facture'; - $mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated",$link); break; case 'BILL_PAYED': - $link='/compta/facture/card.php?facid='.$object->id; + $link ='' . $newref . ''; $dir_output = $conf->facture->dir_output; $object_type = 'facture'; - $mesg = $langs->transnoentitiesnoconv("EMailTextInvoicePayed",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextInvoicePayed",$link); break; case 'ORDER_VALIDATE': - $link='/commande/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->commande->dir_output; $object_type = 'order'; - $mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated",$link); break; case 'PROPAL_VALIDATE': - $link='/comm/propal/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->propal->dir_output; $object_type = 'propal'; - $mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated",$link); break; case 'PROPAL_CLOSE_SIGNED': - $link='/comm/propal/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->propal->dir_output; $object_type = 'propal'; - $mesg = $langs->transnoentitiesnoconv("EMailTextProposalClosedSigned",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextProposalClosedSigned",$link); break; case 'FICHINTER_ADD_CONTACT': - $link='/fichinter/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->facture->dir_output; $object_type = 'ficheinter'; - $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionAddedContact",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionAddedContact",$link); break; case 'FICHINTER_VALIDATE': - $link='/fichinter/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->facture->dir_output; $object_type = 'ficheinter'; - $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated",$link); break; case 'ORDER_SUPPLIER_VALIDATE': - $link='/fourn/commande/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderValidatedBy",$newref,$user->getFullName($langs)); + $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderValidatedBy",$link,$user->getFullName($langs)); $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; break; case 'ORDER_SUPPLIER_APPROVE': - $link='/fourn/commande/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$newref,$user->getFullName($langs)); + $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$link,$user->getFullName($langs)); $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; break; case 'ORDER_SUPPLIER_APPROVE2': - $link='/fourn/commande/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$newref,$user->getFullName($langs)); + $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$link,$user->getFullName($langs)); $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; break; case 'ORDER_SUPPLIER_REFUSE': - $link='/fourn/commande/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->fournisseur->dir_output.'/commande/'; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy",$newref,$user->getFullName($langs)); + $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy",$link,$user->getFullName($langs)); $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; break; case 'SHIPPING_VALIDATE': @@ -650,7 +650,7 @@ class Notify $message.= $langs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n"; $message.= "\n"; $message.= $mesg; - if ($link) $message=dol_concatdesc($message,$urlwithroot.$link); + $message = nl2br($message); // Replace keyword __SUPERVISOREMAIL__ if (preg_match('/__SUPERVISOREMAIL__/', $sendto)) @@ -677,7 +677,6 @@ class Notify if (! empty($hookmanager->resArray['subject'])) $subject.=$hookmanager->resArray['subject']; if (! empty($hookmanager->resArray['message'])) $message.=$hookmanager->resArray['message']; } - $mailfile = new CMailFile( $subject, $sendto, @@ -689,7 +688,7 @@ class Notify '', '', 0, - -1 + 1 ); if ($mailfile->sendfile()) diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php b/htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php new file mode 100644 index 00000000000..882c968154d --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php @@ -0,0 +1,221 @@ + self::S_OPENPARENTHESIS, + ')' => self::S_CLOSEPARENTHESIS, + '<' => self::S_LOWERTHAN, + '>' => self::S_GREATERTHAN, + '[' => self::S_OPENBRACKET, + ']' => self::S_CLOSEBRACKET, + ':' => self::S_COLON, + ';' => self::S_SEMICOLON, + '@' => self::S_AT, + '\\' => self::S_BACKSLASH, + '/' => self::S_SLASH, + ',' => self::S_COMMA, + '.' => self::S_DOT, + '"' => self::S_DQUOTE, + '-' => self::S_HYPHEN, + '::' => self::S_DOUBLECOLON, + ' ' => self::S_SP, + "\t" => self::S_HTAB, + "\r" => self::S_CR, + "\n" => self::S_LF, + "\r\n" => self::CRLF, + 'IPv6' => self::S_IPV6TAG, + '{' => self::S_OPENQBRACKET, + '}' => self::S_CLOSEQBRACKET, + '' => self::S_EMPTY, + '\0' => self::C_NUL, + ); + + protected $hasInvalidTokens = false; + + protected $previous; + + public function reset() + { + $this->hasInvalidTokens = false; + parent::reset(); + } + + public function hasInvalidTokens() + { + return $this->hasInvalidTokens; + } + + /** + * @param $type + * @throws \UnexpectedValueException + * @return boolean + */ + public function find($type) + { + $search = clone $this; + $search->skipUntil($type); + + if (!$search->lookahead) { + throw new \UnexpectedValueException($type . ' not found'); + } + return true; + } + + /** + * getPrevious + * + * @return array token + */ + public function getPrevious() + { + return $this->previous; + } + + /** + * moveNext + * + * @return boolean + */ + public function moveNext() + { + $this->previous = $this->token; + + return parent::moveNext(); + } + + /** + * Lexical catchable patterns. + * + * @return string[] + */ + protected function getCatchablePatterns() + { + return array( + '[a-zA-Z_]+[46]?', //ASCII and domain literal + '[^\x00-\x7F]', //UTF-8 + '[0-9]+', + '\r\n', + '::', + '\s+?', + '.', + ); + } + + /** + * Lexical non-catchable patterns. + * + * @return string[] + */ + protected function getNonCatchablePatterns() + { + return array('[\xA0-\xff]+'); + } + + /** + * Retrieve token type. Also processes the token value if necessary. + * + * @param string $value + * @throws \InvalidArgumentException + * @return integer + */ + protected function getType(&$value) + { + if ($this->isNullType($value)) { + return self::C_NUL; + } + + if ($this->isValid($value)) { + return $this->charValue[$value]; + } + + if ($this->isUTF8Invalid($value)) { + $this->hasInvalidTokens = true; + return self::INVALID; + } + + return self::GENERIC; + } + + protected function isValid($value) + { + if (isset($this->charValue[$value])) { + return true; + } + + return false; + } + + /** + * @param $value + * @return bool + */ + protected function isNullType($value) + { + if ($value === "\0") { + return true; + } + + return false; + } + + /** + * @param $value + * @return bool + */ + protected function isUTF8Invalid($value) + { + if (preg_match('/\p{Cc}+/u', $value)) { + return true; + } + + return false; + } + + protected function getModifiers() + { + return 'iu'; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php b/htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php new file mode 100644 index 00000000000..d0627d82410 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php @@ -0,0 +1,104 @@ + + */ +class EmailParser +{ + const EMAIL_MAX_LENGTH = 254; + + protected $warnings; + protected $domainPart = ''; + protected $localPart = ''; + protected $lexer; + protected $localPartParser; + protected $domainPartParser; + + public function __construct(EmailLexer $lexer) + { + $this->lexer = $lexer; + $this->localPartParser = new LocalPart($this->lexer); + $this->domainPartParser = new DomainPart($this->lexer); + $this->warnings = new \SplObjectStorage(); + } + + /** + * @param $str + * @return array + */ + public function parse($str) + { + $this->lexer->setInput($str); + + if (!$this->hasAtToken()) { + throw new NoLocalPart(); + } + + + $this->localPartParser->parse($str); + $this->domainPartParser->parse($str); + + $this->setParts($str); + + if ($this->lexer->hasInvalidTokens()) { + throw new ExpectingATEXT(); + } + + return array('local' => $this->localPart, 'domain' => $this->domainPart); + } + + public function getWarnings() + { + $localPartWarnings = $this->localPartParser->getWarnings(); + $domainPartWarnings = $this->domainPartParser->getWarnings(); + $this->warnings = array_merge($localPartWarnings, $domainPartWarnings); + + $this->addLongEmailWarning($this->localPart, $this->domainPart); + + return $this->warnings; + } + + public function getParsedDomainPart() + { + return $this->domainPart; + } + + protected function setParts($email) + { + $parts = explode('@', $email); + $this->domainPart = $this->domainPartParser->getDomainPart(); + $this->localPart = $parts[0]; + } + + protected function hasAtToken() + { + $this->lexer->moveNext(); + $this->lexer->moveNext(); + if ($this->lexer->token['type'] === EmailLexer::S_AT) { + return false; + } + + return true; + } + + /** + * @param string $localPart + * @param string $parsedDomainPart + */ + protected function addLongEmailWarning($localPart, $parsedDomainPart) + { + if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAIL_MAX_LENGTH) { + $this->warnings[EmailTooLong::CODE] = new EmailTooLong(); + } + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php b/htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php new file mode 100644 index 00000000000..44b4b93c6bb --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php @@ -0,0 +1,67 @@ +lexer = new EmailLexer(); + } + + /** + * @param $email + * @param EmailValidation $emailValidation + * @return bool + */ + public function isValid($email, EmailValidation $emailValidation) + { + $isValid = $emailValidation->isValid($email, $this->lexer); + $this->warnings = $emailValidation->getWarnings(); + $this->error = $emailValidation->getError(); + + return $isValid; + } + + /** + * @return boolean + */ + public function hasWarnings() + { + return !empty($this->warnings); + } + + /** + * @return array + */ + public function getWarnings() + { + return $this->warnings; + } + + /** + * @return InvalidEmail + */ + public function getError() + { + return $this->error; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php b/htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php new file mode 100644 index 00000000000..97f41a2caae --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php @@ -0,0 +1,9 @@ +lexer->moveNext(); + + if ($this->lexer->token['type'] === EmailLexer::S_DOT) { + throw new DotAtStart(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_EMPTY) { + throw new NoDomainPart(); + } + if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN) { + throw new DomainHyphened(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) { + $this->warnings[DeprecatedComment::CODE] = new DeprecatedComment(); + $this->parseDomainComments(); + } + + $domain = $this->doParseDomainPart(); + + $prev = $this->lexer->getPrevious(); + $length = strlen($domain); + + if ($prev['type'] === EmailLexer::S_DOT) { + throw new DotAtEnd(); + } + if ($prev['type'] === EmailLexer::S_HYPHEN) { + throw new DomainHyphened(); + } + if ($length > self::DOMAIN_MAX_LENGTH) { + $this->warnings[DomainTooLong::CODE] = new DomainTooLong(); + } + if ($prev['type'] === EmailLexer::S_CR) { + throw new CRLFAtTheEnd(); + } + $this->domainPart = $domain; + } + + public function getDomainPart() + { + return $this->domainPart; + } + + public function checkIPV6Tag($addressLiteral, $maxGroups = 8) + { + $prev = $this->lexer->getPrevious(); + if ($prev['type'] === EmailLexer::S_COLON) { + $this->warnings[IPV6ColonEnd::CODE] = new IPV6ColonEnd(); + } + + $IPv6 = substr($addressLiteral, 5); + //Daniel Marschall's new IPv6 testing strategy + $matchesIP = explode(':', $IPv6); + $groupCount = count($matchesIP); + $colons = strpos($IPv6, '::'); + + if (count(preg_grep('/^[0-9A-Fa-f]{0,4}$/', $matchesIP, PREG_GREP_INVERT)) !== 0) { + $this->warnings[IPV6BadChar::CODE] = new IPV6BadChar(); + } + + if ($colons === false) { + // We need exactly the right number of groups + if ($groupCount !== $maxGroups) { + $this->warnings[IPV6GroupCount::CODE] = new IPV6GroupCount(); + } + return; + } + + if ($colons !== strrpos($IPv6, '::')) { + $this->warnings[IPV6DoubleColon::CODE] = new IPV6DoubleColon(); + return; + } + + if ($colons === 0 || $colons === (strlen($IPv6) - 2)) { + // RFC 4291 allows :: at the start or end of an address + //with 7 other groups in addition + ++$maxGroups; + } + + if ($groupCount > $maxGroups) { + $this->warnings[IPV6MaxGroups::CODE] = new IPV6MaxGroups(); + } elseif ($groupCount === $maxGroups) { + $this->warnings[IPV6Deprecated::CODE] = new IPV6Deprecated(); + } + } + + protected function doParseDomainPart() + { + $domain = ''; + $openedParenthesis = 0; + do { + $prev = $this->lexer->getPrevious(); + + $this->checkNotAllowedChars($this->lexer->token); + + if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) { + $this->parseComments(); + $openedParenthesis += $this->getOpenedParenthesis(); + $this->lexer->moveNext(); + $tmpPrev = $this->lexer->getPrevious(); + if ($tmpPrev['type'] === EmailLexer::S_CLOSEPARENTHESIS) { + $openedParenthesis--; + } + } + if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) { + if ($openedParenthesis === 0) { + throw new UnopenedComment(); + } else { + $openedParenthesis--; + } + } + + $this->checkConsecutiveDots(); + $this->checkDomainPartExceptions($prev); + + if ($this->hasBrackets()) { + $this->parseDomainLiteral(); + } + + $this->checkLabelLength($prev); + + if ($this->isFWS()) { + $this->parseFWS(); + } + + $domain .= $this->lexer->token['value']; + $this->lexer->moveNext(); + } while ($this->lexer->token); + + return $domain; + } + + private function checkNotAllowedChars($token) + { + $notAllowed = [EmailLexer::S_BACKSLASH => true, EmailLexer::S_SLASH=> true]; + if (isset($notAllowed[$token['type']])) { + throw new CharNotAllowed(); + } + } + + protected function parseDomainLiteral() + { + if ($this->lexer->isNextToken(EmailLexer::S_COLON)) { + $this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart(); + } + if ($this->lexer->isNextToken(EmailLexer::S_IPV6TAG)) { + $lexer = clone $this->lexer; + $lexer->moveNext(); + if ($lexer->isNextToken(EmailLexer::S_DOUBLECOLON)) { + $this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart(); + } + } + + return $this->doParseDomainLiteral(); + } + + protected function doParseDomainLiteral() + { + $IPv6TAG = false; + $addressLiteral = ''; + do { + if ($this->lexer->token['type'] === EmailLexer::C_NUL) { + throw new ExpectingDTEXT(); + } + + if ($this->lexer->token['type'] === EmailLexer::INVALID || + $this->lexer->token['type'] === EmailLexer::C_DEL || + $this->lexer->token['type'] === EmailLexer::S_LF + ) { + $this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT(); + } + + if ($this->lexer->isNextTokenAny(array(EmailLexer::S_OPENQBRACKET, EmailLexer::S_OPENBRACKET))) { + throw new ExpectingDTEXT(); + } + + if ($this->lexer->isNextTokenAny( + array(EmailLexer::S_HTAB, EmailLexer::S_SP, $this->lexer->token['type'] === EmailLexer::CRLF) + )) { + $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); + $this->parseFWS(); + } + + if ($this->lexer->isNextToken(EmailLexer::S_CR)) { + throw new CRNoLF(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH) { + $this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT(); + $addressLiteral .= $this->lexer->token['value']; + $this->lexer->moveNext(); + $this->validateQuotedPair(); + } + if ($this->lexer->token['type'] === EmailLexer::S_IPV6TAG) { + $IPv6TAG = true; + } + if ($this->lexer->token['type'] === EmailLexer::S_CLOSEQBRACKET) { + break; + } + + $addressLiteral .= $this->lexer->token['value']; + + } while ($this->lexer->moveNext()); + + $addressLiteral = str_replace('[', '', $addressLiteral); + $addressLiteral = $this->checkIPV4Tag($addressLiteral); + + if (false === $addressLiteral) { + return $addressLiteral; + } + + if (!$IPv6TAG) { + $this->warnings[DomainLiteral::CODE] = new DomainLiteral(); + return $addressLiteral; + } + + $this->warnings[AddressLiteral::CODE] = new AddressLiteral(); + + $this->checkIPV6Tag($addressLiteral); + + return $addressLiteral; + } + + protected function checkIPV4Tag($addressLiteral) + { + $matchesIP = array(); + + // Extract IPv4 part from the end of the address-literal (if there is one) + if (preg_match( + '/\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/', + $addressLiteral, + $matchesIP + ) > 0 + ) { + $index = strrpos($addressLiteral, $matchesIP[0]); + if ($index === 0) { + $this->warnings[AddressLiteral::CODE] = new AddressLiteral(); + return false; + } + // Convert IPv4 part to IPv6 format for further testing + $addressLiteral = substr($addressLiteral, 0, $index) . '0:0'; + } + + return $addressLiteral; + } + + protected function checkDomainPartExceptions($prev) + { + $invalidDomainTokens = array( + EmailLexer::S_DQUOTE => true, + EmailLexer::S_SEMICOLON => true, + EmailLexer::S_GREATERTHAN => true, + EmailLexer::S_LOWERTHAN => true, + ); + + if (isset($invalidDomainTokens[$this->lexer->token['type']])) { + throw new ExpectingATEXT(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_COMMA) { + throw new CommaInDomain(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_AT) { + throw new ConsecutiveAt(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_OPENQBRACKET && $prev['type'] !== EmailLexer::S_AT) { + throw new ExpectingATEXT(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN && $this->lexer->isNextToken(EmailLexer::S_DOT)) { + throw new DomainHyphened(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH + && $this->lexer->isNextToken(EmailLexer::GENERIC)) { + throw new ExpectingATEXT(); + } + } + + protected function hasBrackets() + { + if ($this->lexer->token['type'] !== EmailLexer::S_OPENBRACKET) { + return false; + } + + try { + $this->lexer->find(EmailLexer::S_CLOSEBRACKET); + } catch (\RuntimeException $e) { + throw new ExpectingDomainLiteralClose(); + } + + return true; + } + + protected function checkLabelLength($prev) + { + if ($this->lexer->token['type'] === EmailLexer::S_DOT && + $prev['type'] === EmailLexer::GENERIC && + strlen($prev['value']) > 63 + ) { + $this->warnings[LabelTooLong::CODE] = new LabelTooLong(); + } + } + + protected function parseDomainComments() + { + $this->isUnclosedComment(); + while (!$this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) { + $this->warnEscaping(); + $this->lexer->moveNext(); + } + + $this->lexer->moveNext(); + if ($this->lexer->isNextToken(EmailLexer::S_DOT)) { + throw new ExpectingATEXT(); + } + } + + protected function addTLDWarnings() + { + if ($this->warnings[DomainLiteral::CODE]) { + $this->warnings[TLD::CODE] = new TLD(); + } + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php b/htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php new file mode 100644 index 00000000000..8ab16ab4a1f --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php @@ -0,0 +1,138 @@ +lexer->token['type'] !== EmailLexer::S_AT && $this->lexer->token) { + if ($this->lexer->token['type'] === EmailLexer::S_DOT && !$this->lexer->getPrevious()) { + throw new DotAtStart(); + } + + $closingQuote = $this->checkDQUOTE($closingQuote); + if ($closingQuote && $parseDQuote) { + $parseDQuote = $this->parseDoubleQuote(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) { + $this->parseComments(); + $openedParenthesis += $this->getOpenedParenthesis(); + } + if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) { + if ($openedParenthesis === 0) { + throw new UnopenedComment(); + } else { + $openedParenthesis--; + } + } + + $this->checkConsecutiveDots(); + + if ($this->lexer->token['type'] === EmailLexer::S_DOT && + $this->lexer->isNextToken(EmailLexer::S_AT) + ) { + throw new DotAtEnd(); + } + + $this->warnEscaping(); + $this->isInvalidToken($this->lexer->token, $closingQuote); + + if ($this->isFWS()) { + $this->parseFWS(); + } + + $this->lexer->moveNext(); + } + + $prev = $this->lexer->getPrevious(); + if (strlen($prev['value']) > LocalTooLong::LOCAL_PART_LENGTH) { + $this->warnings[LocalTooLong::CODE] = new LocalTooLong(); + } + } + + protected function parseDoubleQuote() + { + $parseAgain = true; + $special = array( + EmailLexer::S_CR => true, + EmailLexer::S_HTAB => true, + EmailLexer::S_LF => true + ); + + $invalid = array( + EmailLexer::C_NUL => true, + EmailLexer::S_HTAB => true, + EmailLexer::S_CR => true, + EmailLexer::S_LF => true + ); + $setSpecialsWarning = true; + + $this->lexer->moveNext(); + + while ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE && $this->lexer->token) { + $parseAgain = false; + if (isset($special[$this->lexer->token['type']]) && $setSpecialsWarning) { + $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); + $setSpecialsWarning = false; + } + if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH && $this->lexer->isNextToken(EmailLexer::S_DQUOTE)) { + $this->lexer->moveNext(); + } + + $this->lexer->moveNext(); + + if (!$this->escaped() && isset($invalid[$this->lexer->token['type']])) { + throw new ExpectingATEXT(); + } + } + + $prev = $this->lexer->getPrevious(); + + if ($prev['type'] === EmailLexer::S_BACKSLASH) { + if (!$this->checkDQUOTE(false)) { + throw new UnclosedQuotedString(); + } + } + + if (!$this->lexer->isNextToken(EmailLexer::S_AT) && $prev['type'] !== EmailLexer::S_BACKSLASH) { + throw new ExpectingAT(); + } + + return $parseAgain; + } + + protected function isInvalidToken($token, $closingQuote) + { + $forbidden = array( + EmailLexer::S_COMMA, + EmailLexer::S_CLOSEBRACKET, + EmailLexer::S_OPENBRACKET, + EmailLexer::S_GREATERTHAN, + EmailLexer::S_LOWERTHAN, + EmailLexer::S_COLON, + EmailLexer::S_SEMICOLON, + EmailLexer::INVALID + ); + + if (in_array($token['type'], $forbidden) && !$closingQuote) { + throw new ExpectingATEXT(); + } + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php b/htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php new file mode 100644 index 00000000000..e5042e1a859 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php @@ -0,0 +1,215 @@ +lexer = $lexer; + } + + public function getWarnings() + { + return $this->warnings; + } + + abstract public function parse($str); + + /** @return int */ + public function getOpenedParenthesis() + { + return $this->openedParenthesis; + } + + /** + * validateQuotedPair + */ + protected function validateQuotedPair() + { + if (!($this->lexer->token['type'] === EmailLexer::INVALID + || $this->lexer->token['type'] === EmailLexer::C_DEL)) { + throw new ExpectedQPair(); + } + + $this->warnings[QuotedPart::CODE] = + new QuotedPart($this->lexer->getPrevious()['type'], $this->lexer->token['type']); + } + + protected function parseComments() + { + $this->openedParenthesis = 1; + $this->isUnclosedComment(); + $this->warnings[Comment::CODE] = new Comment(); + while (!$this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) { + if ($this->lexer->isNextToken(EmailLexer::S_OPENPARENTHESIS)) { + $this->openedParenthesis++; + } + $this->warnEscaping(); + $this->lexer->moveNext(); + } + + $this->lexer->moveNext(); + if ($this->lexer->isNextTokenAny(array(EmailLexer::GENERIC, EmailLexer::S_EMPTY))) { + throw new ExpectingATEXT(); + } + + if ($this->lexer->isNextToken(EmailLexer::S_AT)) { + $this->warnings[CFWSNearAt::CODE] = new CFWSNearAt(); + } + } + + protected function isUnclosedComment() + { + try { + $this->lexer->find(EmailLexer::S_CLOSEPARENTHESIS); + return true; + } catch (\RuntimeException $e) { + throw new UnclosedComment(); + } + } + + protected function parseFWS() + { + $previous = $this->lexer->getPrevious(); + + $this->checkCRLFInFWS(); + + if ($this->lexer->token['type'] === EmailLexer::S_CR) { + throw new CRNoLF(); + } + + if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous['type'] !== EmailLexer::S_AT) { + throw new AtextAfterCFWS(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_LF || $this->lexer->token['type'] === EmailLexer::C_NUL) { + throw new ExpectingCTEXT(); + } + + if ($this->lexer->isNextToken(EmailLexer::S_AT) || $previous['type'] === EmailLexer::S_AT) { + $this->warnings[CFWSNearAt::CODE] = new CFWSNearAt(); + } else { + $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); + } + } + + protected function checkConsecutiveDots() + { + if ($this->lexer->token['type'] === EmailLexer::S_DOT && $this->lexer->isNextToken(EmailLexer::S_DOT)) { + throw new ConsecutiveDot(); + } + } + + protected function isFWS() + { + if ($this->escaped()) { + return false; + } + + if ($this->lexer->token['type'] === EmailLexer::S_SP || + $this->lexer->token['type'] === EmailLexer::S_HTAB || + $this->lexer->token['type'] === EmailLexer::S_CR || + $this->lexer->token['type'] === EmailLexer::S_LF || + $this->lexer->token['type'] === EmailLexer::CRLF + ) { + return true; + } + + return false; + } + + protected function escaped() + { + $previous = $this->lexer->getPrevious(); + + if ($previous['type'] === EmailLexer::S_BACKSLASH + && + $this->lexer->token['type'] !== EmailLexer::GENERIC + ) { + return true; + } + + return false; + } + + protected function warnEscaping() + { + if ($this->lexer->token['type'] !== EmailLexer::S_BACKSLASH) { + return false; + } + + if ($this->lexer->isNextToken(EmailLexer::GENERIC)) { + throw new ExpectingATEXT(); + } + + if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB, EmailLexer::C_DEL))) { + return false; + } + + $this->warnings[QuotedPart::CODE] = + new QuotedPart($this->lexer->getPrevious()['type'], $this->lexer->token['type']); + return true; + + } + + protected function checkDQUOTE($hasClosingQuote) + { + if ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE) { + return $hasClosingQuote; + } + if ($hasClosingQuote) { + return $hasClosingQuote; + } + $previous = $this->lexer->getPrevious(); + if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous['type'] === EmailLexer::GENERIC) { + throw new ExpectingATEXT(); + } + + try { + $this->lexer->find(EmailLexer::S_DQUOTE); + $hasClosingQuote = true; + } catch (\Exception $e) { + throw new UnclosedQuotedString(); + } + $this->warnings[QuotedString::CODE] = new QuotedString($previous['value'], $this->lexer->token['value']); + + return $hasClosingQuote; + } + + protected function checkCRLFInFWS() + { + if ($this->lexer->token['type'] !== EmailLexer::CRLF) { + return; + } + + if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) { + throw new CRLFX2(); + } + + if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) { + throw new CRLFAtTheEnd(); + } + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php new file mode 100644 index 00000000000..ecca1dd976a --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php @@ -0,0 +1,61 @@ +checkDNS($host); + } + + public function getError() + { + return $this->error; + } + + public function getWarnings() + { + return $this->warnings; + } + + protected function checkDNS($host) + { + $host = rtrim($host, '.') . '.'; + + $Aresult = true; + $MXresult = checkdnsrr($host, 'MX'); + + if (!$MXresult) { + $this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord(); + $Aresult = checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA'); + if (!$Aresult) { + $this->error = new NoDNSRecord(); + } + } + return $MXresult || $Aresult; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php new file mode 100644 index 00000000000..d5a015be574 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php @@ -0,0 +1,34 @@ +errors = $errors; + parent::__construct(); + } + + public function getErrors() + { + return $this->errors; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php new file mode 100644 index 00000000000..43fa42a64b7 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php @@ -0,0 +1,110 @@ +validations = $validations; + $this->mode = $mode; + } + + /** + * {@inheritdoc} + */ + public function isValid($email, EmailLexer $emailLexer) + { + $result = true; + $errors = []; + foreach ($this->validations as $validation) { + $emailLexer->reset(); + $result = $result && $validation->isValid($email, $emailLexer); + $this->warnings = array_merge($this->warnings, $validation->getWarnings()); + $errors = $this->addNewError($validation->getError(), $errors); + + if ($this->shouldStop($result)) { + break; + } + } + + if (!empty($errors)) { + $this->error = new MultipleErrors($errors); + } + + return $result; + } + + private function addNewError($possibleError, array $errors) + { + if (null !== $possibleError) { + $errors[] = $possibleError; + } + + return $errors; + } + + private function shouldStop($result) + { + return !$result && $this->mode === self::STOP_ON_ERROR; + } + + /** + * {@inheritdoc} + */ + public function getError() + { + return $this->error; + } + + /** + * {@inheritdoc} + */ + public function getWarnings() + { + return $this->warnings; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php new file mode 100644 index 00000000000..e4bf0cc4df9 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php @@ -0,0 +1,41 @@ +getWarnings())) { + return true; + } + + $this->error = new RFCWarnings(); + + return false; + } + + /** + * {@inheritdoc} + */ + public function getError() + { + return $this->error ?: parent::getError(); + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php new file mode 100644 index 00000000000..c4ffe35034b --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php @@ -0,0 +1,49 @@ +parser = new EmailParser($emailLexer); + try { + $this->parser->parse((string)$email); + } catch (InvalidEmail $invalid) { + $this->error = $invalid; + return false; + } + + $this->warnings = $this->parser->getWarnings(); + return true; + } + + public function getError() + { + return $this->error; + } + + public function getWarnings() + { + return $this->warnings; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php new file mode 100644 index 00000000000..dd270556e8a --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php @@ -0,0 +1,45 @@ +setChecks(Spoofchecker::SINGLE_SCRIPT); + + if ($checker->isSuspicious($email)) { + $this->error = new SpoofEmail(); + } + + return $this->error === null; + } + + public function getError() + { + return $this->error; + } + + public function getWarnings() + { + return []; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php new file mode 100644 index 00000000000..77e70f7f554 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php @@ -0,0 +1,14 @@ +message = 'Address literal in domain part'; + $this->rfcNumber = 5321; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php new file mode 100644 index 00000000000..be43bbe6f62 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php @@ -0,0 +1,13 @@ +message = "Deprecated folding white space near @"; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php new file mode 100644 index 00000000000..dea3450ec8e --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php @@ -0,0 +1,13 @@ +message = 'Folding whites space followed by folding white space'; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php new file mode 100644 index 00000000000..704c2908b9a --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php @@ -0,0 +1,13 @@ +message = "Comments found in this email"; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php new file mode 100644 index 00000000000..ad43bd7c970 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php @@ -0,0 +1,13 @@ +message = 'Deprecated comments'; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php new file mode 100644 index 00000000000..6f36b5e293d --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php @@ -0,0 +1,14 @@ +message = 'Domain Literal'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php new file mode 100644 index 00000000000..61ff17a767d --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php @@ -0,0 +1,14 @@ +message = 'Domain is too long, exceeds 255 chars'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php new file mode 100644 index 00000000000..497309dbb0f --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php @@ -0,0 +1,15 @@ +message = 'Email is too long, exceeds ' . EmailParser::EMAIL_MAX_LENGTH; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php new file mode 100644 index 00000000000..ba2fcc01b83 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php @@ -0,0 +1,14 @@ +message = 'Bad char in IPV6 domain literal'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php new file mode 100644 index 00000000000..41afa78c63f --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php @@ -0,0 +1,14 @@ +message = ':: found at the end of the domain literal'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php new file mode 100644 index 00000000000..1bf754e30cd --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php @@ -0,0 +1,14 @@ +message = ':: found at the start of the domain literal'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php new file mode 100644 index 00000000000..d752caaa19d --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php @@ -0,0 +1,14 @@ +message = 'Deprecated form of IPV6'; + $this->rfcNumber = 5321; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php new file mode 100644 index 00000000000..4f823949962 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php @@ -0,0 +1,14 @@ +message = 'Double colon found after IPV6 tag'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php new file mode 100644 index 00000000000..a59d317f287 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php @@ -0,0 +1,14 @@ +message = 'Group count is not IPV6 valid'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php new file mode 100644 index 00000000000..936274c13ee --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php @@ -0,0 +1,14 @@ +message = 'Reached the maximum number of IPV6 groups allowed'; + $this->rfcNumber = 5321; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php new file mode 100644 index 00000000000..daf07f4083c --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php @@ -0,0 +1,14 @@ +message = 'Label too long'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php new file mode 100644 index 00000000000..0d08d8b35c6 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php @@ -0,0 +1,15 @@ +message = 'Local part is too long, exceeds 64 chars (octets)'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php new file mode 100644 index 00000000000..b3c21a1f3bf --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php @@ -0,0 +1,14 @@ +message = 'No MX DSN record was found for this email'; + $this->rfcNumber = 5321; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php new file mode 100644 index 00000000000..10f19e33409 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php @@ -0,0 +1,14 @@ +rfcNumber = 5322; + $this->message = 'Obsolete DTEXT in domain literal'; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php new file mode 100644 index 00000000000..7be9e6a3f25 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php @@ -0,0 +1,13 @@ +message = "Deprecated Quoted String found between $prevToken and $postToken"; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php new file mode 100644 index 00000000000..e9d56e1e032 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php @@ -0,0 +1,13 @@ +message = "Quoted String found between $prevToken and $postToken"; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php new file mode 100644 index 00000000000..2338b9f442a --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php @@ -0,0 +1,13 @@ +message = "RFC5321, TLD"; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php new file mode 100644 index 00000000000..ec6a365ffb7 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php @@ -0,0 +1,30 @@ +message; + } + + public function code() + { + return self::CODE; + } + + public function RFCNumber() + { + return $this->rfcNumber; + } + + public function __toString() + { + return $this->message() . " rfc: " . $this->rfcNumber . "interal code: " . static::CODE; + } +} diff --git a/htdocs/includes/egulias/email-validator/LICENSE b/htdocs/includes/egulias/email-validator/LICENSE new file mode 100644 index 00000000000..c34d2c197da --- /dev/null +++ b/htdocs/includes/egulias/email-validator/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2016 Eduardo Gulias Davis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/htdocs/includes/egulias/email-validator/README.md b/htdocs/includes/egulias/email-validator/README.md new file mode 100644 index 00000000000..fc7c89ea67c --- /dev/null +++ b/htdocs/includes/egulias/email-validator/README.md @@ -0,0 +1,79 @@ +# EmailValidator +[![Build Status](https://travis-ci.org/egulias/EmailValidator.png?branch=master)](https://travis-ci.org/egulias/EmailValidator) [![Coverage Status](https://coveralls.io/repos/egulias/EmailValidator/badge.png?branch=master)](https://coveralls.io/r/egulias/EmailValidator?branch=master) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/egulias/EmailValidator/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/egulias/EmailValidator/?branch=master) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/22ba6692-9c02-42e5-a65d-1c5696bfffc6/small.png)](https://insight.sensiolabs.com/projects/22ba6692-9c02-42e5-a65d-1c5696bfffc6) +============================= +With the help of [PHPStorm](https://www.jetbrains.com/phpstorm/) + +## Requirements ## + + * [Composer](https://getcomposer.org) is required for installation + * [Spoofchecking](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/SpoofCheckValidation.php) validation requires that your PHP system have the [PHP Internationalization Libraries](http://php.net/manual/en/book.intl.php) (also known as PHP Intl) + +## Installation ## + +Run the command below to install via Composer + +```shell +composer require egulias/email-validator "~2.1" +``` + +## Getting Started ## +`EmailValidator`requires you to decide which (or combination of them) validation/s strategy/ies you'd like to follow for each [validation](#available-validations). + +A basic example with the RFC validation +```php +isValid("example@example.com", new RFCValidation()); //true +``` + + +### Available validations ### + +1. [RFCValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/RFCValidation.php) +2. [NoRFCWarningsValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/NoRFCWarningsValidation.php) +3. [DNSCheckValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/DNSCheckValidation.php) +4. [SpoofCheckValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/SpoofCheckValidation.php) +5. [MultipleValidationWithAnd](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/MultipleValidationWithAnd.php) +6. [Your own validation](#how-to-extend) + +`MultipleValidationWithAnd` + +It is a validation that operates over other validations performing a logical and (&&) over the result of each validation. + +```php +isValid("example@example.com", $multipleValidations); //true +``` + +### How to extend ### + +It's easy! You just need to extend [EmailValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/EmailValidation.php) and you can use your own validation. + + +## Other Contributors ## +(You can find current contributors [here](https://github.com/egulias/EmailValidator/graphs/contributors)) + +As this is a port from another library and work, here are other people related to the previous one: + +* Ricard Clau [@ricardclau](http://github.com/ricardclau): Performance against PHP built-in filter_var +* Josepf Bielawski [@stloyd](http://github.com/stloyd): For its first re-work of Dominic's lib +* Dominic Sayers [@dominicsayers](http://github.com/dominicsayers): The original isemail function + +## License ## +Released under the MIT License attached with this code. + diff --git a/htdocs/includes/lexer/LICENSE b/htdocs/includes/lexer/LICENSE new file mode 100644 index 00000000000..5e781fce4bb --- /dev/null +++ b/htdocs/includes/lexer/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2006-2013 Doctrine Project + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/htdocs/includes/lexer/README.md b/htdocs/includes/lexer/README.md new file mode 100644 index 00000000000..66f443089eb --- /dev/null +++ b/htdocs/includes/lexer/README.md @@ -0,0 +1,5 @@ +# Doctrine Lexer + +Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers. + +This lexer is used in Doctrine Annotations and in Doctrine ORM (DQL). diff --git a/htdocs/includes/lexer/composer.json b/htdocs/includes/lexer/composer.json new file mode 100644 index 00000000000..8cd694c6525 --- /dev/null +++ b/htdocs/includes/lexer/composer.json @@ -0,0 +1,24 @@ +{ + "name": "doctrine/lexer", + "type": "library", + "description": "Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.", + "keywords": ["lexer", "parser"], + "homepage": "http://www.doctrine-project.org", + "license": "MIT", + "authors": [ + {"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"}, + {"name": "Roman Borschel", "email": "roman@code-factory.org"}, + {"name": "Johannes Schmitt", "email": "schmittjoh@gmail.com"} + ], + "require": { + "php": ">=5.3.2" + }, + "autoload": { + "psr-0": { "Doctrine\\Common\\Lexer\\": "lib/" } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php b/htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php new file mode 100644 index 00000000000..399a55230b0 --- /dev/null +++ b/htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php @@ -0,0 +1,327 @@ +. + */ + +namespace Doctrine\Common\Lexer; + +/** + * Base class for writing simple lexers, i.e. for creating small DSLs. + * + * @since 2.0 + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + */ +abstract class AbstractLexer +{ + /** + * Lexer original input string. + * + * @var string + */ + private $input; + + /** + * Array of scanned tokens. + * + * Each token is an associative array containing three items: + * - 'value' : the string value of the token in the input string + * - 'type' : the type of the token (identifier, numeric, string, input + * parameter, none) + * - 'position' : the position of the token in the input string + * + * @var array + */ + private $tokens = array(); + + /** + * Current lexer position in input string. + * + * @var integer + */ + private $position = 0; + + /** + * Current peek of current lexer position. + * + * @var integer + */ + private $peek = 0; + + /** + * The next token in the input. + * + * @var array + */ + public $lookahead; + + /** + * The last matched/seen token. + * + * @var array + */ + public $token; + + /** + * Sets the input data to be tokenized. + * + * The Lexer is immediately reset and the new input tokenized. + * Any unprocessed tokens from any previous input are lost. + * + * @param string $input The input to be tokenized. + * + * @return void + */ + public function setInput($input) + { + $this->input = $input; + $this->tokens = array(); + + $this->reset(); + $this->scan($input); + } + + /** + * Resets the lexer. + * + * @return void + */ + public function reset() + { + $this->lookahead = null; + $this->token = null; + $this->peek = 0; + $this->position = 0; + } + + /** + * Resets the peek pointer to 0. + * + * @return void + */ + public function resetPeek() + { + $this->peek = 0; + } + + /** + * Resets the lexer position on the input to the given position. + * + * @param integer $position Position to place the lexical scanner. + * + * @return void + */ + public function resetPosition($position = 0) + { + $this->position = $position; + } + + /** + * Retrieve the original lexer's input until a given position. + * + * @param integer $position + * + * @return string + */ + public function getInputUntilPosition($position) + { + return substr($this->input, 0, $position); + } + + /** + * Checks whether a given token matches the current lookahead. + * + * @param integer|string $token + * + * @return boolean + */ + public function isNextToken($token) + { + return null !== $this->lookahead && $this->lookahead['type'] === $token; + } + + /** + * Checks whether any of the given tokens matches the current lookahead. + * + * @param array $tokens + * + * @return boolean + */ + public function isNextTokenAny(array $tokens) + { + return null !== $this->lookahead && in_array($this->lookahead['type'], $tokens, true); + } + + /** + * Moves to the next token in the input string. + * + * @return boolean + */ + public function moveNext() + { + $this->peek = 0; + $this->token = $this->lookahead; + $this->lookahead = (isset($this->tokens[$this->position])) + ? $this->tokens[$this->position++] : null; + + return $this->lookahead !== null; + } + + /** + * Tells the lexer to skip input tokens until it sees a token with the given value. + * + * @param string $type The token type to skip until. + * + * @return void + */ + public function skipUntil($type) + { + while ($this->lookahead !== null && $this->lookahead['type'] !== $type) { + $this->moveNext(); + } + } + + /** + * Checks if given value is identical to the given token. + * + * @param mixed $value + * @param integer $token + * + * @return boolean + */ + public function isA($value, $token) + { + return $this->getType($value) === $token; + } + + /** + * Moves the lookahead token forward. + * + * @return array|null The next token or NULL if there are no more tokens ahead. + */ + public function peek() + { + if (isset($this->tokens[$this->position + $this->peek])) { + return $this->tokens[$this->position + $this->peek++]; + } else { + return null; + } + } + + /** + * Peeks at the next token, returns it and immediately resets the peek. + * + * @return array|null The next token or NULL if there are no more tokens ahead. + */ + public function glimpse() + { + $peek = $this->peek(); + $this->peek = 0; + return $peek; + } + + /** + * Scans the input string for tokens. + * + * @param string $input A query string. + * + * @return void + */ + protected function scan($input) + { + static $regex; + + if ( ! isset($regex)) { + $regex = sprintf( + '/(%s)|%s/%s', + implode(')|(', $this->getCatchablePatterns()), + implode('|', $this->getNonCatchablePatterns()), + $this->getModifiers() + ); + } + + $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE; + $matches = preg_split($regex, $input, -1, $flags); + + foreach ($matches as $match) { + // Must remain before 'value' assignment since it can change content + $type = $this->getType($match[0]); + + $this->tokens[] = array( + 'value' => $match[0], + 'type' => $type, + 'position' => $match[1], + ); + } + } + + /** + * Gets the literal for a given token. + * + * @param integer $token + * + * @return string + */ + public function getLiteral($token) + { + $className = get_class($this); + $reflClass = new \ReflectionClass($className); + $constants = $reflClass->getConstants(); + + foreach ($constants as $name => $value) { + if ($value === $token) { + return $className . '::' . $name; + } + } + + return $token; + } + + /** + * Regex modifiers + * + * @return string + */ + protected function getModifiers() + { + return 'i'; + } + + /** + * Lexical catchable patterns. + * + * @return array + */ + abstract protected function getCatchablePatterns(); + + /** + * Lexical non-catchable patterns. + * + * @return array + */ + abstract protected function getNonCatchablePatterns(); + + /** + * Retrieve token type. Also processes the token value if necessary. + * + * @param string $value + * + * @return integer + */ + abstract protected function getType(&$value); +} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift.php b/htdocs/includes/swiftmailer/lib/classes/Swift.php index 72419b334b7..e89703eaebb 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift.php @@ -16,8 +16,7 @@ */ abstract class Swift { - /** Swift Mailer Version number generated during dist release process */ - const VERSION = '@SWIFT_VERSION_NUMBER@'; + const VERSION = '6.0.2'; public static $initialized = false; public static $inits = array(); @@ -47,7 +46,7 @@ abstract class Swift return; } - $path = dirname(__FILE__).'/'.str_replace('_', '/', $class).'.php'; + $path = __DIR__.'/'.str_replace('_', '/', $class).'.php'; if (!file_exists($path)) { return; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Attachment.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Attachment.php index a95bccfdf97..1fb232c9fe6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Attachment.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Attachment.php @@ -9,7 +9,7 @@ */ /** - * Attachment class for attaching files to a {@link Swift_Mime_Message}. + * Attachment class for attaching files to a {@link Swift_Mime_SimpleMessage}. * * @author Chris Corbyn */ @@ -39,20 +39,6 @@ class Swift_Attachment extends Swift_Mime_Attachment } } - /** - * Create a new Attachment. - * - * @param string|Swift_OutputByteStream $data - * @param string $filename - * @param string $contentType - * - * @return Swift_Mime_Attachment - */ - public static function newInstance($data = null, $filename = null, $contentType = null) - { - return new self($data, $filename, $contentType); - } - /** * Create a new Attachment from a filesystem path. * @@ -63,9 +49,9 @@ class Swift_Attachment extends Swift_Mime_Attachment */ public static function fromPath($path, $contentType = null) { - return self::newInstance()->setFile( + return (new self())->setFile( new Swift_ByteStream_FileByteStream($path), $contentType - ); + ); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php index a7b0e3a6207..bfd2c79bcbd 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php @@ -18,38 +18,38 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I /** * Write sequence. */ - protected $_sequence = 0; + protected $sequence = 0; /** * StreamFilters. * * @var Swift_StreamFilter[] */ - private $_filters = array(); + private $filters = array(); /** * A buffer for writing. */ - private $_writeBuffer = ''; + private $writeBuffer = ''; /** * Bound streams. * * @var Swift_InputByteStream[] */ - private $_mirrors = array(); + private $mirrors = array(); /** * Commit the given bytes to the storage medium immediately. * * @param string $bytes */ - abstract protected function _commit($bytes); + abstract protected function doCommit($bytes); /** * Flush any buffers/content with immediate effect. */ - abstract protected function _flush(); + abstract protected function flush(); /** * Add a StreamFilter to this InputByteStream. @@ -59,7 +59,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function addFilter(Swift_StreamFilter $filter, $key) { - $this->_filters[$key] = $filter; + $this->filters[$key] = $filter; } /** @@ -69,7 +69,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function removeFilter($key) { - unset($this->_filters[$key]); + unset($this->filters[$key]); } /** @@ -83,15 +83,15 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function write($bytes) { - $this->_writeBuffer .= $bytes; - foreach ($this->_filters as $filter) { - if ($filter->shouldBuffer($this->_writeBuffer)) { + $this->writeBuffer .= $bytes; + foreach ($this->filters as $filter) { + if ($filter->shouldBuffer($this->writeBuffer)) { return; } } - $this->_doWrite($this->_writeBuffer); + $this->doWrite($this->writeBuffer); - return ++$this->_sequence; + return ++$this->sequence; } /** @@ -102,7 +102,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function commit() { - $this->_doWrite($this->_writeBuffer); + $this->doWrite($this->writeBuffer); } /** @@ -115,7 +115,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function bind(Swift_InputByteStream $is) { - $this->_mirrors[] = $is; + $this->mirrors[] = $is; } /** @@ -129,12 +129,12 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function unbind(Swift_InputByteStream $is) { - foreach ($this->_mirrors as $k => $stream) { + foreach ($this->mirrors as $k => $stream) { if ($is === $stream) { - if ($this->_writeBuffer !== '') { - $stream->write($this->_writeBuffer); + if ($this->writeBuffer !== '') { + $stream->write($this->writeBuffer); } - unset($this->_mirrors[$k]); + unset($this->mirrors[$k]); } } } @@ -147,20 +147,20 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function flushBuffers() { - if ($this->_writeBuffer !== '') { - $this->_doWrite($this->_writeBuffer); + if ($this->writeBuffer !== '') { + $this->doWrite($this->writeBuffer); } - $this->_flush(); + $this->flush(); - foreach ($this->_mirrors as $stream) { + foreach ($this->mirrors as $stream) { $stream->flushBuffers(); } } /** Run $bytes through all filters */ - private function _filter($bytes) + private function filter($bytes) { - foreach ($this->_filters as $filter) { + foreach ($this->filters as $filter) { $bytes = $filter->filter($bytes); } @@ -168,14 +168,14 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I } /** Just write the bytes to the stream */ - private function _doWrite($bytes) + private function doWrite($bytes) { - $this->_commit($this->_filter($bytes)); + $this->doCommit($this->filter($bytes)); - foreach ($this->_mirrors as $stream) { + foreach ($this->mirrors as $stream) { $stream->write($bytes); } - $this->_writeBuffer = ''; + $this->writeBuffer = ''; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php index ef05a6d5e6e..31b85e0e02a 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php @@ -11,7 +11,7 @@ /** * Allows reading and writing of bytes to and from an array. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_OutputByteStream { @@ -20,28 +20,28 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O * * @var string[] */ - private $_array = array(); + private $array = array(); /** * The size of the stack. * * @var int */ - private $_arraySize = 0; + private $arraySize = 0; /** * The internal pointer offset. * * @var int */ - private $_offset = 0; + private $offset = 0; /** * Bound streams. * * @var Swift_InputByteStream[] */ - private $_mirrors = array(); + private $mirrors = array(); /** * Create a new ArrayByteStream. @@ -53,12 +53,12 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O public function __construct($stack = null) { if (is_array($stack)) { - $this->_array = $stack; - $this->_arraySize = count($stack); + $this->array = $stack; + $this->arraySize = count($stack); } elseif (is_string($stack)) { $this->write($stack); } else { - $this->_array = array(); + $this->array = array(); } } @@ -76,16 +76,16 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O */ public function read($length) { - if ($this->_offset == $this->_arraySize) { + if ($this->offset == $this->arraySize) { return false; } // Don't use array slice - $end = $length + $this->_offset; - $end = $this->_arraySize < $end ? $this->_arraySize : $end; + $end = $length + $this->offset; + $end = $this->arraySize < $end ? $this->arraySize : $end; $ret = ''; - for (; $this->_offset < $end; ++$this->_offset) { - $ret .= $this->_array[$this->_offset]; + for (; $this->offset < $end; ++$this->offset) { + $ret .= $this->array[$this->offset]; } return $ret; @@ -100,11 +100,11 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O { $to_add = str_split($bytes); foreach ($to_add as $value) { - $this->_array[] = $value; + $this->array[] = $value; } - $this->_arraySize = count($this->_array); + $this->arraySize = count($this->array); - foreach ($this->_mirrors as $stream) { + foreach ($this->mirrors as $stream) { $stream->write($bytes); } } @@ -126,7 +126,7 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O */ public function bind(Swift_InputByteStream $is) { - $this->_mirrors[] = $is; + $this->mirrors[] = $is; } /** @@ -140,9 +140,9 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O */ public function unbind(Swift_InputByteStream $is) { - foreach ($this->_mirrors as $k => $stream) { + foreach ($this->mirrors as $k => $stream) { if ($is === $stream) { - unset($this->_mirrors[$k]); + unset($this->mirrors[$k]); } } } @@ -156,13 +156,13 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O */ public function setReadPointer($byteOffset) { - if ($byteOffset > $this->_arraySize) { - $byteOffset = $this->_arraySize; + if ($byteOffset > $this->arraySize) { + $byteOffset = $this->arraySize; } elseif ($byteOffset < 0) { $byteOffset = 0; } - $this->_offset = $byteOffset; + $this->offset = $byteOffset; } /** @@ -171,11 +171,11 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O */ public function flushBuffers() { - $this->_offset = 0; - $this->_array = array(); - $this->_arraySize = 0; + $this->offset = 0; + $this->array = array(); + $this->arraySize = 0; - foreach ($this->_mirrors as $stream) { + foreach ($this->mirrors as $stream) { $stream->flushBuffers(); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php index 406104371e8..61f820e5a14 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php @@ -11,30 +11,27 @@ /** * Allows reading and writing of bytes to and from a file. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterableInputStream implements Swift_FileStream { /** The internal pointer offset */ - private $_offset = 0; + private $offset = 0; /** The path to the file */ - private $_path; + private $path; /** The mode this file is opened in for writing */ - private $_mode; + private $mode; /** A lazy-loaded resource handle for reading the file */ - private $_reader; + private $reader; /** A lazy-loaded resource handle for writing the file */ - private $_writer; - - /** If magic_quotes_runtime is on, this will be true */ - private $_quotes = false; + private $writer; /** If stream is seekable true/false, or null if not known */ - private $_seekable = null; + private $seekable = null; /** * Create a new FileByteStream for $path. @@ -47,12 +44,8 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl if (empty($path)) { throw new Swift_IoException('The path cannot be empty'); } - $this->_path = $path; - $this->_mode = $writable ? 'w+b' : 'rb'; - - if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) { - $this->_quotes = true; - } + $this->path = $path; + $this->mode = $writable ? 'w+b' : 'rb'; } /** @@ -62,7 +55,7 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl */ public function getPath() { - return $this->_path; + return $this->path; } /** @@ -75,27 +68,21 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl * * @param int $length * - * @throws Swift_IoException - * * @return string|bool + * + * @throws Swift_IoException */ public function read($length) { - $fp = $this->_getReadHandle(); + $fp = $this->getReadHandle(); if (!feof($fp)) { - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 0); - } $bytes = fread($fp, $length); - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 1); - } - $this->_offset = ftell($fp); + $this->offset = ftell($fp); // If we read one byte after reaching the end of the file // feof() will return false and an empty string is returned if ($bytes === '' && feof($fp)) { - $this->_resetReadHandle(); + $this->resetReadHandle(); return false; } @@ -103,7 +90,7 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl return $bytes; } - $this->_resetReadHandle(); + $this->resetReadHandle(); return false; } @@ -117,93 +104,93 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl */ public function setReadPointer($byteOffset) { - if (isset($this->_reader)) { - $this->_seekReadStreamToPosition($byteOffset); + if (isset($this->reader)) { + $this->seekReadStreamToPosition($byteOffset); } - $this->_offset = $byteOffset; + $this->offset = $byteOffset; } /** Just write the bytes to the file */ - protected function _commit($bytes) + protected function doCommit($bytes) { - fwrite($this->_getWriteHandle(), $bytes); - $this->_resetReadHandle(); + fwrite($this->getWriteHandle(), $bytes); + $this->resetReadHandle(); } /** Not used */ - protected function _flush() + protected function flush() { } /** Get the resource for reading */ - private function _getReadHandle() + private function getReadHandle() { - if (!isset($this->_reader)) { - if (!$this->_reader = fopen($this->_path, 'rb')) { - throw new Swift_IoException( - 'Unable to open file for reading ['.$this->_path.']' - ); + if (!isset($this->reader)) { + $pointer = @fopen($this->path, 'rb'); + if (!$pointer) { + throw new Swift_IoException('Unable to open file for reading ['.$this->path.']'); } - if ($this->_offset != 0) { - $this->_getReadStreamSeekableStatus(); - $this->_seekReadStreamToPosition($this->_offset); + $this->reader = $pointer; + if ($this->offset != 0) { + $this->getReadStreamSeekableStatus(); + $this->seekReadStreamToPosition($this->offset); } } - return $this->_reader; + return $this->reader; } /** Get the resource for writing */ - private function _getWriteHandle() + private function getWriteHandle() { - if (!isset($this->_writer)) { - if (!$this->_writer = fopen($this->_path, $this->_mode)) { + if (!isset($this->writer)) { + if (!$this->writer = fopen($this->path, $this->mode)) { throw new Swift_IoException( - 'Unable to open file for writing ['.$this->_path.']' + 'Unable to open file for writing ['.$this->path.']' ); } } - return $this->_writer; + return $this->writer; } /** Force a reload of the resource for reading */ - private function _resetReadHandle() + private function resetReadHandle() { - if (isset($this->_reader)) { - fclose($this->_reader); - $this->_reader = null; + if (isset($this->reader)) { + fclose($this->reader); + $this->reader = null; } } /** Check if ReadOnly Stream is seekable */ - private function _getReadStreamSeekableStatus() + private function getReadStreamSeekableStatus() { - $metas = stream_get_meta_data($this->_reader); - $this->_seekable = $metas['seekable']; + $metas = stream_get_meta_data($this->reader); + $this->seekable = $metas['seekable']; } /** Streams in a readOnly stream ensuring copy if needed */ - private function _seekReadStreamToPosition($offset) + private function seekReadStreamToPosition($offset) { - if ($this->_seekable === null) { - $this->_getReadStreamSeekableStatus(); + if ($this->seekable === null) { + $this->getReadStreamSeekableStatus(); } - if ($this->_seekable === false) { - $currentPos = ftell($this->_reader); + if ($this->seekable === false) { + $currentPos = ftell($this->reader); if ($currentPos < $offset) { $toDiscard = $offset - $currentPos; - fread($this->_reader, $toDiscard); + fread($this->reader, $toDiscard); return; } - $this->_copyReadStream(); + $this->copyReadStream(); } - fseek($this->_reader, $offset, SEEK_SET); + fseek($this->reader, $offset, SEEK_SET); } /** Copy a readOnly Stream to ensure seekability */ - private function _copyReadStream() + private function copyReadStream() { if ($tmpFile = fopen('php://temp/maxmemory:4096', 'w+b')) { /* We have opened a php:// Stream Should work without problem */ @@ -212,11 +199,11 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl } else { throw new Swift_IoException('Unable to copy the file to make it seekable, sys_temp_dir is not writable, php://memory not available'); } - $currentPos = ftell($this->_reader); - fclose($this->_reader); - $source = fopen($this->_path, 'rb'); + $currentPos = ftell($this->reader); + fclose($this->reader); + $source = fopen($this->path, 'rb'); if (!$source) { - throw new Swift_IoException('Unable to open file for copying ['.$this->_path.']'); + throw new Swift_IoException('Unable to open file for copying ['.$this->path.']'); } fseek($tmpFile, 0, SEEK_SET); while (!feof($source)) { @@ -224,6 +211,6 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl } fseek($tmpFile, $currentPos, SEEK_SET); fclose($source); - $this->_reader = $tmpFile; + $this->reader = $tmpFile; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader.php index 3d5e854a884..4267adbc593 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader.php @@ -48,8 +48,8 @@ interface Swift_CharacterReader * A value of zero means this is already a valid character. * A value of -1 means this cannot possibly be a valid character. * - * @param integer[] $bytes - * @param int $size + * @param int[] $bytes + * @param int $size * * @return int */ diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php index ab8ebfda708..b09bb5b6c38 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php @@ -11,8 +11,8 @@ /** * Provides fixed-width byte sizes for reading fixed-width character sets. * - * @author Chris Corbyn - * @author Xavier De Cock + * @author Chris Corbyn + * @author Xavier De Cock */ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterReader { @@ -21,7 +21,7 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe * * @var int */ - private $_width; + private $width; /** * Creates a new GenericFixedWidthReader using $width bytes per character. @@ -30,7 +30,7 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe */ public function __construct($width) { - $this->_width = $width; + $this->width = $width; } /** @@ -47,11 +47,11 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe { $strlen = strlen($string); // % and / are CPU intensive, so, maybe find a better way - $ignored = $strlen % $this->_width; - $ignoredChars = substr($string, -$ignored); - $currentMap = $this->_width; + $ignored = $strlen % $this->width; + $ignoredChars = $ignored ? substr($string, -$ignored) : ''; + $currentMap = $this->width; - return ($strlen - $ignored) / $this->_width; + return ($strlen - $ignored) / $this->width; } /** @@ -80,7 +80,7 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe */ public function validateByteSequence($bytes, $size) { - $needed = $this->_width - $size; + $needed = $this->width - $size; return $needed > -1 ? $needed : -1; } @@ -92,6 +92,6 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe */ public function getInitialByteSize() { - return $this->_width; + return $this->width; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php index 7379bda258f..22746bd8575 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php @@ -19,22 +19,22 @@ class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader /** Pre-computed for optimization */ private static $length_map = array( // N=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F, - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x0N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x2N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x4N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x6N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7N - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x8N - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9N - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xAN - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBN - 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xCN - 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDN - 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEN - 4,4,4,4,4,4,4,4,5,5,5,5,6,6,0,0, // 0xFN + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x0N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x2N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x4N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x6N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7N + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x8N + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x9N + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xAN + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xBN + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xCN + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDN + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEN + 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0, // 0xFN ); private static $s_length_map = array( diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php index 9171a0bacbf..f3641f46b46 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php @@ -20,14 +20,14 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift * * @var array */ - private static $_map = array(); + private static $map = array(); /** * Factories which have already been loaded. * * @var Swift_CharacterReaderFactory[] */ - private static $_loaded = array(); + private static $loaded = array(); /** * Creates a new CharacterReaderFactory. @@ -44,7 +44,7 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift public function init() { - if (count(self::$_map) > 0) { + if (count(self::$map) > 0) { return; } @@ -66,32 +66,32 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift ); // Utf-8 - self::$_map['utf-?8'] = array( + self::$map['utf-?8'] = array( 'class' => $prefix.'Utf8Reader', 'constructor' => array(), ); //7-8 bit charsets - self::$_map['(us-)?ascii'] = $singleByte; - self::$_map['(iso|iec)-?8859-?[0-9]+'] = $singleByte; - self::$_map['windows-?125[0-9]'] = $singleByte; - self::$_map['cp-?[0-9]+'] = $singleByte; - self::$_map['ansi'] = $singleByte; - self::$_map['macintosh'] = $singleByte; - self::$_map['koi-?7'] = $singleByte; - self::$_map['koi-?8-?.+'] = $singleByte; - self::$_map['mik'] = $singleByte; - self::$_map['(cork|t1)'] = $singleByte; - self::$_map['v?iscii'] = $singleByte; + self::$map['(us-)?ascii'] = $singleByte; + self::$map['(iso|iec)-?8859-?[0-9]+'] = $singleByte; + self::$map['windows-?125[0-9]'] = $singleByte; + self::$map['cp-?[0-9]+'] = $singleByte; + self::$map['ansi'] = $singleByte; + self::$map['macintosh'] = $singleByte; + self::$map['koi-?7'] = $singleByte; + self::$map['koi-?8-?.+'] = $singleByte; + self::$map['mik'] = $singleByte; + self::$map['(cork|t1)'] = $singleByte; + self::$map['v?iscii'] = $singleByte; //16 bits - self::$_map['(ucs-?2|utf-?16)'] = $doubleByte; + self::$map['(ucs-?2|utf-?16)'] = $doubleByte; //32 bits - self::$_map['(ucs-?4|utf-?32)'] = $fourBytes; + self::$map['(ucs-?4|utf-?32)'] = $fourBytes; // Fallback - self::$_map['.*'] = $singleByte; + self::$map['.*'] = $singleByte; } /** @@ -103,21 +103,21 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift */ public function getReaderFor($charset) { - $charset = trim(strtolower($charset)); - foreach (self::$_map as $pattern => $spec) { + $charset = strtolower(trim($charset)); + foreach (self::$map as $pattern => $spec) { $re = '/^'.$pattern.'$/D'; if (preg_match($re, $charset)) { - if (!array_key_exists($pattern, self::$_loaded)) { + if (!array_key_exists($pattern, self::$loaded)) { $reflector = new ReflectionClass($spec['class']); if ($reflector->getConstructor()) { $reader = $reflector->newInstanceArgs($spec['constructor']); } else { $reader = $reflector->newInstance(); } - self::$_loaded[$pattern] = $reader; + self::$loaded[$pattern] = $reader; } - return self::$_loaded[$pattern]; + return self::$loaded[$pattern]; } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php index d695a6e172b..fbfbceb01d1 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php @@ -16,28 +16,28 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStream { /** A map of byte values and their respective characters */ - private static $_charMap; + private static $charMap; /** A map of characters and their derivative byte values */ - private static $_byteMap; + private static $byteMap; /** The char reader (lazy-loaded) for the current charset */ - private $_charReader; + private $charReader; /** A factory for creating CharacterReader instances */ - private $_charReaderFactory; + private $charReaderFactory; /** The character set this stream is using */ - private $_charset; + private $charset; /** Array of characters */ - private $_array = array(); + private $array = array(); /** Size of the array of character */ - private $_array_size = array(); + private $array_size = array(); /** The current character offset in the stream */ - private $_offset = 0; + private $offset = 0; /** * Create a new CharacterStream with the given $chars, if set. @@ -47,7 +47,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function __construct(Swift_CharacterReaderFactory $factory, $charset) { - self::_initializeMaps(); + self::initializeMaps(); $this->setCharacterReaderFactory($factory); $this->setCharacterSet($charset); } @@ -59,8 +59,8 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function setCharacterSet($charset) { - $this->_charset = $charset; - $this->_charReader = null; + $this->charset = $charset; + $this->charReader = null; } /** @@ -70,7 +70,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) { - $this->_charReaderFactory = $factory; + $this->charReaderFactory = $factory; } /** @@ -80,28 +80,28 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function importByteStream(Swift_OutputByteStream $os) { - if (!isset($this->_charReader)) { - $this->_charReader = $this->_charReaderFactory - ->getReaderFor($this->_charset); + if (!isset($this->charReader)) { + $this->charReader = $this->charReaderFactory + ->getReaderFor($this->charset); } - $startLength = $this->_charReader->getInitialByteSize(); + $startLength = $this->charReader->getInitialByteSize(); while (false !== $bytes = $os->read($startLength)) { $c = array(); for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { - $c[] = self::$_byteMap[$bytes[$i]]; + $c[] = self::$byteMap[$bytes[$i]]; } $size = count($c); - $need = $this->_charReader + $need = $this->charReader ->validateByteSequence($c, $size); if ($need > 0 && false !== $bytes = $os->read($need)) { for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { - $c[] = self::$_byteMap[$bytes[$i]]; + $c[] = self::$byteMap[$bytes[$i]]; } } - $this->_array[] = $c; - ++$this->_array_size; + $this->array[] = $c; + ++$this->array_size; } } @@ -127,20 +127,20 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function read($length) { - if ($this->_offset == $this->_array_size) { + if ($this->offset == $this->array_size) { return false; } // Don't use array slice $arrays = array(); - $end = $length + $this->_offset; - for ($i = $this->_offset; $i < $end; ++$i) { - if (!isset($this->_array[$i])) { + $end = $length + $this->offset; + for ($i = $this->offset; $i < $end; ++$i) { + if (!isset($this->array[$i])) { break; } - $arrays[] = $this->_array[$i]; + $arrays[] = $this->array[$i]; } - $this->_offset += $i - $this->_offset; // Limit function calls + $this->offset += $i - $this->offset; // Limit function calls $chars = false; foreach ($arrays as $array) { $chars .= implode('', array_map('chr', $array)); @@ -155,24 +155,24 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea * * @param int $length * - * @return integer[] + * @return int[] */ public function readBytes($length) { - if ($this->_offset == $this->_array_size) { + if ($this->offset == $this->array_size) { return false; } $arrays = array(); - $end = $length + $this->_offset; - for ($i = $this->_offset; $i < $end; ++$i) { - if (!isset($this->_array[$i])) { + $end = $length + $this->offset; + for ($i = $this->offset; $i < $end; ++$i) { + if (!isset($this->array[$i])) { break; } - $arrays[] = $this->_array[$i]; + $arrays[] = $this->array[$i]; } - $this->_offset += ($i - $this->_offset); // Limit function calls + $this->offset += ($i - $this->offset); // Limit function calls - return call_user_func_array('array_merge', $arrays); + return array_merge(...$arrays); } /** @@ -182,12 +182,12 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function write($chars) { - if (!isset($this->_charReader)) { - $this->_charReader = $this->_charReaderFactory->getReaderFor( - $this->_charset); + if (!isset($this->charReader)) { + $this->charReader = $this->charReaderFactory->getReaderFor( + $this->charset); } - $startLength = $this->_charReader->getInitialByteSize(); + $startLength = $this->charReader->getInitialByteSize(); $fp = fopen('php://memory', 'w+b'); fwrite($fp, $chars); @@ -203,7 +203,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea // Buffer Filing if ($buf_len - $buf_pos < $startLength) { $buf = array_splice($buffer, $buf_pos); - $new = $this->_reloadBuffer($fp, 100); + $new = $this->reloadBuffer($fp, 100); if ($new) { $buffer = array_merge($buf, $new); $buf_len = count($buffer); @@ -218,11 +218,11 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea ++$size; $bytes[] = $buffer[$buf_pos++]; } - $need = $this->_charReader->validateByteSequence( + $need = $this->charReader->validateByteSequence( $bytes, $size); if ($need > 0) { if ($buf_len - $buf_pos < $need) { - $new = $this->_reloadBuffer($fp, $need); + $new = $this->reloadBuffer($fp, $need); if ($new) { $buffer = array_merge($buffer, $new); @@ -233,8 +233,8 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea $bytes[] = $buffer[$buf_pos++]; } } - $this->_array[] = $bytes; - ++$this->_array_size; + $this->array[] = $bytes; + ++$this->array_size; } } while ($has_datas); @@ -248,12 +248,12 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function setPointer($charOffset) { - if ($charOffset > $this->_array_size) { - $charOffset = $this->_array_size; + if ($charOffset > $this->array_size) { + $charOffset = $this->array_size; } elseif ($charOffset < 0) { $charOffset = 0; } - $this->_offset = $charOffset; + $this->offset = $charOffset; } /** @@ -261,17 +261,17 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function flushContents() { - $this->_offset = 0; - $this->_array = array(); - $this->_array_size = 0; + $this->offset = 0; + $this->array = array(); + $this->array_size = 0; } - private function _reloadBuffer($fp, $len) + private function reloadBuffer($fp, $len) { if (!feof($fp) && ($bytes = fread($fp, $len)) !== false) { $buf = array(); for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { - $buf[] = self::$_byteMap[$bytes[$i]]; + $buf[] = self::$byteMap[$bytes[$i]]; } return $buf; @@ -280,14 +280,14 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea return false; } - private static function _initializeMaps() + private static function initializeMaps() { - if (!isset(self::$_charMap)) { - self::$_charMap = array(); + if (!isset(self::$charMap)) { + self::$charMap = array(); for ($byte = 0; $byte < 256; ++$byte) { - self::$_charMap[$byte] = chr($byte); + self::$charMap[$byte] = chr($byte); } - self::$_byteMap = array_flip(self::$_charMap); + self::$byteMap = array_flip(self::$charMap); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php index 1e8e2899672..0d62fa68ff3 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php @@ -11,7 +11,7 @@ /** * A CharacterStream implementation which stores characters in an internal array. * - * @author Xavier De Cock + * @author Xavier De Cock */ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream { @@ -20,63 +20,63 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream * * @var Swift_CharacterReader */ - private $_charReader; + private $charReader; /** * A factory for creating CharacterReader instances. * * @var Swift_CharacterReaderFactory */ - private $_charReaderFactory; + private $charReaderFactory; /** * The character set this stream is using. * * @var string */ - private $_charset; + private $charset; /** * The data's stored as-is. * * @var string */ - private $_datas = ''; + private $datas = ''; /** * Number of bytes in the stream. * * @var int */ - private $_datasSize = 0; + private $datasSize = 0; /** * Map. * * @var mixed */ - private $_map; + private $map; /** * Map Type. * * @var int */ - private $_mapType = 0; + private $mapType = 0; /** * Number of characters in the stream. * * @var int */ - private $_charCount = 0; + private $charCount = 0; /** * Position in the stream. * * @var int */ - private $_currentPos = 0; + private $currentPos = 0; /** * Constructor. @@ -99,9 +99,9 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function setCharacterSet($charset) { - $this->_charset = $charset; - $this->_charReader = null; - $this->_mapType = 0; + $this->charset = $charset; + $this->charReader = null; + $this->mapType = 0; } /** @@ -111,7 +111,7 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) { - $this->_charReaderFactory = $factory; + $this->charReaderFactory = $factory; } /** @@ -119,11 +119,11 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function flushContents() { - $this->_datas = null; - $this->_map = null; - $this->_charCount = 0; - $this->_currentPos = 0; - $this->_datasSize = 0; + $this->datas = null; + $this->map = null; + $this->charCount = 0; + $this->currentPos = 0; + $this->datasSize = 0; } /** @@ -161,49 +161,49 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function read($length) { - if ($this->_currentPos >= $this->_charCount) { + if ($this->currentPos >= $this->charCount) { return false; } $ret = false; - $length = $this->_currentPos + $length > $this->_charCount ? $this->_charCount - $this->_currentPos : $length; - switch ($this->_mapType) { + $length = ($this->currentPos + $length > $this->charCount) ? $this->charCount - $this->currentPos : $length; + switch ($this->mapType) { case Swift_CharacterReader::MAP_TYPE_FIXED_LEN: - $len = $length * $this->_map; - $ret = substr($this->_datas, - $this->_currentPos * $this->_map, + $len = $length * $this->map; + $ret = substr($this->datas, + $this->currentPos * $this->map, $len); - $this->_currentPos += $length; + $this->currentPos += $length; break; case Swift_CharacterReader::MAP_TYPE_INVALID: $ret = ''; - for (; $this->_currentPos < $length; ++$this->_currentPos) { - if (isset($this->_map[$this->_currentPos])) { + for (; $this->currentPos < $length; ++$this->currentPos) { + if (isset($this->map[$this->currentPos])) { $ret .= '?'; } else { - $ret .= $this->_datas[$this->_currentPos]; + $ret .= $this->datas[$this->currentPos]; } } break; case Swift_CharacterReader::MAP_TYPE_POSITIONS: - $end = $this->_currentPos + $length; - $end = $end > $this->_charCount ? $this->_charCount : $end; + $end = $this->currentPos + $length; + $end = $end > $this->charCount ? $this->charCount : $end; $ret = ''; $start = 0; - if ($this->_currentPos > 0) { - $start = $this->_map['p'][$this->_currentPos - 1]; + if ($this->currentPos > 0) { + $start = $this->map['p'][$this->currentPos - 1]; } $to = $start; - for (; $this->_currentPos < $end; ++$this->_currentPos) { - if (isset($this->_map['i'][$this->_currentPos])) { - $ret .= substr($this->_datas, $start, $to - $start).'?'; - $start = $this->_map['p'][$this->_currentPos]; + for (; $this->currentPos < $end; ++$this->currentPos) { + if (isset($this->map['i'][$this->currentPos])) { + $ret .= substr($this->datas, $start, $to - $start).'?'; + $start = $this->map['p'][$this->currentPos]; } else { - $to = $this->_map['p'][$this->_currentPos]; + $to = $this->map['p'][$this->currentPos]; } } - $ret .= substr($this->_datas, $start, $to - $start); + $ret .= substr($this->datas, $start, $to - $start); break; } @@ -215,7 +215,7 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream * * @param int $length * - * @return integer[] + * @return int[] */ public function readBytes($length) { @@ -236,10 +236,10 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function setPointer($charOffset) { - if ($this->_charCount < $charOffset) { - $charOffset = $this->_charCount; + if ($this->charCount < $charOffset) { + $charOffset = $this->charCount; } - $this->_currentPos = $charOffset; + $this->currentPos = $charOffset; } /** @@ -249,19 +249,19 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function write($chars) { - if (!isset($this->_charReader)) { - $this->_charReader = $this->_charReaderFactory->getReaderFor( - $this->_charset); - $this->_map = array(); - $this->_mapType = $this->_charReader->getMapType(); + if (!isset($this->charReader)) { + $this->charReader = $this->charReaderFactory->getReaderFor( + $this->charset); + $this->map = array(); + $this->mapType = $this->charReader->getMapType(); } $ignored = ''; - $this->_datas .= $chars; - $this->_charCount += $this->_charReader->getCharPositions(substr($this->_datas, $this->_datasSize), $this->_datasSize, $this->_map, $ignored); + $this->datas .= $chars; + $this->charCount += $this->charReader->getCharPositions(substr($this->datas, $this->datasSize), $this->datasSize, $this->map, $ignored); if ($ignored !== false) { - $this->_datasSize = strlen($this->_datas) - strlen($ignored); + $this->datasSize = strlen($this->datas) - strlen($ignored); } else { - $this->_datasSize = strlen($this->_datas); + $this->datasSize = strlen($this->datas); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/ConfigurableSpool.php b/htdocs/includes/swiftmailer/lib/classes/Swift/ConfigurableSpool.php index 4ae5bacfc40..a711bac478f 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/ConfigurableSpool.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/ConfigurableSpool.php @@ -16,10 +16,10 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool { /** The maximum number of messages to send per flush */ - private $_message_limit; + private $message_limit; /** The time limit per flush */ - private $_time_limit; + private $time_limit; /** * Sets the maximum number of messages to send per flush. @@ -28,7 +28,7 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool */ public function setMessageLimit($limit) { - $this->_message_limit = (int) $limit; + $this->message_limit = (int) $limit; } /** @@ -38,7 +38,7 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool */ public function getMessageLimit() { - return $this->_message_limit; + return $this->message_limit; } /** @@ -48,7 +48,7 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool */ public function setTimeLimit($limit) { - $this->_time_limit = (int) $limit; + $this->time_limit = (int) $limit; } /** @@ -58,6 +58,6 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool */ public function getTimeLimit() { - return $this->_time_limit; + return $this->time_limit; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/DependencyContainer.php b/htdocs/includes/swiftmailer/lib/classes/Swift/DependencyContainer.php index 8c1074a3a37..b1bc3306f22 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/DependencyContainer.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/DependencyContainer.php @@ -11,7 +11,7 @@ /** * Dependency Injection container. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_DependencyContainer { @@ -28,13 +28,13 @@ class Swift_DependencyContainer const TYPE_ALIAS = 0x1000; /** Singleton instance */ - private static $_instance = null; + private static $instance = null; /** The data container */ - private $_store = array(); + private $store = array(); /** The current endpoint in the data container */ - private $_endPoint; + private $endPoint; /** * Constructor should not be used. @@ -48,15 +48,15 @@ class Swift_DependencyContainer /** * Returns a singleton of the DependencyContainer. * - * @return Swift_DependencyContainer + * @return self */ public static function getInstance() { - if (!isset(self::$_instance)) { - self::$_instance = new self(); + if (!isset(self::$instance)) { + self::$instance = new self(); } - return self::$_instance; + return self::$instance; } /** @@ -66,7 +66,7 @@ class Swift_DependencyContainer */ public function listItems() { - return array_keys($this->_store); + return array_keys($this->store); } /** @@ -80,8 +80,8 @@ class Swift_DependencyContainer */ public function has($itemName) { - return array_key_exists($itemName, $this->_store) - && isset($this->_store[$itemName]['lookupType']); + return array_key_exists($itemName, $this->store) + && isset($this->store[$itemName]['lookupType']); } /** @@ -91,9 +91,9 @@ class Swift_DependencyContainer * * @param string $itemName * - * @throws Swift_DependencyException If the dependency is not found - * * @return mixed + * + * @throws Swift_DependencyException If the dependency is not found */ public function lookup($itemName) { @@ -103,15 +103,15 @@ class Swift_DependencyContainer ); } - switch ($this->_store[$itemName]['lookupType']) { + switch ($this->store[$itemName]['lookupType']) { case self::TYPE_ALIAS: - return $this->_createAlias($itemName); + return $this->createAlias($itemName); case self::TYPE_VALUE: - return $this->_getValue($itemName); + return $this->getValue($itemName); case self::TYPE_INSTANCE: - return $this->_createNewInstance($itemName); + return $this->createNewInstance($itemName); case self::TYPE_SHARED: - return $this->_createSharedInstance($itemName); + return $this->createSharedInstance($itemName); } } @@ -125,8 +125,8 @@ class Swift_DependencyContainer public function createDependenciesFor($itemName) { $args = array(); - if (isset($this->_store[$itemName]['args'])) { - $args = $this->_resolveArgs($this->_store[$itemName]['args']); + if (isset($this->store[$itemName]['args'])) { + $args = $this->resolveArgs($this->store[$itemName]['args']); } return $args; @@ -143,12 +143,12 @@ class Swift_DependencyContainer * * @param string $itemName * - * @return Swift_DependencyContainer + * @return $this */ public function register($itemName) { - $this->_store[$itemName] = array(); - $this->_endPoint = &$this->_store[$itemName]; + $this->store[$itemName] = array(); + $this->endPoint = &$this->store[$itemName]; return $this; } @@ -160,11 +160,11 @@ class Swift_DependencyContainer * * @param mixed $value * - * @return Swift_DependencyContainer + * @return $this */ public function asValue($value) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); $endPoint['lookupType'] = self::TYPE_VALUE; $endPoint['value'] = $value; @@ -176,11 +176,11 @@ class Swift_DependencyContainer * * @param string $lookup * - * @return Swift_DependencyContainer + * @return $this */ public function asAliasOf($lookup) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); $endPoint['lookupType'] = self::TYPE_ALIAS; $endPoint['ref'] = $lookup; @@ -198,11 +198,11 @@ class Swift_DependencyContainer * * @param string $className * - * @return Swift_DependencyContainer + * @return $this */ public function asNewInstanceOf($className) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); $endPoint['lookupType'] = self::TYPE_INSTANCE; $endPoint['className'] = $className; @@ -216,11 +216,11 @@ class Swift_DependencyContainer * * @param string $className * - * @return Swift_DependencyContainer + * @return $this */ public function asSharedInstanceOf($className) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); $endPoint['lookupType'] = self::TYPE_SHARED; $endPoint['className'] = $className; @@ -236,11 +236,11 @@ class Swift_DependencyContainer * * @param array $lookups * - * @return Swift_DependencyContainer + * @return $this */ public function withDependencies(array $lookups) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); $endPoint['args'] = array(); foreach ($lookups as $lookup) { $this->addConstructorLookup($lookup); @@ -257,11 +257,11 @@ class Swift_DependencyContainer * * @param mixed $value * - * @return Swift_DependencyContainer + * @return $this */ public function addConstructorValue($value) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); if (!isset($endPoint['args'])) { $endPoint['args'] = array(); } @@ -278,12 +278,12 @@ class Swift_DependencyContainer * * @param string $lookup * - * @return Swift_DependencyContainer + * @return $this */ public function addConstructorLookup($lookup) { - $endPoint = &$this->_getEndPoint(); - if (!isset($this->_endPoint['args'])) { + $endPoint = &$this->getEndPoint(); + if (!isset($this->endPoint['args'])) { $endPoint['args'] = array(); } $endPoint['args'][] = array('type' => 'lookup', 'item' => $lookup); @@ -292,21 +292,21 @@ class Swift_DependencyContainer } /** Get the literal value with $itemName */ - private function _getValue($itemName) + private function getValue($itemName) { - return $this->_store[$itemName]['value']; + return $this->store[$itemName]['value']; } /** Resolve an alias to another item */ - private function _createAlias($itemName) + private function createAlias($itemName) { - return $this->lookup($this->_store[$itemName]['ref']); + return $this->lookup($this->store[$itemName]['ref']); } /** Create a fresh instance of $itemName */ - private function _createNewInstance($itemName) + private function createNewInstance($itemName) { - $reflector = new ReflectionClass($this->_store[$itemName]['className']); + $reflector = new ReflectionClass($this->store[$itemName]['className']); if ($reflector->getConstructor()) { return $reflector->newInstanceArgs( $this->createDependenciesFor($itemName) @@ -317,35 +317,35 @@ class Swift_DependencyContainer } /** Create and register a shared instance of $itemName */ - private function _createSharedInstance($itemName) + private function createSharedInstance($itemName) { - if (!isset($this->_store[$itemName]['instance'])) { - $this->_store[$itemName]['instance'] = $this->_createNewInstance($itemName); + if (!isset($this->store[$itemName]['instance'])) { + $this->store[$itemName]['instance'] = $this->createNewInstance($itemName); } - return $this->_store[$itemName]['instance']; + return $this->store[$itemName]['instance']; } /** Get the current endpoint in the store */ - private function &_getEndPoint() + private function &getEndPoint() { - if (!isset($this->_endPoint)) { + if (!isset($this->endPoint)) { throw new BadMethodCallException( 'Component must first be registered by calling register()' ); } - return $this->_endPoint; + return $this->endPoint; } /** Get an argument list with dependencies resolved */ - private function _resolveArgs(array $args) + private function resolveArgs(array $args) { $resolved = array(); foreach ($args as $argDefinition) { switch ($argDefinition['type']) { case 'lookup': - $resolved[] = $this->_lookupRecursive($argDefinition['item']); + $resolved[] = $this->lookupRecursive($argDefinition['item']); break; case 'value': $resolved[] = $argDefinition['item']; @@ -357,12 +357,12 @@ class Swift_DependencyContainer } /** Resolve a single dependency with an collections */ - private function _lookupRecursive($item) + private function lookupRecursive($item) { if (is_array($item)) { $collection = array(); foreach ($item as $k => $v) { - $collection[$k] = $this->_lookupRecursive($v); + $collection[$k] = $this->lookupRecursive($v); } return $collection; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/EmbeddedFile.php b/htdocs/includes/swiftmailer/lib/classes/Swift/EmbeddedFile.php index d8c72ad4dfb..9755a88e176 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/EmbeddedFile.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/EmbeddedFile.php @@ -39,20 +39,6 @@ class Swift_EmbeddedFile extends Swift_Mime_EmbeddedFile } } - /** - * Create a new EmbeddedFile. - * - * @param string|Swift_OutputByteStream $data - * @param string $filename - * @param string $contentType - * - * @return Swift_Mime_EmbeddedFile - */ - public static function newInstance($data = null, $filename = null, $contentType = null) - { - return new self($data, $filename, $contentType); - } - /** * Create a new EmbeddedFile from a filesystem path. * @@ -62,8 +48,6 @@ class Swift_EmbeddedFile extends Swift_Mime_EmbeddedFile */ public static function fromPath($path) { - return self::newInstance()->setFile( - new Swift_ByteStream_FileByteStream($path) - ); + return (new self())->setFile(new Swift_ByteStream_FileByteStream($path)); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php index 8a81fe39709..b23b07702ef 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php @@ -13,7 +13,7 @@ * * Possibly the most accurate RFC 2045 QP implementation found in PHP. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_Encoder_QpEncoder implements Swift_Encoder { @@ -22,21 +22,21 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder * * @var Swift_CharacterStream */ - protected $_charStream; + protected $charStream; /** * A filter used if input should be canonicalized. * * @var Swift_StreamFilter */ - protected $_filter; + protected $filter; /** * Pre-computed QP for HUGE optimization. * * @var string[] */ - protected static $_qpMap = array( + protected static $qpMap = array( 0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04', 5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09', 10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E', @@ -91,14 +91,14 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder 255 => '=FF', ); - protected static $_safeMapShare = array(); + protected static $safeMapShare = array(); /** * A map of non-encoded ascii characters. * * @var string[] */ - protected $_safeMap = array(); + protected $safeMap = array(); /** * Creates a new QpEncoder for the given CharacterStream. @@ -108,28 +108,28 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder */ public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null) { - $this->_charStream = $charStream; - if (!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) { + $this->charStream = $charStream; + if (!isset(self::$safeMapShare[$this->getSafeMapShareId()])) { $this->initSafeMap(); - self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap; + self::$safeMapShare[$this->getSafeMapShareId()] = $this->safeMap; } else { - $this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()]; + $this->safeMap = self::$safeMapShare[$this->getSafeMapShareId()]; } - $this->_filter = $filter; + $this->filter = $filter; } public function __sleep() { - return array('_charStream', '_filter'); + return array('charStream', 'filter'); } public function __wakeup() { - if (!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) { + if (!isset(self::$safeMapShare[$this->getSafeMapShareId()])) { $this->initSafeMap(); - self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap; + self::$safeMapShare[$this->getSafeMapShareId()] = $this->safeMap; } else { - $this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()]; + $this->safeMap = self::$safeMapShare[$this->getSafeMapShareId()]; } } @@ -142,7 +142,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder { foreach (array_merge( array(0x09, 0x20), range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) { - $this->_safeMap[$byte] = chr($byte); + $this->safeMap[$byte] = chr($byte); } } @@ -173,19 +173,19 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder $currentLine = &$lines[$lNo++]; $size = $lineLen = 0; - $this->_charStream->flushContents(); - $this->_charStream->importString($string); + $this->charStream->flushContents(); + $this->charStream->importString($string); // Fetching more than 4 chars at one is slower, as is fetching fewer bytes // Conveniently 4 chars is the UTF-8 safe number since UTF-8 has up to 6 // bytes per char and (6 * 4 * 3 = 72 chars per line) * =NN is 3 bytes - while (false !== $bytes = $this->_nextSequence()) { + while (false !== $bytes = $this->nextSequence()) { // If we're filtering the input - if (isset($this->_filter)) { + if (isset($this->filter)) { // If we can't filter because we need more bytes - while ($this->_filter->shouldBuffer($bytes)) { + while ($this->filter->shouldBuffer($bytes)) { // Then collect bytes into the buffer - if (false === $moreBytes = $this->_nextSequence(1)) { + if (false === $moreBytes = $this->nextSequence(1)) { break; } @@ -194,10 +194,10 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder } } // And filter them - $bytes = $this->_filter->filter($bytes); + $bytes = $this->filter->filter($bytes); } - $enc = $this->_encodeByteSequence($bytes, $size); + $enc = $this->encodeByteSequence($bytes, $size); $i = strpos($enc, '=0D=0A'); $newLineLength = $lineLen + ($i === false ? $size : $i); @@ -219,7 +219,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder } } - return $this->_standardize(implode("=\r\n", $lines)); + return $this->standardize(implode("=\r\n", $lines)); } /** @@ -229,27 +229,27 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder */ public function charsetChanged($charset) { - $this->_charStream->setCharacterSet($charset); + $this->charStream->setCharacterSet($charset); } /** * Encode the given byte array into a verbatim QP form. * - * @param integer[] $bytes - * @param int $size + * @param int[] $bytes + * @param int $size * * @return string */ - protected function _encodeByteSequence(array $bytes, &$size) + protected function encodeByteSequence(array $bytes, &$size) { $ret = ''; $size = 0; foreach ($bytes as $b) { - if (isset($this->_safeMap[$b])) { - $ret .= $this->_safeMap[$b]; + if (isset($this->safeMap[$b])) { + $ret .= $this->safeMap[$b]; ++$size; } else { - $ret .= self::$_qpMap[$b]; + $ret .= self::$qpMap[$b]; $size += 3; } } @@ -262,11 +262,11 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder * * @param int $size number of bytes to read * - * @return integer[] + * @return int[] */ - protected function _nextSequence($size = 4) + protected function nextSequence($size = 4) { - return $this->_charStream->readBytes($size); + return $this->charStream->readBytes($size); } /** @@ -276,7 +276,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder * * @return string */ - protected function _standardize($string) + protected function standardize($string) { $string = str_replace(array("\t=0D=0A", ' =0D=0A', '=0D=0A'), array("=09\r\n", "=20\r\n", "\r\n"), $string @@ -284,7 +284,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder switch ($end = ord(substr($string, -1))) { case 0x09: case 0x20: - $string = substr_replace($string, self::$_qpMap[$end], -1); + $string = substr_replace($string, self::$qpMap[$end], -1); } return $string; @@ -295,6 +295,6 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder */ public function __clone() { - $this->_charStream = clone $this->_charStream; + $this->charStream = clone $this->charStream; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php index b0215e88380..bebb13494bd 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php @@ -20,7 +20,7 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder * * @var Swift_CharacterStream */ - private $_charStream; + private $charStream; /** * Creates a new Rfc2231Encoder using the given character stream instance. @@ -29,7 +29,7 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder */ public function __construct(Swift_CharacterStream $charStream) { - $this->_charStream = $charStream; + $this->charStream = $charStream; } /** @@ -53,12 +53,12 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder $maxLineLength = 75; } - $this->_charStream->flushContents(); - $this->_charStream->importString($string); + $this->charStream->flushContents(); + $this->charStream->importString($string); $thisLineLength = $maxLineLength - $firstLineOffset; - while (false !== $char = $this->_charStream->read(4)) { + while (false !== $char = $this->charStream->read(4)) { $encodedChar = rawurlencode($char); if (0 != strlen($currentLine) && strlen($currentLine.$encodedChar) > $thisLineLength) { @@ -79,7 +79,7 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder */ public function charsetChanged($charset) { - $this->_charStream->setCharacterSet($charset); + $this->charStream->setCharacterSet($charset); } /** @@ -87,6 +87,6 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder */ public function __clone() { - $this->_charStream = clone $this->_charStream; + $this->charStream = clone $this->charStream; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoding.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Encoding.php deleted file mode 100644 index 253977b608e..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoding.php +++ /dev/null @@ -1,64 +0,0 @@ -lookup($key); - } -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/CommandEvent.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/CommandEvent.php index 7dc381d9844..9834aa95883 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/CommandEvent.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/CommandEvent.php @@ -20,14 +20,14 @@ class Swift_Events_CommandEvent extends Swift_Events_EventObject * * @var string */ - private $_command; + private $command; /** * An array of codes which a successful response will contain. * - * @var integer[] + * @var int[] */ - private $_successCodes = array(); + private $successCodes = array(); /** * Create a new CommandEvent for $source with $command. @@ -39,8 +39,8 @@ class Swift_Events_CommandEvent extends Swift_Events_EventObject public function __construct(Swift_Transport $source, $command, $successCodes = array()) { parent::__construct($source); - $this->_command = $command; - $this->_successCodes = $successCodes; + $this->command = $command; + $this->successCodes = $successCodes; } /** @@ -50,16 +50,16 @@ class Swift_Events_CommandEvent extends Swift_Events_EventObject */ public function getCommand() { - return $this->_command; + return $this->command; } /** * Get the numeric response codes which indicate success for this command. * - * @return integer[] + * @return int[] */ public function getSuccessCodes() { - return $this->_successCodes; + return $this->successCodes; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php index aac36aaa768..f602608eeb6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php @@ -19,11 +19,11 @@ interface Swift_Events_EventDispatcher * Create a new SendEvent for $source and $message. * * @param Swift_Transport $source - * @param Swift_Mime_Message + * @param Swift_Mime_SimpleMessage * * @return Swift_Events_SendEvent */ - public function createSendEvent(Swift_Transport $source, Swift_Mime_Message $message); + public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message); /** * Create a new CommandEvent for $source and $command. diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventObject.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventObject.php index 90694a9a600..21e7c8127d6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventObject.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventObject.php @@ -16,10 +16,10 @@ class Swift_Events_EventObject implements Swift_Events_Event { /** The source of this Event */ - private $_source; + private $source; /** The state of this Event (should it bubble up the stack?) */ - private $_bubbleCancelled = false; + private $bubbleCancelled = false; /** * Create a new EventObject originating at $source. @@ -28,7 +28,7 @@ class Swift_Events_EventObject implements Swift_Events_Event */ public function __construct($source) { - $this->_source = $source; + $this->source = $source; } /** @@ -38,7 +38,7 @@ class Swift_Events_EventObject implements Swift_Events_Event */ public function getSource() { - return $this->_source; + return $this->source; } /** @@ -48,7 +48,7 @@ class Swift_Events_EventObject implements Swift_Events_Event */ public function cancelBubble($cancel = true) { - $this->_bubbleCancelled = $cancel; + $this->bubbleCancelled = $cancel; } /** @@ -58,6 +58,6 @@ class Swift_Events_EventObject implements Swift_Events_Event */ public function bubbleCancelled() { - return $this->_bubbleCancelled; + return $this->bubbleCancelled; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php index 2e92ba9404f..5ae6c04b627 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php @@ -20,14 +20,14 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject * * @var bool */ - private $_valid; + private $valid; /** * The response received from the server. * * @var string */ - private $_response; + private $response; /** * Create a new ResponseEvent for $source and $response. @@ -39,8 +39,8 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject public function __construct(Swift_Transport $source, $response, $valid = false) { parent::__construct($source); - $this->_response = $response; - $this->_valid = $valid; + $this->response = $response; + $this->valid = $valid; } /** @@ -50,7 +50,7 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject */ public function getResponse() { - return $this->_response; + return $this->response; } /** @@ -60,6 +60,6 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject */ public function isValid() { - return $this->_valid; + return $this->valid; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SendEvent.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SendEvent.php index 10da8080f09..5dc8efb1fd6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SendEvent.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SendEvent.php @@ -33,35 +33,35 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject /** * The Message being sent. * - * @var Swift_Mime_Message + * @var Swift_Mime_SimpleMessage */ - private $_message; + private $message; /** * Any recipients which failed after sending. * * @var string[] */ - private $_failedRecipients = array(); + private $failedRecipients = array(); /** * The overall result as a bitmask from the class constants. * * @var int */ - private $_result; + private $result; /** * Create a new SendEvent for $source and $message. * - * @param Swift_Transport $source - * @param Swift_Mime_Message $message + * @param Swift_Transport $source + * @param Swift_Mime_SimpleMessage $message */ - public function __construct(Swift_Transport $source, Swift_Mime_Message $message) + public function __construct(Swift_Transport $source, Swift_Mime_SimpleMessage $message) { parent::__construct($source); - $this->_message = $message; - $this->_result = self::RESULT_PENDING; + $this->message = $message; + $this->result = self::RESULT_PENDING; } /** @@ -77,11 +77,11 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject /** * Get the Message being sent. * - * @return Swift_Mime_Message + * @return Swift_Mime_SimpleMessage */ public function getMessage() { - return $this->_message; + return $this->message; } /** @@ -91,7 +91,7 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject */ public function setFailedRecipients($recipients) { - $this->_failedRecipients = $recipients; + $this->failedRecipients = $recipients; } /** @@ -101,7 +101,7 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject */ public function getFailedRecipients() { - return $this->_failedRecipients; + return $this->failedRecipients; } /** @@ -111,7 +111,7 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject */ public function setResult($result) { - $this->_result = $result; + $this->result = $result; } /** @@ -124,6 +124,6 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject */ public function getResult() { - return $this->_result; + return $this->result; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php index e8aca752f0d..815fa4d922b 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php @@ -16,20 +16,20 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher { /** A map of event types to their associated listener types */ - private $_eventMap = array(); + private $eventMap = array(); /** Event listeners bound to this dispatcher */ - private $_listeners = array(); + private $listeners = array(); /** Listeners queued to have an Event bubbled up the stack to them */ - private $_bubbleQueue = array(); + private $bubbleQueue = array(); /** * Create a new EventDispatcher. */ public function __construct() { - $this->_eventMap = array( + $this->eventMap = array( 'Swift_Events_CommandEvent' => 'Swift_Events_CommandListener', 'Swift_Events_ResponseEvent' => 'Swift_Events_ResponseListener', 'Swift_Events_SendEvent' => 'Swift_Events_SendListener', @@ -42,11 +42,11 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher * Create a new SendEvent for $source and $message. * * @param Swift_Transport $source - * @param Swift_Mime_Message + * @param Swift_Mime_SimpleMessage * * @return Swift_Events_SendEvent */ - public function createSendEvent(Swift_Transport $source, Swift_Mime_Message $message) + public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message) { return new Swift_Events_SendEvent($source, $message); } @@ -111,13 +111,13 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher */ public function bindEventListener(Swift_Events_EventListener $listener) { - foreach ($this->_listeners as $l) { + foreach ($this->listeners as $l) { // Already loaded if ($l === $listener) { return; } } - $this->_listeners[] = $listener; + $this->listeners[] = $listener; } /** @@ -128,29 +128,29 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher */ public function dispatchEvent(Swift_Events_EventObject $evt, $target) { - $this->_prepareBubbleQueue($evt); - $this->_bubble($evt, $target); + $this->prepareBubbleQueue($evt); + $this->bubble($evt, $target); } /** Queue listeners on a stack ready for $evt to be bubbled up it */ - private function _prepareBubbleQueue(Swift_Events_EventObject $evt) + private function prepareBubbleQueue(Swift_Events_EventObject $evt) { - $this->_bubbleQueue = array(); + $this->bubbleQueue = array(); $evtClass = get_class($evt); - foreach ($this->_listeners as $listener) { - if (array_key_exists($evtClass, $this->_eventMap) - && ($listener instanceof $this->_eventMap[$evtClass])) { - $this->_bubbleQueue[] = $listener; + foreach ($this->listeners as $listener) { + if (array_key_exists($evtClass, $this->eventMap) + && ($listener instanceof $this->eventMap[$evtClass])) { + $this->bubbleQueue[] = $listener; } } } /** Bubble $evt up the stack calling $target() on each listener */ - private function _bubble(Swift_Events_EventObject $evt, $target) + private function bubble(Swift_Events_EventObject $evt, $target) { - if (!$evt->bubbleCancelled() && $listener = array_shift($this->_bubbleQueue)) { + if (!$evt->bubbleCancelled() && $listener = array_shift($this->bubbleQueue)) { $listener->$target($evt); - $this->_bubble($evt, $target); + $this->bubble($evt, $target); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php index f87154fb9b0..77534e3e033 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php @@ -20,7 +20,7 @@ class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject * * @var Swift_TransportException */ - private $_exception; + private $exception; /** * Create a new TransportExceptionEvent for $transport. @@ -31,7 +31,7 @@ class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject public function __construct(Swift_Transport $transport, Swift_TransportException $ex) { parent::__construct($transport); - $this->_exception = $ex; + $this->exception = $ex; } /** @@ -41,6 +41,6 @@ class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject */ public function getException() { - return $this->_exception; + return $this->exception; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/FailoverTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/FailoverTransport.php index 53f277da0a2..dc2859f74a0 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/FailoverTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/FailoverTransport.php @@ -30,16 +30,4 @@ class Swift_FailoverTransport extends Swift_Transport_FailoverTransport $this->setTransports($transports); } - - /** - * Create a new FailoverTransport instance. - * - * @param Swift_Transport[] $transports - * - * @return Swift_FailoverTransport - */ - public static function newInstance($transports = array()) - { - return new self($transports); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/FileSpool.php b/htdocs/includes/swiftmailer/lib/classes/Swift/FileSpool.php index 220853989d3..b0b9eb064c5 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/FileSpool.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/FileSpool.php @@ -17,14 +17,14 @@ class Swift_FileSpool extends Swift_ConfigurableSpool { /** The spool directory */ - private $_path; + private $path; /** * File WriteRetry Limit. * * @var int */ - private $_retryLimit = 10; + private $retryLimit = 10; /** * Create a new FileSpool. @@ -35,11 +35,11 @@ class Swift_FileSpool extends Swift_ConfigurableSpool */ public function __construct($path) { - $this->_path = $path; + $this->path = $path; - if (!file_exists($this->_path)) { - if (!mkdir($this->_path, 0777, true)) { - throw new Swift_IoException('Unable to create Path ['.$this->_path.']'); + if (!file_exists($this->path)) { + if (!mkdir($this->path, 0777, true)) { + throw new Swift_IoException(sprintf('Unable to create path "%s".', $this->path)); } } } @@ -77,25 +77,25 @@ class Swift_FileSpool extends Swift_ConfigurableSpool */ public function setRetryLimit($limit) { - $this->_retryLimit = $limit; + $this->retryLimit = $limit; } /** * Queues a message. * - * @param Swift_Mime_Message $message The message to store + * @param Swift_Mime_SimpleMessage $message The message to store * * @throws Swift_IoException * * @return bool */ - public function queueMessage(Swift_Mime_Message $message) + public function queueMessage(Swift_Mime_SimpleMessage $message) { $ser = serialize($message); - $fileName = $this->_path.'/'.$this->getRandomString(10); - for ($i = 0; $i < $this->_retryLimit; ++$i) { + $fileName = $this->path.'/'.$this->getRandomString(10); + for ($i = 0; $i < $this->retryLimit; ++$i) { /* We try an exclusive creation of the file. This is an atomic operation, it avoid locking mechanism */ - $fp = @fopen($fileName.'.message', 'x'); + $fp = @fopen($fileName.'.message', 'xb'); if (false !== $fp) { if (false === fwrite($fp, $ser)) { return false; @@ -108,7 +108,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool } } - throw new Swift_IoException('Unable to create a file for enqueuing Message'); + throw new Swift_IoException(sprintf('Unable to create a file for enqueuing Message in "%s".', $this->path)); } /** @@ -118,7 +118,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool */ public function recover($timeout = 900) { - foreach (new DirectoryIterator($this->_path) as $file) { + foreach (new DirectoryIterator($this->path) as $file) { $file = $file->getRealPath(); if (substr($file, -16) == '.message.sending') { @@ -140,7 +140,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool */ public function flushQueue(Swift_Transport $transport, &$failedRecipients = null) { - $directoryIterator = new DirectoryIterator($this->_path); + $directoryIterator = new DirectoryIterator($this->path); /* Start the transport only if there are queued files to send */ if (!$transport->isStarted()) { @@ -200,7 +200,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool $ret = ''; $strlen = strlen($base); for ($i = 0; $i < $count; ++$i) { - $ret .= $base[((int) rand(0, $strlen - 1))]; + $ret .= $base[random_int(0, $strlen - 1)]; } return $ret; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/IdGenerator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/IdGenerator.php new file mode 100644 index 00000000000..c845d85e3bd --- /dev/null +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/IdGenerator.php @@ -0,0 +1,22 @@ +setFile( - new Swift_ByteStream_FileByteStream($path) - ); - - return $image; + return (new self())->setFile(new Swift_ByteStream_FileByteStream($path)); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php index b37f07f74bd..cdd08503004 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php @@ -20,14 +20,14 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache * * @var array */ - private $_contents = array(); + private $contents = array(); /** * An InputStream for cloning. * * @var Swift_KeyCache_KeyCacheInputStream */ - private $_stream; + private $stream; /** * Create a new ArrayKeyCache with the given $stream for cloning to make @@ -37,7 +37,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function __construct(Swift_KeyCache_KeyCacheInputStream $stream) { - $this->_stream = $stream; + $this->stream = $stream; } /** @@ -52,16 +52,16 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function setString($nsKey, $itemKey, $string, $mode) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: - $this->_contents[$nsKey][$itemKey] = $string; + $this->contents[$nsKey][$itemKey] = $string; break; case self::MODE_APPEND: if (!$this->hasKey($nsKey, $itemKey)) { - $this->_contents[$nsKey][$itemKey] = ''; + $this->contents[$nsKey][$itemKey] = ''; } - $this->_contents[$nsKey][$itemKey] .= $string; + $this->contents[$nsKey][$itemKey] .= $string; break; default: throw new Swift_SwiftException( @@ -83,16 +83,16 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: $this->clearKey($nsKey, $itemKey); case self::MODE_APPEND: if (!$this->hasKey($nsKey, $itemKey)) { - $this->_contents[$nsKey][$itemKey] = ''; + $this->contents[$nsKey][$itemKey] = ''; } while (false !== $bytes = $os->read(8192)) { - $this->_contents[$nsKey][$itemKey] .= $bytes; + $this->contents[$nsKey][$itemKey] .= $bytes; } break; default: @@ -116,7 +116,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) { - $is = clone $this->_stream; + $is = clone $this->stream; $is->setKeyCache($this); $is->setNsKey($nsKey); $is->setItemKey($itemKey); @@ -137,9 +137,9 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function getString($nsKey, $itemKey) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); if ($this->hasKey($nsKey, $itemKey)) { - return $this->_contents[$nsKey][$itemKey]; + return $this->contents[$nsKey][$itemKey]; } } @@ -152,7 +152,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); $is->write($this->getString($nsKey, $itemKey)); } @@ -166,9 +166,9 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function hasKey($nsKey, $itemKey) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); - return array_key_exists($itemKey, $this->_contents[$nsKey]); + return array_key_exists($itemKey, $this->contents[$nsKey]); } /** @@ -179,7 +179,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function clearKey($nsKey, $itemKey) { - unset($this->_contents[$nsKey][$itemKey]); + unset($this->contents[$nsKey][$itemKey]); } /** @@ -189,7 +189,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function clearAll($nsKey) { - unset($this->_contents[$nsKey]); + unset($this->contents[$nsKey]); } /** @@ -197,10 +197,10 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache * * @param string $nsKey */ - private function _prepareCache($nsKey) + private function prepareCache($nsKey) { - if (!array_key_exists($nsKey, $this->_contents)) { - $this->_contents[$nsKey] = array(); + if (!array_key_exists($nsKey, $this->contents)) { + $this->contents[$nsKey] = array(); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php index 453f50a15db..d6a633a1512 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php @@ -29,28 +29,21 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache * * @var Swift_KeyCache_KeyCacheInputStream */ - private $_stream; + private $stream; /** * A path to write to. * * @var string */ - private $_path; + private $path; /** * Stored keys. * * @var array */ - private $_keys = array(); - - /** - * Will be true if magic_quotes_runtime is turned on. - * - * @var bool - */ - private $_quotes = false; + private $keys = array(); /** * Create a new DiskKeyCache with the given $stream for cloning to make @@ -61,12 +54,8 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function __construct(Swift_KeyCache_KeyCacheInputStream $stream, $path) { - $this->_stream = $stream; - $this->_path = $path; - - if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) { - $this->_quotes = true; - } + $this->stream = $stream; + $this->path = $path; } /** @@ -83,13 +72,13 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function setString($nsKey, $itemKey, $string, $mode) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); break; case self::MODE_APPEND: - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END); + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END); break; default: throw new Swift_SwiftException( @@ -99,7 +88,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache break; } fwrite($fp, $string); - $this->_freeHandle($nsKey, $itemKey); + $this->freeHandle($nsKey, $itemKey); } /** @@ -116,13 +105,13 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); break; case self::MODE_APPEND: - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END); + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END); break; default: throw new Swift_SwiftException( @@ -134,7 +123,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache while (false !== $bytes = $os->read(8192)) { fwrite($fp, $bytes); } - $this->_freeHandle($nsKey, $itemKey); + $this->freeHandle($nsKey, $itemKey); } /** @@ -150,7 +139,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) { - $is = clone $this->_stream; + $is = clone $this->stream; $is->setKeyCache($this); $is->setNsKey($nsKey); $is->setItemKey($itemKey); @@ -173,20 +162,14 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function getString($nsKey, $itemKey) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); if ($this->hasKey($nsKey, $itemKey)) { - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 0); - } + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); $str = ''; while (!feof($fp) && false !== $bytes = fread($fp, 8192)) { $str .= $bytes; } - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 1); - } - $this->_freeHandle($nsKey, $itemKey); + $this->freeHandle($nsKey, $itemKey); return $str; } @@ -202,17 +185,11 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) { if ($this->hasKey($nsKey, $itemKey)) { - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 0); - } + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); while (!feof($fp) && false !== $bytes = fread($fp, 8192)) { $is->write($bytes); } - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 1); - } - $this->_freeHandle($nsKey, $itemKey); + $this->freeHandle($nsKey, $itemKey); } } @@ -226,7 +203,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function hasKey($nsKey, $itemKey) { - return is_file($this->_path.'/'.$nsKey.'/'.$itemKey); + return is_file($this->path.'/'.$nsKey.'/'.$itemKey); } /** @@ -238,8 +215,8 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache public function clearKey($nsKey, $itemKey) { if ($this->hasKey($nsKey, $itemKey)) { - $this->_freeHandle($nsKey, $itemKey); - unlink($this->_path.'/'.$nsKey.'/'.$itemKey); + $this->freeHandle($nsKey, $itemKey); + unlink($this->path.'/'.$nsKey.'/'.$itemKey); } } @@ -250,14 +227,14 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function clearAll($nsKey) { - if (array_key_exists($nsKey, $this->_keys)) { - foreach ($this->_keys[$nsKey] as $itemKey => $null) { + if (array_key_exists($nsKey, $this->keys)) { + foreach ($this->keys[$nsKey] as $itemKey => $null) { $this->clearKey($nsKey, $itemKey); } - if (is_dir($this->_path.'/'.$nsKey)) { - rmdir($this->_path.'/'.$nsKey); + if (is_dir($this->path.'/'.$nsKey)) { + rmdir($this->path.'/'.$nsKey); } - unset($this->_keys[$nsKey]); + unset($this->keys[$nsKey]); } } @@ -266,14 +243,14 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache * * @param string $nsKey */ - private function _prepareCache($nsKey) + private function prepareCache($nsKey) { - $cacheDir = $this->_path.'/'.$nsKey; + $cacheDir = $this->path.'/'.$nsKey; if (!is_dir($cacheDir)) { if (!mkdir($cacheDir)) { throw new Swift_IoException('Failed to create cache directory '.$cacheDir); } - $this->_keys[$nsKey] = array(); + $this->keys[$nsKey] = array(); } } @@ -286,27 +263,27 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache * * @return resource */ - private function _getHandle($nsKey, $itemKey, $position) + private function getHandle($nsKey, $itemKey, $position) { - if (!isset($this->_keys[$nsKey][$itemKey])) { + if (!isset($this->keys[$nsKey][$itemKey])) { $openMode = $this->hasKey($nsKey, $itemKey) ? 'r+b' : 'w+b'; - $fp = fopen($this->_path.'/'.$nsKey.'/'.$itemKey, $openMode); - $this->_keys[$nsKey][$itemKey] = $fp; + $fp = fopen($this->path.'/'.$nsKey.'/'.$itemKey, $openMode); + $this->keys[$nsKey][$itemKey] = $fp; } if (self::POSITION_START == $position) { - fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_SET); + fseek($this->keys[$nsKey][$itemKey], 0, SEEK_SET); } elseif (self::POSITION_END == $position) { - fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_END); + fseek($this->keys[$nsKey][$itemKey], 0, SEEK_END); } - return $this->_keys[$nsKey][$itemKey]; + return $this->keys[$nsKey][$itemKey]; } - private function _freeHandle($nsKey, $itemKey) + private function freeHandle($nsKey, $itemKey) { - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_CURRENT); + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_CURRENT); fclose($fp); - $this->_keys[$nsKey][$itemKey] = null; + $this->keys[$nsKey][$itemKey] = null; } /** @@ -314,7 +291,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function __destruct() { - foreach ($this->_keys as $nsKey => $null) { + foreach ($this->keys as $nsKey => $null) { $this->clearAll($nsKey); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php index b00d458a6de..a74df434c46 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php @@ -16,16 +16,16 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCacheInputStream { /** The KeyCache being written to */ - private $_keyCache; + private $keyCache; /** The nsKey of the KeyCache being written to */ - private $_nsKey; + private $nsKey; /** The itemKey of the KeyCache being written to */ - private $_itemKey; + private $itemKey; /** A stream to write through on each write() */ - private $_writeThrough = null; + private $writeThrough = null; /** * Set the KeyCache to wrap. @@ -34,7 +34,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function setKeyCache(Swift_KeyCache $keyCache) { - $this->_keyCache = $keyCache; + $this->keyCache = $keyCache; } /** @@ -44,7 +44,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function setWriteThroughStream(Swift_InputByteStream $is) { - $this->_writeThrough = $is; + $this->writeThrough = $is; } /** @@ -55,14 +55,14 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function write($bytes, Swift_InputByteStream $is = null) { - $this->_keyCache->setString( - $this->_nsKey, $this->_itemKey, $bytes, Swift_KeyCache::MODE_APPEND + $this->keyCache->setString( + $this->nsKey, $this->itemKey, $bytes, Swift_KeyCache::MODE_APPEND ); if (isset($is)) { $is->write($bytes); } - if (isset($this->_writeThrough)) { - $this->_writeThrough->write($bytes); + if (isset($this->writeThrough)) { + $this->writeThrough->write($bytes); } } @@ -93,7 +93,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function flushBuffers() { - $this->_keyCache->clearKey($this->_nsKey, $this->_itemKey); + $this->keyCache->clearKey($this->nsKey, $this->itemKey); } /** @@ -103,7 +103,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function setNsKey($nsKey) { - $this->_nsKey = $nsKey; + $this->nsKey = $nsKey; } /** @@ -113,7 +113,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function setItemKey($itemKey) { - $this->_itemKey = $itemKey; + $this->itemKey = $itemKey; } /** @@ -122,6 +122,6 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function __clone() { - $this->_writeThrough = null; + $this->writeThrough = null; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php index fdba9df50dc..03106e55d4e 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php @@ -30,16 +30,4 @@ class Swift_LoadBalancedTransport extends Swift_Transport_LoadBalancedTransport $this->setTransports($transports); } - - /** - * Create a new LoadBalancedTransport instance. - * - * @param array $transports - * - * @return Swift_LoadBalancedTransport - */ - public static function newInstance($transports = array()) - { - return new self($transports); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/MailTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/MailTransport.php deleted file mode 100644 index 858ca814792..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/MailTransport.php +++ /dev/null @@ -1,45 +0,0 @@ -createDependenciesFor('transport.mail') - ); - - $this->setExtraParams($extraParams); - } - - /** - * Create a new MailTransport instance. - * - * @param string $extraParams To be passed to mail() - * - * @return Swift_MailTransport - */ - public static function newInstance($extraParams = '-f%s') - { - return new self($extraParams); - } -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer.php index 34a78d47b54..3561ec6e68e 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer.php @@ -16,7 +16,7 @@ class Swift_Mailer { /** The Transport used to send messages */ - private $_transport; + private $transport; /** * Create a new Mailer using $transport for delivery. @@ -25,19 +25,7 @@ class Swift_Mailer */ public function __construct(Swift_Transport $transport) { - $this->_transport = $transport; - } - - /** - * Create a new Mailer instance. - * - * @param Swift_Transport $transport - * - * @return Swift_Mailer - */ - public static function newInstance(Swift_Transport $transport) - { - return new self($transport); + $this->transport = $transport; } /** @@ -66,23 +54,23 @@ class Swift_Mailer * The return value is the number of recipients who were accepted for * delivery. * - * @param Swift_Mime_Message $message - * @param array $failedRecipients An array of failures by-reference + * @param Swift_Mime_SimpleMessage $message + * @param array $failedRecipients An array of failures by-reference * - * @return int + * @return int The number of successful recipients. Can be 0 which indicates failure */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { $failedRecipients = (array) $failedRecipients; - if (!$this->_transport->isStarted()) { - $this->_transport->start(); + if (!$this->transport->isStarted()) { + $this->transport->start(); } $sent = 0; try { - $sent = $this->_transport->send($message, $failedRecipients); + $sent = $this->transport->send($message, $failedRecipients); } catch (Swift_RfcComplianceException $e) { foreach ($message->getTo() as $address => $name) { $failedRecipients[] = $address; @@ -99,7 +87,7 @@ class Swift_Mailer */ public function registerPlugin(Swift_Events_EventListener $plugin) { - $this->_transport->registerPlugin($plugin); + $this->transport->registerPlugin($plugin); } /** @@ -109,6 +97,6 @@ class Swift_Mailer */ public function getTransport() { - return $this->_transport; + return $this->transport; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php index e3e6cad05bd..84dacb5f185 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php @@ -20,7 +20,7 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera * * @var array */ - private $_recipients = array(); + private $recipients = array(); /** * Create a new ArrayRecipientIterator from $recipients. @@ -29,7 +29,7 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera */ public function __construct(array $recipients) { - $this->_recipients = $recipients; + $this->recipients = $recipients; } /** @@ -39,7 +39,7 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera */ public function hasNext() { - return !empty($this->_recipients); + return !empty($this->recipients); } /** @@ -50,6 +50,6 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera */ public function nextRecipient() { - return array_splice($this->_recipients, 0, 1); + return array_splice($this->recipients, 0, 1); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/MemorySpool.php b/htdocs/includes/swiftmailer/lib/classes/Swift/MemorySpool.php index 5b239694d81..9aa62835b32 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/MemorySpool.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/MemorySpool.php @@ -16,6 +16,7 @@ class Swift_MemorySpool implements Swift_Spool { protected $messages = array(); + private $flushRetries = 3; /** * Tests if this Transport mechanism has started. @@ -41,14 +42,22 @@ class Swift_MemorySpool implements Swift_Spool { } + /** + * @param int $retries + */ + public function setFlushRetries($retries) + { + $this->flushRetries = $retries; + } + /** * Stores a message in the queue. * - * @param Swift_Mime_Message $message The message to store + * @param Swift_Mime_SimpleMessage $message The message to store * * @return bool Whether the operation has succeeded */ - public function queueMessage(Swift_Mime_Message $message) + public function queueMessage(Swift_Mime_SimpleMessage $message) { //clone the message to make sure it is not changed while in the queue $this->messages[] = clone $message; @@ -75,8 +84,25 @@ class Swift_MemorySpool implements Swift_Spool } $count = 0; - while ($message = array_pop($this->messages)) { - $count += $transport->send($message, $failedRecipients); + $retries = $this->flushRetries; + while ($retries--) { + try { + while ($message = array_pop($this->messages)) { + $count += $transport->send($message, $failedRecipients); + } + } catch (Swift_TransportException $exception) { + if ($retries) { + // re-queue the message at the end of the queue to give a chance + // to the other messages to be sent, in case the failure was due to + // this message and not just the transport failing + array_unshift($this->messages, $message); + + // wait half a second before we try again + usleep(500000); + } else { + throw $exception; + } + } } return $count; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Message.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Message.php index 11aa5a9a06a..00f6e160027 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Message.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Message.php @@ -60,21 +60,6 @@ class Swift_Message extends Swift_Mime_SimpleMessage } } - /** - * Create a new Message. - * - * @param string $subject - * @param string $body - * @param string $contentType - * @param string $charset - * - * @return Swift_Message - */ - public static function newInstance($subject = null, $body = null, $contentType = null, $charset = null) - { - return new self($subject, $body, $contentType, $charset); - } - /** * Add a MimePart to this Message. * @@ -82,21 +67,19 @@ class Swift_Message extends Swift_Mime_SimpleMessage * @param string $contentType * @param string $charset * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addPart($body, $contentType = null, $charset = null) { - return $this->attach(Swift_MimePart::newInstance( - $body, $contentType, $charset - )); + return $this->attach((new Swift_MimePart($body, $contentType, $charset))->setEncoder($this->getEncoder())); } /** - * Attach a new signature handler to the message. + * Detach a signature handler from a message. * * @param Swift_Signer $signer * - * @return Swift_Message + * @return $this */ public function attachSigner(Swift_Signer $signer) { @@ -114,7 +97,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage * * @param Swift_Signer $signer * - * @return Swift_Message + * @return $this */ public function detachSigner(Swift_Signer $signer) { @@ -207,7 +190,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage $signer->setHeaders($this->getHeaders()); $signer->startBody(); - $this->_bodyToByteStream($signer); + $this->bodyToByteStream($signer); $signer->endBody(); $signer->addSignature($this->getHeaders()); @@ -223,7 +206,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage $this->savedMessage['body'] = $this->getBody(); $this->savedMessage['children'] = $this->getChildren(); if (count($this->savedMessage['children']) > 0 && $this->getBody() != '') { - $this->setChildren(array_merge(array($this->_becomeMimePart()), $this->savedMessage['children'])); + $this->setChildren(array_merge(array($this->becomeMimePart()), $this->savedMessage['children'])); $this->setBody(''); } } @@ -281,11 +264,11 @@ class Swift_Message extends Swift_Mime_SimpleMessage { parent::__clone(); foreach ($this->bodySigners as $key => $bodySigner) { - $this->bodySigners[$key] = clone($bodySigner); + $this->bodySigners[$key] = clone $bodySigner; } foreach ($this->headerSigners as $key => $headerSigner) { - $this->headerSigners[$key] = clone($headerSigner); + $this->headerSigners[$key] = clone $headerSigner; } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Attachment.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Attachment.php index 46a5e8da946..a36ce7237cf 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Attachment.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Attachment.php @@ -16,23 +16,23 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity { /** Recognized MIME types */ - private $_mimeTypes = array(); + private $mimeTypes = array(); /** * Create a new Attachment with $headers, $encoder and $cache. * - * @param Swift_Mime_HeaderSet $headers - * @param Swift_Mime_ContentEncoder $encoder - * @param Swift_KeyCache $cache - * @param Swift_Mime_Grammar $grammar - * @param array $mimeTypes optional + * @param Swift_Mime_SimpleHeaderSet $headers + * @param Swift_Mime_ContentEncoder $encoder + * @param Swift_KeyCache $cache + * @param Swift_IdGenerator $idGenerator + * @param array $mimeTypes */ - public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $mimeTypes = array()) + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = array()) { - parent::__construct($headers, $encoder, $cache, $grammar); + parent::__construct($headers, $encoder, $cache, $idGenerator); $this->setDisposition('attachment'); $this->setContentType('application/octet-stream'); - $this->_mimeTypes = $mimeTypes; + $this->mimeTypes = $mimeTypes; } /** @@ -56,7 +56,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity */ public function getDisposition() { - return $this->_getHeaderFieldModel('Content-Disposition'); + return $this->getHeaderFieldModel('Content-Disposition'); } /** @@ -64,11 +64,11 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity * * @param string $disposition * - * @return Swift_Mime_Attachment + * @return $this */ public function setDisposition($disposition) { - if (!$this->_setHeaderFieldModel('Content-Disposition', $disposition)) { + if (!$this->setHeaderFieldModel('Content-Disposition', $disposition)) { $this->getHeaders()->addParameterizedHeader('Content-Disposition', $disposition); } @@ -82,7 +82,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity */ public function getFilename() { - return $this->_getHeaderParameter('Content-Disposition', 'filename'); + return $this->getHeaderParameter('Content-Disposition', 'filename'); } /** @@ -90,12 +90,12 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity * * @param string $filename * - * @return Swift_Mime_Attachment + * @return $this */ public function setFilename($filename) { - $this->_setHeaderParameter('Content-Disposition', 'filename', $filename); - $this->_setHeaderParameter('Content-Type', 'name', $filename); + $this->setHeaderParameter('Content-Disposition', 'filename', $filename); + $this->setHeaderParameter('Content-Type', 'name', $filename); return $this; } @@ -107,7 +107,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity */ public function getSize() { - return $this->_getHeaderParameter('Content-Disposition', 'size'); + return $this->getHeaderParameter('Content-Disposition', 'size'); } /** @@ -115,11 +115,11 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity * * @param int $size * - * @return Swift_Mime_Attachment + * @return $this */ public function setSize($size) { - $this->_setHeaderParameter('Content-Disposition', 'size', $size); + $this->setHeaderParameter('Content-Disposition', 'size', $size); return $this; } @@ -130,7 +130,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity * @param Swift_FileStream $file * @param string $contentType optional * - * @return Swift_Mime_Attachment + * @return $this */ public function setFile(Swift_FileStream $file, $contentType = null) { @@ -139,8 +139,8 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity if (!isset($contentType)) { $extension = strtolower(substr($file->getPath(), strrpos($file->getPath(), '.') + 1)); - if (array_key_exists($extension, $this->_mimeTypes)) { - $this->setContentType($this->_mimeTypes[$extension]); + if (array_key_exists($extension, $this->mimeTypes)) { + $this->setContentType($this->mimeTypes[$extension]); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php index 710b5ac9edc..34de4ef39a4 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php @@ -92,7 +92,7 @@ class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_Con sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset)); } - return $this->_standardize(quoted_printable_encode($string)); + return $this->standardize(quoted_printable_encode($string)); } /** @@ -102,7 +102,7 @@ class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_Con * * @return string */ - protected function _standardize($string) + protected function standardize($string) { // transform CR or LF to CRLF $string = preg_replace('~=0D(?!=0A)|(?_name = $name; - $this->_canonical = $canonical; + $this->name = $name; + $this->canonical = $canonical; } /** @@ -52,11 +52,11 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { - if ($this->_canonical) { - $string = $this->_canonicalize($string); + if ($this->canonical) { + $string = $this->canonicalize($string); } - return $this->_safeWordWrap($string, $maxLineLength, "\r\n"); + return $this->safeWordwrap($string, $maxLineLength, "\r\n"); } /** @@ -72,10 +72,10 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten $leftOver = ''; while (false !== $bytes = $os->read(8192)) { $toencode = $leftOver.$bytes; - if ($this->_canonical) { - $toencode = $this->_canonicalize($toencode); + if ($this->canonical) { + $toencode = $this->canonicalize($toencode); } - $wrapped = $this->_safeWordWrap($toencode, $maxLineLength, "\r\n"); + $wrapped = $this->safeWordwrap($toencode, $maxLineLength, "\r\n"); $lastLinePos = strrpos($wrapped, "\r\n"); $leftOver = substr($wrapped, $lastLinePos); $wrapped = substr($wrapped, 0, $lastLinePos); @@ -94,7 +94,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten */ public function getName() { - return $this->_name; + return $this->name; } /** @@ -113,7 +113,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten * * @return string */ - private function _safeWordwrap($string, $length = 75, $le = "\r\n") + private function safeWordwrap($string, $length = 75, $le = "\r\n") { if (0 >= $length) { return $string; @@ -151,7 +151,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten * * @return string */ - private function _canonicalize($string) + private function canonicalize($string) { return str_replace( array("\r\n", "\r", "\n"), diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php index 5cc907b8e7e..b3577dbe61f 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php @@ -11,11 +11,11 @@ /** * Handles Quoted Printable (QP) Transfer Encoding in Swift Mailer. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder implements Swift_Mime_ContentEncoder { - protected $_dotEscape; + protected $dotEscape; /** * Creates a new QpContentEncoder for the given CharacterStream. @@ -26,26 +26,26 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder */ public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null, $dotEscape = false) { - $this->_dotEscape = $dotEscape; + $this->dotEscape = $dotEscape; parent::__construct($charStream, $filter); } public function __sleep() { - return array('_charStream', '_filter', '_dotEscape'); + return array('charStream', 'filter', 'dotEscape'); } protected function getSafeMapShareId() { - return get_class($this).($this->_dotEscape ? '.dotEscape' : ''); + return get_class($this).($this->dotEscape ? '.dotEscape' : ''); } protected function initSafeMap() { parent::initSafeMap(); - if ($this->_dotEscape) { + if ($this->dotEscape) { /* Encode . as =2e for buggy remote servers */ - unset($this->_safeMap[0x2e]); + unset($this->safeMap[0x2e]); } } @@ -69,20 +69,20 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder $thisLineLength = $maxLineLength - $firstLineOffset; - $this->_charStream->flushContents(); - $this->_charStream->importByteStream($os); + $this->charStream->flushContents(); + $this->charStream->importByteStream($os); $currentLine = ''; $prepend = ''; $size = $lineLen = 0; - while (false !== $bytes = $this->_nextSequence()) { + while (false !== $bytes = $this->nextSequence()) { // If we're filtering the input - if (isset($this->_filter)) { + if (isset($this->filter)) { // If we can't filter because we need more bytes - while ($this->_filter->shouldBuffer($bytes)) { + while ($this->filter->shouldBuffer($bytes)) { // Then collect bytes into the buffer - if (false === $moreBytes = $this->_nextSequence(1)) { + if (false === $moreBytes = $this->nextSequence(1)) { break; } @@ -91,16 +91,16 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder } } // And filter them - $bytes = $this->_filter->filter($bytes); + $bytes = $this->filter->filter($bytes); } - $enc = $this->_encodeByteSequence($bytes, $size); + $enc = $this->encodeByteSequence($bytes, $size); $i = strpos($enc, '=0D=0A'); $newLineLength = $lineLen + ($i === false ? $size : $i); if ($currentLine && $newLineLength >= $thisLineLength) { - $is->write($prepend.$this->_standardize($currentLine)); + $is->write($prepend.$this->standardize($currentLine)); $currentLine = ''; $prepend = "=\r\n"; $thisLineLength = $maxLineLength; @@ -117,7 +117,7 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder } } if (strlen($currentLine)) { - $is->write($prepend.$this->_standardize($currentLine)); + $is->write($prepend.$this->standardize($currentLine)); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php index 6af757124d3..7835a492873 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php @@ -18,15 +18,15 @@ class Swift_Mime_EmbeddedFile extends Swift_Mime_Attachment /** * Creates a new Attachment with $headers and $encoder. * - * @param Swift_Mime_HeaderSet $headers - * @param Swift_Mime_ContentEncoder $encoder - * @param Swift_KeyCache $cache - * @param Swift_Mime_Grammar $grammar - * @param array $mimeTypes optional + * @param Swift_Mime_SimpleHeaderSet $headers + * @param Swift_Mime_ContentEncoder $encoder + * @param Swift_KeyCache $cache + * @param Swift_IdGenerator $idGenerator + * @param array $mimeTypes optional */ - public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $mimeTypes = array()) + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = array()) { - parent::__construct($headers, $encoder, $cache, $grammar, $mimeTypes); + parent::__construct($headers, $encoder, $cache, $idGenerator, $mimeTypes); $this->setDisposition('inline'); $this->setId($this->getId()); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Grammar.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Grammar.php deleted file mode 100644 index a09f338315c..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Grammar.php +++ /dev/null @@ -1,176 +0,0 @@ -init(); - } - - public function __wakeup() - { - $this->init(); - } - - protected function init() - { - if (count(self::$_specials) > 0) { - return; - } - - self::$_specials = array( - '(', ')', '<', '>', '[', ']', - ':', ';', '@', ',', '.', '"', - ); - - /*** Refer to RFC 2822 for ABNF grammar ***/ - - // All basic building blocks - self::$_grammar['NO-WS-CTL'] = '[\x01-\x08\x0B\x0C\x0E-\x19\x7F]'; - self::$_grammar['WSP'] = '[ \t]'; - self::$_grammar['CRLF'] = '(?:\r\n)'; - self::$_grammar['FWS'] = '(?:(?:'.self::$_grammar['WSP'].'*'. - self::$_grammar['CRLF'].')?'.self::$_grammar['WSP'].')'; - self::$_grammar['text'] = '[\x00-\x08\x0B\x0C\x0E-\x7F]'; - self::$_grammar['quoted-pair'] = '(?:\\\\'.self::$_grammar['text'].')'; - self::$_grammar['ctext'] = '(?:'.self::$_grammar['NO-WS-CTL']. - '|[\x21-\x27\x2A-\x5B\x5D-\x7E])'; - // Uses recursive PCRE (?1) -- could be a weak point?? - self::$_grammar['ccontent'] = '(?:'.self::$_grammar['ctext'].'|'. - self::$_grammar['quoted-pair'].'|(?1))'; - self::$_grammar['comment'] = '(\((?:'.self::$_grammar['FWS'].'|'. - self::$_grammar['ccontent'].')*'.self::$_grammar['FWS'].'?\))'; - self::$_grammar['CFWS'] = '(?:(?:'.self::$_grammar['FWS'].'?'. - self::$_grammar['comment'].')*(?:(?:'.self::$_grammar['FWS'].'?'. - self::$_grammar['comment'].')|'.self::$_grammar['FWS'].'))'; - self::$_grammar['qtext'] = '(?:'.self::$_grammar['NO-WS-CTL']. - '|[\x21\x23-\x5B\x5D-\x7E])'; - self::$_grammar['qcontent'] = '(?:'.self::$_grammar['qtext'].'|'. - self::$_grammar['quoted-pair'].')'; - self::$_grammar['quoted-string'] = '(?:'.self::$_grammar['CFWS'].'?"'. - '('.self::$_grammar['FWS'].'?'.self::$_grammar['qcontent'].')*'. - self::$_grammar['FWS'].'?"'.self::$_grammar['CFWS'].'?)'; - self::$_grammar['atext'] = '[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]'; - self::$_grammar['atom'] = '(?:'.self::$_grammar['CFWS'].'?'. - self::$_grammar['atext'].'+'.self::$_grammar['CFWS'].'?)'; - self::$_grammar['dot-atom-text'] = '(?:'.self::$_grammar['atext'].'+'. - '(\.'.self::$_grammar['atext'].'+)*)'; - self::$_grammar['dot-atom'] = '(?:'.self::$_grammar['CFWS'].'?'. - self::$_grammar['dot-atom-text'].'+'.self::$_grammar['CFWS'].'?)'; - self::$_grammar['word'] = '(?:'.self::$_grammar['atom'].'|'. - self::$_grammar['quoted-string'].')'; - self::$_grammar['phrase'] = '(?:'.self::$_grammar['word'].'+?)'; - self::$_grammar['no-fold-quote'] = '(?:"(?:'.self::$_grammar['qtext']. - '|'.self::$_grammar['quoted-pair'].')*")'; - self::$_grammar['dtext'] = '(?:'.self::$_grammar['NO-WS-CTL']. - '|[\x21-\x5A\x5E-\x7E])'; - self::$_grammar['no-fold-literal'] = '(?:\[(?:'.self::$_grammar['dtext']. - '|'.self::$_grammar['quoted-pair'].')*\])'; - - // Message IDs - self::$_grammar['id-left'] = '(?:'.self::$_grammar['dot-atom-text'].'|'. - self::$_grammar['no-fold-quote'].')'; - self::$_grammar['id-right'] = '(?:'.self::$_grammar['dot-atom-text'].'|'. - self::$_grammar['no-fold-literal'].')'; - - // Addresses, mailboxes and paths - self::$_grammar['local-part'] = '(?:'.self::$_grammar['dot-atom'].'|'. - self::$_grammar['quoted-string'].')'; - self::$_grammar['dcontent'] = '(?:'.self::$_grammar['dtext'].'|'. - self::$_grammar['quoted-pair'].')'; - self::$_grammar['domain-literal'] = '(?:'.self::$_grammar['CFWS'].'?\[('. - self::$_grammar['FWS'].'?'.self::$_grammar['dcontent'].')*?'. - self::$_grammar['FWS'].'?\]'.self::$_grammar['CFWS'].'?)'; - self::$_grammar['domain'] = '(?:'.self::$_grammar['dot-atom'].'|'. - self::$_grammar['domain-literal'].')'; - self::$_grammar['addr-spec'] = '(?:'.self::$_grammar['local-part'].'@'. - self::$_grammar['domain'].')'; - } - - /** - * Get the grammar defined for $name token. - * - * @param string $name exactly as written in the RFC - * - * @return string - */ - public function getDefinition($name) - { - if (array_key_exists($name, self::$_grammar)) { - return self::$_grammar[$name]; - } - - throw new Swift_RfcComplianceException( - "No such grammar '".$name."' defined." - ); - } - - /** - * Returns the tokens defined in RFC 2822 (and some related RFCs). - * - * @return array - */ - public function getGrammarDefinitions() - { - return self::$_grammar; - } - - /** - * Returns the current special characters used in the syntax which need to be escaped. - * - * @return array - */ - public function getSpecials() - { - return self::$_specials; - } - - /** - * Escape special characters in a string (convert to quoted-pairs). - * - * @param string $token - * @param string[] $include additional chars to escape - * @param string[] $exclude chars from escaping - * - * @return string - */ - public function escapeSpecials($token, $include = array(), $exclude = array()) - { - foreach (array_merge(array('\\'), array_diff(self::$_specials, $exclude), $include) as $char) { - $token = str_replace($char, '\\'.$char, $token); - } - - return $token; - } -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php index 510dd6637b3..062be7d7967 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php @@ -31,7 +31,7 @@ class Swift_Mime_HeaderEncoder_QpHeaderEncoder extends Swift_Encoder_QpEncoder i range(0x61, 0x7A), range(0x41, 0x5A), range(0x30, 0x39), array(0x20, 0x21, 0x2A, 0x2B, 0x2D, 0x2F) ) as $byte) { - $this->_safeMap[$byte] = chr($byte); + $this->safeMap[$byte] = chr($byte); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php deleted file mode 100644 index c65f26d7213..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php +++ /dev/null @@ -1,78 +0,0 @@ -setGrammar($grammar); - } + private $cachedValue = null; /** * Set the character set used in this Header. @@ -81,10 +66,10 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function setCharset($charset) { - $this->clearCachedValueIf($charset != $this->_charset); - $this->_charset = $charset; - if (isset($this->_encoder)) { - $this->_encoder->charsetChanged($charset); + $this->clearCachedValueIf($charset != $this->charset); + $this->charset = $charset; + if (isset($this->encoder)) { + $this->encoder->charsetChanged($charset); } } @@ -95,7 +80,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function getCharset() { - return $this->_charset; + return $this->charset; } /** @@ -108,8 +93,8 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function setLanguage($lang) { - $this->clearCachedValueIf($this->_lang != $lang); - $this->_lang = $lang; + $this->clearCachedValueIf($this->lang != $lang); + $this->lang = $lang; } /** @@ -119,7 +104,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function getLanguage() { - return $this->_lang; + return $this->lang; } /** @@ -129,7 +114,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function setEncoder(Swift_Mime_HeaderEncoder $encoder) { - $this->_encoder = $encoder; + $this->encoder = $encoder; $this->setCachedValue(null); } @@ -140,28 +125,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function getEncoder() { - return $this->_encoder; - } - - /** - * Set the grammar used for the header. - * - * @param Swift_Mime_Grammar $grammar - */ - public function setGrammar(Swift_Mime_Grammar $grammar) - { - $this->_grammar = $grammar; - $this->setCachedValue(null); - } - - /** - * Get the grammar used for this Header. - * - * @return Swift_Mime_Grammar - */ - public function getGrammar() - { - return $this->_grammar; + return $this->encoder; } /** @@ -171,7 +135,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function getFieldName() { - return $this->_name; + return $this->name; } /** @@ -181,8 +145,8 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function setMaxLineLength($lineLength) { - $this->clearCachedValueIf($this->_lineLength != $lineLength); - $this->_lineLength = $lineLength; + $this->clearCachedValueIf($this->lineLength != $lineLength); + $this->lineLength = $lineLength; } /** @@ -192,19 +156,19 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function getMaxLineLength() { - return $this->_lineLength; + return $this->lineLength; } /** * Get this Header rendered as a RFC 2822 compliant string. * - * @throws Swift_RfcComplianceException - * * @return string + * + * @throws Swift_RfcComplianceException */ public function toString() { - return $this->_tokensToString($this->toTokens()); + return $this->tokensToString($this->toTokens()); } /** @@ -219,8 +183,6 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header return $this->toString(); } - // -- Points of extension - /** * Set the name of this Header field. * @@ -228,7 +190,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ protected function setFieldName($name) { - $this->_name = $name; + $this->name = $name; } /** @@ -247,13 +209,12 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header // Treat token as exactly what was given $phraseStr = $string; // If it's not valid - if (!preg_match('/^'.$this->getGrammar()->getDefinition('phrase').'$/D', $phraseStr)) { + + if (!preg_match('/^'.self::PHRASE_PATTERN.'$/D', $phraseStr)) { // .. but it is just ascii text, try escaping some characters // and make it a quoted-string - if (preg_match('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $phraseStr)) { - $phraseStr = $this->getGrammar()->escapeSpecials( - $phraseStr, array('"'), $this->getGrammar()->getSpecials() - ); + if (preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $phraseStr)) { + $phraseStr = $this->escapeSpecials($phraseStr, array('"')); $phraseStr = '"'.$phraseStr.'"'; } else { // ... otherwise it needs encoding @@ -270,6 +231,23 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header return $phraseStr; } + /** + * Escape special characters in a string (convert to quoted-pairs). + * + * @param string $token + * @param string[] $include additional chars to escape + * + * @return string + */ + private function escapeSpecials($token, $include = array()) + { + foreach (array_merge(array('\\'), $include) as $char) { + $token = str_replace($char, '\\'.$char, $token); + } + + return $token; + } + /** * Encode needed word tokens within a string of input. * @@ -365,12 +343,12 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header protected function getTokenAsEncodedWord($token, $firstLineOffset = 0) { // Adjust $firstLineOffset to account for space needed for syntax - $charsetDecl = $this->_charset; - if (isset($this->_lang)) { - $charsetDecl .= '*'.$this->_lang; + $charsetDecl = $this->charset; + if (isset($this->lang)) { + $charsetDecl .= '*'.$this->lang; } $encodingWrapperLength = strlen( - '=?'.$charsetDecl.'?'.$this->_encoder->getName().'??=' + '=?'.$charsetDecl.'?'.$this->encoder->getName().'??=' ); if ($firstLineOffset >= 75) { @@ -379,16 +357,16 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header } $encodedTextLines = explode("\r\n", - $this->_encoder->encodeString( - $token, $firstLineOffset, 75 - $encodingWrapperLength, $this->_charset + $this->encoder->encodeString( + $token, $firstLineOffset, 75 - $encodingWrapperLength, $this->charset ) ); - if (strtolower($this->_charset) !== 'iso-2022-jp') { + if (strtolower($this->charset) !== 'iso-2022-jp') { // special encoding for iso-2022-jp using mb_encode_mimeheader foreach ($encodedTextLines as $lineNum => $line) { $encodedTextLines[$lineNum] = '=?'.$charsetDecl. - '?'.$this->_encoder->getName(). + '?'.$this->encoder->getName(). '?'.$line.'?='; } } @@ -415,7 +393,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ protected function setCachedValue($value) { - $this->_cachedValue = $value; + $this->cachedValue = $value; } /** @@ -425,7 +403,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ protected function getCachedValue() { - return $this->_cachedValue; + return $this->cachedValue; } /** @@ -449,7 +427,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ protected function toTokens($string = null) { - if (is_null($string)) { + if (null === $string) { $string = $this->getFieldBody(); } @@ -474,18 +452,18 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header * * @return string */ - private function _tokensToString(array $tokens) + private function tokensToString(array $tokens) { $lineCount = 0; $headerLines = array(); - $headerLines[] = $this->_name.': '; + $headerLines[] = $this->name.': '; $currentLine = &$headerLines[$lineCount++]; // Build all tokens back into compliant header foreach ($tokens as $i => $token) { // Line longer than specified maximum or token was just a new line if (("\r\n" == $token) || - ($i > 0 && strlen($currentLine.$token) > $this->_lineLength) + ($i > 0 && strlen($currentLine.$token) > $this->lineLength) && 0 < strlen($currentLine)) { $headerLines[] = ''; $currentLine = &$headerLines[$lineCount++]; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php index 4fd6674296e..6dcc92bfdd6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php @@ -16,29 +16,20 @@ class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader { /** - * The UNIX timestamp value of this Header. + * Date-time value of this Header. * - * @var int + * @var DateTimeImmutable */ - private $_timestamp; + private $dateTime; /** - * Creates a new DateHeader with $name and $timestamp. + * Creates a new DateHeader with $name. * - * Example: - * - * - * - * - * @param string $name of Header - * @param Swift_Mime_Grammar $grammar + * @param string $name of Header */ - public function __construct($name, Swift_Mime_Grammar $grammar) + public function __construct($name) { $this->setFieldName($name); - parent::__construct($grammar); } /** @@ -57,49 +48,48 @@ class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader /** * Set the model for the field body. * - * This method takes a UNIX timestamp. - * - * @param int $model + * @param DateTimeInterface $model */ public function setFieldBodyModel($model) { - $this->setTimestamp($model); + $this->setDateTime($model); } /** * Get the model for the field body. * - * This method returns a UNIX timestamp. - * - * @return mixed + * @return DateTimeImmutable */ public function getFieldBodyModel() { - return $this->getTimestamp(); + return $this->getDateTime(); } /** - * Get the UNIX timestamp of the Date in this Header. + * Get the date-time representing the Date in this Header. * - * @return int + * @return DateTimeImmutable */ - public function getTimestamp() + public function getDateTime() { - return $this->_timestamp; + return $this->dateTime; } /** - * Set the UNIX timestamp of the Date in this Header. + * Set the date-time of the Date in this Header. * - * @param int $timestamp + * If a DateTime instance is provided, it is converted to DateTimeImmutable. + * + * @param DateTimeInterface $dateTime */ - public function setTimestamp($timestamp) + public function setDateTime(DateTimeInterface $dateTime) { - if (!is_null($timestamp)) { - $timestamp = (int) $timestamp; + $this->clearCachedValueIf($this->getCachedValue() != $dateTime->format(DateTime::RFC2822)); + if ($dateTime instanceof DateTime) { + $immutable = new DateTimeImmutable('@'.$dateTime->getTimestamp()); + $dateTime = $immutable->setTimezone($dateTime->getTimezone()); } - $this->clearCachedValueIf($this->_timestamp != $timestamp); - $this->_timestamp = $timestamp; + $this->dateTime = $dateTime; } /** @@ -115,8 +105,8 @@ class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader public function getFieldBody() { if (!$this->getCachedValue()) { - if (isset($this->_timestamp)) { - $this->setCachedValue(date('r', $this->_timestamp)); + if (isset($this->dateTime)) { + $this->setCachedValue($this->dateTime->format(DateTime::RFC2822)); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php index b114506b4a4..acf794479b6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php @@ -8,6 +8,9 @@ * file that was distributed with this source code. */ +use Egulias\EmailValidator\EmailValidator; +use Egulias\EmailValidator\Validation\RFCValidation; + /** * An ID MIME Header for something like Message-ID or Content-ID. * @@ -22,18 +25,25 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac * * @var string[] */ - private $_ids = array(); + private $ids = array(); + + /** + * The strict EmailValidator. + * + * @var EmailValidator + */ + private $emailValidator; /** * Creates a new IdentificationHeader with the given $name and $id. * - * @param string $name - * @param Swift_Mime_Grammar $grammar + * @param string $name + * @param EmailValidator $emailValidator */ - public function __construct($name, Swift_Mime_Grammar $grammar) + public function __construct($name, EmailValidator $emailValidator) { $this->setFieldName($name); - parent::__construct($grammar); + $this->emailValidator = $emailValidator; } /** @@ -96,8 +106,8 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac */ public function getId() { - if (count($this->_ids) > 0) { - return $this->_ids[0]; + if (count($this->ids) > 0) { + return $this->ids[0]; } } @@ -113,12 +123,12 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac $actualIds = array(); foreach ($ids as $id) { - $this->_assertValidId($id); + $this->assertValidId($id); $actualIds[] = $id; } - $this->clearCachedValueIf($this->_ids != $actualIds); - $this->_ids = $actualIds; + $this->clearCachedValueIf($this->ids != $actualIds); + $this->ids = $actualIds; } /** @@ -128,7 +138,7 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac */ public function getIds() { - return $this->_ids; + return $this->ids; } /** @@ -148,7 +158,7 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac if (!$this->getCachedValue()) { $angleAddrs = array(); - foreach ($this->_ids as $id) { + foreach ($this->ids as $id) { $angleAddrs[] = '<'.$id.'>'; } @@ -165,16 +175,10 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac * * @throws Swift_RfcComplianceException */ - private function _assertValidId($id) + private function assertValidId($id) { - if (!preg_match( - '/^'.$this->getGrammar()->getDefinition('id-left').'@'. - $this->getGrammar()->getDefinition('id-right').'$/D', - $id - )) { - throw new Swift_RfcComplianceException( - 'Invalid ID given <'.$id.'>' - ); + if (!$this->emailValidator->isValid($id, new RFCValidation())) { + throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>'); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php index 798e7f42ace..450e0f25b7e 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php @@ -8,6 +8,9 @@ * file that was distributed with this source code. */ +use Egulias\EmailValidator\EmailValidator; +use Egulias\EmailValidator\Validation\RFCValidation; + /** * A Mailbox Address MIME Header for something like From or Sender. * @@ -20,20 +23,27 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader * * @var string[] */ - private $_mailboxes = array(); + private $mailboxes = array(); + + /** + * The strict EmailValidator. + * + * @var EmailValidator + */ + private $emailValidator; /** * Creates a new MailboxHeader with $name. * - * @param string $name of Header + * @param string $name of Header * @param Swift_Mime_HeaderEncoder $encoder - * @param Swift_Mime_Grammar $grammar + * @param EmailValidator $emailValidator */ - public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Mime_Grammar $grammar) + public function __construct($name, Swift_Mime_HeaderEncoder $encoder, EmailValidator $emailValidator) { $this->setFieldName($name); $this->setEncoder($encoder); - parent::__construct($grammar); + $this->emailValidator = $emailValidator; } /** @@ -103,7 +113,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ public function setNameAddresses($mailboxes) { - $this->_mailboxes = $this->normalizeMailboxes((array) $mailboxes); + $this->mailboxes = $this->normalizeMailboxes((array) $mailboxes); $this->setCachedValue(null); //Clear any cached value } @@ -134,7 +144,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ public function getNameAddressStrings() { - return $this->_createNameAddressStrings($this->getNameAddresses()); + return $this->createNameAddressStrings($this->getNameAddresses()); } /** @@ -163,7 +173,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ public function getNameAddresses() { - return $this->_mailboxes; + return $this->mailboxes; } /** @@ -200,7 +210,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ public function getAddresses() { - return array_keys($this->_mailboxes); + return array_keys($this->mailboxes); } /** @@ -212,7 +222,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader { $this->setCachedValue(null); foreach ((array) $addresses as $address) { - unset($this->_mailboxes[$address]); + unset($this->mailboxes[$address]); } } @@ -231,15 +241,13 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader public function getFieldBody() { // Compute the string value of the header only if needed - if (is_null($this->getCachedValue())) { - $this->setCachedValue($this->createMailboxListString($this->_mailboxes)); + if (null === $this->getCachedValue()) { + $this->setCachedValue($this->createMailboxListString($this->mailboxes)); } return $this->getCachedValue(); } - // -- Points of extension - /** * Normalizes a user-input list of mailboxes into consistent key=>value pairs. * @@ -260,7 +268,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader $address = $value; $name = null; } - $this->_assertValidAddress($address); + $this->assertValidAddress($address); $actualMailboxes[$address] = $name; } @@ -277,9 +285,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ protected function createDisplayNameString($displayName, $shorten = false) { - return $this->createPhrase($this, $displayName, - $this->getCharset(), $this->getEncoder(), $shorten - ); + return $this->createPhrase($this, $displayName, $this->getCharset(), $this->getEncoder(), $shorten); } /** @@ -293,14 +299,15 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ protected function createMailboxListString(array $mailboxes) { - return implode(', ', $this->_createNameAddressStrings($mailboxes)); + return implode(', ', $this->createNameAddressStrings($mailboxes)); } /** * Redefine the encoding requirements for mailboxes. * - * Commas and semicolons are used to separate - * multiple addresses, and should therefore be encoded + * All "specials" must be encoded as the full header value will not be quoted + * + * @see RFC 2822 3.2.1 * * @param string $token * @@ -308,7 +315,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ protected function tokenNeedsEncoding($token) { - return preg_match('/[,;]/', $token) || parent::tokenNeedsEncoding($token); + return preg_match('/[()<>\[\]:;@\,."]/', $token) || parent::tokenNeedsEncoding($token); } /** @@ -318,13 +325,13 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader * * @return string[] */ - private function _createNameAddressStrings(array $mailboxes) + private function createNameAddressStrings(array $mailboxes) { $strings = array(); foreach ($mailboxes as $email => $name) { $mailboxStr = $email; - if (!is_null($name)) { + if (null !== $name) { $nameStr = $this->createDisplayNameString($name, empty($strings)); $mailboxStr = $nameStr.' <'.$mailboxStr.'>'; } @@ -341,14 +348,12 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader * * @throws Swift_RfcComplianceException If invalid. */ - private function _assertValidAddress($address) + private function assertValidAddress($address) { - if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D', - $address)) { + if (!$this->emailValidator->isValid($address, new RFCValidation())) { throw new Swift_RfcComplianceException( - 'Address in mailbox given ['.$address. - '] does not comply with RFC 2822, 3.6.2.' - ); + 'Address in mailbox given ['.$address.'] does not comply with RFC 2822, 3.6.2.' + ); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php index b52b964b773..29277994c0a 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php @@ -20,25 +20,21 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header * * @var string */ - private $_value; + private $value; /** * The name of this Header. * * @var string */ - private $_fieldName; + private $fieldName; /** - * Creates a new SimpleHeader with $name. - * - * @param string $name - * @param Swift_Mime_HeaderEncoder $encoder - * @param Swift_Mime_Grammar $grammar + * @param string $name */ public function __construct($name) { - $this->_fieldName = $name; + $this->fieldName = $name; } /** @@ -85,7 +81,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header */ public function getValue() { - return $this->_value; + return $this->value; } /** @@ -95,7 +91,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header */ public function setValue($value) { - $this->_value = $value; + $this->value = $value; } /** @@ -105,7 +101,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header */ public function getFieldBody() { - return $this->_value; + return $this->value; } /** @@ -115,7 +111,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header */ public function toString() { - return $this->_fieldName.': '.$this->_value; + return $this->fieldName.': '.$this->value; } /** @@ -125,7 +121,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header */ public function getFieldName() { - return $this->_fieldName; + return $this->fieldName; } /** diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php index c506daec146..b4a0ddf1224 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php @@ -13,7 +13,7 @@ * * @author Chris Corbyn */ -class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_UnstructuredHeader implements Swift_Mime_ParameterizedHeader +class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_UnstructuredHeader { /** * RFC 2231's definition of a token. @@ -27,14 +27,14 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct * * @var Swift_Encoder */ - private $_paramEncoder; + private $paramEncoder; /** * The parameters as an associative array. * * @var string[] */ - private $_params = array(); + private $params = array(); /** * Creates a new ParameterizedHeader with $name. @@ -42,12 +42,11 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct * @param string $name * @param Swift_Mime_HeaderEncoder $encoder * @param Swift_Encoder $paramEncoder, optional - * @param Swift_Mime_Grammar $grammar */ - public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder = null, Swift_Mime_Grammar $grammar) + public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder = null) { - parent::__construct($name, $encoder, $grammar); - $this->_paramEncoder = $paramEncoder; + parent::__construct($name, $encoder); + $this->paramEncoder = $paramEncoder; } /** @@ -71,8 +70,8 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct public function setCharset($charset) { parent::setCharset($charset); - if (isset($this->_paramEncoder)) { - $this->_paramEncoder->charsetChanged($charset); + if (isset($this->paramEncoder)) { + $this->paramEncoder->charsetChanged($charset); } } @@ -98,7 +97,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct { $params = $this->getParameters(); - return array_key_exists($parameter, $params) ? $params[$parameter] : null; + return $params[$parameter] ?? null; } /** @@ -108,8 +107,8 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct */ public function setParameters(array $parameters) { - $this->clearCachedValueIf($this->_params != $parameters); - $this->_params = $parameters; + $this->clearCachedValueIf($this->params != $parameters); + $this->params = $parameters; } /** @@ -119,7 +118,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct */ public function getParameters() { - return $this->_params; + return $this->params; } /** @@ -130,10 +129,10 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct public function getFieldBody() //TODO: Check caching here { $body = parent::getFieldBody(); - foreach ($this->_params as $name => $value) { - if (!is_null($value)) { + foreach ($this->params as $name => $value) { + if (null !== $value) { // Add the parameter - $body .= '; '.$this->_createParameter($name, $value); + $body .= '; '.$this->createParameter($name, $value); } } @@ -155,12 +154,12 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct $tokens = parent::toTokens(parent::getFieldBody()); // Try creating any parameters - foreach ($this->_params as $name => $value) { - if (!is_null($value)) { + foreach ($this->params as $name => $value) { + if (null !== $value) { // Add the semi-colon separator $tokens[count($tokens) - 1] .= ';'; $tokens = array_merge($tokens, $this->generateTokenLines( - ' '.$this->_createParameter($name, $value) + ' '.$this->createParameter($name, $value) )); } } @@ -176,7 +175,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct * * @return string */ - private function _createParameter($name, $value) + private function createParameter($name, $value) { $origValue = $value; @@ -189,7 +188,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { // TODO: text, or something else?? // ... and it's not ascii - if (!preg_match('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $value)) { + if (!preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $value)) { $encoded = true; // Allow space for the indices, charset and language $maxValueLength = $this->getMaxLineLength() - strlen($name.'*N*="";') - 1; @@ -201,8 +200,8 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct // Encode if we need to if ($encoded || strlen($value) > $maxValueLength) { - if (isset($this->_paramEncoder)) { - $value = $this->_paramEncoder->encodeString( + if (isset($this->paramEncoder)) { + $value = $this->paramEncoder->encodeString( $origValue, $firstLineOffset, $maxValueLength, $this->getCharset() ); } else { @@ -212,19 +211,19 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct } } - $valueLines = isset($this->_paramEncoder) ? explode("\r\n", $value) : array($value); + $valueLines = isset($this->paramEncoder) ? explode("\r\n", $value) : array($value); // Need to add indices if (count($valueLines) > 1) { $paramLines = array(); foreach ($valueLines as $i => $line) { $paramLines[] = $name.'*'.$i. - $this->_getEndOfParameterValue($line, true, $i == 0); + $this->getEndOfParameterValue($line, true, $i == 0); } return implode(";\r\n ", $paramLines); } else { - return $name.$this->_getEndOfParameterValue( + return $name.$this->getEndOfParameterValue( $valueLines[0], $encoded, true ); } @@ -239,7 +238,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct * * @return string */ - private function _getEndOfParameterValue($value, $encoded = false, $firstLine = false) + private function getEndOfParameterValue($value, $encoded = false, $firstLine = false) { if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { $value = '"'.$value.'"'; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php index 2fffc7b4aac..f79e19fd8b3 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php @@ -8,6 +8,9 @@ * file that was distributed with this source code. */ +use Egulias\EmailValidator\EmailValidator; +use Egulias\EmailValidator\Validation\RFCValidation; + /** * A Path Header in Swift Mailer, such a Return-Path. * @@ -20,18 +23,25 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader * * @var string */ - private $_address; + private $address; + + /** + * The strict EmailValidator. + * + * @var EmailValidator + */ + private $emailValidator; /** * Creates a new PathHeader with the given $name. * - * @param string $name - * @param Swift_Mime_Grammar $grammar + * @param string $name + * @param EmailValidator $emailValidator */ - public function __construct($name, Swift_Mime_Grammar $grammar) + public function __construct($name, EmailValidator $emailValidator) { $this->setFieldName($name); - parent::__construct($grammar); + $this->emailValidator = $emailValidator; } /** @@ -80,13 +90,13 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader */ public function setAddress($address) { - if (is_null($address)) { - $this->_address = null; + if (null === $address) { + $this->address = null; } elseif ('' == $address) { - $this->_address = ''; + $this->address = ''; } else { - $this->_assertValidAddress($address); - $this->_address = $address; + $this->assertValidAddress($address); + $this->address = $address; } $this->setCachedValue(null); } @@ -100,7 +110,7 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader */ public function getAddress() { - return $this->_address; + return $this->address; } /** @@ -116,8 +126,8 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader public function getFieldBody() { if (!$this->getCachedValue()) { - if (isset($this->_address)) { - $this->setCachedValue('<'.$this->_address.'>'); + if (isset($this->address)) { + $this->setCachedValue('<'.$this->address.'>'); } } @@ -131,13 +141,12 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader * * @throws Swift_RfcComplianceException If address is invalid */ - private function _assertValidAddress($address) + private function assertValidAddress($address) { - if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D', - $address)) { + if (!$this->emailValidator->isValid($address, new RFCValidation())) { throw new Swift_RfcComplianceException( 'Address set in PathHeader does not comply with addr-spec of RFC 2822.' - ); + ); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php index 86177f14a1f..d9d9f5e25d3 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php @@ -20,20 +20,18 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH * * @var string */ - private $_value; + private $value; /** * Creates a new SimpleHeader with $name. * * @param string $name * @param Swift_Mime_HeaderEncoder $encoder - * @param Swift_Mime_Grammar $grammar */ - public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Mime_Grammar $grammar) + public function __construct($name, Swift_Mime_HeaderEncoder $encoder) { $this->setFieldName($name); $this->setEncoder($encoder); - parent::__construct($grammar); } /** @@ -80,7 +78,7 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH */ public function getValue() { - return $this->_value; + return $this->value; } /** @@ -90,8 +88,8 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH */ public function setValue($value) { - $this->clearCachedValueIf($this->_value != $value); - $this->_value = $value; + $this->clearCachedValueIf($this->value != $value); + $this->value = $value; } /** @@ -103,7 +101,7 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH { if (!$this->getCachedValue()) { $this->setCachedValue( - $this->encodeWords($this, $this->_value) + $this->encodeWords($this, $this->value) ); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php new file mode 100644 index 00000000000..6e98ee8975d --- /dev/null +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php @@ -0,0 +1,53 @@ +idRight = $idRight; + } + + /** + * Returns the right-hand side of the "@" used in all generated IDs. + * + * @return string + */ + public function getIdRight() + { + return $this->idRight; + } + + /** + * Sets the right-hand side of the "@" to use in all generated IDs. + * + * @param string $idRight + */ + public function setIdRight($idRight) + { + $this->idRight = $idRight; + } + + /** + * @return string + */ + public function generateId() + { + $idLeft = bin2hex(random_bytes(16)); // set 32 hex values + + return $idLeft.'@'.$this->idRight; + } +} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Message.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Message.php deleted file mode 100644 index 9b36d216271..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Message.php +++ /dev/null @@ -1,223 +0,0 @@ - 'Real Name'). - * - * If the second parameter is provided and the first is a string, then $name - * is associated with the address. - * - * @param mixed $address - * @param string $name optional - */ - public function setSender($address, $name = null); - - /** - * Get the sender address for this message. - * - * This has a higher significance than the From address. - * - * @return string - */ - public function getSender(); - - /** - * Set the From address of this message. - * - * It is permissible for multiple From addresses to be set using an array. - * - * If multiple From addresses are used, you SHOULD set the Sender address and - * according to RFC 2822, MUST set the sender address. - * - * An array can be used if display names are to be provided: i.e. - * array('email@address.com' => 'Real Name'). - * - * If the second parameter is provided and the first is a string, then $name - * is associated with the address. - * - * @param mixed $addresses - * @param string $name optional - */ - public function setFrom($addresses, $name = null); - - /** - * Get the From address(es) of this message. - * - * This method always returns an associative array where the keys are the - * addresses. - * - * @return string[] - */ - public function getFrom(); - - /** - * Set the Reply-To address(es). - * - * Any replies from the receiver will be sent to this address. - * - * It is permissible for multiple reply-to addresses to be set using an array. - * - * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. - * - * If the second parameter is provided and the first is a string, then $name - * is associated with the address. - * - * @param mixed $addresses - * @param string $name optional - */ - public function setReplyTo($addresses, $name = null); - - /** - * Get the Reply-To addresses for this message. - * - * This method always returns an associative array where the keys provide the - * email addresses. - * - * @return string[] - */ - public function getReplyTo(); - - /** - * Set the To address(es). - * - * Recipients set in this field will receive a copy of this message. - * - * This method has the same synopsis as {@link setFrom()} and {@link setCc()}. - * - * If the second parameter is provided and the first is a string, then $name - * is associated with the address. - * - * @param mixed $addresses - * @param string $name optional - */ - public function setTo($addresses, $name = null); - - /** - * Get the To addresses for this message. - * - * This method always returns an associative array, whereby the keys provide - * the actual email addresses. - * - * @return string[] - */ - public function getTo(); - - /** - * Set the Cc address(es). - * - * Recipients set in this field will receive a 'carbon-copy' of this message. - * - * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. - * - * @param mixed $addresses - * @param string $name optional - */ - public function setCc($addresses, $name = null); - - /** - * Get the Cc addresses for this message. - * - * This method always returns an associative array, whereby the keys provide - * the actual email addresses. - * - * @return string[] - */ - public function getCc(); - - /** - * Set the Bcc address(es). - * - * Recipients set in this field will receive a 'blind-carbon-copy' of this - * message. - * - * In other words, they will get the message, but any other recipients of the - * message will have no such knowledge of their receipt of it. - * - * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. - * - * @param mixed $addresses - * @param string $name optional - */ - public function setBcc($addresses, $name = null); - - /** - * Get the Bcc addresses for this message. - * - * This method always returns an associative array, whereby the keys provide - * the actual email addresses. - * - * @return string[] - */ - public function getBcc(); -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php deleted file mode 100644 index 30f460cdcdb..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php +++ /dev/null @@ -1,117 +0,0 @@ -setContentType('text/plain'); - if (!is_null($charset)) { + if (null !== $charset) { $this->setCharset($charset); } } @@ -53,14 +53,14 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity * @param string $contentType optional * @param string $charset optional * - * @return Swift_Mime_MimePart + * @return $this */ public function setBody($body, $contentType = null, $charset = null) { if (isset($charset)) { $this->setCharset($charset); } - $body = $this->_convertString($body); + $body = $this->convertString($body); parent::setBody($body, $contentType); @@ -74,7 +74,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity */ public function getCharset() { - return $this->_getHeaderParameter('Content-Type', 'charset'); + return $this->getHeaderParameter('Content-Type', 'charset'); } /** @@ -82,15 +82,15 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity * * @param string $charset * - * @return Swift_Mime_MimePart + * @return $this */ public function setCharset($charset) { - $this->_setHeaderParameter('Content-Type', 'charset', $charset); - if ($charset !== $this->_userCharset) { - $this->_clearCache(); + $this->setHeaderParameter('Content-Type', 'charset', $charset); + if ($charset !== $this->userCharset) { + $this->clearCache(); } - $this->_userCharset = $charset; + $this->userCharset = $charset; parent::charsetChanged($charset); return $this; @@ -103,7 +103,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity */ public function getFormat() { - return $this->_getHeaderParameter('Content-Type', 'format'); + return $this->getHeaderParameter('Content-Type', 'format'); } /** @@ -111,12 +111,12 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity * * @param string $format * - * @return Swift_Mime_MimePart + * @return $this */ public function setFormat($format) { - $this->_setHeaderParameter('Content-Type', 'format', $format); - $this->_userFormat = $format; + $this->setHeaderParameter('Content-Type', 'format', $format); + $this->userFormat = $format; return $this; } @@ -128,7 +128,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity */ public function getDelSp() { - return 'yes' == $this->_getHeaderParameter('Content-Type', 'delsp') ? true : false; + return 'yes' === $this->getHeaderParameter('Content-Type', 'delsp'); } /** @@ -136,12 +136,12 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity * * @param bool $delsp * - * @return Swift_Mime_MimePart + * @return $this */ public function setDelSp($delsp = true) { - $this->_setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null); - $this->_userDelSp = $delsp; + $this->setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null); + $this->userDelSp = $delsp; return $this; } @@ -155,7 +155,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity */ public function getNestingLevel() { - return $this->_nestingLevel; + return $this->nestingLevel; } /** @@ -170,31 +170,31 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity } /** Fix the content-type and encoding of this entity */ - protected function _fixHeaders() + protected function fixHeaders() { - parent::_fixHeaders(); + parent::fixHeaders(); if (count($this->getChildren())) { - $this->_setHeaderParameter('Content-Type', 'charset', null); - $this->_setHeaderParameter('Content-Type', 'format', null); - $this->_setHeaderParameter('Content-Type', 'delsp', null); + $this->setHeaderParameter('Content-Type', 'charset', null); + $this->setHeaderParameter('Content-Type', 'format', null); + $this->setHeaderParameter('Content-Type', 'delsp', null); } else { - $this->setCharset($this->_userCharset); - $this->setFormat($this->_userFormat); - $this->setDelSp($this->_userDelSp); + $this->setCharset($this->userCharset); + $this->setFormat($this->userFormat); + $this->setDelSp($this->userDelSp); } } /** Set the nesting level of this entity */ - protected function _setNestingLevel($level) + protected function setNestingLevel($level) { - $this->_nestingLevel = $level; + $this->nestingLevel = $level; } /** Encode charset when charset is not utf-8 */ - protected function _convertString($string) + protected function convertString($string) { $charset = strtolower($this->getCharset()); - if (!in_array($charset, array('utf-8', 'iso-8859-1', ''))) { + if (!in_array($charset, array('utf-8', 'iso-8859-1', 'iso-8859-15', ''))) { // mb_convert_encoding must be the first one to check, since iconv cannot convert some words. if (function_exists('mb_convert_encoding')) { $string = mb_convert_encoding($string, $charset, 'utf-8'); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php deleted file mode 100644 index e15c6ef95b1..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php +++ /dev/null @@ -1,34 +0,0 @@ -_encoder = $encoder; - $this->_paramEncoder = $paramEncoder; - $this->_grammar = $grammar; - $this->_charset = $charset; + $this->encoder = $encoder; + $this->paramEncoder = $paramEncoder; + $this->emailValidator = $emailValidator; + $this->charset = $charset; } /** @@ -53,30 +58,30 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function createMailboxHeader($name, $addresses = null) { - $header = new Swift_Mime_Headers_MailboxHeader($name, $this->_encoder, $this->_grammar); + $header = new Swift_Mime_Headers_MailboxHeader($name, $this->encoder, $this->emailValidator); if (isset($addresses)) { $header->setFieldBodyModel($addresses); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } /** - * Create a new Date header using $timestamp (UNIX time). + * Create a new Date header using $dateTime. * - * @param string $name - * @param int|null $timestamp + * @param string $name + * @param DateTimeInterface|null $dateTime * * @return Swift_Mime_Header */ - public function createDateHeader($name, $timestamp = null) + public function createDateHeader($name, DateTimeInterface $dateTime = null) { - $header = new Swift_Mime_Headers_DateHeader($name, $this->_grammar); - if (isset($timestamp)) { - $header->setFieldBodyModel($timestamp); + $header = new Swift_Mime_Headers_DateHeader($name); + if (isset($dateTime)) { + $header->setFieldBodyModel($dateTime); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } @@ -91,11 +96,11 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function createTextHeader($name, $value = null) { - $header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->_encoder, $this->_grammar); + $header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->encoder); if (isset($value)) { $header->setFieldBodyModel($value); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } @@ -107,19 +112,18 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory * @param string $value * @param array $params * - * @return Swift_Mime_ParameterizedHeader + * @return Swift_Mime_Headers_ParameterizedHeader */ - public function createParameterizedHeader($name, $value = null, - $params = array()) + public function createParameterizedHeader($name, $value = null, $params = array()) { - $header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->_encoder, strtolower($name) == 'content-disposition' ? $this->_paramEncoder : null, $this->_grammar); + $header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->encoder, (strtolower($name) == 'content-disposition') ? $this->paramEncoder : null); if (isset($value)) { $header->setFieldBodyModel($value); } foreach ($params as $k => $v) { $header->setParameter($k, $v); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } @@ -134,11 +138,11 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function createIdHeader($name, $ids = null) { - $header = new Swift_Mime_Headers_IdentificationHeader($name, $this->_grammar); + $header = new Swift_Mime_Headers_IdentificationHeader($name, $this->emailValidator); if (isset($ids)) { $header->setFieldBodyModel($ids); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } @@ -153,11 +157,11 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function createPathHeader($name, $path = null) { - $header = new Swift_Mime_Headers_PathHeader($name, $this->_grammar); + $header = new Swift_Mime_Headers_PathHeader($name, $this->emailValidator); if (isset($path)) { $header->setFieldBodyModel($path); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } @@ -169,9 +173,9 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function charsetChanged($charset) { - $this->_charset = $charset; - $this->_encoder->charsetChanged($charset); - $this->_paramEncoder->charsetChanged($charset); + $this->charset = $charset; + $this->encoder->charsetChanged($charset); + $this->paramEncoder->charsetChanged($charset); } /** @@ -179,15 +183,15 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function __clone() { - $this->_encoder = clone $this->_encoder; - $this->_paramEncoder = clone $this->_paramEncoder; + $this->encoder = clone $this->encoder; + $this->paramEncoder = clone $this->paramEncoder; } /** Apply the charset to the Header */ - private function _setHeaderCharset(Swift_Mime_Header $header) + private function setHeaderCharset(Swift_Mime_Header $header) { - if (isset($this->_charset)) { - $header->setCharset($this->_charset); + if (isset($this->charset)) { + $header->setCharset($this->charset); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php index cf8bf14a750..6f71fcac132 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php @@ -13,37 +13,42 @@ * * @author Chris Corbyn */ -class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet +class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver { /** HeaderFactory */ - private $_factory; + private $factory; /** Collection of set Headers */ - private $_headers = array(); + private $headers = array(); /** Field ordering details */ - private $_order = array(); + private $order = array(); /** List of fields which are required to be displayed */ - private $_required = array(); + private $required = array(); /** The charset used by Headers */ - private $_charset; + private $charset; /** * Create a new SimpleHeaderSet with the given $factory. * - * @param Swift_Mime_HeaderFactory $factory - * @param string $charset + * @param Swift_Mime_SimpleHeaderFactory $factory + * @param string $charset */ - public function __construct(Swift_Mime_HeaderFactory $factory, $charset = null) + public function __construct(Swift_Mime_SimpleHeaderFactory $factory, $charset = null) { - $this->_factory = $factory; + $this->factory = $factory; if (isset($charset)) { $this->setCharset($charset); } } + public function newInstance() + { + return new self($this->factory); + } + /** * Set the charset used by these headers. * @@ -51,9 +56,9 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function setCharset($charset) { - $this->_charset = $charset; - $this->_factory->charsetChanged($charset); - $this->_notifyHeadersOfCharset($charset); + $this->charset = $charset; + $this->factory->charsetChanged($charset); + $this->notifyHeadersOfCharset($charset); } /** @@ -64,20 +69,20 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function addMailboxHeader($name, $addresses = null) { - $this->_storeHeader($name, - $this->_factory->createMailboxHeader($name, $addresses)); + $this->storeHeader($name, + $this->factory->createMailboxHeader($name, $addresses)); } /** - * Add a new Date header using $timestamp (UNIX time). + * Add a new Date header using $dateTime. * - * @param string $name - * @param int $timestamp + * @param string $name + * @param DateTimeInterface $dateTime */ - public function addDateHeader($name, $timestamp = null) + public function addDateHeader($name, DateTimeInterface $dateTime = null) { - $this->_storeHeader($name, - $this->_factory->createDateHeader($name, $timestamp)); + $this->storeHeader($name, + $this->factory->createDateHeader($name, $dateTime)); } /** @@ -88,8 +93,8 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function addTextHeader($name, $value = null) { - $this->_storeHeader($name, - $this->_factory->createTextHeader($name, $value)); + $this->storeHeader($name, + $this->factory->createTextHeader($name, $value)); } /** @@ -101,7 +106,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function addParameterizedHeader($name, $value = null, $params = array()) { - $this->_storeHeader($name, $this->_factory->createParameterizedHeader($name, $value, $params)); + $this->storeHeader($name, $this->factory->createParameterizedHeader($name, $value, $params)); } /** @@ -112,7 +117,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function addIdHeader($name, $ids = null) { - $this->_storeHeader($name, $this->_factory->createIdHeader($name, $ids)); + $this->storeHeader($name, $this->factory->createIdHeader($name, $ids)); } /** @@ -123,7 +128,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function addPathHeader($name, $path = null) { - $this->_storeHeader($name, $this->_factory->createPathHeader($name, $path)); + $this->storeHeader($name, $this->factory->createPathHeader($name, $path)); } /** @@ -140,7 +145,16 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet { $lowerName = strtolower($name); - return array_key_exists($lowerName, $this->_headers) && array_key_exists($index, $this->_headers[$lowerName]); + if (!array_key_exists($lowerName, $this->headers)) { + return false; + } + + if (func_num_args() < 2) { + // index was not specified, so we only need to check that there is at least one header value set + return (bool) count($this->headers[$lowerName]); + } + + return array_key_exists($index, $this->headers[$lowerName]); } /** @@ -157,7 +171,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function set(Swift_Mime_Header $header, $index = 0) { - $this->_storeHeader($header->getFieldName(), $header, $index); + $this->storeHeader($header->getFieldName(), $header, $index); } /** @@ -173,10 +187,18 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function get($name, $index = 0) { - if ($this->has($name, $index)) { - $lowerName = strtolower($name); + $name = strtolower($name); - return $this->_headers[$lowerName][$index]; + if (func_num_args() < 2) { + if ($this->has($name)) { + $values = array_values($this->headers[$name]); + + return array_shift($values); + } + } else { + if ($this->has($name, $index)) { + return $this->headers[$name][$index]; + } } } @@ -191,7 +213,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet { if (!isset($name)) { $headers = array(); - foreach ($this->_headers as $collection) { + foreach ($this->headers as $collection) { $headers = array_merge($headers, $collection); } @@ -199,11 +221,11 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet } $lowerName = strtolower($name); - if (!array_key_exists($lowerName, $this->_headers)) { + if (!array_key_exists($lowerName, $this->headers)) { return array(); } - return $this->_headers[$lowerName]; + return $this->headers[$lowerName]; } /** @@ -213,9 +235,9 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function listAll() { - $headers = $this->_headers; - if ($this->_canSort()) { - uksort($headers, array($this, '_sortHeaders')); + $headers = $this->headers; + if ($this->canSort()) { + uksort($headers, array($this, 'sortHeaders')); } return array_keys($headers); @@ -232,7 +254,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet public function remove($name, $index = 0) { $lowerName = strtolower($name); - unset($this->_headers[$lowerName][$index]); + unset($this->headers[$lowerName][$index]); } /** @@ -243,17 +265,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet public function removeAll($name) { $lowerName = strtolower($name); - unset($this->_headers[$lowerName]); - } - - /** - * Create a new instance of this HeaderSet. - * - * @return Swift_Mime_HeaderSet - */ - public function newInstance() - { - return new self($this->_factory); + unset($this->headers[$lowerName]); } /** @@ -265,7 +277,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function defineOrdering(array $sequence) { - $this->_order = array_flip(array_map('strtolower', $sequence)); + $this->order = array_flip(array_map('strtolower', $sequence)); } /** @@ -277,7 +289,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function setAlwaysDisplayed(array $names) { - $this->_required = array_flip(array_map('strtolower', $names)); + $this->required = array_flip(array_map('strtolower', $names)); } /** @@ -298,13 +310,13 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet public function toString() { $string = ''; - $headers = $this->_headers; - if ($this->_canSort()) { - uksort($headers, array($this, '_sortHeaders')); + $headers = $this->headers; + if ($this->canSort()) { + uksort($headers, array($this, 'sortHeaders')); } foreach ($headers as $collection) { foreach ($collection as $header) { - if ($this->_isDisplayed($header) || $header->getFieldBody() != '') { + if ($this->isDisplayed($header) || $header->getFieldBody() != '') { $string .= $header->toString(); } } @@ -326,31 +338,31 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet } /** Save a Header to the internal collection */ - private function _storeHeader($name, Swift_Mime_Header $header, $offset = null) + private function storeHeader($name, Swift_Mime_Header $header, $offset = null) { - if (!isset($this->_headers[strtolower($name)])) { - $this->_headers[strtolower($name)] = array(); + if (!isset($this->headers[strtolower($name)])) { + $this->headers[strtolower($name)] = array(); } if (!isset($offset)) { - $this->_headers[strtolower($name)][] = $header; + $this->headers[strtolower($name)][] = $header; } else { - $this->_headers[strtolower($name)][$offset] = $header; + $this->headers[strtolower($name)][$offset] = $header; } } /** Test if the headers can be sorted */ - private function _canSort() + private function canSort() { - return count($this->_order) > 0; + return count($this->order) > 0; } /** uksort() algorithm for Header ordering */ - private function _sortHeaders($a, $b) + private function sortHeaders($a, $b) { $lowerA = strtolower($a); $lowerB = strtolower($b); - $aPos = array_key_exists($lowerA, $this->_order) ? $this->_order[$lowerA] : -1; - $bPos = array_key_exists($lowerB, $this->_order) ? $this->_order[$lowerB] : -1; + $aPos = array_key_exists($lowerA, $this->order) ? $this->order[$lowerA] : -1; + $bPos = array_key_exists($lowerB, $this->order) ? $this->order[$lowerB] : -1; if (-1 === $aPos && -1 === $bPos) { // just be sure to be determinist here @@ -367,15 +379,15 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet } /** Test if the given Header is always displayed */ - private function _isDisplayed(Swift_Mime_Header $header) + private function isDisplayed(Swift_Mime_Header $header) { - return array_key_exists(strtolower($header->getFieldName()), $this->_required); + return array_key_exists(strtolower($header->getFieldName()), $this->required); } /** Notify all Headers of the new charset */ - private function _notifyHeadersOfCharset($charset) + private function notifyHeadersOfCharset($charset) { - foreach ($this->_headers as $headerGroup) { + foreach ($this->headers as $headerGroup) { foreach ($headerGroup as $header) { $header->setCharset($charset); } @@ -387,10 +399,10 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function __clone() { - $this->_factory = clone $this->_factory; - foreach ($this->_headers as $groupKey => $headerGroup) { + $this->factory = clone $this->factory; + foreach ($this->headers as $groupKey => $headerGroup) { foreach ($headerGroup as $key => $header) { - $this->_headers[$groupKey][$key] = clone $header; + $this->headers[$groupKey][$key] = clone $header; } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php index 124644b5a93..768de07f812 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php @@ -13,20 +13,26 @@ * * @author Chris Corbyn */ -class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime_Message +class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart { + const PRIORITY_HIGHEST = 1; + const PRIORITY_HIGH = 2; + const PRIORITY_NORMAL = 3; + const PRIORITY_LOW = 4; + const PRIORITY_LOWEST = 5; + /** * Create a new SimpleMessage with $headers, $encoder and $cache. * - * @param Swift_Mime_HeaderSet $headers - * @param Swift_Mime_ContentEncoder $encoder - * @param Swift_KeyCache $cache - * @param Swift_Mime_Grammar $grammar - * @param string $charset + * @param Swift_Mime_SimpleHeaderSet $headers + * @param Swift_Mime_ContentEncoder $encoder + * @param Swift_KeyCache $cache + * @param Swift_IdGenerator $idGenerator + * @param string $charset */ - public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $charset = null) + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null) { - parent::__construct($headers, $encoder, $cache, $grammar, $charset); + parent::__construct($headers, $encoder, $cache, $idGenerator, $charset); $this->getHeaders()->defineOrdering(array( 'Return-Path', 'Received', @@ -47,7 +53,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime )); $this->getHeaders()->setAlwaysDisplayed(array('Date', 'Message-ID', 'From')); $this->getHeaders()->addTextHeader('MIME-Version', '1.0'); - $this->setDate(time()); + $this->setDate(new DateTimeImmutable()); $this->setId($this->getId()); $this->getHeaders()->addMailboxHeader('From'); } @@ -67,11 +73,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * * @param string $subject * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setSubject($subject) { - if (!$this->_setHeaderFieldModel('Subject', $subject)) { + if (!$this->setHeaderFieldModel('Subject', $subject)) { $this->getHeaders()->addTextHeader('Subject', $subject); } @@ -85,20 +91,20 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getSubject() { - return $this->_getHeaderFieldModel('Subject'); + return $this->getHeaderFieldModel('Subject'); } /** * Set the date at which this message was created. * - * @param int $date + * @param DateTimeInterface $dateTime * - * @return Swift_Mime_SimpleMessage + * @return $this */ - public function setDate($date) + public function setDate(DateTimeInterface $dateTime) { - if (!$this->_setHeaderFieldModel('Date', $date)) { - $this->getHeaders()->addDateHeader('Date', $date); + if (!$this->setHeaderFieldModel('Date', $dateTime)) { + $this->getHeaders()->addDateHeader('Date', $dateTime); } return $this; @@ -107,11 +113,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime /** * Get the date at which this message was created. * - * @return int + * @return DateTimeInterface */ public function getDate() { - return $this->_getHeaderFieldModel('Date'); + return $this->getHeaderFieldModel('Date'); } /** @@ -119,11 +125,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * * @param string $address * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setReturnPath($address) { - if (!$this->_setHeaderFieldModel('Return-Path', $address)) { + if (!$this->setHeaderFieldModel('Return-Path', $address)) { $this->getHeaders()->addPathHeader('Return-Path', $address); } @@ -137,7 +143,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getReturnPath() { - return $this->_getHeaderFieldModel('Return-Path'); + return $this->getHeaderFieldModel('Return-Path'); } /** @@ -148,7 +154,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setSender($address, $name = null) { @@ -156,7 +162,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $address = array($address => $name); } - if (!$this->_setHeaderFieldModel('Sender', (array) $address)) { + if (!$this->setHeaderFieldModel('Sender', (array) $address)) { $this->getHeaders()->addMailboxHeader('Sender', (array) $address); } @@ -170,7 +176,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getSender() { - return $this->_getHeaderFieldModel('Sender'); + return $this->getHeaderFieldModel('Sender'); } /** @@ -181,7 +187,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addFrom($address, $name = null) { @@ -202,7 +208,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string|array $addresses * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setFrom($addresses, $name = null) { @@ -210,7 +216,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $addresses = array($addresses => $name); } - if (!$this->_setHeaderFieldModel('From', (array) $addresses)) { + if (!$this->setHeaderFieldModel('From', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('From', (array) $addresses); } @@ -224,7 +230,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getFrom() { - return $this->_getHeaderFieldModel('From'); + return $this->getHeaderFieldModel('From'); } /** @@ -235,7 +241,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addReplyTo($address, $name = null) { @@ -256,7 +262,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param mixed $addresses * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setReplyTo($addresses, $name = null) { @@ -264,7 +270,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $addresses = array($addresses => $name); } - if (!$this->_setHeaderFieldModel('Reply-To', (array) $addresses)) { + if (!$this->setHeaderFieldModel('Reply-To', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('Reply-To', (array) $addresses); } @@ -278,7 +284,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getReplyTo() { - return $this->_getHeaderFieldModel('Reply-To'); + return $this->getHeaderFieldModel('Reply-To'); } /** @@ -289,7 +295,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addTo($address, $name = null) { @@ -311,7 +317,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param mixed $addresses * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setTo($addresses, $name = null) { @@ -319,7 +325,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $addresses = array($addresses => $name); } - if (!$this->_setHeaderFieldModel('To', (array) $addresses)) { + if (!$this->setHeaderFieldModel('To', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('To', (array) $addresses); } @@ -333,7 +339,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getTo() { - return $this->_getHeaderFieldModel('To'); + return $this->getHeaderFieldModel('To'); } /** @@ -344,7 +350,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addCc($address, $name = null) { @@ -363,7 +369,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param mixed $addresses * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setCc($addresses, $name = null) { @@ -371,7 +377,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $addresses = array($addresses => $name); } - if (!$this->_setHeaderFieldModel('Cc', (array) $addresses)) { + if (!$this->setHeaderFieldModel('Cc', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('Cc', (array) $addresses); } @@ -385,7 +391,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getCc() { - return $this->_getHeaderFieldModel('Cc'); + return $this->getHeaderFieldModel('Cc'); } /** @@ -396,7 +402,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addBcc($address, $name = null) { @@ -415,7 +421,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param mixed $addresses * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setBcc($addresses, $name = null) { @@ -423,7 +429,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $addresses = array($addresses => $name); } - if (!$this->_setHeaderFieldModel('Bcc', (array) $addresses)) { + if (!$this->setHeaderFieldModel('Bcc', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('Bcc', (array) $addresses); } @@ -437,7 +443,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getBcc() { - return $this->_getHeaderFieldModel('Bcc'); + return $this->getHeaderFieldModel('Bcc'); } /** @@ -447,16 +453,16 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * * @param int $priority * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setPriority($priority) { $priorityMap = array( - 1 => 'Highest', - 2 => 'High', - 3 => 'Normal', - 4 => 'Low', - 5 => 'Lowest', + self::PRIORITY_HIGHEST => 'Highest', + self::PRIORITY_HIGH => 'High', + self::PRIORITY_NORMAL => 'Normal', + self::PRIORITY_LOW => 'Low', + self::PRIORITY_LOWEST => 'Lowest', ); $pMapKeys = array_keys($priorityMap); if ($priority > max($pMapKeys)) { @@ -464,7 +470,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime } elseif ($priority < min($pMapKeys)) { $priority = min($pMapKeys); } - if (!$this->_setHeaderFieldModel('X-Priority', + if (!$this->setHeaderFieldModel('X-Priority', sprintf('%d (%s)', $priority, $priorityMap[$priority]))) { $this->getHeaders()->addTextHeader('X-Priority', sprintf('%d (%s)', $priority, $priorityMap[$priority])); @@ -483,11 +489,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getPriority() { - list($priority) = sscanf($this->_getHeaderFieldModel('X-Priority'), + list($priority) = sscanf($this->getHeaderFieldModel('X-Priority'), '%[1-5]' ); - return isset($priority) ? $priority : 3; + return $priority ?? 3; } /** @@ -495,11 +501,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * * @param array $addresses * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setReadReceiptTo($addresses) { - if (!$this->_setHeaderFieldModel('Disposition-Notification-To', $addresses)) { + if (!$this->setHeaderFieldModel('Disposition-Notification-To', $addresses)) { $this->getHeaders() ->addMailboxHeader('Disposition-Notification-To', $addresses); } @@ -514,17 +520,17 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getReadReceiptTo() { - return $this->_getHeaderFieldModel('Disposition-Notification-To'); + return $this->getHeaderFieldModel('Disposition-Notification-To'); } /** - * Attach a {@link Swift_Mime_MimeEntity} such as an Attachment or MimePart. + * Attach a {@link Swift_Mime_SimpleMimeEntity} such as an Attachment or MimePart. * - * @param Swift_Mime_MimeEntity $entity + * @param Swift_Mime_SimpleMimeEntity $entity * - * @return Swift_Mime_SimpleMessage + * @return $this */ - public function attach(Swift_Mime_MimeEntity $entity) + public function attach(Swift_Mime_SimpleMimeEntity $entity) { $this->setChildren(array_merge($this->getChildren(), array($entity))); @@ -534,11 +540,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime /** * Remove an already attached entity. * - * @param Swift_Mime_MimeEntity $entity + * @param Swift_Mime_SimpleMimeEntity $entity * - * @return Swift_Mime_SimpleMessage + * @return $this */ - public function detach(Swift_Mime_MimeEntity $entity) + public function detach(Swift_Mime_SimpleMimeEntity $entity) { $newChildren = array(); foreach ($this->getChildren() as $child) { @@ -552,14 +558,14 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime } /** - * Attach a {@link Swift_Mime_MimeEntity} and return it's CID source. + * Attach a {@link Swift_Mime_SimpleMimeEntity} and return it's CID source. * This method should be used when embedding images or other data in a message. * - * @param Swift_Mime_MimeEntity $entity + * @param Swift_Mime_SimpleMimeEntity $entity * * @return string */ - public function embed(Swift_Mime_MimeEntity $entity) + public function embed(Swift_Mime_SimpleMimeEntity $entity) { $this->attach($entity); @@ -574,7 +580,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime public function toString() { if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') { - $this->setChildren(array_merge(array($this->_becomeMimePart()), $children)); + $this->setChildren(array_merge(array($this->becomeMimePart()), $children)); $string = parent::toString(); $this->setChildren($children); } else { @@ -604,7 +610,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime public function toByteStream(Swift_InputByteStream $is) { if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') { - $this->setChildren(array_merge(array($this->_becomeMimePart()), $children)); + $this->setChildren(array_merge(array($this->becomeMimePart()), $children)); parent::toByteStream($is); $this->setChildren($children); } else { @@ -612,29 +618,29 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime } } - /** @see Swift_Mime_SimpleMimeEntity::_getIdField() */ - protected function _getIdField() + /** @see Swift_Mime_SimpleMimeEntity::getIdField() */ + protected function getIdField() { return 'Message-ID'; } /** Turn the body of this message into a child of itself if needed */ - protected function _becomeMimePart() + protected function becomeMimePart() { $part = new parent($this->getHeaders()->newInstance(), $this->getEncoder(), - $this->_getCache(), $this->_getGrammar(), $this->_userCharset + $this->getCache(), $this->getIdGenerator(), $this->userCharset ); - $part->setContentType($this->_userContentType); + $part->setContentType($this->userContentType); $part->setBody($this->getBody()); - $part->setFormat($this->_userFormat); - $part->setDelSp($this->_userDelSp); - $part->_setNestingLevel($this->_getTopNestingLevel()); + $part->setFormat($this->userFormat); + $part->setDelSp($this->userDelSp); + $part->setNestingLevel($this->getTopNestingLevel()); return $part; } /** Get the highest nesting level nested inside this message */ - private function _getTopNestingLevel() + private function getTopNestingLevel() { $highestLevel = $this->getNestingLevel(); foreach ($this->getChildren() as $child) { diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php index 6b91718fb85..2d1a9b47d56 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php @@ -13,79 +13,91 @@ * * @author Chris Corbyn */ -class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity +class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_Mime_EncodingObserver { + /** Main message document; there can only be one of these */ + const LEVEL_TOP = 16; + + /** An entity which nests with the same precedence as an attachment */ + const LEVEL_MIXED = 256; + + /** An entity which nests with the same precedence as a mime part */ + const LEVEL_ALTERNATIVE = 4096; + + /** An entity which nests with the same precedence as embedded content */ + const LEVEL_RELATED = 65536; + /** A collection of Headers for this mime entity */ - private $_headers; + private $headers; /** The body as a string, or a stream */ - private $_body; + private $body; /** The encoder that encodes the body into a streamable format */ - private $_encoder; + private $encoder; - /** The grammar to use for id validation */ - private $_grammar; + /** Message ID generator */ + private $idGenerator; /** A mime boundary, if any is used */ - private $_boundary; + private $boundary; /** Mime types to be used based on the nesting level */ - private $_compositeRanges = array( + private $compositeRanges = array( 'multipart/mixed' => array(self::LEVEL_TOP, self::LEVEL_MIXED), 'multipart/alternative' => array(self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE), 'multipart/related' => array(self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED), ); /** A set of filter rules to define what level an entity should be nested at */ - private $_compoundLevelFilters = array(); + private $compoundLevelFilters = array(); /** The nesting level of this entity */ - private $_nestingLevel = self::LEVEL_ALTERNATIVE; + private $nestingLevel = self::LEVEL_ALTERNATIVE; /** A KeyCache instance used during encoding and streaming */ - private $_cache; + private $cache; /** Direct descendants of this entity */ - private $_immediateChildren = array(); + private $immediateChildren = array(); /** All descendants of this entity */ - private $_children = array(); + private $children = array(); /** The maximum line length of the body of this entity */ - private $_maxLineLength = 78; + private $maxLineLength = 78; /** The order in which alternative mime types should appear */ - private $_alternativePartOrder = array( + private $alternativePartOrder = array( 'text/plain' => 1, 'text/html' => 2, 'multipart/related' => 3, ); /** The CID of this entity */ - private $_id; + private $id; /** The key used for accessing the cache */ - private $_cacheKey; + private $cacheKey; - protected $_userContentType; + protected $userContentType; /** * Create a new SimpleMimeEntity with $headers, $encoder and $cache. * - * @param Swift_Mime_HeaderSet $headers - * @param Swift_Mime_ContentEncoder $encoder - * @param Swift_KeyCache $cache - * @param Swift_Mime_Grammar $grammar + * @param Swift_Mime_SimpleHeaderSet $headers + * @param Swift_Mime_ContentEncoder $encoder + * @param Swift_KeyCache $cache + * @param Swift_IdGenerator $idGenerator */ - public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar) + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator) { - $this->_cacheKey = md5(uniqid(getmypid().mt_rand(), true)); - $this->_cache = $cache; - $this->_headers = $headers; - $this->_grammar = $grammar; + $this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values + $this->cache = $cache; + $this->headers = $headers; + $this->idGenerator = $idGenerator; $this->setEncoder($encoder); - $this->_headers->defineOrdering(array('Content-Type', 'Content-Transfer-Encoding')); + $this->headers->defineOrdering(array('Content-Type', 'Content-Transfer-Encoding')); // This array specifies that, when the entire MIME document contains // $compoundLevel, then for each child within $level, if its Content-Type @@ -100,7 +112,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity // ) // ) - $this->_compoundLevelFilters = array( + $this->compoundLevelFilters = array( (self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => array( self::LEVEL_ALTERNATIVE => array( 'text/plain' => self::LEVEL_ALTERNATIVE, @@ -109,7 +121,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity ), ); - $this->_id = $this->getRandomId(); + $this->id = $this->idGenerator->generateId(); } /** @@ -119,19 +131,19 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function generateId() { - $this->setId($this->getRandomId()); + $this->setId($this->idGenerator->generateId()); - return $this->_id; + return $this->id; } /** - * Get the {@link Swift_Mime_HeaderSet} for this entity. + * Get the {@link Swift_Mime_SimpleHeaderSet} for this entity. * - * @return Swift_Mime_HeaderSet + * @return Swift_Mime_SimpleHeaderSet */ public function getHeaders() { - return $this->_headers; + return $this->headers; } /** @@ -143,7 +155,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getNestingLevel() { - return $this->_nestingLevel; + return $this->nestingLevel; } /** @@ -153,7 +165,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getContentType() { - return $this->_getHeaderFieldModel('Content-Type'); + return $this->getHeaderFieldModel('Content-Type'); } /** @@ -161,14 +173,14 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param string $type * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setContentType($type) { - $this->_setContentTypeInHeaders($type); + $this->setContentTypeInHeaders($type); // Keep track of the value so that if the content-type changes automatically // due to added child entities, it can be restored if they are later removed - $this->_userContentType = $type; + $this->userContentType = $type; return $this; } @@ -182,9 +194,9 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getId() { - $tmp = (array) $this->_getHeaderFieldModel($this->_getIdField()); + $tmp = (array) $this->getHeaderFieldModel($this->getIdField()); - return $this->_headers->has($this->_getIdField()) ? current($tmp) : $this->_id; + return $this->headers->has($this->getIdField()) ? current($tmp) : $this->id; } /** @@ -192,14 +204,14 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param string $id * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setId($id) { - if (!$this->_setHeaderFieldModel($this->_getIdField(), $id)) { - $this->_headers->addIdHeader($this->_getIdField(), $id); + if (!$this->setHeaderFieldModel($this->getIdField(), $id)) { + $this->headers->addIdHeader($this->getIdField(), $id); } - $this->_id = $id; + $this->id = $id; return $this; } @@ -213,7 +225,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getDescription() { - return $this->_getHeaderFieldModel('Content-Description'); + return $this->getHeaderFieldModel('Content-Description'); } /** @@ -223,12 +235,12 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param string $description * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setDescription($description) { - if (!$this->_setHeaderFieldModel('Content-Description', $description)) { - $this->_headers->addTextHeader('Content-Description', $description); + if (!$this->setHeaderFieldModel('Content-Description', $description)) { + $this->headers->addTextHeader('Content-Description', $description); } return $this; @@ -241,7 +253,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getMaxLineLength() { - return $this->_maxLineLength; + return $this->maxLineLength; } /** @@ -251,11 +263,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param int $length * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setMaxLineLength($length) { - $this->_maxLineLength = $length; + $this->maxLineLength = $length; return $this; } @@ -263,37 +275,36 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity /** * Get all children added to this entity. * - * @return Swift_Mime_MimeEntity[] + * @return Swift_Mime_SimpleMimeEntity[] */ public function getChildren() { - return $this->_children; + return $this->children; } /** * Set all children of this entity. * - * @param Swift_Mime_MimeEntity[] $children - * @param int $compoundLevel For internal use only + * @param Swift_Mime_SimpleMimeEntity[] $children + * @param int $compoundLevel For internal use only * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setChildren(array $children, $compoundLevel = null) { // TODO: Try to refactor this logic - - $compoundLevel = isset($compoundLevel) ? $compoundLevel : $this->_getCompoundLevel($children); + $compoundLevel = $compoundLevel ?? $this->getCompoundLevel($children); $immediateChildren = array(); $grandchildren = array(); - $newContentType = $this->_userContentType; + $newContentType = $this->userContentType; foreach ($children as $child) { - $level = $this->_getNeededChildLevel($child, $compoundLevel); + $level = $this->getNeededChildLevel($child, $compoundLevel); if (empty($immediateChildren)) { //first iteration $immediateChildren = array($child); } else { - $nextLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel); + $nextLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel); if ($nextLevel == $level) { $immediateChildren[] = $child; } elseif ($level < $nextLevel) { @@ -308,11 +319,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity } if ($immediateChildren) { - $lowestLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel); + $lowestLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel); // Determine which composite media type is needed to accommodate the // immediate children - foreach ($this->_compositeRanges as $mediaType => $range) { + foreach ($this->compositeRanges as $mediaType => $range) { if ($lowestLevel > $range[0] && $lowestLevel <= $range[1]) { $newContentType = $mediaType; @@ -322,18 +333,18 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity // Put any grandchildren in a subpart if (!empty($grandchildren)) { - $subentity = $this->_createChild(); - $subentity->_setNestingLevel($lowestLevel); + $subentity = $this->createChild(); + $subentity->setNestingLevel($lowestLevel); $subentity->setChildren($grandchildren, $compoundLevel); array_unshift($immediateChildren, $subentity); } } - $this->_immediateChildren = $immediateChildren; - $this->_children = $children; - $this->_setContentTypeInHeaders($newContentType); - $this->_fixHeaders(); - $this->_sortChildren(); + $this->immediateChildren = $immediateChildren; + $this->children = $children; + $this->setContentTypeInHeaders($newContentType); + $this->fixHeaders(); + $this->sortChildren(); return $this; } @@ -345,7 +356,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getBody() { - return $this->_body instanceof Swift_OutputByteStream ? $this->_readStream($this->_body) : $this->_body; + return $this->body instanceof Swift_OutputByteStream ? $this->readStream($this->body) : $this->body; } /** @@ -355,15 +366,15 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * @param mixed $body * @param string $contentType optional * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setBody($body, $contentType = null) { - if ($body !== $this->_body) { - $this->_clearCache(); + if ($body !== $this->body) { + $this->clearCache(); } - $this->_body = $body; + $this->body = $body; if (isset($contentType)) { $this->setContentType($contentType); } @@ -378,7 +389,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getEncoder() { - return $this->_encoder; + return $this->encoder; } /** @@ -386,17 +397,17 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param Swift_Mime_ContentEncoder $encoder * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setEncoder(Swift_Mime_ContentEncoder $encoder) { - if ($encoder !== $this->_encoder) { - $this->_clearCache(); + if ($encoder !== $this->encoder) { + $this->clearCache(); } - $this->_encoder = $encoder; - $this->_setEncoding($encoder->getName()); - $this->_notifyEncoderChanged($encoder); + $this->encoder = $encoder; + $this->setEncoding($encoder->getName()); + $this->notifyEncoderChanged($encoder); return $this; } @@ -408,11 +419,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getBoundary() { - if (!isset($this->_boundary)) { - $this->_boundary = '_=_swift_v4_'.time().'_'.md5(getmypid().mt_rand().uniqid('', true)).'_=_'; + if (!isset($this->boundary)) { + $this->boundary = '_=_swift_'.time().'_'.bin2hex(random_bytes(16)).'_=_'; } - return $this->_boundary; + return $this->boundary; } /** @@ -422,12 +433,12 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @throws Swift_RfcComplianceException * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setBoundary($boundary) { - $this->_assertValidBoundary($boundary); - $this->_boundary = $boundary; + $this->assertValidBoundary($boundary); + $this->boundary = $boundary; return $this; } @@ -440,7 +451,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function charsetChanged($charset) { - $this->_notifyCharsetChanged($charset); + $this->notifyCharsetChanged($charset); } /** @@ -451,7 +462,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function encoderChanged(Swift_Mime_ContentEncoder $encoder) { - $this->_notifyEncoderChanged($encoder); + $this->notifyEncoderChanged($encoder); } /** @@ -461,8 +472,8 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function toString() { - $string = $this->_headers->toString(); - $string .= $this->_bodyToString(); + $string = $this->headers->toString(); + $string .= $this->bodyToString(); return $string; } @@ -472,22 +483,22 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @return string */ - protected function _bodyToString() + protected function bodyToString() { $string = ''; - if (isset($this->_body) && empty($this->_immediateChildren)) { - if ($this->_cache->hasKey($this->_cacheKey, 'body')) { - $body = $this->_cache->getString($this->_cacheKey, 'body'); + if (isset($this->body) && empty($this->immediateChildren)) { + if ($this->cache->hasKey($this->cacheKey, 'body')) { + $body = $this->cache->getString($this->cacheKey, 'body'); } else { - $body = "\r\n".$this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength()); - $this->_cache->setString($this->_cacheKey, 'body', $body, Swift_KeyCache::MODE_WRITE); + $body = "\r\n".$this->encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength()); + $this->cache->setString($this->cacheKey, 'body', $body, Swift_KeyCache::MODE_WRITE); } $string .= $body; } - if (!empty($this->_immediateChildren)) { - foreach ($this->_immediateChildren as $child) { + if (!empty($this->immediateChildren)) { + foreach ($this->immediateChildren as $child) { $string .= "\r\n\r\n--".$this->getBoundary()."\r\n"; $string .= $child->toString(); } @@ -516,10 +527,10 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function toByteStream(Swift_InputByteStream $is) { - $is->write($this->_headers->toString()); + $is->write($this->headers->toString()); $is->commit(); - $this->_bodyToByteStream($is); + $this->bodyToByteStream($is); } /** @@ -527,26 +538,26 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param Swift_InputByteStream */ - protected function _bodyToByteStream(Swift_InputByteStream $is) + protected function bodyToByteStream(Swift_InputByteStream $is) { - if (empty($this->_immediateChildren)) { - if (isset($this->_body)) { - if ($this->_cache->hasKey($this->_cacheKey, 'body')) { - $this->_cache->exportToByteStream($this->_cacheKey, 'body', $is); + if (empty($this->immediateChildren)) { + if (isset($this->body)) { + if ($this->cache->hasKey($this->cacheKey, 'body')) { + $this->cache->exportToByteStream($this->cacheKey, 'body', $is); } else { - $cacheIs = $this->_cache->getInputByteStream($this->_cacheKey, 'body'); + $cacheIs = $this->cache->getInputByteStream($this->cacheKey, 'body'); if ($cacheIs) { $is->bind($cacheIs); } $is->write("\r\n"); - if ($this->_body instanceof Swift_OutputByteStream) { - $this->_body->setReadPointer(0); + if ($this->body instanceof Swift_OutputByteStream) { + $this->body->setReadPointer(0); - $this->_encoder->encodeByteStream($this->_body, $is, 0, $this->getMaxLineLength()); + $this->encoder->encodeByteStream($this->body, $is, 0, $this->getMaxLineLength()); } else { - $is->write($this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength())); + $is->write($this->encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength())); } if ($cacheIs) { @@ -556,8 +567,8 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity } } - if (!empty($this->_immediateChildren)) { - foreach ($this->_immediateChildren as $child) { + if (!empty($this->immediateChildren)) { + foreach ($this->immediateChildren as $child) { $is->write("\r\n\r\n--".$this->getBoundary()."\r\n"); $child->toByteStream($is); } @@ -568,7 +579,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity /** * Get the name of the header that provides the ID of this entity. */ - protected function _getIdField() + protected function getIdField() { return 'Content-ID'; } @@ -576,20 +587,20 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity /** * Get the model data (usually an array or a string) for $field. */ - protected function _getHeaderFieldModel($field) + protected function getHeaderFieldModel($field) { - if ($this->_headers->has($field)) { - return $this->_headers->get($field)->getFieldBodyModel(); + if ($this->headers->has($field)) { + return $this->headers->get($field)->getFieldBodyModel(); } } /** * Set the model data for $field. */ - protected function _setHeaderFieldModel($field, $model) + protected function setHeaderFieldModel($field, $model) { - if ($this->_headers->has($field)) { - $this->_headers->get($field)->setFieldBodyModel($model); + if ($this->headers->has($field)) { + $this->headers->get($field)->setFieldBodyModel($model); return true; } @@ -600,20 +611,20 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity /** * Get the parameter value of $parameter on $field header. */ - protected function _getHeaderParameter($field, $parameter) + protected function getHeaderParameter($field, $parameter) { - if ($this->_headers->has($field)) { - return $this->_headers->get($field)->getParameter($parameter); + if ($this->headers->has($field)) { + return $this->headers->get($field)->getParameter($parameter); } } /** * Set the parameter value of $parameter on $field header. */ - protected function _setHeaderParameter($field, $parameter, $value) + protected function setHeaderParameter($field, $parameter, $value) { - if ($this->_headers->has($field)) { - $this->_headers->get($field)->setParameter($parameter, $value); + if ($this->headers->has($field)) { + $this->headers->get($field)->setParameter($parameter, $value); return true; } @@ -624,16 +635,16 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity /** * Re-evaluate what content type and encoding should be used on this entity. */ - protected function _fixHeaders() + protected function fixHeaders() { - if (count($this->_immediateChildren)) { - $this->_setHeaderParameter('Content-Type', 'boundary', + if (count($this->immediateChildren)) { + $this->setHeaderParameter('Content-Type', 'boundary', $this->getBoundary() ); - $this->_headers->remove('Content-Transfer-Encoding'); + $this->headers->remove('Content-Transfer-Encoding'); } else { - $this->_setHeaderParameter('Content-Type', 'boundary', null); - $this->_setEncoding($this->_encoder->getName()); + $this->setHeaderParameter('Content-Type', 'boundary', null); + $this->setEncoding($this->encoder->getName()); } } @@ -642,50 +653,30 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @return Swift_KeyCache */ - protected function _getCache() + protected function getCache() { - return $this->_cache; + return $this->cache; } /** - * Get the grammar used for validation. + * Get the ID generator. * - * @return Swift_Mime_Grammar + * @return Swift_IdGenerator */ - protected function _getGrammar() + protected function getIdGenerator() { - return $this->_grammar; + return $this->idGenerator; } /** * Empty the KeyCache for this entity. */ - protected function _clearCache() + protected function clearCache() { - $this->_cache->clearKey($this->_cacheKey, 'body'); + $this->cache->clearKey($this->cacheKey, 'body'); } - /** - * Returns a random Content-ID or Message-ID. - * - * @return string - */ - protected function getRandomId() - { - $idLeft = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true)); - $idRight = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'swift.generated'; - $id = $idLeft.'@'.$idRight; - - try { - $this->_assertValidId($id); - } catch (Swift_RfcComplianceException $e) { - $id = $idLeft.'@swift.generated'; - } - - return $id; - } - - private function _readStream(Swift_OutputByteStream $os) + private function readStream(Swift_OutputByteStream $os) { $string = ''; while (false !== $bytes = $os->read(8192)) { @@ -697,33 +688,33 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity return $string; } - private function _setEncoding($encoding) + private function setEncoding($encoding) { - if (!$this->_setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) { - $this->_headers->addTextHeader('Content-Transfer-Encoding', $encoding); + if (!$this->setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) { + $this->headers->addTextHeader('Content-Transfer-Encoding', $encoding); } } - private function _assertValidBoundary($boundary) + private function assertValidBoundary($boundary) { if (!preg_match('/^[a-z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-z0-9\'\(\)\+_\-,\.\/:=\?]$/Di', $boundary)) { throw new Swift_RfcComplianceException('Mime boundary set is not RFC 2046 compliant.'); } } - private function _setContentTypeInHeaders($type) + private function setContentTypeInHeaders($type) { - if (!$this->_setHeaderFieldModel('Content-Type', $type)) { - $this->_headers->addParameterizedHeader('Content-Type', $type); + if (!$this->setHeaderFieldModel('Content-Type', $type)) { + $this->headers->addParameterizedHeader('Content-Type', $type); } } - private function _setNestingLevel($level) + private function setNestingLevel($level) { - $this->_nestingLevel = $level; + $this->nestingLevel = $level; } - private function _getCompoundLevel($children) + private function getCompoundLevel($children) { $level = 0; foreach ($children as $child) { @@ -733,10 +724,10 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity return $level; } - private function _getNeededChildLevel($child, $compoundLevel) + private function getNeededChildLevel($child, $compoundLevel) { $filter = array(); - foreach ($this->_compoundLevelFilters as $bitmask => $rules) { + foreach ($this->compoundLevelFilters as $bitmask => $rules) { if (($compoundLevel & $bitmask) === $bitmask) { $filter = $rules + $filter; } @@ -752,31 +743,31 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity return $realLevel; } - private function _createChild() + private function createChild() { - return new self($this->_headers->newInstance(), $this->_encoder, $this->_cache, $this->_grammar); + return new self($this->headers->newInstance(), $this->encoder, $this->cache, $this->idGenerator); } - private function _notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder) + private function notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder) { - foreach ($this->_immediateChildren as $child) { + foreach ($this->immediateChildren as $child) { $child->encoderChanged($encoder); } } - private function _notifyCharsetChanged($charset) + private function notifyCharsetChanged($charset) { - $this->_encoder->charsetChanged($charset); - $this->_headers->charsetChanged($charset); - foreach ($this->_immediateChildren as $child) { + $this->encoder->charsetChanged($charset); + $this->headers->charsetChanged($charset); + foreach ($this->immediateChildren as $child) { $child->charsetChanged($charset); } } - private function _sortChildren() + private function sortChildren() { $shouldSort = false; - foreach ($this->_immediateChildren as $child) { + foreach ($this->immediateChildren as $child) { // NOTE: This include alternative parts moved into a related part if ($child->getNestingLevel() == self::LEVEL_ALTERNATIVE) { $shouldSort = true; @@ -786,43 +777,32 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity // Sort in order of preference, if there is one if ($shouldSort) { - usort($this->_immediateChildren, array($this, '_childSortAlgorithm')); + // Group the messages by order of preference + $sorted = array(); + foreach ($this->immediateChildren as $child) { + $type = $child->getContentType(); + $level = array_key_exists($type, $this->alternativePartOrder) ? $this->alternativePartOrder[$type] : max($this->alternativePartOrder) + 1; + + if (empty($sorted[$level])) { + $sorted[$level] = array(); + } + + $sorted[$level][] = $child; + } + + ksort($sorted); + + $this->immediateChildren = array_reduce($sorted, 'array_merge', array()); } } - private function _childSortAlgorithm($a, $b) - { - $typePrefs = array(); - $types = array(strtolower($a->getContentType()), strtolower($b->getContentType())); - - foreach ($types as $type) { - $typePrefs[] = array_key_exists($type, $this->_alternativePartOrder) ? $this->_alternativePartOrder[$type] : max($this->_alternativePartOrder) + 1; - } - - return $typePrefs[0] >= $typePrefs[1] ? 1 : -1; - } - - // -- Destructor - /** * Empties it's own contents from the cache. */ public function __destruct() { - $this->_cache->clearAll($this->_cacheKey); - } - - /** - * Throws an Exception if the id passed does not comply with RFC 2822. - * - * @param string $id - * - * @throws Swift_RfcComplianceException - */ - private function _assertValidId($id) - { - if (!preg_match('/^'.$this->_grammar->getDefinition('id-left').'@'.$this->_grammar->getDefinition('id-right').'$/D', $id)) { - throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>'); + if ($this->cache instanceof Swift_KeyCache) { + $this->cache->clearAll($this->cacheKey); } } @@ -831,11 +811,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function __clone() { - $this->_headers = clone $this->_headers; - $this->_encoder = clone $this->_encoder; - $this->_cacheKey = uniqid(); + $this->headers = clone $this->headers; + $this->encoder = clone $this->encoder; + $this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values $children = array(); - foreach ($this->_children as $pos => $child) { + foreach ($this->children as $pos => $child) { $children[$pos] = clone $child; } $this->setChildren($children); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/MimePart.php b/htdocs/includes/swiftmailer/lib/classes/Swift/MimePart.php index 215f8db348a..8fa0cbebcd2 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/MimePart.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/MimePart.php @@ -42,18 +42,4 @@ class Swift_MimePart extends Swift_Mime_MimePart $this->setContentType($contentType); } } - - /** - * Create a new MimePart. - * - * @param string $body - * @param string $contentType - * @param string $charset - * - * @return Swift_Mime_MimePart - */ - public static function newInstance($body = null, $contentType = null, $charset = null) - { - return new self($body, $contentType, $charset); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/NullTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/NullTransport.php index b38e1cf7697..a580dfbefb6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/NullTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/NullTransport.php @@ -15,9 +15,6 @@ */ class Swift_NullTransport extends Swift_Transport_NullTransport { - /** - * Create a new NullTransport. - */ public function __construct() { call_user_func_array( @@ -26,14 +23,4 @@ class Swift_NullTransport extends Swift_Transport_NullTransport ->createDependenciesFor('transport.null') ); } - - /** - * Create a new NullTransport instance. - * - * @return Swift_NullTransport - */ - public static function newInstance() - { - return new self(); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php index a2ec2abcd50..06b3109e62c 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php @@ -20,28 +20,28 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ * * @var int */ - private $_threshold; + private $threshold; /** * The number of seconds to sleep for during a restart. * * @var int */ - private $_sleep; + private $sleep; /** * The internal counter. * * @var int */ - private $_counter = 0; + private $counter = 0; /** * The Sleeper instance for sleeping. * * @var Swift_Plugins_Sleeper */ - private $_sleeper; + private $sleeper; /** * Create a new AntiFloodPlugin with $threshold and $sleep time. @@ -54,7 +54,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ { $this->setThreshold($threshold); $this->setSleepTime($sleep); - $this->_sleeper = $sleeper; + $this->sleeper = $sleeper; } /** @@ -64,7 +64,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function setThreshold($threshold) { - $this->_threshold = $threshold; + $this->threshold = $threshold; } /** @@ -74,7 +74,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function getThreshold() { - return $this->_threshold; + return $this->threshold; } /** @@ -84,7 +84,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function setSleepTime($sleep) { - $this->_sleep = $sleep; + $this->sleep = $sleep; } /** @@ -94,7 +94,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function getSleepTime() { - return $this->_sleep; + return $this->sleep; } /** @@ -113,15 +113,15 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function sendPerformed(Swift_Events_SendEvent $evt) { - ++$this->_counter; - if ($this->_counter >= $this->_threshold) { + ++$this->counter; + if ($this->counter >= $this->threshold) { $transport = $evt->getTransport(); $transport->stop(); - if ($this->_sleep) { - $this->sleep($this->_sleep); + if ($this->sleep) { + $this->sleep($this->sleep); } $transport->start(); - $this->_counter = 0; + $this->counter = 0; } } @@ -132,8 +132,8 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function sleep($seconds) { - if (isset($this->_sleeper)) { - $this->_sleeper->sleep($seconds); + if (isset($this->sleeper)) { + $this->sleeper->sleep($seconds); } else { sleep($seconds); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php index f7e18d0ebea..af060a99cc3 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php @@ -20,17 +20,17 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, * * @var int */ - private $_out = 0; + private $out = 0; /** * The incoming traffic counter. * * @var int */ - private $_in = 0; + private $in = 0; /** Bound byte streams */ - private $_mirrors = array(); + private $mirrors = array(); /** * Not used. @@ -58,7 +58,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, public function commandSent(Swift_Events_CommandEvent $evt) { $command = $evt->getCommand(); - $this->_out += strlen($command); + $this->out += strlen($command); } /** @@ -69,7 +69,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, public function responseReceived(Swift_Events_ResponseEvent $evt) { $response = $evt->getResponse(); - $this->_in += strlen($response); + $this->in += strlen($response); } /** @@ -79,8 +79,8 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function write($bytes) { - $this->_out += strlen($bytes); - foreach ($this->_mirrors as $stream) { + $this->out += strlen($bytes); + foreach ($this->mirrors as $stream) { $stream->write($bytes); } } @@ -102,7 +102,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function bind(Swift_InputByteStream $is) { - $this->_mirrors[] = $is; + $this->mirrors[] = $is; } /** @@ -116,9 +116,9 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function unbind(Swift_InputByteStream $is) { - foreach ($this->_mirrors as $k => $stream) { + foreach ($this->mirrors as $k => $stream) { if ($is === $stream) { - unset($this->_mirrors[$k]); + unset($this->mirrors[$k]); } } } @@ -128,7 +128,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function flushBuffers() { - foreach ($this->_mirrors as $stream) { + foreach ($this->mirrors as $stream) { $stream->flushBuffers(); } } @@ -140,7 +140,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function getBytesOut() { - return $this->_out; + return $this->out; } /** @@ -150,7 +150,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function getBytesIn() { - return $this->_in; + return $this->in; } /** @@ -158,7 +158,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function reset() { - $this->_out = 0; - $this->_in = 0; + $this->out = 0; + $this->in = 0; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php index 0762b36d218..9d5feefb92c 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php @@ -17,19 +17,19 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_Plugins_Decorator_Replacements { /** The replacement map */ - private $_replacements; + private $replacements; /** The body as it was before replacements */ - private $_originalBody; + private $originalBody; /** The original headers of the message, before replacements */ - private $_originalHeaders = array(); + private $originalHeaders = array(); /** Bodies of children before they are replaced */ - private $_originalChildBodies = array(); + private $originalChildBodies = array(); /** The Message that was last replaced */ - private $_lastMessage; + private $lastMessage; /** * Create a new DecoratorPlugin with $replacements. @@ -66,9 +66,9 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ public function setReplacements($replacements) { if (!($replacements instanceof Swift_Plugins_Decorator_Replacements)) { - $this->_replacements = (array) $replacements; + $this->replacements = (array) $replacements; } else { - $this->_replacements = $replacements; + $this->replacements = $replacements; } } @@ -80,7 +80,7 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ public function beforeSendPerformed(Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); - $this->_restoreMessage($message); + $this->restoreMessage($message); $to = array_keys($message->getTo()); $address = array_shift($to); if ($replacements = $this->getReplacementsFor($address)) { @@ -91,7 +91,7 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ $search, $replace, $body ); if ($body != $bodyReplaced) { - $this->_originalBody = $body; + $this->originalBody = $body; $message->setBody($bodyReplaced); } @@ -111,12 +111,12 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ $count = 1; } } - } else { + } elseif (is_string($body)) { $bodyReplaced = str_replace($search, $replace, $body, $count); } if ($count) { - $this->_originalHeaders[$header->getFieldName()] = $body; + $this->originalHeaders[$header->getFieldName()] = $body; $header->setFieldBodyModel($bodyReplaced); } } @@ -131,11 +131,11 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ ); if ($body != $bodyReplaced) { $child->setBody($bodyReplaced); - $this->_originalChildBodies[$child->getId()] = $body; + $this->originalChildBodies[$child->getId()] = $body; } } } - $this->_lastMessage = $message; + $this->lastMessage = $message; } } @@ -155,11 +155,11 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ */ public function getReplacementsFor($address) { - if ($this->_replacements instanceof Swift_Plugins_Decorator_Replacements) { - return $this->_replacements->getReplacementsFor($address); + if ($this->replacements instanceof Swift_Plugins_Decorator_Replacements) { + return $this->replacements->getReplacementsFor($address); } - return isset($this->_replacements[$address]) ? $this->_replacements[$address] : null; + return $this->replacements[$address] ?? null; } /** @@ -169,36 +169,36 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ */ public function sendPerformed(Swift_Events_SendEvent $evt) { - $this->_restoreMessage($evt->getMessage()); + $this->restoreMessage($evt->getMessage()); } /** Restore a changed message back to its original state */ - private function _restoreMessage(Swift_Mime_Message $message) + private function restoreMessage(Swift_Mime_SimpleMessage $message) { - if ($this->_lastMessage === $message) { - if (isset($this->_originalBody)) { - $message->setBody($this->_originalBody); - $this->_originalBody = null; + if ($this->lastMessage === $message) { + if (isset($this->originalBody)) { + $message->setBody($this->originalBody); + $this->originalBody = null; } - if (!empty($this->_originalHeaders)) { + if (!empty($this->originalHeaders)) { foreach ($message->getHeaders()->getAll() as $header) { - if (array_key_exists($header->getFieldName(), $this->_originalHeaders)) { - $header->setFieldBodyModel($this->_originalHeaders[$header->getFieldName()]); + if (array_key_exists($header->getFieldName(), $this->originalHeaders)) { + $header->setFieldBodyModel($this->originalHeaders[$header->getFieldName()]); } } - $this->_originalHeaders = array(); + $this->originalHeaders = array(); } - if (!empty($this->_originalChildBodies)) { + if (!empty($this->originalChildBodies)) { $children = (array) $message->getChildren(); foreach ($children as $child) { $id = $child->getId(); - if (array_key_exists($id, $this->_originalChildBodies)) { - $child->setBody($this->_originalChildBodies[$id]); + if (array_key_exists($id, $this->originalChildBodies)) { + $child->setBody($this->originalChildBodies[$id]); } } - $this->_originalChildBodies = array(); + $this->originalChildBodies = array(); } - $this->_lastMessage = null; + $this->lastMessage = null; } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php index 7552b67a2f7..b975d36b858 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php @@ -18,9 +18,9 @@ class Swift_Plugins_ImpersonatePlugin implements Swift_Events_SendListener /** * The sender to impersonate. * - * @var String + * @var string */ - private $_sender; + private $sender; /** * Create a new ImpersonatePlugin to impersonate $sender. @@ -29,7 +29,7 @@ class Swift_Plugins_ImpersonatePlugin implements Swift_Events_SendListener */ public function __construct($sender) { - $this->_sender = $sender; + $this->sender = $sender; } /** @@ -46,7 +46,7 @@ class Swift_Plugins_ImpersonatePlugin implements Swift_Events_SendListener $headers->addPathHeader('X-Swift-Return-Path', $message->getReturnPath()); // replace them with the one to send to - $message->setReturnPath($this->_sender); + $message->setReturnPath($this->sender); } /** diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php index 64db4384648..7ddf1fd16db 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php @@ -11,12 +11,12 @@ /** * Does real time logging of Transport level information. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_Events_ResponseListener, Swift_Events_TransportChangeListener, Swift_Events_TransportExceptionListener, Swift_Plugins_Logger { /** The logger which is delegated to */ - private $_logger; + private $logger; /** * Create a new LoggerPlugin using $logger. @@ -25,7 +25,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ */ public function __construct(Swift_Plugins_Logger $logger) { - $this->_logger = $logger; + $this->logger = $logger; } /** @@ -35,7 +35,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ */ public function add($entry) { - $this->_logger->add($entry); + $this->logger->add($entry); } /** @@ -43,7 +43,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ */ public function clear() { - $this->_logger->clear(); + $this->logger->clear(); } /** @@ -53,7 +53,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ */ public function dump() { - return $this->_logger->dump(); + return $this->logger->dump(); } /** @@ -64,7 +64,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function commandSent(Swift_Events_CommandEvent $evt) { $command = $evt->getCommand(); - $this->_logger->add(sprintf('>> %s', $command)); + $this->logger->add(sprintf('>> %s', $command)); } /** @@ -75,7 +75,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function responseReceived(Swift_Events_ResponseEvent $evt) { $response = $evt->getResponse(); - $this->_logger->add(sprintf('<< %s', $response)); + $this->logger->add(sprintf('<< %s', $response)); } /** @@ -86,7 +86,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); - $this->_logger->add(sprintf('++ Starting %s', $transportName)); + $this->logger->add(sprintf('++ Starting %s', $transportName)); } /** @@ -97,7 +97,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function transportStarted(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); - $this->_logger->add(sprintf('++ %s started', $transportName)); + $this->logger->add(sprintf('++ %s started', $transportName)); } /** @@ -108,7 +108,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); - $this->_logger->add(sprintf('++ Stopping %s', $transportName)); + $this->logger->add(sprintf('++ Stopping %s', $transportName)); } /** @@ -119,7 +119,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function transportStopped(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); - $this->_logger->add(sprintf('++ %s stopped', $transportName)); + $this->logger->add(sprintf('++ %s stopped', $transportName)); } /** @@ -132,10 +132,10 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ $e = $evt->getException(); $message = $e->getMessage(); $code = $e->getCode(); - $this->_logger->add(sprintf('!! %s (code: %s)', $message, $code)); + $this->logger->add(sprintf('!! %s (code: %s)', $message, $code)); $message .= PHP_EOL; $message .= 'Log data:'.PHP_EOL; - $message .= $this->_logger->dump(); + $message .= $this->logger->dump(); $evt->cancelBubble(); throw new Swift_TransportException($message, $code, $e->getPrevious()); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php index 865bb0aa3b9..186b6b41bcd 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php @@ -20,14 +20,14 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger * * @var array */ - private $_log = array(); + private $log = array(); /** * Max size of the log. * * @var int */ - private $_size = 0; + private $size = 0; /** * Create a new ArrayLogger with a maximum of $size entries. @@ -36,7 +36,7 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger */ public function __construct($size = 50) { - $this->_size = $size; + $this->size = $size; } /** @@ -46,9 +46,9 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger */ public function add($entry) { - $this->_log[] = $entry; - while (count($this->_log) > $this->_size) { - array_shift($this->_log); + $this->log[] = $entry; + while (count($this->log) > $this->size) { + array_shift($this->log); } } @@ -57,7 +57,7 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger */ public function clear() { - $this->_log = array(); + $this->log = array(); } /** @@ -67,6 +67,6 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger */ public function dump() { - return implode(PHP_EOL, $this->_log); + return implode(PHP_EOL, $this->log); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php index 3583297ab10..40a53d2bba2 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php @@ -16,7 +16,7 @@ class Swift_Plugins_Loggers_EchoLogger implements Swift_Plugins_Logger { /** Whether or not HTML should be output */ - private $_isHtml; + private $isHtml; /** * Create a new EchoLogger. @@ -25,7 +25,7 @@ class Swift_Plugins_Loggers_EchoLogger implements Swift_Plugins_Logger */ public function __construct($isHtml = true) { - $this->_isHtml = $isHtml; + $this->isHtml = $isHtml; } /** @@ -35,7 +35,7 @@ class Swift_Plugins_Loggers_EchoLogger implements Swift_Plugins_Logger */ public function add($entry) { - if ($this->_isHtml) { + if ($this->isHtml) { printf('%s%s%s', htmlspecialchars($entry, ENT_QUOTES), '
', PHP_EOL); } else { printf('%s%s', $entry, PHP_EOL); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php index e622cb37d16..5ff1d9321c0 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php @@ -16,7 +16,7 @@ class Swift_Plugins_MessageLogger implements Swift_Events_SendListener { /** - * @var array + * @var Swift_Mime_Message[] */ private $messages; @@ -28,7 +28,7 @@ class Swift_Plugins_MessageLogger implements Swift_Events_SendListener /** * Get the message list. * - * @return array + * @return Swift_Mime_Message[] */ public function getMessages() { diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php index 18abb770632..c19403aec61 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php @@ -11,36 +11,36 @@ /** * Makes sure a connection to a POP3 host has been established prior to connecting to SMTP. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeListener, Swift_Plugins_Pop_Pop3Connection { /** A delegate connection to use (mostly a test hook) */ - private $_connection; + private $connection; /** Hostname of the POP3 server */ - private $_host; + private $host; /** Port number to connect on */ - private $_port; + private $port; /** Encryption type to use (if any) */ - private $_crypto; + private $crypto; /** Username to use (if any) */ - private $_username; + private $username; /** Password to use (if any) */ - private $_password; + private $password; /** Established connection via TCP socket */ - private $_socket; + private $socket; /** Connect timeout in seconds */ - private $_timeout = 10; + private $timeout = 10; /** SMTP Transport to bind to */ - private $_transport; + private $transport; /** * Create a new PopBeforeSmtpPlugin for $host and $port. @@ -51,23 +51,9 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL */ public function __construct($host, $port = 110, $crypto = null) { - $this->_host = $host; - $this->_port = $port; - $this->_crypto = $crypto; - } - - /** - * Create a new PopBeforeSmtpPlugin for $host and $port. - * - * @param string $host - * @param int $port - * @param string $crypto as "tls" or "ssl" - * - * @return Swift_Plugins_PopBeforeSmtpPlugin - */ - public static function newInstance($host, $port = 110, $crypto = null) - { - return new self($host, $port, $crypto); + $this->host = $host; + $this->port = $port; + $this->crypto = $crypto; } /** @@ -75,11 +61,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL * * @param Swift_Plugins_Pop_Pop3Connection $connection * - * @return Swift_Plugins_PopBeforeSmtpPlugin + * @return $this */ public function setConnection(Swift_Plugins_Pop_Pop3Connection $connection) { - $this->_connection = $connection; + $this->connection = $connection; return $this; } @@ -91,7 +77,7 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL */ public function bindSmtp(Swift_Transport $smtp) { - $this->_transport = $smtp; + $this->transport = $smtp; } /** @@ -99,11 +85,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL * * @param int $timeout * - * @return Swift_Plugins_PopBeforeSmtpPlugin + * @return $this */ public function setTimeout($timeout) { - $this->_timeout = (int) $timeout; + $this->timeout = (int) $timeout; return $this; } @@ -113,11 +99,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL * * @param string $username * - * @return Swift_Plugins_PopBeforeSmtpPlugin + * @return $this */ public function setUsername($username) { - $this->_username = $username; + $this->username = $username; return $this; } @@ -127,11 +113,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL * * @param string $password * - * @return Swift_Plugins_PopBeforeSmtpPlugin + * @return $this */ public function setPassword($password) { - $this->_password = $password; + $this->password = $password; return $this; } @@ -143,29 +129,29 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL */ public function connect() { - if (isset($this->_connection)) { - $this->_connection->connect(); + if (isset($this->connection)) { + $this->connection->connect(); } else { - if (!isset($this->_socket)) { + if (!isset($this->socket)) { if (!$socket = fsockopen( - $this->_getHostString(), $this->_port, $errno, $errstr, $this->_timeout)) { + $this->getHostString(), $this->port, $errno, $errstr, $this->timeout)) { throw new Swift_Plugins_Pop_Pop3Exception( - sprintf('Failed to connect to POP3 host [%s]: %s', $this->_host, $errstr) + sprintf('Failed to connect to POP3 host [%s]: %s', $this->host, $errstr) ); } - $this->_socket = $socket; + $this->socket = $socket; - if (false === $greeting = fgets($this->_socket)) { + if (false === $greeting = fgets($this->socket)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('Failed to connect to POP3 host [%s]', trim($greeting)) ); } - $this->_assertOk($greeting); + $this->assertOk($greeting); - if ($this->_username) { - $this->_command(sprintf("USER %s\r\n", $this->_username)); - $this->_command(sprintf("PASS %s\r\n", $this->_password)); + if ($this->username) { + $this->command(sprintf("USER %s\r\n", $this->username)); + $this->command(sprintf("PASS %s\r\n", $this->password)); } } } @@ -176,16 +162,16 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL */ public function disconnect() { - if (isset($this->_connection)) { - $this->_connection->disconnect(); + if (isset($this->connection)) { + $this->connection->disconnect(); } else { - $this->_command("QUIT\r\n"); - if (!fclose($this->_socket)) { + $this->command("QUIT\r\n"); + if (!fclose($this->socket)) { throw new Swift_Plugins_Pop_Pop3Exception( - sprintf('POP3 host [%s] connection could not be stopped', $this->_host) + sprintf('POP3 host [%s] connection could not be stopped', $this->host) ); } - $this->_socket = null; + $this->socket = null; } } @@ -196,8 +182,8 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL */ public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt) { - if (isset($this->_transport)) { - if ($this->_transport !== $evt->getTransport()) { + if (isset($this->transport)) { + if ($this->transport !== $evt->getTransport()) { return; } } @@ -227,26 +213,26 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL { } - private function _command($command) + private function command($command) { - if (!fwrite($this->_socket, $command)) { + if (!fwrite($this->socket, $command)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('Failed to write command [%s] to POP3 host', trim($command)) ); } - if (false === $response = fgets($this->_socket)) { + if (false === $response = fgets($this->socket)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('Failed to read from POP3 host after command [%s]', trim($command)) ); } - $this->_assertOk($response); + $this->assertOk($response); return $response; } - private function _assertOk($response) + private function assertOk($response) { if (substr($response, 0, 3) != '+OK') { throw new Swift_Plugins_Pop_Pop3Exception( @@ -255,10 +241,10 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL } } - private function _getHostString() + private function getHostString() { - $host = $this->_host; - switch (strtolower($this->_crypto)) { + $host = $this->host; + switch (strtolower($this->crypto)) { case 'ssl': $host = 'ssl://'.$host; break; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php index c3a1f868544..8d797dd117b 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php @@ -11,7 +11,7 @@ /** * Redirects all email to a single recipient. * - * @author Fabien Potencier + * @author Fabien Potencier */ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener { @@ -20,14 +20,14 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener * * @var mixed */ - private $_recipient; + private $recipient; /** * List of regular expression for recipient whitelisting. * * @var array */ - private $_whitelist = array(); + private $whitelist = array(); /** * Create a new RedirectingPlugin. @@ -37,8 +37,8 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function __construct($recipient, array $whitelist = array()) { - $this->_recipient = $recipient; - $this->_whitelist = $whitelist; + $this->recipient = $recipient; + $this->whitelist = $whitelist; } /** @@ -48,7 +48,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function setRecipient($recipient) { - $this->_recipient = $recipient; + $this->recipient = $recipient; } /** @@ -58,7 +58,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function getRecipient() { - return $this->_recipient; + return $this->recipient; } /** @@ -68,7 +68,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function setWhitelist(array $whitelist) { - $this->_whitelist = $whitelist; + $this->whitelist = $whitelist; } /** @@ -78,7 +78,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function getWhitelist() { - return $this->_whitelist; + return $this->whitelist; } /** @@ -106,9 +106,9 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener } // Filter remaining headers against whitelist - $this->_filterHeaderSet($headers, 'To'); - $this->_filterHeaderSet($headers, 'Cc'); - $this->_filterHeaderSet($headers, 'Bcc'); + $this->filterHeaderSet($headers, 'To'); + $this->filterHeaderSet($headers, 'Cc'); + $this->filterHeaderSet($headers, 'Bcc'); // Add each hard coded recipient $to = $message->getTo(); @@ -116,7 +116,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener $to = array(); } - foreach ((array) $this->_recipient as $recipient) { + foreach ((array) $this->recipient as $recipient) { if (!array_key_exists($recipient, $to)) { $message->addTo($recipient); } @@ -126,13 +126,13 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener /** * Filter header set against a whitelist of regular expressions. * - * @param Swift_Mime_HeaderSet $headerSet - * @param string $type + * @param Swift_Mime_SimpleHeaderSet $headerSet + * @param string $type */ - private function _filterHeaderSet(Swift_Mime_HeaderSet $headerSet, $type) + private function filterHeaderSet(Swift_Mime_SimpleHeaderSet $headerSet, $type) { foreach ($headerSet->getAll($type) as $headers) { - $headers->setNameAddresses($this->_filterNameAddresses($headers->getNameAddresses())); + $headers->setNameAddresses($this->filterNameAddresses($headers->getNameAddresses())); } } @@ -143,12 +143,12 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener * * @return array */ - private function _filterNameAddresses(array $recipients) + private function filterNameAddresses(array $recipients) { $filtered = array(); foreach ($recipients as $address => $name) { - if ($this->_isWhitelisted($address)) { + if ($this->isWhitelisted($address)) { $filtered[$address] = $name; } } @@ -163,13 +163,13 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener * * @return bool */ - protected function _isWhitelisted($recipient) + protected function isWhitelisted($recipient) { - if (in_array($recipient, (array) $this->_recipient)) { + if (in_array($recipient, (array) $this->recipient)) { return true; } - foreach ($this->_whitelist as $pattern) { + foreach ($this->whitelist as $pattern) { if (preg_match($pattern, $recipient)) { return true; } @@ -185,10 +185,10 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function sendPerformed(Swift_Events_SendEvent $evt) { - $this->_restoreMessage($evt->getMessage()); + $this->restoreMessage($evt->getMessage()); } - private function _restoreMessage(Swift_Mime_Message $message) + private function restoreMessage(Swift_Mime_SimpleMessage $message) { // restore original headers $headers = $message->getHeaders(); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporter.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporter.php index 0f21b7d6052..3a2b6657c09 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporter.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporter.php @@ -24,9 +24,9 @@ interface Swift_Plugins_Reporter /** * Notifies this ReportNotifier that $address failed or succeeded. * - * @param Swift_Mime_Message $message - * @param string $address - * @param int $result from {@link RESULT_PASS, RESULT_FAIL} + * @param Swift_Mime_SimpleMessage $message + * @param string $address + * @param int $result from {@link RESULT_PASS, RESULT_FAIL} */ - public function notify(Swift_Mime_Message $message, $address, $result); + public function notify(Swift_Mime_SimpleMessage $message, $address, $result); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php index a37901ff0d4..5ffca24c61c 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php @@ -20,7 +20,7 @@ class Swift_Plugins_ReporterPlugin implements Swift_Events_SendListener * * @var Swift_Plugins_Reporter */ - private $_reporter; + private $reporter; /** * Create a new ReporterPlugin using $reporter. @@ -29,7 +29,7 @@ class Swift_Plugins_ReporterPlugin implements Swift_Events_SendListener */ public function __construct(Swift_Plugins_Reporter $reporter) { - $this->_reporter = $reporter; + $this->reporter = $reporter; } /** @@ -49,13 +49,13 @@ class Swift_Plugins_ReporterPlugin implements Swift_Events_SendListener $message = $evt->getMessage(); $failures = array_flip($evt->getFailedRecipients()); foreach ((array) $message->getTo() as $address => $null) { - $this->_reporter->notify($message, $address, array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS); + $this->reporter->notify($message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS)); } foreach ((array) $message->getCc() as $address => $null) { - $this->_reporter->notify($message, $address, array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS); + $this->reporter->notify($message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS)); } foreach ((array) $message->getBcc() as $address => $null) { - $this->_reporter->notify($message, $address, array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS); + $this->reporter->notify($message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS)); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php index cad9d168ef2..67c117ac7c2 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php @@ -20,22 +20,22 @@ class Swift_Plugins_Reporters_HitReporter implements Swift_Plugins_Reporter * * @var array */ - private $_failures = array(); + private $failures = array(); - private $_failures_cache = array(); + private $failures_cache = array(); /** * Notifies this ReportNotifier that $address failed or succeeded. * - * @param Swift_Mime_Message $message - * @param string $address - * @param int $result from {@link RESULT_PASS, RESULT_FAIL} + * @param Swift_Mime_SimpleMessage $message + * @param string $address + * @param int $result from {@link RESULT_PASS, RESULT_FAIL} */ - public function notify(Swift_Mime_Message $message, $address, $result) + public function notify(Swift_Mime_SimpleMessage $message, $address, $result) { - if (self::RESULT_FAIL == $result && !isset($this->_failures_cache[$address])) { - $this->_failures[] = $address; - $this->_failures_cache[$address] = true; + if (self::RESULT_FAIL == $result && !isset($this->failures_cache[$address])) { + $this->failures[] = $address; + $this->failures_cache[$address] = true; } } @@ -46,7 +46,7 @@ class Swift_Plugins_Reporters_HitReporter implements Swift_Plugins_Reporter */ public function getFailedRecipients() { - return $this->_failures; + return $this->failures; } /** @@ -54,6 +54,6 @@ class Swift_Plugins_Reporters_HitReporter implements Swift_Plugins_Reporter */ public function clear() { - $this->_failures = $this->_failures_cache = array(); + $this->failures = $this->failures_cache = array(); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php index c62593557e3..525eef570a9 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php @@ -18,11 +18,11 @@ class Swift_Plugins_Reporters_HtmlReporter implements Swift_Plugins_Reporter /** * Notifies this ReportNotifier that $address failed or succeeded. * - * @param Swift_Mime_Message $message - * @param string $address - * @param int $result from {@see RESULT_PASS, RESULT_FAIL} + * @param Swift_Mime_SimpleMessage $message + * @param string $address + * @param int $result from {@see RESULT_PASS, RESULT_FAIL} */ - public function notify(Swift_Mime_Message $message, $address, $result) + public function notify(Swift_Mime_SimpleMessage $message, $address, $result) { if (self::RESULT_PASS == $result) { echo '
'.PHP_EOL; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php index 24bc929ee6b..77c2e8db6ec 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php @@ -29,28 +29,28 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin * * @var Swift_Plugins_Sleeper */ - private $_sleeper; + private $sleeper; /** * The Timer instance which provides the timestamp. * * @var Swift_Plugins_Timer */ - private $_timer; + private $timer; /** * The time at which the first email was sent. * * @var int */ - private $_start; + private $start; /** * The rate at which messages should be sent. * * @var int */ - private $_rate; + private $rate; /** * The mode for throttling. @@ -59,14 +59,14 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin * * @var int */ - private $_mode; + private $mode; /** * An internal counter of the number of messages sent. * * @var int */ - private $_messages = 0; + private $messages = 0; /** * Create a new ThrottlerPlugin. @@ -78,10 +78,10 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin */ public function __construct($rate, $mode = self::BYTES_PER_MINUTE, Swift_Plugins_Sleeper $sleeper = null, Swift_Plugins_Timer $timer = null) { - $this->_rate = $rate; - $this->_mode = $mode; - $this->_sleeper = $sleeper; - $this->_timer = $timer; + $this->rate = $rate; + $this->mode = $mode; + $this->sleeper = $sleeper; + $this->timer = $timer; } /** @@ -92,22 +92,22 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin public function beforeSendPerformed(Swift_Events_SendEvent $evt) { $time = $this->getTimestamp(); - if (!isset($this->_start)) { - $this->_start = $time; + if (!isset($this->start)) { + $this->start = $time; } - $duration = $time - $this->_start; + $duration = $time - $this->start; - switch ($this->_mode) { - case self::BYTES_PER_MINUTE : - $sleep = $this->_throttleBytesPerMinute($duration); + switch ($this->mode) { + case self::BYTES_PER_MINUTE: + $sleep = $this->throttleBytesPerMinute($duration); break; - case self::MESSAGES_PER_SECOND : - $sleep = $this->_throttleMessagesPerSecond($duration); + case self::MESSAGES_PER_SECOND: + $sleep = $this->throttleMessagesPerSecond($duration); break; - case self::MESSAGES_PER_MINUTE : - $sleep = $this->_throttleMessagesPerMinute($duration); + case self::MESSAGES_PER_MINUTE: + $sleep = $this->throttleMessagesPerMinute($duration); break; - default : + default: $sleep = 0; break; } @@ -125,7 +125,7 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin public function sendPerformed(Swift_Events_SendEvent $evt) { parent::sendPerformed($evt); - ++$this->_messages; + ++$this->messages; } /** @@ -135,8 +135,8 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin */ public function sleep($seconds) { - if (isset($this->_sleeper)) { - $this->_sleeper->sleep($seconds); + if (isset($this->sleeper)) { + $this->sleeper->sleep($seconds); } else { sleep($seconds); } @@ -149,8 +149,8 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin */ public function getTimestamp() { - if (isset($this->_timer)) { - return $this->_timer->getTimestamp(); + if (isset($this->timer)) { + return $this->timer->getTimestamp(); } return time(); @@ -163,9 +163,9 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin * * @return int */ - private function _throttleBytesPerMinute($timePassed) + private function throttleBytesPerMinute($timePassed) { - $expectedDuration = $this->getBytesOut() / ($this->_rate / 60); + $expectedDuration = $this->getBytesOut() / ($this->rate / 60); return (int) ceil($expectedDuration - $timePassed); } @@ -177,9 +177,9 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin * * @return int */ - private function _throttleMessagesPerSecond($timePassed) + private function throttleMessagesPerSecond($timePassed) { - $expectedDuration = $this->_messages / ($this->_rate); + $expectedDuration = $this->messages / $this->rate; return (int) ceil($expectedDuration - $timePassed); } @@ -191,9 +191,9 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin * * @return int */ - private function _throttleMessagesPerMinute($timePassed) + private function throttleMessagesPerMinute($timePassed) { - $expectedDuration = $this->_messages / ($this->_rate / 60); + $expectedDuration = $this->messages / ($this->rate / 60); return (int) ceil($expectedDuration - $timePassed); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Preferences.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Preferences.php index 503db84d883..79eafde9ad9 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Preferences.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Preferences.php @@ -16,7 +16,7 @@ class Swift_Preferences { /** Singleton instance */ - private static $_instance = null; + private static $instance = null; /** Constructor not to be used */ private function __construct() @@ -26,15 +26,15 @@ class Swift_Preferences /** * Gets the instance of Preferences. * - * @return Swift_Preferences + * @return self */ public static function getInstance() { - if (!isset(self::$_instance)) { - self::$_instance = new self(); + if (!isset(self::$instance)) { + self::$instance = new self(); } - return self::$_instance; + return self::$instance; } /** @@ -42,12 +42,11 @@ class Swift_Preferences * * @param string $charset * - * @return Swift_Preferences + * @return $this */ public function setCharset($charset) { - Swift_DependencyContainer::getInstance() - ->register('properties.charset')->asValue($charset); + Swift_DependencyContainer::getInstance()->register('properties.charset')->asValue($charset); return $this; } @@ -57,12 +56,11 @@ class Swift_Preferences * * @param string $dir * - * @return Swift_Preferences + * @return $this */ public function setTempDir($dir) { - Swift_DependencyContainer::getInstance() - ->register('tempdir')->asValue($dir); + Swift_DependencyContainer::getInstance()->register('tempdir')->asValue($dir); return $this; } @@ -72,12 +70,11 @@ class Swift_Preferences * * @param string $type * - * @return Swift_Preferences + * @return $this */ public function setCacheType($type) { - Swift_DependencyContainer::getInstance() - ->register('cache')->asAliasOf(sprintf('cache.%s', $type)); + Swift_DependencyContainer::getInstance()->register('cache')->asAliasOf(sprintf('cache.%s', $type)); return $this; } @@ -87,7 +84,7 @@ class Swift_Preferences * * @param bool $dotEscape * - * @return Swift_Preferences + * @return $this */ public function setQPDotEscape($dotEscape) { diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/SendmailTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/SendmailTransport.php index 974b24f2701..c129281b347 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/SendmailTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/SendmailTransport.php @@ -30,16 +30,4 @@ class Swift_SendmailTransport extends Swift_Transport_SendmailTransport $this->setCommand($command); } - - /** - * Create a new SendmailTransport instance. - * - * @param string $command - * - * @return Swift_SendmailTransport - */ - public static function newInstance($command = '/usr/sbin/sendmail -bs') - { - return new self($command); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/SignedMessage.php b/htdocs/includes/swiftmailer/lib/classes/Swift/SignedMessage.php deleted file mode 100644 index 2e7a8726d21..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/SignedMessage.php +++ /dev/null @@ -1,23 +0,0 @@ - - * - * @deprecated - */ -class Swift_SignedMessage extends Swift_Message -{ -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/BodySigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/BodySigner.php index 9ffcef39c9f..8e66e18f4e0 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/BodySigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/BodySigner.php @@ -20,7 +20,7 @@ interface Swift_Signers_BodySigner extends Swift_Signer * * @param Swift_Message $message * - * @return Swift_Signers_BodySigner + * @return self */ public function signMessage(Swift_Message $message); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php index 6040b2856f2..a88daa19815 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php @@ -11,7 +11,7 @@ /** * DKIM Signer used to apply DKIM Signature to a message. * - * @author Xavier De Cock + * @author Xavier De Cock */ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner { @@ -20,99 +20,103 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @var string */ - protected $_privateKey; + protected $privateKey; /** * DomainName. * * @var string */ - protected $_domainName; + protected $domainName; /** * Selector. * * @var string */ - protected $_selector; + protected $selector; + + private $passphrase = ''; /** * Hash algorithm used. * + * @see RFC6376 3.3: Signers MUST implement and SHOULD sign using rsa-sha256. + * * @var string */ - protected $_hashAlgorithm = 'rsa-sha1'; + protected $hashAlgorithm = 'rsa-sha256'; /** * Body canon method. * * @var string */ - protected $_bodyCanon = 'simple'; + protected $bodyCanon = 'simple'; /** * Header canon method. * * @var string */ - protected $_headerCanon = 'simple'; + protected $headerCanon = 'simple'; /** * Headers not being signed. * * @var array */ - protected $_ignoredHeaders = array('return-path' => true); + protected $ignoredHeaders = array('return-path' => true); /** * Signer identity. * * @var string */ - protected $_signerIdentity; + protected $signerIdentity; /** * BodyLength. * * @var int */ - protected $_bodyLen = 0; + protected $bodyLen = 0; /** * Maximum signedLen. * * @var int */ - protected $_maxLen = PHP_INT_MAX; + protected $maxLen = PHP_INT_MAX; /** * Embbed bodyLen in signature. * * @var bool */ - protected $_showLen = false; + protected $showLen = false; /** * When the signature has been applied (true means time()), false means not embedded. * * @var mixed */ - protected $_signatureTimestamp = true; + protected $signatureTimestamp = true; /** * When will the signature expires false means not embedded, if sigTimestamp is auto - * Expiration is relative, otherwhise it's absolute. + * Expiration is relative, otherwise it's absolute. * * @var int */ - protected $_signatureExpiration = false; + protected $signatureExpiration = false; /** * Must we embed signed headers? * * @var bool */ - protected $_debugHeaders = false; + protected $debugHeaders = false; // work variables /** @@ -120,46 +124,46 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @var array */ - protected $_signedHeaders = array(); + protected $signedHeaders = array(); /** - * If debugHeaders is set store debugDatas here. + * If debugHeaders is set store debugData here. * * @var string */ - private $_debugHeadersData = ''; + private $debugHeadersData = ''; /** * Stores the bodyHash. * * @var string */ - private $_bodyHash = ''; + private $bodyHash = ''; /** * Stores the signature header. * * @var Swift_Mime_Headers_ParameterizedHeader */ - protected $_dkimHeader; + protected $dkimHeader; - private $_bodyHashHandler; + private $bodyHashHandler; - private $_headerHash; + private $headerHash; - private $_headerCanonData = ''; + private $headerCanonData = ''; - private $_bodyCanonEmptyCounter = 0; + private $bodyCanonEmptyCounter = 0; - private $_bodyCanonIgnoreStart = 2; + private $bodyCanonIgnoreStart = 2; - private $_bodyCanonSpace = false; + private $bodyCanonSpace = false; - private $_bodyCanonLastChar = null; + private $bodyCanonLastChar = null; - private $_bodyCanonLine = ''; + private $bodyCanonLine = ''; - private $_bound = array(); + private $bound = array(); /** * Constructor. @@ -167,27 +171,15 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * @param string $privateKey * @param string $domainName * @param string $selector + * @param string $passphrase */ - public function __construct($privateKey, $domainName, $selector) + public function __construct($privateKey, $domainName, $selector, $passphrase = '') { - $this->_privateKey = $privateKey; - $this->_domainName = $domainName; - $this->_signerIdentity = '@'.$domainName; - $this->_selector = $selector; - } - - /** - * Instanciate DKIMSigner. - * - * @param string $privateKey - * @param string $domainName - * @param string $selector - * - * @return Swift_Signers_DKIMSigner - */ - public static function newInstance($privateKey, $domainName, $selector) - { - return new static($privateKey, $domainName, $selector); + $this->privateKey = $privateKey; + $this->domainName = $domainName; + $this->signerIdentity = '@'.$domainName; + $this->selector = $selector; + $this->passphrase = $passphrase; } /** @@ -197,14 +189,14 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner */ public function reset() { - $this->_headerHash = null; - $this->_signedHeaders = array(); - $this->_bodyHash = null; - $this->_bodyHashHandler = null; - $this->_bodyCanonIgnoreStart = 2; - $this->_bodyCanonEmptyCounter = 0; - $this->_bodyCanonLastChar = null; - $this->_bodyCanonSpace = false; + $this->headerHash = null; + $this->signedHeaders = array(); + $this->bodyHash = null; + $this->bodyHashHandler = null; + $this->bodyCanonIgnoreStart = 2; + $this->bodyCanonEmptyCounter = 0; + $this->bodyCanonLastChar = null; + $this->bodyCanonSpace = false; } /** @@ -219,14 +211,15 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param string $bytes * - * @throws Swift_IoException - * * @return int + * + * @throws Swift_IoException */ + // TODO fix return public function write($bytes) { - $this->_canonicalizeBody($bytes); - foreach ($this->_bound as $is) { + $this->canonicalizeBody($bytes); + foreach ($this->bound as $is) { $is->write($bytes); } } @@ -234,8 +227,6 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner /** * For any bytes that are currently buffered inside the stream, force them * off the buffer. - * - * @throws Swift_IoException */ public function commit() { @@ -253,7 +244,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner public function bind(Swift_InputByteStream $is) { // Don't have to mirror anything - $this->_bound[] = $is; + $this->bound[] = $is; return; } @@ -269,15 +260,13 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner public function unbind(Swift_InputByteStream $is) { // Don't have to mirror anything - foreach ($this->_bound as $k => $stream) { + foreach ($this->bound as $k => $stream) { if ($stream === $is) { - unset($this->_bound[$k]); + unset($this->bound[$k]); return; } } - - return; } /** @@ -292,19 +281,28 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner } /** - * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1 defaults to rsa-sha256. + * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1. * - * @param string $hash + * @param string $hash 'rsa-sha1' or 'rsa-sha256' * - * @return Swift_Signers_DKIMSigner + * @throws Swift_SwiftException + * + * @return $this */ public function setHashAlgorithm($hash) { - // Unable to sign with rsa-sha256 - if ($hash == 'rsa-sha1') { - $this->_hashAlgorithm = 'rsa-sha1'; - } else { - $this->_hashAlgorithm = 'rsa-sha256'; + switch ($hash) { + case 'rsa-sha1': + $this->hashAlgorithm = 'rsa-sha1'; + break; + case 'rsa-sha256': + $this->hashAlgorithm = 'rsa-sha256'; + if (!defined('OPENSSL_ALGO_SHA256')) { + throw new Swift_SwiftException('Unable to set sha256 as it is not supported by OpenSSL.'); + } + break; + default: + throw new Swift_SwiftException('Unable to set the hash algorithm, must be one of rsa-sha1 or rsa-sha256 (%s given).', $hash); } return $this; @@ -315,14 +313,14 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param string $canon * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setBodyCanon($canon) { if ($canon == 'relaxed') { - $this->_bodyCanon = 'relaxed'; + $this->bodyCanon = 'relaxed'; } else { - $this->_bodyCanon = 'simple'; + $this->bodyCanon = 'simple'; } return $this; @@ -333,14 +331,14 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param string $canon * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setHeaderCanon($canon) { if ($canon == 'relaxed') { - $this->_headerCanon = 'relaxed'; + $this->headerCanon = 'relaxed'; } else { - $this->_headerCanon = 'simple'; + $this->headerCanon = 'simple'; } return $this; @@ -351,11 +349,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param string $identity * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setSignerIdentity($identity) { - $this->_signerIdentity = $identity; + $this->signerIdentity = $identity; return $this; } @@ -365,19 +363,19 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param mixed $len (bool or int) * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setBodySignedLen($len) { if ($len === true) { - $this->_showLen = true; - $this->_maxLen = PHP_INT_MAX; + $this->showLen = true; + $this->maxLen = PHP_INT_MAX; } elseif ($len === false) { $this->showLen = false; - $this->_maxLen = PHP_INT_MAX; + $this->maxLen = PHP_INT_MAX; } else { - $this->_showLen = true; - $this->_maxLen = (int) $len; + $this->showLen = true; + $this->maxLen = (int) $len; } return $this; @@ -388,11 +386,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param int $time A timestamp * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setSignatureTimestamp($time) { - $this->_signatureTimestamp = $time; + $this->signatureTimestamp = $time; return $this; } @@ -402,11 +400,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param int $time A timestamp * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setSignatureExpiration($time) { - $this->_signatureExpiration = $time; + $this->signatureExpiration = $time; return $this; } @@ -420,7 +418,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner */ public function setDebugHeaders($debug) { - $this->_debugHeaders = (bool) $debug; + $this->debugHeaders = (bool) $debug; return $this; } @@ -431,15 +429,15 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner public function startBody() { // Init - switch ($this->_hashAlgorithm) { - case 'rsa-sha256' : - $this->_bodyHashHandler = hash_init('sha256'); + switch ($this->hashAlgorithm) { + case 'rsa-sha256': + $this->bodyHashHandler = hash_init('sha256'); break; - case 'rsa-sha1' : - $this->_bodyHashHandler = hash_init('sha1'); + case 'rsa-sha1': + $this->bodyHashHandler = hash_init('sha1'); break; } - $this->_bodyCanonLine = ''; + $this->bodyCanonLine = ''; } /** @@ -447,7 +445,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner */ public function endBody() { - $this->_endOfBody(); + $this->endOfBody(); } /** @@ -457,7 +455,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner */ public function getAlteredHeaders() { - if ($this->_debugHeaders) { + if ($this->debugHeaders) { return array('DKIM-Signature', 'X-DebugHash'); } else { return array('DKIM-Signature'); @@ -473,7 +471,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner */ public function ignoreHeader($header_name) { - $this->_ignoredHeaders[strtolower($header_name)] = true; + $this->ignoredHeaders[strtolower($header_name)] = true; return $this; } @@ -481,24 +479,24 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner /** * Set the headers to sign. * - * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_SimpleHeaderSet $headers * * @return Swift_Signers_DKIMSigner */ - public function setHeaders(Swift_Mime_HeaderSet $headers) + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers) { - $this->_headerCanonData = ''; + $this->headerCanonData = ''; // Loop through Headers $listHeaders = $headers->listAll(); foreach ($listHeaders as $hName) { // Check if we need to ignore Header - if (!isset($this->_ignoredHeaders[strtolower($hName)])) { + if (!isset($this->ignoredHeaders[strtolower($hName)])) { if ($headers->has($hName)) { $tmp = $headers->getAll($hName); foreach ($tmp as $header) { if ($header->getFieldBody() != '') { - $this->_addHeader($header->toString()); - $this->_signedHeaders[] = $header->getFieldName(); + $this->addHeader($header->toString()); + $this->signedHeaders[] = $header->getFieldName(); } } } @@ -511,37 +509,37 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner /** * Add the signature to the given Headers. * - * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_SimpleHeaderSet $headers * * @return Swift_Signers_DKIMSigner */ - public function addSignature(Swift_Mime_HeaderSet $headers) + public function addSignature(Swift_Mime_SimpleHeaderSet $headers) { // Prepare the DKIM-Signature - $params = array('v' => '1', 'a' => $this->_hashAlgorithm, 'bh' => base64_encode($this->_bodyHash), 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'i' => $this->_signerIdentity, 's' => $this->_selector); - if ($this->_bodyCanon != 'simple') { - $params['c'] = $this->_headerCanon.'/'.$this->_bodyCanon; - } elseif ($this->_headerCanon != 'simple') { - $params['c'] = $this->_headerCanon; + $params = array('v' => '1', 'a' => $this->hashAlgorithm, 'bh' => base64_encode($this->bodyHash), 'd' => $this->domainName, 'h' => implode(': ', $this->signedHeaders), 'i' => $this->signerIdentity, 's' => $this->selector); + if ($this->bodyCanon != 'simple') { + $params['c'] = $this->headerCanon.'/'.$this->bodyCanon; + } elseif ($this->headerCanon != 'simple') { + $params['c'] = $this->headerCanon; } - if ($this->_showLen) { - $params['l'] = $this->_bodyLen; + if ($this->showLen) { + $params['l'] = $this->bodyLen; } - if ($this->_signatureTimestamp === true) { + if ($this->signatureTimestamp === true) { $params['t'] = time(); - if ($this->_signatureExpiration !== false) { - $params['x'] = $params['t'] + $this->_signatureExpiration; + if ($this->signatureExpiration !== false) { + $params['x'] = $params['t'] + $this->signatureExpiration; } } else { - if ($this->_signatureTimestamp !== false) { - $params['t'] = $this->_signatureTimestamp; + if ($this->signatureTimestamp !== false) { + $params['t'] = $this->signatureTimestamp; } - if ($this->_signatureExpiration !== false) { - $params['x'] = $this->_signatureExpiration; + if ($this->signatureExpiration !== false) { + $params['x'] = $this->signatureExpiration; } } - if ($this->_debugHeaders) { - $params['z'] = implode('|', $this->_debugHeadersData); + if ($this->debugHeaders) { + $params['z'] = implode('|', $this->debugHeadersData); } $string = ''; foreach ($params as $k => $v) { @@ -551,67 +549,57 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner $headers->addTextHeader('DKIM-Signature', $string); // Add the last DKIM-Signature $tmp = $headers->getAll('DKIM-Signature'); - $this->_dkimHeader = end($tmp); - $this->_addHeader(trim($this->_dkimHeader->toString())."\r\n b=", true); - $this->_endOfHeaders(); - if ($this->_debugHeaders) { - $headers->addTextHeader('X-DebugHash', base64_encode($this->_headerHash)); + $this->dkimHeader = end($tmp); + $this->addHeader(trim($this->dkimHeader->toString())."\r\n b=", true); + if ($this->debugHeaders) { + $headers->addTextHeader('X-DebugHash', base64_encode($this->headerHash)); } - $this->_dkimHeader->setValue($string.' b='.trim(chunk_split(base64_encode($this->_getEncryptedHash()), 73, ' '))); + $this->dkimHeader->setValue($string.' b='.trim(chunk_split(base64_encode($this->getEncryptedHash()), 73, ' '))); return $this; } /* Private helpers */ - protected function _addHeader($header, $is_sig = false) + protected function addHeader($header, $is_sig = false) { - switch ($this->_headerCanon) { - case 'relaxed' : + switch ($this->headerCanon) { + case 'relaxed': // Prepare Header and cascade $exploded = explode(':', $header, 2); $name = strtolower(trim($exploded[0])); $value = str_replace("\r\n", '', $exploded[1]); $value = preg_replace("/[ \t][ \t]+/", ' ', $value); $header = $name.':'.trim($value).($is_sig ? '' : "\r\n"); - case 'simple' : + case 'simple': // Nothing to do } - $this->_addToHeaderHash($header); + $this->addToHeaderHash($header); } - /** - * @deprecated This method is currently useless in this class but it must be - * kept for BC reasons due to its "protected" scope. This method - * might be overriden by custom client code. - */ - protected function _endOfHeaders() - { - } - - protected function _canonicalizeBody($string) + protected function canonicalizeBody($string) { $len = strlen($string); $canon = ''; - $method = ($this->_bodyCanon == 'relaxed'); + $method = ($this->bodyCanon == 'relaxed'); for ($i = 0; $i < $len; ++$i) { - if ($this->_bodyCanonIgnoreStart > 0) { - --$this->_bodyCanonIgnoreStart; + if ($this->bodyCanonIgnoreStart > 0) { + --$this->bodyCanonIgnoreStart; continue; } switch ($string[$i]) { - case "\r" : - $this->_bodyCanonLastChar = "\r"; + case "\r": + $this->bodyCanonLastChar = "\r"; break; - case "\n" : - if ($this->_bodyCanonLastChar == "\r") { + case "\n": + if ($this->bodyCanonLastChar == "\r") { if ($method) { - $this->_bodyCanonSpace = false; + $this->bodyCanonSpace = false; } - if ($this->_bodyCanonLine == '') { - ++$this->_bodyCanonEmptyCounter; + if ($this->bodyCanonLine == '') { + ++$this->bodyCanonEmptyCounter; } else { - $this->_bodyCanonLine = ''; + $this->bodyCanonLine = ''; $canon .= "\r\n"; } } else { @@ -619,55 +607,55 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner // todo handle it but should never happen } break; - case ' ' : - case "\t" : + case ' ': + case "\t": if ($method) { - $this->_bodyCanonSpace = true; + $this->bodyCanonSpace = true; break; } - default : - if ($this->_bodyCanonEmptyCounter > 0) { - $canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter); - $this->_bodyCanonEmptyCounter = 0; + default: + if ($this->bodyCanonEmptyCounter > 0) { + $canon .= str_repeat("\r\n", $this->bodyCanonEmptyCounter); + $this->bodyCanonEmptyCounter = 0; } - if ($this->_bodyCanonSpace) { - $this->_bodyCanonLine .= ' '; + if ($this->bodyCanonSpace) { + $this->bodyCanonLine .= ' '; $canon .= ' '; - $this->_bodyCanonSpace = false; + $this->bodyCanonSpace = false; } - $this->_bodyCanonLine .= $string[$i]; + $this->bodyCanonLine .= $string[$i]; $canon .= $string[$i]; } } - $this->_addToBodyHash($canon); + $this->addToBodyHash($canon); } - protected function _endOfBody() + protected function endOfBody() { // Add trailing Line return if last line is non empty - if (strlen($this->_bodyCanonLine) > 0) { - $this->_addToBodyHash("\r\n"); + if (strlen($this->bodyCanonLine) > 0) { + $this->addToBodyHash("\r\n"); } - $this->_bodyHash = hash_final($this->_bodyHashHandler, true); + $this->bodyHash = hash_final($this->bodyHashHandler, true); } - private function _addToBodyHash($string) + private function addToBodyHash($string) { $len = strlen($string); - if ($len > ($new_len = ($this->_maxLen - $this->_bodyLen))) { + if ($len > ($new_len = ($this->maxLen - $this->bodyLen))) { $string = substr($string, 0, $new_len); $len = $new_len; } - hash_update($this->_bodyHashHandler, $string); - $this->_bodyLen += $len; + hash_update($this->bodyHashHandler, $string); + $this->bodyLen += $len; } - private function _addToHeaderHash($header) + private function addToHeaderHash($header) { - if ($this->_debugHeaders) { - $this->_debugHeadersData[] = trim($header); + if ($this->debugHeaders) { + $this->debugHeadersData[] = trim($header); } - $this->_headerCanonData .= $header; + $this->headerCanonData .= $header; } /** @@ -675,10 +663,10 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @return string */ - private function _getEncryptedHash() + private function getEncryptedHash() { $signature = ''; - switch ($this->_hashAlgorithm) { + switch ($this->hashAlgorithm) { case 'rsa-sha1': $algorithm = OPENSSL_ALGO_SHA1; break; @@ -686,11 +674,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner $algorithm = OPENSSL_ALGO_SHA256; break; } - $pkeyId = openssl_get_privatekey($this->_privateKey); + $pkeyId = openssl_get_privatekey($this->privateKey, $this->passphrase); if (!$pkeyId) { throw new Swift_SwiftException('Unable to load DKIM Private Key ['.openssl_error_string().']'); } - if (openssl_sign($this->_headerCanonData, $signature, $pkeyId, $algorithm)) { + if (openssl_sign($this->headerCanonData, $signature, $pkeyId, $algorithm)) { return $signature; } throw new Swift_SwiftException('Unable to sign DKIM Hash ['.openssl_error_string().']'); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php index 3f42d3f6e90..40654987f9b 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php @@ -11,7 +11,7 @@ /** * DomainKey Signer used to apply DomainKeys Signature to a message. * - * @author Xavier De Cock + * @author Xavier De Cock */ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner { @@ -20,56 +20,56 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @var string */ - protected $_privateKey; + protected $privateKey; /** * DomainName. * * @var string */ - protected $_domainName; + protected $domainName; /** * Selector. * * @var string */ - protected $_selector; + protected $selector; /** * Hash algorithm used. * * @var string */ - protected $_hashAlgorithm = 'rsa-sha1'; + protected $hashAlgorithm = 'rsa-sha1'; /** * Canonisation method. * * @var string */ - protected $_canon = 'simple'; + protected $canon = 'simple'; /** * Headers not being signed. * * @var array */ - protected $_ignoredHeaders = array(); + protected $ignoredHeaders = array(); /** * Signer identity. * * @var string */ - protected $_signerIdentity; + protected $signerIdentity; /** * Must we embed signed headers? * * @var bool */ - protected $_debugHeaders = false; + protected $debugHeaders = false; // work variables /** @@ -77,37 +77,37 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @var array */ - private $_signedHeaders = array(); + private $signedHeaders = array(); /** * Stores the signature header. * * @var Swift_Mime_Headers_ParameterizedHeader */ - protected $_domainKeyHeader; + protected $domainKeyHeader; /** * Hash Handler. * * @var resource|null */ - private $_hashHandler; + private $hashHandler; - private $_hash; + private $hash; - private $_canonData = ''; + private $canonData = ''; - private $_bodyCanonEmptyCounter = 0; + private $bodyCanonEmptyCounter = 0; - private $_bodyCanonIgnoreStart = 2; + private $bodyCanonIgnoreStart = 2; - private $_bodyCanonSpace = false; + private $bodyCanonSpace = false; - private $_bodyCanonLastChar = null; + private $bodyCanonLastChar = null; - private $_bodyCanonLine = ''; + private $bodyCanonLine = ''; - private $_bound = array(); + private $bound = array(); /** * Constructor. @@ -118,39 +118,25 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner */ public function __construct($privateKey, $domainName, $selector) { - $this->_privateKey = $privateKey; - $this->_domainName = $domainName; - $this->_signerIdentity = '@'.$domainName; - $this->_selector = $selector; - } - - /** - * Instanciate DomainKeySigner. - * - * @param string $privateKey - * @param string $domainName - * @param string $selector - * - * @return Swift_Signers_DomainKeySigner - */ - public static function newInstance($privateKey, $domainName, $selector) - { - return new static($privateKey, $domainName, $selector); + $this->privateKey = $privateKey; + $this->domainName = $domainName; + $this->signerIdentity = '@'.$domainName; + $this->selector = $selector; } /** * Resets internal states. * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function reset() { - $this->_hash = null; - $this->_hashHandler = null; - $this->_bodyCanonIgnoreStart = 2; - $this->_bodyCanonEmptyCounter = 0; - $this->_bodyCanonLastChar = null; - $this->_bodyCanonSpace = false; + $this->hash = null; + $this->hashHandler = null; + $this->bodyCanonIgnoreStart = 2; + $this->bodyCanonEmptyCounter = 0; + $this->bodyCanonLastChar = null; + $this->bodyCanonSpace = false; return $this; } @@ -167,15 +153,16 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param string $bytes * + * @return int + * * @throws Swift_IoException * - * @return int - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function write($bytes) { - $this->_canonicalizeBody($bytes); - foreach ($this->_bound as $is) { + $this->canonicalizeBody($bytes); + foreach ($this->bound as $is) { $is->write($bytes); } @@ -188,7 +175,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @throws Swift_IoException * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function commit() { @@ -203,12 +190,12 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param Swift_InputByteStream $is * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function bind(Swift_InputByteStream $is) { // Don't have to mirror anything - $this->_bound[] = $is; + $this->bound[] = $is; return $this; } @@ -221,16 +208,16 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param Swift_InputByteStream $is * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function unbind(Swift_InputByteStream $is) { // Don't have to mirror anything - foreach ($this->_bound as $k => $stream) { + foreach ($this->bound as $k => $stream) { if ($stream === $is) { - unset($this->_bound[$k]); + unset($this->bound[$k]); - return; + break; } } @@ -243,7 +230,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @throws Swift_IoException * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function flushBuffers() { @@ -257,11 +244,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param string $hash * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function setHashAlgorithm($hash) { - $this->_hashAlgorithm = 'rsa-sha1'; + $this->hashAlgorithm = 'rsa-sha1'; return $this; } @@ -271,14 +258,14 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param string $canon simple | nofws defaults to simple * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function setCanon($canon) { if ($canon == 'nofws') { - $this->_canon = 'nofws'; + $this->canon = 'nofws'; } else { - $this->_canon = 'simple'; + $this->canon = 'simple'; } return $this; @@ -289,11 +276,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param string $identity * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function setSignerIdentity($identity) { - $this->_signerIdentity = $identity; + $this->signerIdentity = $identity; return $this; } @@ -303,11 +290,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param bool $debug * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function setDebugHeaders($debug) { - $this->_debugHeaders = (bool) $debug; + $this->debugHeaders = (bool) $debug; return $this; } @@ -324,7 +311,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner */ public function endBody() { - $this->_endOfBody(); + $this->endOfBody(); } /** @@ -334,7 +321,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner */ public function getAlteredHeaders() { - if ($this->_debugHeaders) { + if ($this->debugHeaders) { return array('DomainKey-Signature', 'X-DebugHash'); } @@ -346,11 +333,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param string $header_name * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function ignoreHeader($header_name) { - $this->_ignoredHeaders[strtolower($header_name)] = true; + $this->ignoredHeaders[strtolower($header_name)] = true; return $this; } @@ -358,31 +345,31 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner /** * Set the headers to sign. * - * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_SimpleHeaderSet $headers * - * @return Swift_Signers_DomainKeySigner + * @return $this */ - public function setHeaders(Swift_Mime_HeaderSet $headers) + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers) { - $this->_startHash(); - $this->_canonData = ''; + $this->startHash(); + $this->canonData = ''; // Loop through Headers $listHeaders = $headers->listAll(); foreach ($listHeaders as $hName) { // Check if we need to ignore Header - if (!isset($this->_ignoredHeaders[strtolower($hName)])) { + if (!isset($this->ignoredHeaders[strtolower($hName)])) { if ($headers->has($hName)) { $tmp = $headers->getAll($hName); foreach ($tmp as $header) { if ($header->getFieldBody() != '') { - $this->_addHeader($header->toString()); - $this->_signedHeaders[] = $header->getFieldName(); + $this->addHeader($header->toString()); + $this->signedHeaders[] = $header->getFieldName(); } } } } } - $this->_endOfHeaders(); + $this->endOfHeaders(); return $this; } @@ -390,14 +377,14 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner /** * Add the signature to the given Headers. * - * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_SimpleHeaderSet $headers * - * @return Swift_Signers_DomainKeySigner + * @return $this */ - public function addSignature(Swift_Mime_HeaderSet $headers) + public function addSignature(Swift_Mime_SimpleHeaderSet $headers) { // Prepare the DomainKey-Signature Header - $params = array('a' => $this->_hashAlgorithm, 'b' => chunk_split(base64_encode($this->_getEncryptedHash()), 73, ' '), 'c' => $this->_canon, 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'q' => 'dns', 's' => $this->_selector); + $params = array('a' => $this->hashAlgorithm, 'b' => chunk_split(base64_encode($this->getEncryptedHash()), 73, ' '), 'c' => $this->canon, 'd' => $this->domainName, 'h' => implode(': ', $this->signedHeaders), 'q' => 'dns', 's' => $this->selector); $string = ''; foreach ($params as $k => $v) { $string .= $k.'='.$v.'; '; @@ -410,50 +397,50 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner /* Private helpers */ - protected function _addHeader($header) + protected function addHeader($header) { - switch ($this->_canon) { - case 'nofws' : + switch ($this->canon) { + case 'nofws': // Prepare Header and cascade $exploded = explode(':', $header, 2); $name = strtolower(trim($exploded[0])); $value = str_replace("\r\n", '', $exploded[1]); $value = preg_replace("/[ \t][ \t]+/", ' ', $value); $header = $name.':'.trim($value)."\r\n"; - case 'simple' : + case 'simple': // Nothing to do } - $this->_addToHash($header); + $this->addToHash($header); } - protected function _endOfHeaders() + protected function endOfHeaders() { - $this->_bodyCanonEmptyCounter = 1; + $this->bodyCanonEmptyCounter = 1; } - protected function _canonicalizeBody($string) + protected function canonicalizeBody($string) { $len = strlen($string); $canon = ''; - $nofws = ($this->_canon == 'nofws'); + $nofws = ($this->canon == 'nofws'); for ($i = 0; $i < $len; ++$i) { - if ($this->_bodyCanonIgnoreStart > 0) { - --$this->_bodyCanonIgnoreStart; + if ($this->bodyCanonIgnoreStart > 0) { + --$this->bodyCanonIgnoreStart; continue; } switch ($string[$i]) { - case "\r" : - $this->_bodyCanonLastChar = "\r"; + case "\r": + $this->bodyCanonLastChar = "\r"; break; - case "\n" : - if ($this->_bodyCanonLastChar == "\r") { + case "\n": + if ($this->bodyCanonLastChar == "\r") { if ($nofws) { - $this->_bodyCanonSpace = false; + $this->bodyCanonSpace = false; } - if ($this->_bodyCanonLine == '') { - ++$this->_bodyCanonEmptyCounter; + if ($this->bodyCanonLine == '') { + ++$this->bodyCanonEmptyCounter; } else { - $this->_bodyCanonLine = ''; + $this->bodyCanonLine = ''; $canon .= "\r\n"; } } else { @@ -461,48 +448,48 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner throw new Swift_SwiftException('Invalid new line sequence in mail found \n without preceding \r'); } break; - case ' ' : - case "\t" : + case ' ': + case "\t": case "\x09": //HTAB if ($nofws) { - $this->_bodyCanonSpace = true; + $this->bodyCanonSpace = true; break; } - default : - if ($this->_bodyCanonEmptyCounter > 0) { - $canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter); - $this->_bodyCanonEmptyCounter = 0; + default: + if ($this->bodyCanonEmptyCounter > 0) { + $canon .= str_repeat("\r\n", $this->bodyCanonEmptyCounter); + $this->bodyCanonEmptyCounter = 0; } - $this->_bodyCanonLine .= $string[$i]; + $this->bodyCanonLine .= $string[$i]; $canon .= $string[$i]; } } - $this->_addToHash($canon); + $this->addToHash($canon); } - protected function _endOfBody() + protected function endOfBody() { - if (strlen($this->_bodyCanonLine) > 0) { - $this->_addToHash("\r\n"); + if (strlen($this->bodyCanonLine) > 0) { + $this->addToHash("\r\n"); } - $this->_hash = hash_final($this->_hashHandler, true); + $this->hash = hash_final($this->hashHandler, true); } - private function _addToHash($string) + private function addToHash($string) { - $this->_canonData .= $string; - hash_update($this->_hashHandler, $string); + $this->canonData .= $string; + hash_update($this->hashHandler, $string); } - private function _startHash() + private function startHash() { // Init - switch ($this->_hashAlgorithm) { - case 'rsa-sha1' : - $this->_hashHandler = hash_init('sha1'); + switch ($this->hashAlgorithm) { + case 'rsa-sha1': + $this->hashHandler = hash_init('sha1'); break; } - $this->_canonLine = ''; + $this->bodyCanonLine = ''; } /** @@ -510,14 +497,14 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @return string */ - private function _getEncryptedHash() + private function getEncryptedHash() { $signature = ''; - $pkeyId = openssl_get_privatekey($this->_privateKey); + $pkeyId = openssl_get_privatekey($this->privateKey); if (!$pkeyId) { throw new Swift_SwiftException('Unable to load DomainKey Private Key ['.openssl_error_string().']'); } - if (openssl_sign($this->_canonData, $signature, $pkeyId, OPENSSL_ALGO_SHA1)) { + if (openssl_sign($this->canonData, $signature, $pkeyId, OPENSSL_ALGO_SHA1)) { return $signature; } throw new Swift_SwiftException('Unable to sign DomainKey Hash ['.openssl_error_string().']'); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php index c75cb08a518..6104e34f3f5 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php @@ -20,21 +20,21 @@ interface Swift_Signers_HeaderSigner extends Swift_Signer, Swift_InputByteStream * * @param string $header_name * - * @return Swift_Signers_HeaderSigner + * @return self */ public function ignoreHeader($header_name); /** * Prepare the Signer to get a new Body. * - * @return Swift_Signers_HeaderSigner + * @return self */ public function startBody(); /** * Give the signal that the body has finished streaming. * - * @return Swift_Signers_HeaderSigner + * @return self */ public function endBody(); @@ -43,18 +43,18 @@ interface Swift_Signers_HeaderSigner extends Swift_Signer, Swift_InputByteStream * * @param Swift_Mime_SimpleHeaderSet $headers * - * @return Swift_Signers_HeaderSigner + * @return self */ - public function setHeaders(Swift_Mime_HeaderSet $headers); + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers); /** * Add the header(s) to the headerSet. * - * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_SimpleHeaderSet $headers * - * @return Swift_Signers_HeaderSigner + * @return self */ - public function addSignature(Swift_Mime_HeaderSet $headers); + public function addSignature(Swift_Mime_SimpleHeaderSet $headers); /** * Return the list of header a signer might tamper. diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php index 3a35ad55d07..deb29f575f2 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php @@ -12,13 +12,13 @@ * DKIM Signer used to apply DKIM Signature to a message * Takes advantage of pecl extension. * - * @author Xavier De Cock + * @author Xavier De Cock */ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner { - private $_peclLoaded = false; + private $peclLoaded = false; - private $_dkimHandler = null; + private $dkimHandler = null; private $dropFirstLF = true; @@ -33,22 +33,17 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner throw new Swift_SwiftException('php-opendkim extension not found'); } - $this->_peclLoaded = true; + $this->peclLoaded = true; parent::__construct($privateKey, $domainName, $selector); } - public static function newInstance($privateKey, $domainName, $selector) - { - return new static($privateKey, $domainName, $selector); - } - - public function addSignature(Swift_Mime_HeaderSet $headers) + public function addSignature(Swift_Mime_SimpleHeaderSet $headers) { $header = new Swift_Mime_Headers_OpenDKIMHeader('DKIM-Signature'); - $headerVal = $this->_dkimHandler->getSignatureHeader(); + $headerVal = $this->dkimHandler->getSignatureHeader(); if (!$headerVal) { - throw new Swift_SwiftException('OpenDKIM Error: '.$this->_dkimHandler->getError()); + throw new Swift_SwiftException('OpenDKIM Error: '.$this->dkimHandler->getError()); } $header->setValue($headerVal); $headers->set($header); @@ -56,40 +51,40 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner return $this; } - public function setHeaders(Swift_Mime_HeaderSet $headers) + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers) { - $bodyLen = $this->_bodyLen; + $bodyLen = $this->bodyLen; if (is_bool($bodyLen)) { $bodyLen = -1; } - $hash = $this->_hashAlgorithm == 'rsa-sha1' ? OpenDKIMSign::ALG_RSASHA1 : OpenDKIMSign::ALG_RSASHA256; - $bodyCanon = $this->_bodyCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; - $headerCanon = $this->_headerCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; - $this->_dkimHandler = new OpenDKIMSign($this->_privateKey, $this->_selector, $this->_domainName, $headerCanon, $bodyCanon, $hash, $bodyLen); + $hash = $this->hashAlgorithm == 'rsa-sha1' ? OpenDKIMSign::ALG_RSASHA1 : OpenDKIMSign::ALG_RSASHA256; + $bodyCanon = $this->bodyCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; + $headerCanon = $this->headerCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; + $this->dkimHandler = new OpenDKIMSign($this->privateKey, $this->selector, $this->domainName, $headerCanon, $bodyCanon, $hash, $bodyLen); // Hardcode signature Margin for now - $this->_dkimHandler->setMargin(78); + $this->dkimHandler->setMargin(78); - if (!is_numeric($this->_signatureTimestamp)) { + if (!is_numeric($this->signatureTimestamp)) { OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, time()); } else { - if (!OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, $this->_signatureTimestamp)) { + if (!OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, $this->signatureTimestamp)) { throw new Swift_SwiftException('Unable to force signature timestamp ['.openssl_error_string().']'); } } - if (isset($this->_signerIdentity)) { - $this->_dkimHandler->setSigner($this->_signerIdentity); + if (isset($this->signerIdentity)) { + $this->dkimHandler->setSigner($this->signerIdentity); } $listHeaders = $headers->listAll(); foreach ($listHeaders as $hName) { // Check if we need to ignore Header - if (!isset($this->_ignoredHeaders[strtolower($hName)])) { + if (!isset($this->ignoredHeaders[strtolower($hName)])) { $tmp = $headers->getAll($hName); if ($headers->has($hName)) { foreach ($tmp as $header) { if ($header->getFieldBody() != '') { $htosign = $header->toString(); - $this->_dkimHandler->header($htosign); - $this->_signedHeaders[] = $header->getFieldName(); + $this->dkimHandler->header($htosign); + $this->signedHeaders[] = $header->getFieldName(); } } } @@ -101,28 +96,28 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner public function startBody() { - if (!$this->_peclLoaded) { + if (!$this->peclLoaded) { return parent::startBody(); } $this->dropFirstLF = true; - $this->_dkimHandler->eoh(); + $this->dkimHandler->eoh(); return $this; } public function endBody() { - if (!$this->_peclLoaded) { + if (!$this->peclLoaded) { return parent::endBody(); } - $this->_dkimHandler->eom(); + $this->dkimHandler->eom(); return $this; } public function reset() { - $this->_dkimHandler = null; + $this->dkimHandler = null; parent::reset(); return $this; @@ -133,11 +128,11 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner * * @param int $time * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setSignatureTimestamp($time) { - $this->_signatureTimestamp = $time; + $this->signatureTimestamp = $time; return $this; } @@ -147,11 +142,11 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner * * @param int $time * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setSignatureExpiration($time) { - $this->_signatureExpiration = $time; + $this->signatureExpiration = $time; return $this; } @@ -161,21 +156,21 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner * * @param bool $debug * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setDebugHeaders($debug) { - $this->_debugHeaders = (bool) $debug; + $this->debugHeaders = (bool) $debug; return $this; } // Protected - protected function _canonicalizeBody($string) + protected function canonicalizeBody($string) { - if (!$this->_peclLoaded) { - return parent::_canonicalizeBody($string); + if (!$this->peclLoaded) { + return parent::canonicalizeBody($string); } if (false && $this->dropFirstLF === true) { if ($string[0] == "\r" && $string[1] == "\n") { @@ -184,7 +179,7 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner } $this->dropFirstLF = false; if (strlen($string)) { - $this->_dkimHandler->body($string); + $this->dkimHandler->body($string); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php index b267099a860..eea2648c9e9 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php @@ -34,7 +34,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner protected $replacementFactory; /** - * @var Swift_Mime_HeaderFactory + * @var Swift_Mime_SimpleHeaderFactory */ protected $headerFactory; @@ -59,39 +59,20 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner ->lookup('transport.replacementfactory'); $this->signOptions = PKCS7_DETACHED; - - // Supported since php5.4 - if (defined('OPENSSL_CIPHER_AES_128_CBC')) { - $this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC; - } else { - $this->encryptCipher = OPENSSL_CIPHER_RC2_128; - } - } - - /** - * Returns an new Swift_Signers_SMimeSigner instance. - * - * @param string $certificate - * @param string $privateKey - * - * @return Swift_Signers_SMimeSigner - */ - public static function newInstance($certificate = null, $privateKey = null) - { - return new self($certificate, $privateKey); + $this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC; } /** * Set the certificate location to use for signing. * - * @link http://www.php.net/manual/en/openssl.pkcs7.flags.php + * @see http://www.php.net/manual/en/openssl.pkcs7.flags.php * * @param string $certificate * @param string|array $privateKey If the key needs an passphrase use array('file-location', 'passphrase') instead * @param int $signOptions Bitwise operator options for openssl_pkcs7_sign() * @param string $extraCerts A file containing intermediate certificates needed by the signing certificate * - * @return Swift_Signers_SMimeSigner + * @return $this */ public function setSignCertificate($certificate, $privateKey = null, $signOptions = PKCS7_DETACHED, $extraCerts = null) { @@ -117,13 +98,13 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner /** * Set the certificate location to use for encryption. * - * @link http://www.php.net/manual/en/openssl.pkcs7.flags.php - * @link http://nl3.php.net/manual/en/openssl.ciphers.php + * @see http://www.php.net/manual/en/openssl.pkcs7.flags.php + * @see http://nl3.php.net/manual/en/openssl.ciphers.php * * @param string|array $recipientCerts Either an single X.509 certificate, or an assoc array of X.509 certificates. * @param int $cipher * - * @return Swift_Signers_SMimeSigner + * @return $this */ public function setEncryptCertificate($recipientCerts, $cipher = null) { @@ -169,7 +150,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner * * @param bool $signThenEncrypt * - * @return Swift_Signers_SMimeSigner + * @return $this */ public function setSignThenEncrypt($signThenEncrypt = true) { @@ -189,7 +170,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner /** * Resets internal states. * - * @return Swift_Signers_SMimeSigner + * @return $this */ public function reset() { @@ -201,7 +182,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner * * @param Swift_Message $message * - * @return Swift_Signers_SMimeSigner + * @return $this */ public function signMessage(Swift_Message $message) { @@ -297,7 +278,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner $args[] = $this->extraCerts; } - if (!call_user_func_array('openssl_pkcs7_sign', $args)) { + if (!openssl_pkcs7_sign(...$args)) { throw new Swift_IoException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string())); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/SmtpTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/SmtpTransport.php index 62516114019..011c03ab188 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/SmtpTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/SmtpTransport.php @@ -11,7 +11,7 @@ /** * Sends Messages over SMTP with ESMTP support. * - * @author Chris Corbyn + * @author Chris Corbyn * * @method Swift_SmtpTransport setUsername(string $username) Set the username to authenticate with. * @method string getUsername() Get the username to authenticate with. @@ -41,18 +41,4 @@ class Swift_SmtpTransport extends Swift_Transport_EsmtpTransport $this->setPort($port); $this->setEncryption($security); } - - /** - * Create a new SmtpTransport instance. - * - * @param string $host - * @param int $port - * @param string $security - * - * @return Swift_SmtpTransport - */ - public static function newInstance($host = 'localhost', $port = 25, $security = null) - { - return new self($host, $port, $security); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Spool.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Spool.php index c16ab4b38eb..9d0e8fee2be 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Spool.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Spool.php @@ -35,11 +35,11 @@ interface Swift_Spool /** * Queues a message. * - * @param Swift_Mime_Message $message The message to store + * @param Swift_Mime_SimpleMessage $message The message to store * * @return bool Whether the operation has succeeded */ - public function queueMessage(Swift_Mime_Message $message); + public function queueMessage(Swift_Mime_SimpleMessage $message); /** * Sends messages using the given transport instance. diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/SpoolTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/SpoolTransport.php index cf9bf78fb8f..f92567ba021 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/SpoolTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/SpoolTransport.php @@ -32,16 +32,4 @@ class Swift_SpoolTransport extends Swift_Transport_SpoolTransport $arguments ); } - - /** - * Create a new SpoolTransport instance. - * - * @param Swift_Spool $spool - * - * @return Swift_SpoolTransport - */ - public static function newInstance(Swift_Spool $spool) - { - return new self($spool); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php index d5735667b94..ba1f6d323fc 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php @@ -13,26 +13,26 @@ * * This stream filter deals with Byte arrays rather than simple strings. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilter { /** The needle(s) to search for */ - private $_search; + private $search; /** The replacement(s) to make */ - private $_replace; + private $replace; /** The Index for searching */ - private $_index; + private $index; /** The Search Tree */ - private $_tree = array(); + private $tree = array(); /** Gives the size of the largest search */ - private $_treeMaxLen = 0; + private $treeMaxLen = 0; - private $_repSize; + private $repSize; /** * Create a new ByteArrayReplacementFilter with $search and $replace. @@ -42,11 +42,11 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt */ public function __construct($search, $replace) { - $this->_search = $search; - $this->_index = array(); - $this->_tree = array(); - $this->_replace = array(); - $this->_repSize = array(); + $this->search = $search; + $this->index = array(); + $this->tree = array(); + $this->replace = array(); + $this->repSize = array(); $tree = null; $i = null; @@ -56,10 +56,10 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt $tree[-1] = min(count($replace) - 1, $i - 1); $tree[-2] = $last_size; } - $tree = &$this->_tree; + $tree = &$this->tree; if (is_array($search_element)) { foreach ($search_element as $k => $char) { - $this->_index[$char] = true; + $this->index[$char] = true; if (!isset($tree[$char])) { $tree[$char] = array(); } @@ -74,23 +74,23 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt } $tree = &$tree[$search_element]; $size = max($last_size, $size); - $this->_index[$search_element] = true; + $this->index[$search_element] = true; } } if ($i !== null) { $tree[-1] = min(count($replace) - 1, $i); $tree[-2] = $last_size; - $this->_treeMaxLen = $size; + $this->treeMaxLen = $size; } foreach ($replace as $rep) { if (!is_array($rep)) { $rep = array($rep); } - $this->_replace[] = $rep; + $this->replace[] = $rep; } - for ($i = count($this->_replace) - 1; $i >= 0; --$i) { - $this->_replace[$i] = $rep = $this->filter($this->_replace[$i], $i); - $this->_repSize[$i] = count($rep); + for ($i = count($this->replace) - 1; $i >= 0; --$i) { + $this->replace[$i] = $rep = $this->filter($this->replace[$i], $i); + $this->repSize[$i] = count($rep); } } @@ -105,36 +105,37 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt { $endOfBuffer = end($buffer); - return isset($this->_index[$endOfBuffer]); + return isset($this->index[$endOfBuffer]); } /** * Perform the actual replacements on $buffer and return the result. * * @param array $buffer - * @param int $_minReplaces + * @param int $minReplaces * * @return array */ - public function filter($buffer, $_minReplaces = -1) + public function filter($buffer, $minReplaces = -1) { - if ($this->_treeMaxLen == 0) { + if ($this->treeMaxLen == 0) { return $buffer; } $newBuffer = array(); $buf_size = count($buffer); + $last_size = 0; for ($i = 0; $i < $buf_size; ++$i) { - $search_pos = $this->_tree; + $search_pos = $this->tree; $last_found = PHP_INT_MAX; // We try to find if the next byte is part of a search pattern - for ($j = 0; $j <= $this->_treeMaxLen; ++$j) { + for ($j = 0; $j <= $this->treeMaxLen; ++$j) { // We have a new byte for a search pattern - if (isset($buffer [$p = $i + $j]) && isset($search_pos[$buffer[$p]])) { + if (isset($buffer[$p = $i + $j]) && isset($search_pos[$buffer[$p]])) { $search_pos = $search_pos[$buffer[$p]]; // We have a complete pattern, save, in case we don't find a better match later if (isset($search_pos[-1]) && $search_pos[-1] < $last_found - && $search_pos[-1] > $_minReplaces) { + && $search_pos[-1] > $minReplaces) { $last_found = $search_pos[-1]; $last_size = $search_pos[-2]; } @@ -142,9 +143,9 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt // We got a complete pattern elseif ($last_found !== PHP_INT_MAX) { // Adding replacement datas to output buffer - $rep_size = $this->_repSize[$last_found]; + $rep_size = $this->repSize[$last_found]; for ($j = 0; $j < $rep_size; ++$j) { - $newBuffer[] = $this->_replace[$last_found][$j]; + $newBuffer[] = $this->replace[$last_found][$j]; } // We Move cursor forward $i += $last_size - 1; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php index d0db8b96197..50a63f1aaa2 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php @@ -16,10 +16,10 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter { /** The needle(s) to search for */ - private $_search; + private $search; /** The replacement(s) to make */ - private $_replace; + private $replace; /** * Create a new StringReplacementFilter with $search and $replace. @@ -29,8 +29,8 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter */ public function __construct($search, $replace) { - $this->_search = $search; - $this->_replace = $replace; + $this->search = $search; + $this->replace = $replace; } /** @@ -42,8 +42,12 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter */ public function shouldBuffer($buffer) { + if ('' === $buffer) { + return false; + } + $endOfBuffer = substr($buffer, -1); - foreach ((array) $this->_search as $needle) { + foreach ((array) $this->search as $needle) { if (false !== strpos($needle, $endOfBuffer)) { return true; } @@ -61,6 +65,6 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter */ public function filter($buffer) { - return str_replace($this->_search, $this->_replace, $buffer); + return str_replace($this->search, $this->replace, $buffer); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php index e98240b5bc5..f60f0cf8218 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php @@ -16,7 +16,7 @@ class Swift_StreamFilters_StringReplacementFilterFactory implements Swift_ReplacementFilterFactory { /** Lazy-loaded filters */ - private $_filters = array(); + private $filters = array(); /** * Create a new StreamFilter to replace $search with $replace in a string. @@ -28,18 +28,18 @@ class Swift_StreamFilters_StringReplacementFilterFactory implements Swift_Replac */ public function createFilter($search, $replace) { - if (!isset($this->_filters[$search][$replace])) { - if (!isset($this->_filters[$search])) { - $this->_filters[$search] = array(); + if (!isset($this->filters[$search][$replace])) { + if (!isset($this->filters[$search])) { + $this->filters[$search] = array(); } - if (!isset($this->_filters[$search][$replace])) { - $this->_filters[$search][$replace] = array(); + if (!isset($this->filters[$search][$replace])) { + $this->filters[$search][$replace] = array(); } - $this->_filters[$search][$replace] = new Swift_StreamFilters_StringReplacementFilter($search, $replace); + $this->filters[$search][$replace] = new Swift_StreamFilters_StringReplacementFilter($search, $replace); } - return $this->_filters[$search][$replace]; + return $this->filters[$search][$replace]; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport.php index 6535eadf253..f6214b7bfc5 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport.php @@ -32,18 +32,41 @@ interface Swift_Transport */ public function stop(); + /** + * Check if this Transport mechanism is alive. + * + * If a Transport mechanism session is no longer functional, the method + * returns FALSE. It is the responsibility of the developer to handle this + * case and restart the Transport mechanism manually. + * + * @example + * + * if (!$transport->ping()) { + * $transport->stop(); + * $transport->start(); + * } + * + * The Transport mechanism will be started, if it is not already. + * + * It is undefined if the Transport mechanism attempts to restart as long as + * the return value reflects whether the mechanism is now functional. + * + * @return bool TRUE if the transport is alive + */ + public function ping(); + /** * Send the given Message. * * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null); + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null); /** * Register a plugin in the Transport. diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php index 72d4ecdff4d..34c3323fdba 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php @@ -16,34 +16,35 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport { /** Input-Output buffer for sending/receiving SMTP commands and responses */ - protected $_buffer; + protected $buffer; /** Connection status */ - protected $_started = false; + protected $started = false; /** The domain name to use in HELO command */ - protected $_domain = '[127.0.0.1]'; + protected $domain = '[127.0.0.1]'; /** The event dispatching layer */ - protected $_eventDispatcher; + protected $eventDispatcher; /** Source Ip */ - protected $_sourceIp; + protected $sourceIp; /** Return an array of params for the Buffer */ - abstract protected function _getBufferParams(); + abstract protected function getBufferParams(); /** * Creates a new EsmtpTransport using the given I/O buffer. * * @param Swift_Transport_IoBuffer $buf * @param Swift_Events_EventDispatcher $dispatcher + * @param string $localDomain */ - public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher) + public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1') { - $this->_eventDispatcher = $dispatcher; - $this->_buffer = $buf; - $this->_lookupHostname(); + $this->eventDispatcher = $dispatcher; + $this->buffer = $buf; + $this->setLocalDomain($localDomain); } /** @@ -52,16 +53,25 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport * This should be a fully-qualified domain name and should be truly the domain * you're using. * - * If your server doesn't have a domain name, use the IP in square - * brackets (i.e. [127.0.0.1]). + * If your server does not have a domain name, use the IP address. This will + * automatically be wrapped in square brackets as described in RFC 5321, + * section 4.1.3. * * @param string $domain * - * @return Swift_Transport_AbstractSmtpTransport + * @return $this */ public function setLocalDomain($domain) { - $this->_domain = $domain; + if (substr($domain, 0, 1) !== '[') { + if (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + $domain = '['.$domain.']'; + } elseif (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + $domain = '[IPv6:'.$domain.']'; + } + } + + $this->domain = $domain; return $this; } @@ -69,11 +79,14 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport /** * Get the name of the domain Swift will identify as. * + * If an IP address was specified, this will be returned wrapped in square + * brackets as described in RFC 5321, section 4.1.3. + * * @return string */ public function getLocalDomain() { - return $this->_domain; + return $this->domain; } /** @@ -83,7 +96,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function setSourceIp($source) { - $this->_sourceIp = $source; + $this->sourceIp = $source; } /** @@ -93,7 +106,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function getSourceIp() { - return $this->_sourceIp; + return $this->sourceIp; } /** @@ -101,27 +114,27 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function start() { - if (!$this->_started) { - if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStarted'); + if (!$this->started) { + if ($evt = $this->eventDispatcher->createTransportChangeEvent($this)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeTransportStarted'); if ($evt->bubbleCancelled()) { return; } } try { - $this->_buffer->initialize($this->_getBufferParams()); + $this->buffer->initialize($this->getBufferParams()); } catch (Swift_TransportException $e) { - $this->_throwException($e); + $this->throwException($e); } - $this->_readGreeting(); - $this->_doHeloCommand(); + $this->readGreeting(); + $this->doHeloCommand(); if ($evt) { - $this->_eventDispatcher->dispatchEvent($evt, 'transportStarted'); + $this->eventDispatcher->dispatchEvent($evt, 'transportStarted'); } - $this->_started = true; + $this->started = true; } } @@ -132,7 +145,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function isStarted() { - return $this->_started; + return $this->started; } /** @@ -141,25 +154,25 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { $sent = 0; $failedRecipients = (array) $failedRecipients; - if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } - if (!$reversePath = $this->_getReversePath($message)) { - $this->_throwException(new Swift_TransportException( + if (!$reversePath = $this->getReversePath($message)) { + $this->throwException(new Swift_TransportException( 'Cannot send message without a sender address' ) ); @@ -173,8 +186,8 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport $message->setBcc(array()); try { - $sent += $this->_sendTo($message, $reversePath, $tos, $failedRecipients); - $sent += $this->_sendBcc($message, $reversePath, $bcc, $failedRecipients); + $sent += $this->sendTo($message, $reversePath, $tos, $failedRecipients); + $sent += $this->sendBcc($message, $reversePath, $bcc, $failedRecipients); } catch (Exception $e) { $message->setBcc($bcc); throw $e; @@ -191,7 +204,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED); } $evt->setFailedRecipients($failedRecipients); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } $message->generateId(); //Make sure a new Message ID is used @@ -204,9 +217,9 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function stop() { - if ($this->_started) { - if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped'); + if ($this->started) { + if ($evt = $this->eventDispatcher->createTransportChangeEvent($this)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped'); if ($evt->bubbleCancelled()) { return; } @@ -218,16 +231,39 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } try { - $this->_buffer->terminate(); + $this->buffer->terminate(); if ($evt) { - $this->_eventDispatcher->dispatchEvent($evt, 'transportStopped'); + $this->eventDispatcher->dispatchEvent($evt, 'transportStopped'); } } catch (Swift_TransportException $e) { - $this->_throwException($e); + $this->throwException($e); } } - $this->_started = false; + $this->started = false; + } + + /** + * {@inheritdoc} + */ + public function ping() + { + try { + if (!$this->isStarted()) { + $this->start(); + } + + $this->executeCommand("NOOP\r\n", array(250)); + } catch (Swift_TransportException $e) { + try { + $this->stop(); + } catch (Swift_TransportException $e) { + } + + return false; + } + + return true; } /** @@ -237,7 +273,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function registerPlugin(Swift_Events_EventListener $plugin) { - $this->_eventDispatcher->bindEventListener($plugin); + $this->eventDispatcher->bindEventListener($plugin); } /** @@ -255,7 +291,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function getBuffer() { - return $this->_buffer; + return $this->buffer; } /** @@ -273,32 +309,32 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport public function executeCommand($command, $codes = array(), &$failures = null) { $failures = (array) $failures; - $seq = $this->_buffer->write($command); - $response = $this->_getFullResponse($seq); - if ($evt = $this->_eventDispatcher->createCommandEvent($this, $command, $codes)) { - $this->_eventDispatcher->dispatchEvent($evt, 'commandSent'); + $seq = $this->buffer->write($command); + $response = $this->getFullResponse($seq); + if ($evt = $this->eventDispatcher->createCommandEvent($this, $command, $codes)) { + $this->eventDispatcher->dispatchEvent($evt, 'commandSent'); } - $this->_assertResponseCode($response, $codes); + $this->assertResponseCode($response, $codes); return $response; } /** Read the opening SMTP greeting */ - protected function _readGreeting() + protected function readGreeting() { - $this->_assertResponseCode($this->_getFullResponse(0), array(220)); + $this->assertResponseCode($this->getFullResponse(0), array(220)); } /** Send the HELO welcome */ - protected function _doHeloCommand() + protected function doHeloCommand() { $this->executeCommand( - sprintf("HELO %s\r\n", $this->_domain), array(250) + sprintf("HELO %s\r\n", $this->domain), array(250) ); } /** Send the MAIL FROM command */ - protected function _doMailFromCommand($address) + protected function doMailFromCommand($address) { $this->executeCommand( sprintf("MAIL FROM:<%s>\r\n", $address), array(250) @@ -306,7 +342,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Send the RCPT TO command */ - protected function _doRcptToCommand($address) + protected function doRcptToCommand($address) { $this->executeCommand( sprintf("RCPT TO:<%s>\r\n", $address), array(250, 251, 252) @@ -314,27 +350,27 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Send the DATA command */ - protected function _doDataCommand() + protected function doDataCommand() { $this->executeCommand("DATA\r\n", array(354)); } /** Stream the contents of the message over the buffer */ - protected function _streamMessage(Swift_Mime_Message $message) + protected function streamMessage(Swift_Mime_SimpleMessage $message) { - $this->_buffer->setWriteTranslations(array("\r\n." => "\r\n..")); + $this->buffer->setWriteTranslations(array("\r\n." => "\r\n..")); try { - $message->toByteStream($this->_buffer); - $this->_buffer->flushBuffers(); + $message->toByteStream($this->buffer); + $this->buffer->flushBuffers(); } catch (Swift_TransportException $e) { - $this->_throwException($e); + $this->throwException($e); } - $this->_buffer->setWriteTranslations(array()); + $this->buffer->setWriteTranslations(array()); $this->executeCommand("\r\n.\r\n", array(250)); } /** Determine the best-use reverse path for this message */ - protected function _getReversePath(Swift_Mime_Message $message) + protected function getReversePath(Swift_Mime_SimpleMessage $message) { $return = $message->getReturnPath(); $sender = $message->getSender(); @@ -355,10 +391,10 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Throw a TransportException, first sending it to any listeners */ - protected function _throwException(Swift_TransportException $e) + protected function throwException(Swift_TransportException $e) { - if ($evt = $this->_eventDispatcher->createTransportExceptionEvent($this, $e)) { - $this->_eventDispatcher->dispatchEvent($evt, 'exceptionThrown'); + if ($evt = $this->eventDispatcher->createTransportExceptionEvent($this, $e)) { + $this->eventDispatcher->dispatchEvent($evt, 'exceptionThrown'); if (!$evt->bubbleCancelled()) { throw $e; } @@ -368,18 +404,18 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Throws an Exception if a response code is incorrect */ - protected function _assertResponseCode($response, $wanted) + protected function assertResponseCode($response, $wanted) { list($code) = sscanf($response, '%3d'); $valid = (empty($wanted) || in_array($code, $wanted)); - if ($evt = $this->_eventDispatcher->createResponseEvent($this, $response, + if ($evt = $this->eventDispatcher->createResponseEvent($this, $response, $valid)) { - $this->_eventDispatcher->dispatchEvent($evt, 'responseReceived'); + $this->eventDispatcher->dispatchEvent($evt, 'responseReceived'); } if (!$valid) { - $this->_throwException( + $this->throwException( new Swift_TransportException( 'Expected response code '.implode('/', $wanted).' but got code '. '"'.$code.'", with message "'.$response.'"', @@ -389,18 +425,18 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Get an entire multi-line response using its sequence number */ - protected function _getFullResponse($seq) + protected function getFullResponse($seq) { $response = ''; try { do { - $line = $this->_buffer->readLine($seq); + $line = $this->buffer->readLine($seq); $response .= $line; - } while (null !== $line && false !== $line && ' ' != $line{3}); + } while (null !== $line && false !== $line && ' ' != $line[3]); } catch (Swift_TransportException $e) { - $this->_throwException($e); + $this->throwException($e); } catch (Swift_IoException $e) { - $this->_throwException( + $this->throwException( new Swift_TransportException( $e->getMessage()) ); @@ -410,13 +446,13 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Send an email to the given recipients from the given reverse path */ - private function _doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients) + private function doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients) { $sent = 0; - $this->_doMailFromCommand($reversePath); + $this->doMailFromCommand($reversePath); foreach ($recipients as $forwardPath) { try { - $this->_doRcptToCommand($forwardPath); + $this->doRcptToCommand($forwardPath); ++$sent; } catch (Swift_TransportException $e) { $failedRecipients[] = $forwardPath; @@ -424,8 +460,8 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } if ($sent != 0) { - $this->_doDataCommand(); - $this->_streamMessage($message); + $this->doDataCommand(); + $this->streamMessage($message); } else { $this->reset(); } @@ -434,23 +470,23 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Send a message to the given To: recipients */ - private function _sendTo(Swift_Mime_Message $message, $reversePath, array $to, array &$failedRecipients) + private function sendTo(Swift_Mime_SimpleMessage $message, $reversePath, array $to, array &$failedRecipients) { if (empty($to)) { return 0; } - return $this->_doMailTransaction($message, $reversePath, array_keys($to), + return $this->doMailTransaction($message, $reversePath, array_keys($to), $failedRecipients); } /** Send a message to all Bcc: recipients */ - private function _sendBcc(Swift_Mime_Message $message, $reversePath, array $bcc, array &$failedRecipients) + private function sendBcc(Swift_Mime_SimpleMessage $message, $reversePath, array $bcc, array &$failedRecipients) { $sent = 0; foreach ($bcc as $forwardPath => $name) { $message->setBcc(array($forwardPath => $name)); - $sent += $this->_doMailTransaction( + $sent += $this->doMailTransaction( $message, $reversePath, array($forwardPath), $failedRecipients ); } @@ -458,33 +494,14 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport return $sent; } - /** Try to determine the hostname of the server this is run on */ - private function _lookupHostname() - { - if (!empty($_SERVER['SERVER_NAME']) - && $this->_isFqdn($_SERVER['SERVER_NAME'])) { - $this->_domain = $_SERVER['SERVER_NAME']; - } elseif (!empty($_SERVER['SERVER_ADDR'])) { - $this->_domain = sprintf('[%s]', $_SERVER['SERVER_ADDR']); - } - } - - /** Determine is the $hostname is a fully-qualified name */ - private function _isFqdn($hostname) - { - // We could do a really thorough check, but there's really no point - if (false !== $dotPos = strpos($hostname, '.')) { - return ($dotPos > 0) && ($dotPos != strlen($hostname) - 1); - } - - return false; - } - /** * Destructor. */ public function __destruct() { - $this->stop(); + try { + $this->stop(); + } catch (Exception $e) { + } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php index 53f721d03c6..26c2d745a95 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php @@ -40,7 +40,7 @@ class Swift_Transport_Esmtp_Auth_CramMd5Authenticator implements Swift_Transport $challenge = $agent->executeCommand("AUTH CRAM-MD5\r\n", array(334)); $challenge = base64_decode(substr($challenge, 4)); $message = base64_encode( - $username.' '.$this->_getResponse($password, $challenge) + $username.' '.$this->getResponse($password, $challenge) ); $agent->executeCommand(sprintf("%s\r\n", $message), array(235)); @@ -60,7 +60,7 @@ class Swift_Transport_Esmtp_Auth_CramMd5Authenticator implements Swift_Transport * * @return string */ - private function _getResponse($secret, $challenge) + private function getResponse($secret, $challenge) { if (strlen($secret) > 64) { $secret = pack('H32', md5($secret)); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php index d8331316963..fa5d2110041 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php @@ -13,7 +13,7 @@ /** * Handles NTLM authentication. * - * @author Ward Peeters + * @author Ward Peeters */ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Esmtp_Authenticator { @@ -38,19 +38,17 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es * @param string $password * * @return bool + * + * @throws \LogicException */ public function authenticate(Swift_Transport_SmtpAgent $agent, $username, $password) { - if (!function_exists('mcrypt_module_open')) { - throw new LogicException('The mcrypt functions need to be enabled to use the NTLM authenticator.'); - } - - if (!function_exists('openssl_random_pseudo_bytes')) { + if (!function_exists('openssl_encrypt')) { throw new LogicException('The OpenSSL extension must be enabled to use the NTLM authenticator.'); } if (!function_exists('bcmul')) { - throw new LogicException('The BCMatch functions must be enabled to use the NTLM authenticator.'); + throw new LogicException('The BCMath functions must be enabled to use the NTLM authenticator.'); } try { @@ -60,7 +58,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es // extra parameters for our unit cases $timestamp = func_num_args() > 3 ? func_get_arg(3) : $this->getCorrectTimestamp(bcmul(microtime(true), '1000')); - $client = func_num_args() > 4 ? func_get_arg(4) : $this->getRandomBytes(8); + $client = func_num_args() > 4 ? func_get_arg(4) : random_bytes(8); // Message 3 response $this->sendMessage3($response, $username, $password, $timestamp, $client, $agent); @@ -125,10 +123,10 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es $responseHex = bin2hex($response); $length = floor(hexdec(substr($responseHex, 28, 4)) / 256) * 2; $offset = floor(hexdec(substr($responseHex, 32, 4)) / 256) * 2; - $challenge = $this->hex2bin(substr($responseHex, 48, 16)); - $context = $this->hex2bin(substr($responseHex, 64, 16)); - $targetInfoH = $this->hex2bin(substr($responseHex, 80, 16)); - $targetName = $this->hex2bin(substr($responseHex, $offset, $length)); + $challenge = hex2bin(substr($responseHex, 48, 16)); + $context = hex2bin(substr($responseHex, 64, 16)); + $targetInfoH = hex2bin(substr($responseHex, 80, 16)); + $targetName = hex2bin(substr($responseHex, $offset, $length)); $offset = floor(hexdec(substr($responseHex, 88, 4)) / 256) * 2; $targetInfoBlock = substr($responseHex, $offset); list($domainName, $serverName, $DNSDomainName, $DNSServerName, $terminatorByte) = $this->readSubBlock($targetInfoBlock); @@ -142,7 +140,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es $serverName, $DNSDomainName, $DNSServerName, - $this->hex2bin($targetInfoBlock), + hex2bin($targetInfoBlock), $terminatorByte, ); } @@ -165,7 +163,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es while ($offset < $length) { $blockLength = hexdec(substr(substr($block, $offset, 8), -4)) / 256; $offset += 8; - $data[] = $this->hex2bin(substr($block, $offset, $blockLength * 2)); + $data[] = hex2bin(substr($block, $offset, $blockLength * 2)); $offset += $blockLength * 2; } @@ -300,9 +298,14 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es return explode('\\', $name); } - list($user, $domain) = explode('@', $name); + if (false !== strpos($name, '@')) { + list($user, $domain) = explode('@', $name); - return array($domain, $user); + return array($domain, $user); + } + + // no domain passed + return array('', $name); } /** @@ -365,11 +368,9 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es protected function getCorrectTimestamp($time) { // Get our timestamp (tricky!) - bcscale(0); - $time = number_format($time, 0, '.', ''); // save microtime to string - $time = bcadd($time, '11644473600000'); // add epoch time - $time = bcmul($time, 10000); // tenths of a microsecond. + $time = bcadd($time, '11644473600000', 0); // add epoch time + $time = bcmul($time, 10000, 0); // tenths of a microsecond. $binary = $this->si2bin($time, 64); // create 64 bit binary string $timestamp = ''; @@ -459,10 +460,11 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es } } - return $this->hex2bin(implode('', $material)); + return hex2bin(implode('', $material)); } /** HELPER FUNCTIONS */ + /** * Create our security buffer depending on length and offset. * @@ -538,7 +540,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es protected function createByte($input, $bytes = 4, $isHex = true) { if ($isHex) { - $byte = $this->hex2bin(str_pad($input, $bytes * 2, '00')); + $byte = hex2bin(str_pad($input, $bytes * 2, '00')); } else { $byte = str_pad($input, $bytes, "\x00"); } @@ -546,39 +548,19 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es return $byte; } - /** - * Create random bytes. - * - * @param $length - * - * @return string - */ - protected function getRandomBytes($length) - { - $bytes = openssl_random_pseudo_bytes($length, $strong); - - if (false !== $bytes && true === $strong) { - return $bytes; - } - - throw new RuntimeException('OpenSSL did not produce a secure random number.'); - } - /** ENCRYPTION ALGORITHMS */ + /** * DES Encryption. * - * @param string $value + * @param string $value An 8-byte string * @param string $key * * @return string */ protected function desEncrypt($value, $key) { - $cipher = mcrypt_module_open(MCRYPT_DES, '', 'ecb', ''); - mcrypt_generic_init($cipher, $key, mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_DEV_RANDOM)); - - return mcrypt_generic($cipher, $value); + return substr(openssl_encrypt($value, 'DES-ECB', $key, \OPENSSL_RAW_DATA), 0, 8); } /** @@ -616,7 +598,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es { $input = $this->convertTo16bit($input); - return function_exists('hash') ? $this->hex2bin(hash('md4', $input)) : mhash(MHASH_MD4, $input); + return function_exists('hash') ? hex2bin(hash('md4', $input)) : mhash(MHASH_MD4, $input); } /** @@ -631,22 +613,6 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es return iconv('UTF-8', 'UTF-16LE', $input); } - /** - * Hex2bin replacement for < PHP 5.4. - * - * @param string $hex - * - * @return string Binary - */ - protected function hex2bin($hex) - { - if (function_exists('hex2bin')) { - return hex2bin($hex); - } else { - return pack('H*', $hex); - } - } - /** * @param string $message */ @@ -671,7 +637,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es 'Target Information Terminator', ); - $data = $this->parseMessage2($this->hex2bin($message)); + $data = $this->parseMessage2(hex2bin($message)); foreach ($map as $key => $value) { echo bin2hex($data[$key]).' - '.$data[$key].' ||| '.$value."
\n"; @@ -717,7 +683,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es ); foreach ($map as $key => $value) { - echo $data[$key].' - '.$this->hex2bin($data[$key]).' ||| '.$value."
\n"; + echo $data[$key].' - '.hex2bin($data[$key]).' ||| '.$value."
\n"; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php index ca35e7b83ad..d1a4cc3d774 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php @@ -13,7 +13,7 @@ * * Example: * - * $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls') + * $transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls')) * ->setAuthMode('XOAUTH2') * ->setUsername('YOUR_EMAIL_ADDRESS') * ->setPassword('YOUR_ACCESS_TOKEN'); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php index cb36133c94d..94387f01a2e 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php @@ -20,35 +20,35 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler * * @var Swift_Transport_Esmtp_Authenticator[] */ - private $_authenticators = array(); + private $authenticators = array(); /** * The username for authentication. * * @var string */ - private $_username; + private $username; /** * The password for authentication. * * @var string */ - private $_password; + private $password; /** * The auth mode for authentication. * * @var string */ - private $_auth_mode; + private $auth_mode; /** * The ESMTP AUTH parameters available. * * @var string[] */ - private $_esmtpParams = array(); + private $esmtpParams = array(); /** * Create a new AuthHandler with $authenticators for support. @@ -67,7 +67,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function setAuthenticators(array $authenticators) { - $this->_authenticators = $authenticators; + $this->authenticators = $authenticators; } /** @@ -77,7 +77,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function getAuthenticators() { - return $this->_authenticators; + return $this->authenticators; } /** @@ -87,7 +87,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function setUsername($username) { - $this->_username = $username; + $this->username = $username; } /** @@ -97,7 +97,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function getUsername() { - return $this->_username; + return $this->username; } /** @@ -107,7 +107,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function setPassword($password) { - $this->_password = $password; + $this->password = $password; } /** @@ -117,7 +117,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function getPassword() { - return $this->_password; + return $this->password; } /** @@ -127,7 +127,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function setAuthMode($mode) { - $this->_auth_mode = $mode; + $this->auth_mode = $mode; } /** @@ -137,7 +137,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function getAuthMode() { - return $this->_auth_mode; + return $this->auth_mode; } /** @@ -157,7 +157,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function setKeywordParams(array $parameters) { - $this->_esmtpParams = $parameters; + $this->esmtpParams = $parameters; } /** @@ -167,20 +167,20 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function afterEhlo(Swift_Transport_SmtpAgent $agent) { - if ($this->_username) { + if ($this->username) { $count = 0; - foreach ($this->_getAuthenticatorsForAgent() as $authenticator) { + foreach ($this->getAuthenticatorsForAgent() as $authenticator) { if (in_array(strtolower($authenticator->getAuthKeyword()), - array_map('strtolower', $this->_esmtpParams))) { + array_map('strtolower', $this->esmtpParams))) { ++$count; - if ($authenticator->authenticate($agent, $this->_username, $this->_password)) { + if ($authenticator->authenticate($agent, $this->username, $this->password)) { return; } } } throw new Swift_TransportException( 'Failed to authenticate on SMTP server with username "'. - $this->_username.'" using '.$count.' possible authenticators' + $this->username.'" using '.$count.' possible authenticators' ); } } @@ -246,13 +246,13 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler * * @return array */ - protected function _getAuthenticatorsForAgent() + protected function getAuthenticatorsForAgent() { - if (!$mode = strtolower($this->_auth_mode)) { - return $this->_authenticators; + if (!$mode = strtolower($this->auth_mode)) { + return $this->authenticators; } - foreach ($this->_authenticators as $authenticator) { + foreach ($this->authenticators as $authenticator) { if (strtolower($authenticator->getAuthKeyword()) == $mode) { return array($authenticator); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php index a1cd0dcd1de..7eb7ef33086 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php @@ -20,21 +20,21 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @var Swift_Transport_EsmtpHandler[] */ - private $_handlers = array(); + private $handlers = array(); /** * ESMTP capabilities. * * @var string[] */ - private $_capabilities = array(); + private $capabilities = array(); /** * Connection buffer parameters. * * @var array */ - private $_params = array( + private $params = array( 'protocol' => 'tcp', 'host' => 'localhost', 'port' => 25, @@ -51,10 +51,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * @param Swift_Transport_IoBuffer $buf * @param Swift_Transport_EsmtpHandler[] $extensionHandlers * @param Swift_Events_EventDispatcher $dispatcher + * @param string $localDomain */ - public function __construct(Swift_Transport_IoBuffer $buf, array $extensionHandlers, Swift_Events_EventDispatcher $dispatcher) + public function __construct(Swift_Transport_IoBuffer $buf, array $extensionHandlers, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1') { - parent::__construct($buf, $dispatcher); + parent::__construct($buf, $dispatcher, $localDomain); $this->setExtensionHandlers($extensionHandlers); } @@ -63,11 +64,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param string $host * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setHost($host) { - $this->_params['host'] = $host; + $this->params['host'] = $host; return $this; } @@ -79,7 +80,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getHost() { - return $this->_params['host']; + return $this->params['host']; } /** @@ -87,11 +88,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param int $port * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setPort($port) { - $this->_params['port'] = (int) $port; + $this->params['port'] = (int) $port; return $this; } @@ -103,7 +104,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getPort() { - return $this->_params['port']; + return $this->params['port']; } /** @@ -111,12 +112,12 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param int $timeout seconds * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setTimeout($timeout) { - $this->_params['timeout'] = (int) $timeout; - $this->_buffer->setParam('timeout', (int) $timeout); + $this->params['timeout'] = (int) $timeout; + $this->buffer->setParam('timeout', (int) $timeout); return $this; } @@ -128,7 +129,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getTimeout() { - return $this->_params['timeout']; + return $this->params['timeout']; } /** @@ -136,16 +137,17 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param string $encryption * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setEncryption($encryption) { + $encryption = strtolower($encryption); if ('tls' == $encryption) { - $this->_params['protocol'] = 'tcp'; - $this->_params['tls'] = true; + $this->params['protocol'] = 'tcp'; + $this->params['tls'] = true; } else { - $this->_params['protocol'] = $encryption; - $this->_params['tls'] = false; + $this->params['protocol'] = $encryption; + $this->params['tls'] = false; } return $this; @@ -158,7 +160,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getEncryption() { - return $this->_params['tls'] ? 'tls' : $this->_params['protocol']; + return $this->params['tls'] ? 'tls' : $this->params['protocol']; } /** @@ -166,11 +168,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param array $options * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setStreamOptions($options) { - $this->_params['stream_context_options'] = $options; + $this->params['stream_context_options'] = $options; return $this; } @@ -182,7 +184,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getStreamOptions() { - return $this->_params['stream_context_options']; + return $this->params['stream_context_options']; } /** @@ -190,11 +192,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param string $source * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setSourceIp($source) { - $this->_params['sourceIp'] = $source; + $this->params['sourceIp'] = $source; return $this; } @@ -206,7 +208,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getSourceIp() { - return isset($this->_params['sourceIp']) ? $this->_params['sourceIp'] : null; + return $this->params['sourceIp'] ?? null; } /** @@ -214,7 +216,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param Swift_Transport_EsmtpHandler[] $handlers * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setExtensionHandlers(array $handlers) { @@ -222,10 +224,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo foreach ($handlers as $handler) { $assoc[$handler->getHandledKeyword()] = $handler; } - - @uasort($assoc, array($this, '_sortHandlers')); - $this->_handlers = $assoc; - $this->_setHandlerParams(); + uasort($assoc, function ($a, $b) { + return $a->getPriorityOver($b->getHandledKeyword()); + }); + $this->handlers = $assoc; + $this->setHandlerParams(); return $this; } @@ -237,7 +240,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getExtensionHandlers() { - return array_values($this->_handlers); + return array_values($this->handlers); } /** @@ -257,7 +260,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo $failures = (array) $failures; $stopSignal = false; $response = null; - foreach ($this->_getActiveHandlers() as $handler) { + foreach ($this->getActiveHandlers() as $handler) { $response = $handler->onCommand( $this, $command, $codes, $failures, $stopSignal ); @@ -269,18 +272,16 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo return parent::executeCommand($command, $codes, $failures); } - // -- Mixin invocation code - /** Mixin handling method for ESMTP handlers */ public function __call($method, $args) { - foreach ($this->_handlers as $handler) { + foreach ($this->handlers as $handler) { if (in_array(strtolower($method), array_map('strtolower', (array) $handler->exposeMixinMethods()) )) { $return = call_user_func_array(array($handler, $method), $args); // Allow fluid method calls - if (is_null($return) && substr($method, 0, 3) == 'set') { + if (null === $return && substr($method, 0, 3) == 'set') { return $this; } else { return $return; @@ -291,53 +292,53 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo } /** Get the params to initialize the buffer */ - protected function _getBufferParams() + protected function getBufferParams() { - return $this->_params; + return $this->params; } /** Overridden to perform EHLO instead */ - protected function _doHeloCommand() + protected function doHeloCommand() { try { $response = $this->executeCommand( - sprintf("EHLO %s\r\n", $this->_domain), array(250) + sprintf("EHLO %s\r\n", $this->domain), array(250) ); } catch (Swift_TransportException $e) { - return parent::_doHeloCommand(); + return parent::doHeloCommand(); } - if ($this->_params['tls']) { + if ($this->params['tls']) { try { $this->executeCommand("STARTTLS\r\n", array(220)); - if (!$this->_buffer->startTLS()) { + if (!$this->buffer->startTLS()) { throw new Swift_TransportException('Unable to connect with TLS encryption'); } try { $response = $this->executeCommand( - sprintf("EHLO %s\r\n", $this->_domain), array(250) + sprintf("EHLO %s\r\n", $this->domain), array(250) ); } catch (Swift_TransportException $e) { - return parent::_doHeloCommand(); + return parent::doHeloCommand(); } } catch (Swift_TransportException $e) { - $this->_throwException($e); + $this->throwException($e); } } - $this->_capabilities = $this->_getCapabilities($response); - $this->_setHandlerParams(); - foreach ($this->_getActiveHandlers() as $handler) { + $this->capabilities = $this->getCapabilities($response); + $this->setHandlerParams(); + foreach ($this->getActiveHandlers() as $handler) { $handler->afterEhlo($this); } } /** Overridden to add Extension support */ - protected function _doMailFromCommand($address) + protected function doMailFromCommand($address) { - $handlers = $this->_getActiveHandlers(); + $handlers = $this->getActiveHandlers(); $params = array(); foreach ($handlers as $handler) { $params = array_merge($params, (array) $handler->getMailParams()); @@ -349,9 +350,9 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo } /** Overridden to add Extension support */ - protected function _doRcptToCommand($address) + protected function doRcptToCommand($address) { - $handlers = $this->_getActiveHandlers(); + $handlers = $this->getActiveHandlers(); $params = array(); foreach ($handlers as $handler) { $params = array_merge($params, (array) $handler->getRcptParams()); @@ -363,7 +364,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo } /** Determine ESMTP capabilities by function group */ - private function _getCapabilities($ehloResponse) + private function getCapabilities($ehloResponse) { $capabilities = array(); $ehloResponse = trim($ehloResponse); @@ -382,31 +383,25 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo } /** Set parameters which are used by each extension handler */ - private function _setHandlerParams() + private function setHandlerParams() { - foreach ($this->_handlers as $keyword => $handler) { - if (array_key_exists($keyword, $this->_capabilities)) { - $handler->setKeywordParams($this->_capabilities[$keyword]); + foreach ($this->handlers as $keyword => $handler) { + if (array_key_exists($keyword, $this->capabilities)) { + $handler->setKeywordParams($this->capabilities[$keyword]); } } } /** Get ESMTP handlers which are currently ok to use */ - private function _getActiveHandlers() + private function getActiveHandlers() { $handlers = array(); - foreach ($this->_handlers as $keyword => $handler) { - if (array_key_exists($keyword, $this->_capabilities)) { + foreach ($this->handlers as $keyword => $handler) { + if (array_key_exists($keyword, $this->capabilities)) { $handlers[] = $handler; } } return $handlers; } - - /** Custom sort for extension handler ordering */ - private function _sortHandlers($a, $b) - { - return $a->getPriorityOver($b->getHandledKeyword()); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php index c039f3beccf..94151f89fef 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php @@ -20,7 +20,31 @@ class Swift_Transport_FailoverTransport extends Swift_Transport_LoadBalancedTran * * @var Swift_Transport */ - private $_currentTransport; + private $currentTransport; + + // needed as __construct is called from elsewhere explicitly + public function __construct() + { + parent::__construct(); + } + + /** + * {@inheritdoc} + */ + public function ping() + { + $maxTransports = count($this->transports); + for ($i = 0; $i < $maxTransports + && $transport = $this->getNextTransport(); ++$i) { + if ($transport->ping()) { + return true; + } else { + $this->killCurrentTransport(); + } + } + + return count($this->transports) > 0; + } /** * Send the given Message. @@ -28,35 +52,35 @@ class Swift_Transport_FailoverTransport extends Swift_Transport_LoadBalancedTran * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { - $maxTransports = count($this->_transports); + $maxTransports = count($this->transports); $sent = 0; - $this->_lastUsedTransport = null; + $this->lastUsedTransport = null; for ($i = 0; $i < $maxTransports - && $transport = $this->_getNextTransport(); ++$i) { + && $transport = $this->getNextTransport(); ++$i) { try { if (!$transport->isStarted()) { $transport->start(); } if ($sent = $transport->send($message, $failedRecipients)) { - $this->_lastUsedTransport = $transport; + $this->lastUsedTransport = $transport; return $sent; } } catch (Swift_TransportException $e) { - $this->_killCurrentTransport(); + $this->killCurrentTransport(); } } - if (count($this->_transports) == 0) { + if (count($this->transports) == 0) { throw new Swift_TransportException( 'All Transports in FailoverTransport failed, or no Transports available' ); @@ -65,18 +89,18 @@ class Swift_Transport_FailoverTransport extends Swift_Transport_LoadBalancedTran return $sent; } - protected function _getNextTransport() + protected function getNextTransport() { - if (!isset($this->_currentTransport)) { - $this->_currentTransport = parent::_getNextTransport(); + if (!isset($this->currentTransport)) { + $this->currentTransport = parent::getNextTransport(); } - return $this->_currentTransport; + return $this->currentTransport; } - protected function _killCurrentTransport() + protected function killCurrentTransport() { - $this->_currentTransport = null; - parent::_killCurrentTransport(); + $this->currentTransport = null; + parent::killCurrentTransport(); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php index fbf0b2602e4..dc6a2149bab 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php @@ -20,21 +20,26 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport * * @var Swift_Transport[] */ - private $_deadTransports = array(); + private $deadTransports = array(); /** * The Transports which are used in rotation. * * @var Swift_Transport[] */ - protected $_transports = array(); + protected $transports = array(); /** * The Transport used in the last successful send operation. * * @var Swift_Transport */ - protected $_lastUsedTransport = null; + protected $lastUsedTransport = null; + + // needed as __construct is called from elsewhere explicitly + public function __construct() + { + } /** * Set $transports to delegate to. @@ -43,8 +48,8 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function setTransports(array $transports) { - $this->_transports = $transports; - $this->_deadTransports = array(); + $this->transports = $transports; + $this->deadTransports = array(); } /** @@ -54,7 +59,7 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function getTransports() { - return array_merge($this->_transports, $this->_deadTransports); + return array_merge($this->transports, $this->deadTransports); } /** @@ -64,7 +69,7 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function getLastUsedTransport() { - return $this->_lastUsedTransport; + return $this->lastUsedTransport; } /** @@ -74,7 +79,7 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function isStarted() { - return count($this->_transports) > 0; + return count($this->transports) > 0; } /** @@ -82,7 +87,7 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function start() { - $this->_transports = array_merge($this->_transports, $this->_deadTransports); + $this->transports = array_merge($this->transports, $this->deadTransports); } /** @@ -90,44 +95,58 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function stop() { - foreach ($this->_transports as $transport) { + foreach ($this->transports as $transport) { $transport->stop(); } } + /** + * {@inheritdoc} + */ + public function ping() + { + foreach ($this->transports as $transport) { + if (!$transport->ping()) { + $this->killCurrentTransport(); + } + } + + return count($this->transports) > 0; + } + /** * Send the given Message. * * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { - $maxTransports = count($this->_transports); + $maxTransports = count($this->transports); $sent = 0; - $this->_lastUsedTransport = null; + $this->lastUsedTransport = null; for ($i = 0; $i < $maxTransports - && $transport = $this->_getNextTransport(); ++$i) { + && $transport = $this->getNextTransport(); ++$i) { try { if (!$transport->isStarted()) { $transport->start(); } if ($sent = $transport->send($message, $failedRecipients)) { - $this->_lastUsedTransport = $transport; + $this->lastUsedTransport = $transport; break; } } catch (Swift_TransportException $e) { - $this->_killCurrentTransport(); + $this->killCurrentTransport(); } } - if (count($this->_transports) == 0) { + if (count($this->transports) == 0) { throw new Swift_TransportException( 'All Transports in LoadBalancedTransport failed, or no Transports available' ); @@ -143,7 +162,7 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function registerPlugin(Swift_Events_EventListener $plugin) { - foreach ($this->_transports as $transport) { + foreach ($this->transports as $transport) { $transport->registerPlugin($plugin); } } @@ -153,10 +172,10 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport * * @return Swift_Transport */ - protected function _getNextTransport() + protected function getNextTransport() { - if ($next = array_shift($this->_transports)) { - $this->_transports[] = $next; + if ($next = array_shift($this->transports)) { + $this->transports[] = $next; } return $next; @@ -165,14 +184,14 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport /** * Tag the currently used (top of stack) transport as dead/useless. */ - protected function _killCurrentTransport() + protected function killCurrentTransport() { - if ($transport = array_pop($this->_transports)) { + if ($transport = array_pop($this->transports)) { try { $transport->stop(); } catch (Exception $e) { } - $this->_deadTransports[] = $transport; + $this->deadTransports[] = $transport; } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php deleted file mode 100644 index 77489cedc68..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php +++ /dev/null @@ -1,32 +0,0 @@ -_invoker = $invoker; - $this->_eventDispatcher = $eventDispatcher; - } - - /** - * Not used. - */ - public function isStarted() - { - return false; - } - - /** - * Not used. - */ - public function start() - { - } - - /** - * Not used. - */ - public function stop() - { - } - - /** - * Set the additional parameters used on the mail() function. - * - * This string is formatted for sprintf() where %s is the sender address. - * - * @param string $params - * - * @return Swift_Transport_MailTransport - */ - public function setExtraParams($params) - { - $this->_extraParams = $params; - - return $this; - } - - /** - * Get the additional parameters used on the mail() function. - * - * This string is formatted for sprintf() where %s is the sender address. - * - * @return string - */ - public function getExtraParams() - { - return $this->_extraParams; - } - - /** - * Send the given Message. - * - * Recipient/sender data will be retrieved from the Message API. - * The return value is the number of recipients who were accepted for delivery. - * - * @param Swift_Mime_Message $message - * @param string[] $failedRecipients An array of failures by-reference - * - * @return int - */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) - { - $failedRecipients = (array) $failedRecipients; - - if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); - if ($evt->bubbleCancelled()) { - return 0; - } - } - - $count = ( - count((array) $message->getTo()) - + count((array) $message->getCc()) - + count((array) $message->getBcc()) - ); - - $toHeader = $message->getHeaders()->get('To'); - $subjectHeader = $message->getHeaders()->get('Subject'); - - if (!$toHeader) { - $this->_throwException(new Swift_TransportException('Cannot send message without a recipient')); - } - $to = $toHeader->getFieldBody(); - $subject = $subjectHeader ? $subjectHeader->getFieldBody() : ''; - - $reversePath = $this->_getReversePath($message); - - // Remove headers that would otherwise be duplicated - $message->getHeaders()->remove('To'); - $message->getHeaders()->remove('Subject'); - - $messageStr = $message->toString(); - - $message->getHeaders()->set($toHeader); - $message->getHeaders()->set($subjectHeader); - - // Separate headers from body - if (false !== $endHeaders = strpos($messageStr, "\r\n\r\n")) { - $headers = substr($messageStr, 0, $endHeaders)."\r\n"; //Keep last EOL - $body = substr($messageStr, $endHeaders + 4); - } else { - $headers = $messageStr."\r\n"; - $body = ''; - } - - unset($messageStr); - - if ("\r\n" != PHP_EOL) { - // Non-windows (not using SMTP) - $headers = str_replace("\r\n", PHP_EOL, $headers); - $subject = str_replace("\r\n", PHP_EOL, $subject); - $body = str_replace("\r\n", PHP_EOL, $body); - } else { - // Windows, using SMTP - $headers = str_replace("\r\n.", "\r\n..", $headers); - $subject = str_replace("\r\n.", "\r\n..", $subject); - $body = str_replace("\r\n.", "\r\n..", $body); - } - - if ($this->_invoker->mail($to, $subject, $body, $headers, - sprintf($this->_extraParams, escapeshellarg($reversePath)))) { - if ($evt) { - $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); - $evt->setFailedRecipients($failedRecipients); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); - } - } else { - $failedRecipients = array_merge( - $failedRecipients, - array_keys((array) $message->getTo()), - array_keys((array) $message->getCc()), - array_keys((array) $message->getBcc()) - ); - - if ($evt) { - $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED); - $evt->setFailedRecipients($failedRecipients); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); - } - - $message->generateId(); - - $count = 0; - } - - return $count; - } - - /** - * Register a plugin. - * - * @param Swift_Events_EventListener $plugin - */ - public function registerPlugin(Swift_Events_EventListener $plugin) - { - $this->_eventDispatcher->bindEventListener($plugin); - } - - /** Throw a TransportException, first sending it to any listeners */ - protected function _throwException(Swift_TransportException $e) - { - if ($evt = $this->_eventDispatcher->createTransportExceptionEvent($this, $e)) { - $this->_eventDispatcher->dispatchEvent($evt, 'exceptionThrown'); - if (!$evt->bubbleCancelled()) { - throw $e; - } - } else { - throw $e; - } - } - - /** Determine the best-use reverse path for this message */ - private function _getReversePath(Swift_Mime_Message $message) - { - $return = $message->getReturnPath(); - $sender = $message->getSender(); - $from = $message->getFrom(); - $path = null; - if (!empty($return)) { - $path = $return; - } elseif (!empty($sender)) { - $keys = array_keys($sender); - $path = array_shift($keys); - } elseif (!empty($from)) { - $keys = array_keys($from); - $path = array_shift($keys); - } - - return $path; - } -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/NullTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/NullTransport.php index ad20e0e535f..dc38078c3c3 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/NullTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/NullTransport.php @@ -16,14 +16,14 @@ class Swift_Transport_NullTransport implements Swift_Transport { /** The event dispatcher from the plugin API */ - private $_eventDispatcher; + private $eventDispatcher; /** * Constructor. */ public function __construct(Swift_Events_EventDispatcher $eventDispatcher) { - $this->_eventDispatcher = $eventDispatcher; + $this->eventDispatcher = $eventDispatcher; } /** @@ -50,18 +50,26 @@ class Swift_Transport_NullTransport implements Swift_Transport { } + /** + * {@inheritdoc} + */ + public function ping() + { + return true; + } + /** * Sends the given message. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int The number of sent emails */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { - if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } @@ -69,7 +77,7 @@ class Swift_Transport_NullTransport implements Swift_Transport if ($evt) { $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } $count = ( @@ -88,6 +96,6 @@ class Swift_Transport_NullTransport implements Swift_Transport */ public function registerPlugin(Swift_Events_EventListener $plugin) { - $this->_eventDispatcher->bindEventListener($plugin); + $this->eventDispatcher->bindEventListener($plugin); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php index 34ac4ce3af8..807538505bf 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php @@ -24,7 +24,7 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran * * @var array */ - private $_params = array( + private $params = array( 'timeout' => 30, 'blocking' => 1, 'command' => '/usr/sbin/sendmail -bs', @@ -36,10 +36,11 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran * * @param Swift_Transport_IoBuffer $buf * @param Swift_Events_EventDispatcher $dispatcher + * @param string $localDomain */ - public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher) + public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1') { - parent::__construct($buf, $dispatcher); + parent::__construct($buf, $dispatcher, $localDomain); } /** @@ -64,11 +65,11 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran * * @param string $command * - * @return Swift_Transport_SendmailTransport + * @return $this */ public function setCommand($command) { - $this->_params['command'] = $command; + $this->params['command'] = $command; return $this; } @@ -80,7 +81,7 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran */ public function getCommand() { - return $this->_params['command']; + return $this->params['command']; } /** @@ -92,12 +93,12 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran * NOTE: If using 'sendmail -t' you will not be aware of any failures until * they bounce (i.e. send() will always return 100% success). * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { $failedRecipients = (array) $failedRecipients; $command = $this->getCommand(); @@ -105,18 +106,18 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran $count = 0; if (false !== strpos($command, ' -t')) { - if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } if (false === strpos($command, ' -f')) { - $command .= ' -f'.escapeshellarg($this->_getReversePath($message)); + $command .= ' -f'.escapeshellarg($this->getReversePath($message)); } - $buffer->initialize(array_merge($this->_params, array('command' => $command))); + $buffer->initialize(array_merge($this->params, array('command' => $command))); if (false === strpos($command, ' -i') && false === strpos($command, ' -oi')) { $buffer->setWriteTranslations(array("\r\n" => "\n", "\n." => "\n..")); @@ -136,14 +137,14 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran if ($evt) { $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); $evt->setFailedRecipients($failedRecipients); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } $message->generateId(); } elseif (false !== strpos($command, ' -bs')) { $count = parent::send($message, $failedRecipients); } else { - $this->_throwException(new Swift_TransportException( + $this->throwException(new Swift_TransportException( 'Unsupported sendmail command flags ['.$command.']. '. 'Must be one of "-bs" or "-t" but can include additional flags.' )); @@ -153,8 +154,8 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran } /** Get the params to initialize the buffer */ - protected function _getBufferParams() + protected function getBufferParams() { - return $this->_params; + return $this->params; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php deleted file mode 100644 index 4cab66bd6bf..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php +++ /dev/null @@ -1,39 +0,0 @@ -_eventDispatcher = $eventDispatcher; - $this->_spool = $spool; + $this->eventDispatcher = $eventDispatcher; + $this->spool = $spool; } /** @@ -35,11 +35,11 @@ class Swift_Transport_SpoolTransport implements Swift_Transport * * @param Swift_Spool $spool * - * @return Swift_Transport_SpoolTransport + * @return $this */ public function setSpool(Swift_Spool $spool) { - $this->_spool = $spool; + $this->spool = $spool; return $this; } @@ -51,7 +51,7 @@ class Swift_Transport_SpoolTransport implements Swift_Transport */ public function getSpool() { - return $this->_spool; + return $this->spool; } /** @@ -78,28 +78,36 @@ class Swift_Transport_SpoolTransport implements Swift_Transport { } + /** + * {@inheritdoc} + */ + public function ping() + { + return true; + } + /** * Sends the given message. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int The number of sent e-mail's */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { - if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } - $success = $this->_spool->queueMessage($message); + $success = $this->spool->queueMessage($message); if ($evt) { $evt->setResult($success ? Swift_Events_SendEvent::RESULT_SPOOLED : Swift_Events_SendEvent::RESULT_FAILED); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } return 1; @@ -112,6 +120,6 @@ class Swift_Transport_SpoolTransport implements Swift_Transport */ public function registerPlugin(Swift_Events_EventListener $plugin) { - $this->_eventDispatcher->bindEventListener($plugin); + $this->eventDispatcher->bindEventListener($plugin); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php index 5134ea48a45..bc6ed5a34b4 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php @@ -11,27 +11,27 @@ /** * A generic IoBuffer implementation supporting remote sockets and local processes. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableInputStream implements Swift_Transport_IoBuffer { /** A primary socket */ - private $_stream; + private $stream; /** The input stream */ - private $_in; + private $in; /** The output stream */ - private $_out; + private $out; /** Buffer initialization parameters */ - private $_params = array(); + private $params = array(); /** The ReplacementFilterFactory */ - private $_replacementFactory; + private $replacementFactory; /** Translations performed on data being streamed into the buffer */ - private $_translations = array(); + private $translations = array(); /** * Create a new StreamBuffer using $replacementFactory for transformations. @@ -40,7 +40,7 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn */ public function __construct(Swift_ReplacementFilterFactory $replacementFactory) { - $this->_replacementFactory = $replacementFactory; + $this->replacementFactory = $replacementFactory; } /** @@ -52,14 +52,14 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn */ public function initialize(array $params) { - $this->_params = $params; + $this->params = $params; switch ($params['type']) { case self::TYPE_PROCESS: - $this->_establishProcessConnection(); + $this->establishProcessConnection(); break; case self::TYPE_SOCKET: default: - $this->_establishSocketConnection(); + $this->establishSocketConnection(); break; } } @@ -72,27 +72,26 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn */ public function setParam($param, $value) { - if (isset($this->_stream)) { + if (isset($this->stream)) { switch ($param) { case 'timeout': - if ($this->_stream) { - stream_set_timeout($this->_stream, $value); + if ($this->stream) { + stream_set_timeout($this->stream, $value); } break; case 'blocking': - if ($this->_stream) { - stream_set_blocking($this->_stream, 1); + if ($this->stream) { + stream_set_blocking($this->stream, 1); } - } } - $this->_params[$param] = $value; + $this->params[$param] = $value; } public function startTLS() { - return stream_socket_enable_crypto($this->_stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); + return stream_socket_enable_crypto($this->stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); } /** @@ -100,22 +99,22 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn */ public function terminate() { - if (isset($this->_stream)) { - switch ($this->_params['type']) { + if (isset($this->stream)) { + switch ($this->params['type']) { case self::TYPE_PROCESS: - fclose($this->_in); - fclose($this->_out); - proc_close($this->_stream); + fclose($this->in); + fclose($this->out); + proc_close($this->stream); break; case self::TYPE_SOCKET: default: - fclose($this->_stream); + fclose($this->stream); break; } } - $this->_stream = null; - $this->_out = null; - $this->_in = null; + $this->stream = null; + $this->out = null; + $this->in = null; } /** @@ -128,19 +127,19 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn */ public function setWriteTranslations(array $replacements) { - foreach ($this->_translations as $search => $replace) { + foreach ($this->translations as $search => $replace) { if (!isset($replacements[$search])) { $this->removeFilter($search); - unset($this->_translations[$search]); + unset($this->translations[$search]); } } foreach ($replacements as $search => $replace) { - if (!isset($this->_translations[$search])) { + if (!isset($this->translations[$search])) { $this->addFilter( - $this->_replacementFactory->createFilter($search, $replace), $search + $this->replacementFactory->createFilter($search, $replace), $search ); - $this->_translations[$search] = true; + $this->translations[$search] = true; } } } @@ -153,20 +152,20 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn * * @param int $sequence of last write to scan from * - * @throws Swift_IoException - * * @return string + * + * @throws Swift_IoException */ public function readLine($sequence) { - if (isset($this->_out) && !feof($this->_out)) { - $line = fgets($this->_out); + if (isset($this->out) && !feof($this->out)) { + $line = fgets($this->out); if (strlen($line) == 0) { - $metas = stream_get_meta_data($this->_out); + $metas = stream_get_meta_data($this->out); if ($metas['timed_out']) { throw new Swift_IoException( 'Connection to '. - $this->_getReadConnectionDescription(). + $this->getReadConnectionDescription(). ' Timed Out' ); } @@ -185,20 +184,20 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn * * @param int $length * - * @throws Swift_IoException - * * @return string|bool + * + * @throws Swift_IoException */ public function read($length) { - if (isset($this->_out) && !feof($this->_out)) { - $ret = fread($this->_out, $length); + if (isset($this->out) && !feof($this->out)) { + $ret = fread($this->out, $length); if (strlen($ret) == 0) { - $metas = stream_get_meta_data($this->_out); + $metas = stream_get_meta_data($this->out); if ($metas['timed_out']) { throw new Swift_IoException( 'Connection to '. - $this->_getReadConnectionDescription(). + $this->getReadConnectionDescription(). ' Timed Out' ); } @@ -214,22 +213,22 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn } /** Flush the stream contents */ - protected function _flush() + protected function flush() { - if (isset($this->_in)) { - fflush($this->_in); + if (isset($this->in)) { + fflush($this->in); } } /** Write this bytes to the stream */ - protected function _commit($bytes) + protected function doCommit($bytes) { - if (isset($this->_in)) { + if (isset($this->in)) { $bytesToWrite = strlen($bytes); $totalBytesWritten = 0; while ($totalBytesWritten < $bytesToWrite) { - $bytesWritten = fwrite($this->_in, substr($bytes, $totalBytesWritten)); + $bytesWritten = fwrite($this->in, substr($bytes, $totalBytesWritten)); if (false === $bytesWritten || 0 === $bytesWritten) { break; } @@ -238,7 +237,7 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn } if ($totalBytesWritten > 0) { - return ++$this->_sequence; + return ++$this->sequence; } } } @@ -246,77 +245,79 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn /** * Establishes a connection to a remote server. */ - private function _establishSocketConnection() + private function establishSocketConnection() { - $host = $this->_params['host']; - if (!empty($this->_params['protocol'])) { - $host = $this->_params['protocol'].'://'.$host; + $host = $this->params['host']; + if (!empty($this->params['protocol'])) { + $host = $this->params['protocol'].'://'.$host; } $timeout = 15; - if (!empty($this->_params['timeout'])) { - $timeout = $this->_params['timeout']; + if (!empty($this->params['timeout'])) { + $timeout = $this->params['timeout']; } $options = array(); - if (!empty($this->_params['sourceIp'])) { - $options['socket']['bindto'] = $this->_params['sourceIp'].':0'; + if (!empty($this->params['sourceIp'])) { + $options['socket']['bindto'] = $this->params['sourceIp'].':0'; } - if (isset($this->_params['stream_context_options'])) { - $options = array_merge($options, $this->_params['stream_context_options']); + + if (isset($this->params['stream_context_options'])) { + $options = array_merge($options, $this->params['stream_context_options']); } $streamContext = stream_context_create($options); - $this->_stream = @stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext); - if (false === $this->_stream) { + $this->stream = @stream_socket_client($host.':'.$this->params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext); + if (false === $this->stream) { throw new Swift_TransportException( - 'Connection could not be established with host '.$this->_params['host']. + 'Connection could not be established with host '.$this->params['host']. ' ['.$errstr.' #'.$errno.']' ); } - if (!empty($this->_params['blocking'])) { - stream_set_blocking($this->_stream, 1); + if (!empty($this->params['blocking'])) { + stream_set_blocking($this->stream, 1); } else { - stream_set_blocking($this->_stream, 0); + stream_set_blocking($this->stream, 0); } - stream_set_timeout($this->_stream, $timeout); - $this->_in = &$this->_stream; - $this->_out = &$this->_stream; + stream_set_timeout($this->stream, $timeout); + $this->in = &$this->stream; + $this->out = &$this->stream; } /** * Opens a process for input/output. */ - private function _establishProcessConnection() + private function establishProcessConnection() { - $command = $this->_params['command']; + $command = $this->params['command']; $descriptorSpec = array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'), ); - $this->_stream = proc_open($command, $descriptorSpec, $pipes); + $pipes = array(); + $this->stream = proc_open($command, $descriptorSpec, $pipes); stream_set_blocking($pipes[2], 0); if ($err = stream_get_contents($pipes[2])) { throw new Swift_TransportException( 'Process could not be started ['.$err.']' ); } - $this->_in = &$pipes[0]; - $this->_out = &$pipes[1]; + $this->in = &$pipes[0]; + $this->out = &$pipes[1]; } - private function _getReadConnectionDescription() + private function getReadConnectionDescription() { - switch ($this->_params['type']) { + switch ($this->params['type']) { case self::TYPE_PROCESS: - return 'Process '.$this->_params['command']; + return 'Process '.$this->params['command']; break; case self::TYPE_SOCKET: default: - $host = $this->_params['host']; - if (!empty($this->_params['protocol'])) { - $host = $this->_params['protocol'].'://'.$host; + $host = $this->params['host']; + if (!empty($this->params['protocol'])) { + $host = $this->params['protocol'].'://'.$host; } - $host .= ':'.$this->_params['port']; + $host .= ':'.$this->params['port']; return $host; break; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Validate.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Validate.php deleted file mode 100644 index e16c212c49f..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Validate.php +++ /dev/null @@ -1,43 +0,0 @@ - - */ -class Swift_Validate -{ - /** - * Grammar Object. - * - * @var Swift_Mime_Grammar - */ - private static $grammar = null; - - /** - * Checks if an e-mail address matches the current grammars. - * - * @param string $email - * - * @return bool - */ - public static function email($email) - { - if (self::$grammar === null) { - self::$grammar = Swift_DependencyContainer::getInstance() - ->lookup('mime.grammar'); - } - - return (bool) preg_match( - '/^'.self::$grammar->getDefinition('addr-spec').'$/D', - $email - ); - } -} diff --git a/htdocs/includes/swiftmailer/lib/dependency_maps/mime_deps.php b/htdocs/includes/swiftmailer/lib/dependency_maps/mime_deps.php index 04f394b3267..4ce9c7cbbc5 100644 --- a/htdocs/includes/swiftmailer/lib/dependency_maps/mime_deps.php +++ b/htdocs/includes/swiftmailer/lib/dependency_maps/mime_deps.php @@ -1,13 +1,25 @@ register('properties.charset') ->asValue('utf-8') - ->register('mime.grammar') - ->asSharedInstanceOf('Swift_Mime_Grammar') + ->register('email.validator') + ->asSharedInstanceOf('Egulias\EmailValidator\EmailValidator') + + ->register('mime.idgenerator.idright') + // As SERVER_NAME can come from the user in certain configurations, check that + // it does not contain forbidden characters (see RFC 952 and RFC 2181). Use + // preg_replace() instead of preg_match() to prevent DoS attacks with long host names. + ->asValue(!empty($_SERVER['SERVER_NAME']) && preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $_SERVER['SERVER_NAME']) === '' ? $_SERVER['SERVER_NAME'] : 'swift.generated') + + ->register('mime.idgenerator') + ->asSharedInstanceOf('Swift_Mime_IdGenerator') + ->withDependencies(array( + 'mime.idgenerator.idright', + )) ->register('mime.message') ->asNewInstanceOf('Swift_Mime_SimpleMessage') @@ -15,7 +27,7 @@ Swift_DependencyContainer::getInstance() 'mime.headerset', 'mime.qpcontentencoder', 'cache', - 'mime.grammar', + 'mime.idgenerator', 'properties.charset', )) @@ -25,7 +37,7 @@ Swift_DependencyContainer::getInstance() 'mime.headerset', 'mime.qpcontentencoder', 'cache', - 'mime.grammar', + 'mime.idgenerator', 'properties.charset', )) @@ -35,7 +47,7 @@ Swift_DependencyContainer::getInstance() 'mime.headerset', 'mime.base64contentencoder', 'cache', - 'mime.grammar', + 'mime.idgenerator', )) ->addConstructorValue($swift_mime_types) @@ -45,7 +57,7 @@ Swift_DependencyContainer::getInstance() 'mime.headerset', 'mime.base64contentencoder', 'cache', - 'mime.grammar', + 'mime.idgenerator', )) ->addConstructorValue($swift_mime_types) @@ -54,7 +66,7 @@ Swift_DependencyContainer::getInstance() ->withDependencies(array( 'mime.qpheaderencoder', 'mime.rfc2231encoder', - 'mime.grammar', + 'email.validator', 'properties.charset', )) @@ -93,7 +105,7 @@ Swift_DependencyContainer::getInstance() ->withDependencies(array('properties.charset')) ->asNewInstanceOf('Swift_Mime_ContentEncoder_NativeQpContentEncoder') - ->register('mime.qpcontentencoderproxy') + ->register('mime.qpcontentencoder') ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoderProxy') ->withDependencies(array('mime.safeqpcontentencoder', 'mime.nativeqpcontentencoder', 'properties.charset')) @@ -113,11 +125,6 @@ Swift_DependencyContainer::getInstance() ->register('mime.rfc2231encoder') ->asNewInstanceOf('Swift_Encoder_Rfc2231Encoder') ->withDependencies(array('mime.charstream')) - - // As of PHP 5.4.7, the quoted_printable_encode() function behaves correctly. - // see https://github.com/php/php-src/commit/18bb426587d62f93c54c40bf8535eb8416603629 - ->register('mime.qpcontentencoder') - ->asAliasOf(version_compare(phpversion(), '5.4.7', '>=') ? 'mime.qpcontentencoderproxy' : 'mime.safeqpcontentencoder') ; unset($swift_mime_types); diff --git a/htdocs/includes/swiftmailer/lib/dependency_maps/transport_deps.php b/htdocs/includes/swiftmailer/lib/dependency_maps/transport_deps.php index 77e432cfac0..15772abb255 100644 --- a/htdocs/includes/swiftmailer/lib/dependency_maps/transport_deps.php +++ b/htdocs/includes/swiftmailer/lib/dependency_maps/transport_deps.php @@ -1,12 +1,19 @@ register('transport.localdomain') + // As SERVER_NAME can come from the user in certain configurations, check that + // it does not contain forbidden characters (see RFC 952 and RFC 2181). Use + // preg_replace() instead of preg_match() to prevent DoS attacks with long host names. + ->asValue(!empty($_SERVER['SERVER_NAME']) && preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $_SERVER['SERVER_NAME']) === '' ? trim($_SERVER['SERVER_NAME'], '[]') : '127.0.0.1') + ->register('transport.smtp') ->asNewInstanceOf('Swift_Transport_EsmtpTransport') ->withDependencies(array( 'transport.buffer', array('transport.authhandler'), 'transport.eventdispatcher', + 'transport.localdomain', )) ->register('transport.sendmail') @@ -14,12 +21,9 @@ Swift_DependencyContainer::getInstance() ->withDependencies(array( 'transport.buffer', 'transport.eventdispatcher', + 'transport.localdomain', )) - ->register('transport.mail') - ->asNewInstanceOf('Swift_Transport_MailTransport') - ->withDependencies(array('transport.mailinvoker', 'transport.eventdispatcher')) - ->register('transport.loadbalanced') ->asNewInstanceOf('Swift_Transport_LoadBalancedTransport') @@ -34,9 +38,6 @@ Swift_DependencyContainer::getInstance() ->asNewInstanceOf('Swift_Transport_NullTransport') ->withDependencies(array('transport.eventdispatcher')) - ->register('transport.mailinvoker') - ->asSharedInstanceOf('Swift_Transport_SimpleMailInvoker') - ->register('transport.buffer') ->asNewInstanceOf('Swift_Transport_StreamBuffer') ->withDependencies(array('transport.replacementfactory')) diff --git a/htdocs/includes/swiftmailer/lib/mime_types.php b/htdocs/includes/swiftmailer/lib/mime_types.php index 2d7b98dc1aa..b42c1cc1a3e 100644 --- a/htdocs/includes/swiftmailer/lib/mime_types.php +++ b/htdocs/includes/swiftmailer/lib/mime_types.php @@ -7,7 +7,7 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * - * autogenerated using http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types + * autogenerated using https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types * and https://raw.github.com/minad/mimemagic/master/script/freedesktop.org.xml */ diff --git a/htdocs/includes/swiftmailer/lib/preferences.php b/htdocs/includes/swiftmailer/lib/preferences.php index e5195014824..27b7065dbee 100644 --- a/htdocs/includes/swiftmailer/lib/preferences.php +++ b/htdocs/includes/swiftmailer/lib/preferences.php @@ -17,9 +17,3 @@ $preferences->setCharset('utf-8'); if (@is_writable($tmpDir = sys_get_temp_dir())) { $preferences->setTempDir($tmpDir)->setCacheType('disk'); } - -// this should only be done when Swiftmailer won't use the native QP content encoder -// see mime_deps.php -if (version_compare(phpversion(), '5.4.7', '<')) { - $preferences->setQPDotEscape(false); -} diff --git a/htdocs/includes/swiftmailer/lib/swift_init.php b/htdocs/includes/swiftmailer/lib/swift_init.php deleted file mode 100644 index 5c4bae4f4f1..00000000000 --- a/htdocs/includes/swiftmailer/lib/swift_init.php +++ /dev/null @@ -1,28 +0,0 @@ - 'audio/wav', 'wma' => 'audio/x-ms-wma', 'wmv' => 'audio/x-ms-wmv', - 'xls' => 'application/excel', + 'xls' => 'application/vnd.ms-excel', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xml' => 'application/xml', ); From d31684376a28c1592c79b21233cdb6e767acf4df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Sun, 21 Jan 2018 18:59:48 +0100 Subject: [PATCH 010/413] swiftmailer --- htdocs/core/class/CMailFile.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 25988fd801d..be1eb75a8d1 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -399,6 +399,8 @@ class CMailFile require_once DOL_DOCUMENT_ROOT.'/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailParser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailLexer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailValidator.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/Warning.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/Parser.php'; @@ -406,8 +408,6 @@ class CMailFile require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailLexer.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailValidator.php'; require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; // Create the message //$this->message = Swift_Message::newInstance(); From 0568461a7b5fb2bdb781f9a8f27238d9cb335872 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Thu, 25 Jan 2018 22:03:51 +0100 Subject: [PATCH 011/413] swiftmailer --- htdocs/admin/mails.php | 123 +++++++++++++++--- htdocs/core/class/CMailFile.class.php | 46 ++++--- .../EmailValidator/EmailLexer.php | 0 .../EmailValidator/EmailParser.php | 0 .../EmailValidator/EmailValidator.php | 0 .../Exception/AtextAfterCFWS.php | 0 .../EmailValidator/Exception/CRLFAtTheEnd.php | 0 .../EmailValidator/Exception/CRLFX2.php | 0 .../EmailValidator/Exception/CRNoLF.php | 0 .../Exception/CharNotAllowed.php | 0 .../Exception/CommaInDomain.php | 0 .../Exception/ConsecutiveAt.php | 0 .../Exception/ConsecutiveDot.php | 0 .../Exception/DomainHyphened.php | 0 .../EmailValidator/Exception/DotAtEnd.php | 0 .../EmailValidator/Exception/DotAtStart.php | 0 .../EmailValidator/Exception/ExpectingAT.php | 0 .../Exception/ExpectingATEXT.php | 0 .../Exception/ExpectingCTEXT.php | 0 .../Exception/ExpectingDTEXT.php | 0 .../Exception/ExpectingDomainLiteralClose.php | 0 .../Exception/ExpectingQPair.php | 0 .../EmailValidator/Exception/InvalidEmail.php | 0 .../EmailValidator/Exception/NoDNSRecord.php | 0 .../EmailValidator/Exception/NoDomainPart.php | 0 .../EmailValidator/Exception/NoLocalPart.php | 0 .../Exception/UnclosedComment.php | 0 .../Exception/UnclosedQuotedString.php | 0 .../Exception/UnopenedComment.php | 0 .../EmailValidator/Parser/DomainPart.php | 0 .../EmailValidator/Parser/LocalPart.php | 0 .../EmailValidator/Parser/Parser.php | 0 .../Validation/DNSCheckValidation.php | 0 .../Validation/EmailValidation.php | 0 .../Validation/Error/RFCWarnings.php | 0 .../Validation/Error/SpoofEmail.php | 0 .../Exception/EmptyValidationList.php | 0 .../Validation/MultipleErrors.php | 0 .../Validation/MultipleValidationWithAnd.php | 0 .../Validation/NoRFCWarningsValidation.php | 0 .../Validation/RFCValidation.php | 0 .../Validation/SpoofCheckValidation.php | 0 .../EmailValidator/Warning/AddressLiteral.php | 0 .../EmailValidator/Warning/CFWSNearAt.php | 0 .../EmailValidator/Warning/CFWSWithFWS.php | 0 .../EmailValidator/Warning/Comment.php | 0 .../Warning/DeprecatedComment.php | 0 .../EmailValidator/Warning/DomainLiteral.php | 0 .../EmailValidator/Warning/DomainTooLong.php | 0 .../EmailValidator/Warning/EmailTooLong.php | 0 .../EmailValidator/Warning/IPV6BadChar.php | 0 .../EmailValidator/Warning/IPV6ColonEnd.php | 0 .../EmailValidator/Warning/IPV6ColonStart.php | 0 .../EmailValidator/Warning/IPV6Deprecated.php | 0 .../Warning/IPV6DoubleColon.php | 0 .../EmailValidator/Warning/IPV6GroupCount.php | 0 .../EmailValidator/Warning/IPV6MaxGroups.php | 0 .../EmailValidator/Warning/LabelTooLong.php | 0 .../EmailValidator/Warning/LocalTooLong.php | 0 .../EmailValidator/Warning/NoDNSMXRecord.php | 0 .../EmailValidator/Warning/ObsoleteDTEXT.php | 0 .../EmailValidator/Warning/QuotedPart.php | 0 .../EmailValidator/Warning/QuotedString.php | 0 .../EmailValidator/Warning/TLD.php | 0 .../EmailValidator/Warning/Warning.php | 0 .../egulias/email-validator/LICENSE | 0 .../egulias/email-validator/README.md | 0 .../includes/{ => swiftmailer}/lexer/LICENSE | 0 .../{ => swiftmailer}/lexer/README.md | 0 .../{ => swiftmailer}/lexer/composer.json | 0 .../Doctrine/Common/Lexer/AbstractLexer.php | 0 htdocs/langs/fr_FR/admin.lang | 4 + 72 files changed, 137 insertions(+), 36 deletions(-) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/EmailLexer.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/EmailParser.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/EmailValidator.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/CRLFX2.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/CRNoLF.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/DotAtStart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Parser/DomainPart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Parser/LocalPart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Parser/Parser.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/EmailValidation.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/RFCValidation.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/Comment.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/QuotedPart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/QuotedString.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/TLD.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/Warning.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/LICENSE (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/README.md (100%) rename htdocs/includes/{ => swiftmailer}/lexer/LICENSE (100%) rename htdocs/includes/{ => swiftmailer}/lexer/README.md (100%) rename htdocs/includes/{ => swiftmailer}/lexer/composer.json (100%) rename htdocs/includes/{ => swiftmailer}/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php (100%) diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index d482322a054..e9cbdbb8736 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -78,6 +78,10 @@ if ($action == 'update' && empty($_POST["cancel"])) dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW", GETPOST("MAIN_MAIL_SMTPS_PW"), 'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS", GETPOST("MAIN_MAIL_EMAIL_TLS"),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS", GETPOST("MAIN_MAIL_EMAIL_STARTTLS"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_ENABLED", GETPOST("MAIN_MAIL_EMAIL_DKIM_ENABLED"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_DOMAIN", GETPOST("MAIN_MAIL_EMAIL_DKIM_DOMAIN"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_SELECTOR", GETPOST("MAIN_MAIL_EMAIL_DKIM_SELECTOR"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY", GETPOST("MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY"),'chaine',0,'',$conf->entity); // Content parameters dolibarr_set_const($db, "MAIN_MAIL_EMAIL_FROM", GETPOST("MAIN_MAIL_EMAIL_FROM"), 'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_ERRORS_TO", GETPOST("MAIN_MAIL_ERRORS_TO"), 'chaine',0,'',$conf->entity); @@ -151,26 +155,32 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_EMAIL_TLS").prop("disabled", true); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val(0); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").val(0); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").hide(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").hide(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").hide(); '; if ($linuxlike) { print ' - jQuery("#MAIN_MAIL_SMTP_SERVER").hide(); - jQuery("#MAIN_MAIL_SMTP_PORT").hide(); - jQuery("#smtp_server_mess").show(); - jQuery("#smtp_port_mess").show(); - '; + jQuery("#MAIN_MAIL_SMTP_SERVER").hide(); + jQuery("#MAIN_MAIL_SMTP_PORT").hide(); + jQuery("#smtp_server_mess").show(); + jQuery("#smtp_port_mess").show();'; } else { - print ' - jQuery("#MAIN_MAIL_SMTP_SERVER").prop("disabled", true); - jQuery("#MAIN_MAIL_SMTP_PORT").prop("disabled", true); - jQuery("#smtp_server_mess").hide(); - jQuery("#smtp_port_mess").hide(); - '; - } - print ' + print ' + jQuery("#MAIN_MAIL_SMTP_SERVER").prop("disabled", true); + jQuery("#MAIN_MAIL_SMTP_PORT").prop("disabled", true); + jQuery("#smtp_server_mess").hide(); + jQuery("#smtp_port_mess").hide();'; + } + print ' } if (jQuery("#MAIN_MAIL_SENDMODE").val()==\'smtps\') { @@ -179,6 +189,14 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_EMAIL_TLS").removeAttr("disabled"); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val('.$conf->global->MAIN_MAIL_EMAIL_STARTTLS.'); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").val(0); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").hide(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").hide(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").hide(); jQuery("#MAIN_MAIL_SMTP_SERVER").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_PORT").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_SERVER").show(); @@ -193,6 +211,14 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_EMAIL_TLS").removeAttr("disabled"); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val('.$conf->global->MAIN_MAIL_EMAIL_STARTTLS.'); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").val('.$conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED.'); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").show(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").show(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").show(); jQuery("#MAIN_MAIL_SMTP_SERVER").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_PORT").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_SERVER").show(); @@ -205,16 +231,16 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_SENDMODE").change(function() { initfields(); }); - jQuery("#MAIN_MAIL_EMAIL_TLS").change(function() { + jQuery("#MAIN_MAIL_EMAIL_TLS").change(function() { if (jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val() == 1) jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val(0); }); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").change(function() { if (jQuery("#MAIN_MAIL_EMAIL_TLS").val() == 1) jQuery("#MAIN_MAIL_EMAIL_TLS").val(0); - }); + }); })'; - print ''."\n"; + print ''."\n"; } print '
'; @@ -368,9 +394,9 @@ if ($action == 'edit') print ''; } - // TLS + // TLS - print ''.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; + print ''.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer')))) { if (function_exists('openssl_open')) @@ -383,7 +409,6 @@ if ($action == 'edit') print ''; // STARTTLS - print ''.$langs->trans("MAIN_MAIL_EMAIL_STARTTLS").''; if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer')))) { @@ -396,8 +421,35 @@ if ($action == 'edit') else print yn(0).' ('.$langs->trans("NotSupported").')'; print ''; - // Separator + // DKIM + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_ENABLED").''; + if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('swiftmailer')))) + { + if (function_exists('openssl_open')) + { + print $form->selectyesno('MAIN_MAIL_EMAIL_DKIM_ENABLED',(! empty($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED)?$conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED:0),1); + } + else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } + else print yn(0).' ('.$langs->trans("NotSupported").')'; + print ''; + // Domain + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_DOMAIN").''; + print ''; + + // Selector + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_SELECTOR").''; + print ''; + + // PRIVATE KEY + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").''; + print ''; + print ''; + + // Separator print ' '; // From @@ -554,7 +606,36 @@ else else print yn(0).' ('.$langs->trans("NotSupported").')'; print ''; - // Separator + // DKIM + + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_ENABLED").''; + if (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('swiftmailer'))) + { + if (function_exists('openssl_open')) + { + print yn($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED); + } + else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } + else print yn(0).' ('.$langs->trans("NotSupported").')'; + print ''; + + // Domain + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_DOMAIN").''; + print '' . $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; + print ''; + + // Selector + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_SELECTOR").''; + print '' . $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; + print ''; + + // PRIVATE KEY + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").''; + print '' . $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; + print ''; + + // Separator print ' '; diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index be1eb75a8d1..e99581de1ed 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -395,25 +395,32 @@ class CMailFile // Use Swift Mailer library // ------------------------------------------ - $host = dol_getprefix('email'); + $host = dol_getprefix('email'); - require_once DOL_DOCUMENT_ROOT.'/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailParser.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailLexer.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailValidator.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/Warning.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/Parser.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/DomainPart.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; + + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailParser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php'; + + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/InputByteStream.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php'; + //require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/SignedMessage.php'; require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; // Create the message //$this->message = Swift_Message::newInstance(); $this->message = new Swift_Message(); - - // Adding a trackid header to a message + //$this->message = new Swift_SignedMessage(); + // Adding a trackid header to a message $headers = $this->message->getHeaders(); $headers->addTextHeader('X-Dolibarr-TRACKID', $trackid); $headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host; @@ -749,7 +756,16 @@ class CMailFile // Create the Mailer using your created Transport $this->mailer = new Swift_Mailer($this->transport); - if (! empty($conf->global->MAIN_MAIL_DEBUG)) { + // DKIM SIGN + if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) { + $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; + $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; + $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; + $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector); + $this->message->attachSigner($signer); + } + + if (! empty($conf->global->MAIN_MAIL_DEBUG)) { // To use the ArrayLogger $this->logger = new Swift_Plugins_Loggers_ArrayLogger(); // Or to use the Echo Logger diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailParser.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailParser.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFX2.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRLFX2.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFX2.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRLFX2.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRNoLF.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRNoLF.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRNoLF.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRNoLF.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtStart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DotAtStart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtStart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DotAtStart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Parser/DomainPart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Parser/DomainPart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Comment.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Comment.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/QuotedPart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/QuotedPart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/QuotedString.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/QuotedString.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/TLD.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/TLD.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php diff --git a/htdocs/includes/egulias/email-validator/LICENSE b/htdocs/includes/swiftmailer/egulias/email-validator/LICENSE similarity index 100% rename from htdocs/includes/egulias/email-validator/LICENSE rename to htdocs/includes/swiftmailer/egulias/email-validator/LICENSE diff --git a/htdocs/includes/egulias/email-validator/README.md b/htdocs/includes/swiftmailer/egulias/email-validator/README.md similarity index 100% rename from htdocs/includes/egulias/email-validator/README.md rename to htdocs/includes/swiftmailer/egulias/email-validator/README.md diff --git a/htdocs/includes/lexer/LICENSE b/htdocs/includes/swiftmailer/lexer/LICENSE similarity index 100% rename from htdocs/includes/lexer/LICENSE rename to htdocs/includes/swiftmailer/lexer/LICENSE diff --git a/htdocs/includes/lexer/README.md b/htdocs/includes/swiftmailer/lexer/README.md similarity index 100% rename from htdocs/includes/lexer/README.md rename to htdocs/includes/swiftmailer/lexer/README.md diff --git a/htdocs/includes/lexer/composer.json b/htdocs/includes/swiftmailer/lexer/composer.json similarity index 100% rename from htdocs/includes/lexer/composer.json rename to htdocs/includes/swiftmailer/lexer/composer.json diff --git a/htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php b/htdocs/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php similarity index 100% rename from htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php rename to htdocs/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php diff --git a/htdocs/langs/fr_FR/admin.lang b/htdocs/langs/fr_FR/admin.lang index 0953014aa91..29c5381af80 100644 --- a/htdocs/langs/fr_FR/admin.lang +++ b/htdocs/langs/fr_FR/admin.lang @@ -277,6 +277,10 @@ MAIN_MAIL_SMTPS_ID=Identifiant d'authentification SMTP si authentification SMTP MAIN_MAIL_SMTPS_PW=Mot de passe d'authentification SMTP si authentification SMTP requise MAIN_MAIL_EMAIL_TLS= Utilisation du chiffrement TLS (SSL) MAIN_MAIL_EMAIL_STARTTLS= Utiliser le cryptage TTS (STARTTLS) +MAIN_MAIL_EMAIL_DKIM_ENABLED= Utiliser la signature DKIM +MAIN_MAIL_EMAIL_DKIM_DOMAIN=Domaine DKIM +MAIN_MAIL_EMAIL_DKIM_SELECTOR=Sélecteur de clé DKIM +MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY=Clé privée RSA DKIM MAIN_DISABLE_ALL_SMS=Désactiver globalement tout envoi de SMS (pour mode test ou démos) MAIN_SMS_SENDMODE=Méthode d'envoi des SMS MAIN_MAIL_SMS_FROM=Numéro de téléphone par défaut pour l'envoi des SMS From b387c3fdf84b00e220906cdb2dba65f40746dac5 Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Wed, 31 Jan 2018 11:45:30 +0000 Subject: [PATCH 012/413] Forgot to update other files to same PR changes --- htdocs/admin/company.php | 2 +- htdocs/core/class/commonobject.class.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index 825f4a89be9..4456cd918be 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -742,7 +742,7 @@ else print ''.$langs->trans("State").''; if ($mysoc->state_id) { - print getState($mysoc->state_id,$conf->global->MAIN_SHOW_STATE_CODE,0,$conf->global->MAIN_SHOW_REGION_IN_STATE); + print getState($mysoc->state_id,$conf->global->MAIN_SHOW_STATE_CODE,0,$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); } else print ' '; print ''; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 0ee5a371c73..43c216de26c 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -507,7 +507,7 @@ abstract class CommonObject $out=''; $outdone=0; - $coords = $this->getFullAddress(1,', ',$conf->global->MAIN_SHOW_REGION_IN_STATE); + $coords = $this->getFullAddress(1,', ',$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); if ($coords) { if (! empty($conf->use_javascript_ajax)) @@ -525,7 +525,7 @@ abstract class CommonObject if (! in_array($this->country_code,$countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) { - if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE) && $conf->global->MAIN_SHOW_REGION_IN_STATE == 1 && $this->region) { + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) { $out.=($outdone?' - ':'').$this->region.' - '.$this->state; } else { From 9f7496ce04b0ec565889f8bf0782e0e3e5980018 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Mon, 5 Feb 2018 17:47:29 +0100 Subject: [PATCH 013/413] Update price.php --- htdocs/product/price.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/htdocs/product/price.php b/htdocs/product/price.php index a2afb5f9bb8..61b6316ca01 100644 --- a/htdocs/product/price.php +++ b/htdocs/product/price.php @@ -11,6 +11,7 @@ * Copyright (C) 2015 Alexandre Spangaro * Copyright (C) 2015 Marcos García * Copyright (C) 2016 Ferran Marcet + * Copyright (C) 2018 Frédéric France * * 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 @@ -1439,7 +1440,12 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_ // Il doit au moins y avoir la ligne de prix initial. // On l'ajoute donc pour remettre a niveau (pb vieilles versions) - $object->updatePrice($object->price, $object->price_base_type, $user, $newprice_min); + //$object->updatePrice($object->price, $object->price_base_type, $user, $newprice_min); + if (! empty($conf->global->PRODUIT_MULTIPRICES)) { + $object->updatePrice($object->multiprices[1], $object->multiprices_base_type[1], $user, $object->multiprices_tva_tx[1], $object->multiprices_min[1], 1); + } else { + $object->updatePrice($object->price, $object->price_base_type, $user, $object->tva_tx, $object->price_min); + } $result = $db->query($sql); $num = $db->num_rows($result); From 8c732a14431c9a78c010051a25bac7a548516954 Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Tue, 6 Feb 2018 12:01:54 +0000 Subject: [PATCH 014/413] Trying to not include sql request into method setMysoc --- htdocs/admin/company.php | 21 +- htdocs/core/class/commonobject.class.php | 8 +- htdocs/core/class/commonobject.class.php.orig | 6652 ----------------- htdocs/societe/class/societe.class.php | 32 +- 4 files changed, 17 insertions(+), 6696 deletions(-) delete mode 100644 htdocs/core/class/commonobject.class.php.orig diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index 4456cd918be..2b63bc7a4e8 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -78,19 +78,8 @@ if ( ($action == 'update' && ! GETPOST("cancel",'alpha')) dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ADDRESS", GETPOST("address",'nohtml'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_TOWN", GETPOST("town",'nohtml'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ZIP", GETPOST("zipcode",'alpha'),'chaine',0,'',$conf->entity); - - //dolibarr_set_const($db, "MAIN_INFO_SOCIETE_STATE", GETPOST("state_id",'alpha'),'chaine',0,'',$conf->entity); - $tmparray=getState(GETPOST('state_id','int'),'all','',$db,$langs,0); - if (! empty($tmparray['id'])) - { - $mysoc->state_id =$tmparray['id']; - $mysoc->state_code =$tmparray['code']; - $mysoc->state_label=$tmparray['label']; - - $s=$mysoc->state_id.':'.$mysoc->state_code.':'.$mysoc->state_label; - dolibarr_set_const($db, "MAIN_INFO_SOCIETE_STATE", $s,'chaine',0,'',$conf->entity); - } - + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_STATE", GETPOST("state_id",'alpha'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_REGION", GETPOST("region_code",'alpha'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MONNAIE", GETPOST("currency",'alpha'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_TEL", GETPOST("tel",'alpha'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_FAX", GETPOST("fax",'alpha'),'chaine',0,'',$conf->entity); @@ -359,7 +348,7 @@ if ($action == 'edit' || $action == 'updateedit') print ''; - $formcompany->select_departement($mysoc->state_id,$mysoc->country_code,'state_id'); + $formcompany->select_departement($conf->global->MAIN_INFO_SOCIETE_STATE,$mysoc->country_code,'state_id'); print ''."\n"; @@ -741,9 +730,7 @@ else print ''.$langs->trans("State").''; - if ($mysoc->state_id) { - print getState($mysoc->state_id,$conf->global->MAIN_SHOW_STATE_CODE,0,$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); - } + if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) print getState($conf->global->MAIN_INFO_SOCIETE_STATE,$conf->global->MAIN_SHOW_STATE_CODE,0,$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); else print ' '; print ''; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index a62c0d671ac..c935b02e555 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -465,10 +465,10 @@ abstract class CommonObject { require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; $tmparray=getState($this->state_id,'all',0,1); - $this->state_code =$tmparray['code']; - $this->state =$tmparray['label']; - $this->region_code =$tmparray['region_code']; - $this->region =$tmparray['region']; + $this->state_code =$tmparray['code']; + $this->state =$tmparray['label']; + $this->region_code =$tmparray['region_code']; + $this->region =$tmparray['region']; } return dol_format_address($this, $withcountry, $sep); diff --git a/htdocs/core/class/commonobject.class.php.orig b/htdocs/core/class/commonobject.class.php.orig deleted file mode 100644 index c5e2115c6cd..00000000000 --- a/htdocs/core/class/commonobject.class.php.orig +++ /dev/null @@ -1,6652 +0,0 @@ - - * Copyright (C) 2005-2013 Regis Houssin - * Copyright (C) 2010-2013 Juanjo Menent - * Copyright (C) 2012 Christophe Battarel - * Copyright (C) 2010-2015 Juanjo Menent - * Copyright (C) 2012-2013 Christophe Battarel - * Copyright (C) 2011-2014 Philippe Grand - * Copyright (C) 2012-2015 Marcos García - * Copyright (C) 2012-2015 Raphaël Doursenaud - * Copyright (C) 2012 Cedric Salvador - * Copyright (C) 2015 Alexandre Spangaro - * Copyright (C) 2016 Bahfir abbes - * Copyright (C) 2017 ATM Consulting - * Copyright (C) 2017 Nicolas ZABOURI -<<<<<<< HEAD - * Copyright (C) 2017 Rui Strecht -======= - * Copyright (C) 2018 Frederic France ->>>>>>> develop - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/core/class/commonobject.class.php - * \ingroup core - * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...) - */ - - -/** - * Parent class of all other business classes (invoices, contracts, proposals, orders, ...) - */ -abstract class CommonObject -{ - /** - * @var DoliDb Database handler (result of a new DoliDB) - */ - public $db; - /** - * @var int The object identifier - */ - public $id; - /** - * @var string Error string - * @see errors - */ - public $error; - /** - * @var string[] Array of error strings - */ - public $errors=array(); - /** - * @var string - */ - public $element; - /** - * @var string - */ - public $table_element; - /** - * @var - */ - public $table_element_line; - /** - * @var string Key value used to track if data is coming from import wizard - */ - public $import_key; - /** - * @var mixed Contains data to manage extrafields - */ - public $array_options=array(); - /** - * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked - */ - public $linkedObjectsIds; - /** - * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked - */ - public $linkedObjects; - /** - * @var Object To store a cloned copy of object before to edit it and keep track of old properties - */ - public $oldcopy; - - /** - * @var string Column name of the ref field. - */ - protected $table_ref_field = ''; - - - - // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them. - - /** - * @var array Can be used to pass information when only object is provided to method - */ - public $context=array(); - - /** - * @var string Contains canvas name if record is an alternative canvas record - */ - public $canvas; - - /** - * @var Project The related project - * @see fetch_projet() - */ - public $project; - /** - * @var int The related project ID - * @see setProject(), project - */ - public $fk_project; - /** - * @deprecated - * @see project - */ - public $projet; - - /** - * @var Contact a related contact - * @see fetch_contact() - */ - public $contact; - /** - * @var int The related contact ID - * @see fetch_contact() - */ - public $contact_id; - - /** - * @var Societe A related thirdparty - * @see fetch_thirdparty() - */ - public $thirdparty; - - /** - * @var User A related user - * @see fetch_user() - */ - public $user; - - /** - * @var string The type of originating object ('commande', 'facture', ...) - * @see fetch_origin() - */ - public $origin; - /** - * @var int The id of originating object - * @see fetch_origin() - */ - public $origin_id; - - /** - * @var string The object's reference - */ - public $ref; - /** - * @var string The object's previous reference - */ - public $ref_previous; - /** - * @var string The object's next reference - */ - public $ref_next; - /** - * @var string An external reference for the object - */ - public $ref_ext; - - /** - * @var int The object's status - * @see setStatut() - */ - public $statut; - - /** - * @var string - * @see getFullAddress() - */ - public $country; - /** - * @var int - * @see getFullAddress(), country - */ - public $country_id; - /** - * @var string - * @see getFullAddress(), isInEEC(), country - */ - public $country_code; - /** - * @var string - * @see getFullAddress() - */ - public $state; - /** - * @var int - * @see getFullAddress(), state - */ - public $state_id; - /** - * @var string - * @see getFullAddress(), state - */ - public $state_code; - /** - * @var string - * @see getFullAddress(), region - */ - public $region; - /** - * @var string - * @see getFullAddress(), region - */ - public $region_code; - - /** - * @var int - * @see fetch_barcode() - */ - public $barcode_type; - /** - * @var string - * @see fetch_barcode(), barcode_type - */ - public $barcode_type_code; - /** - * @var string - * @see fetch_barcode(), barcode_type - */ - public $barcode_type_label; - /** - * @var string - * @see fetch_barcode(), barcode_type - */ - public $barcode_type_coder; - - /** - * @var int Payment method ID (cheque, cash, ...) - * @see setPaymentMethods() - */ - public $mode_reglement_id; - - /** - * @var int Payment terms ID - * @see setPaymentTerms() - */ - public $cond_reglement_id; - /** - * @var int Payment terms ID - * @deprecated Kept for compatibility - * @see cond_reglement_id; - */ - public $cond_reglement; - - /** - * @var int Delivery address ID - * @deprecated - * @see setDeliveryAddress() - */ - public $fk_delivery_address; - - /** - * @var int Shipping method ID - * @see setShippingMethod() - */ - public $shipping_method_id; - - /** - * @var string - * @see SetDocModel() - */ - public $modelpdf; - - /** - * @var int Bank account ID - * @see SetBankAccount() - */ - public $fk_account; - - /** - * @var string Public note - * @see update_note() - */ - public $note_public; - /** - * @var string Private note - * @see update_note() - */ - public $note_private; - /** - * @deprecated - * @see note_public - */ - public $note; - - /** - * @var float Total amount before taxes - * @see update_price() - */ - public $total_ht; - /** - * @var float Total VAT amount - * @see update_price() - */ - public $total_tva; - /** - * @var float Total local tax 1 amount - * @see update_price() - */ - public $total_localtax1; - /** - * @var float Total local tax 2 amount - * @see update_price() - */ - public $total_localtax2; - /** - * @var float Total amount with taxes - * @see update_price() - */ - public $total_ttc; - - /** - * @var CommonObjectLine[] - */ - public $lines; - - /** - * @var mixed Contains comments - * @see fetchComments() - */ - public $comments=array(); - - /** - * @var int - * @see setIncoterms() - */ - public $fk_incoterms; - /** - * @var string - * @see SetIncoterms() - */ - public $libelle_incoterms; - /** - * @var string - * @see display_incoterms() - */ - public $location_incoterms; - - public $name; - public $lastname; - public $firstname; - public $civility_id; - - - // No constructor as it is an abstract class - - /** - * Check an object id/ref exists - * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch - * - * @param string $element String of element ('product', 'facture', ...) - * @param int $id Id of object - * @param string $ref Ref of object to check - * @param string $ref_ext Ref ext of object to check - * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists - */ - static function isExistingObject($element, $id, $ref='', $ref_ext='') - { - global $db,$conf; - - $sql = "SELECT rowid, ref, ref_ext"; - $sql.= " FROM ".MAIN_DB_PREFIX.$element; - $sql.= " WHERE entity IN (".getEntity($element).")" ; - - if ($id > 0) $sql.= " AND rowid = ".$db->escape($id); - else if ($ref) $sql.= " AND ref = '".$db->escape($ref)."'"; - else if ($ref_ext) $sql.= " AND ref_ext = '".$db->escape($ref_ext)."'"; - else { - $error='ErrorWrongParameters'; - dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR); - return -1; - } - if ($ref || $ref_ext) $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class()."::isExistingObject", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $num=$db->num_rows($resql); - if ($num > 0) return 1; - else return 0; - } - return -1; - } - - /** - * Method to output saved errors - * - * @return string String with errors - */ - function errorsToString() - { - return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):''); - } - - /** - * Return full name (civility+' '+name+' '+lastname) - * - * @param Translate $langs Language object for translation of civility (used only if option is 1) - * @param int $option 0=No option, 1=Add civility - * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname - * @param int $maxlen Maximum length - * @return string String with full name - */ - function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0) - { - //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."
\n"; - $lastname=$this->lastname; - $firstname=$this->firstname; - if (empty($lastname)) $lastname=(isset($this->lastname)?$this->lastname:(isset($this->name)?$this->name:(isset($this->nom)?$this->nom:(isset($this->societe)?$this->societe:(isset($this->company)?$this->company:''))))); - - $ret=''; - if ($option && $this->civility_id) - { - if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' '; - else $ret.=$this->civility_id.' '; - } - - $ret.=dolGetFirstLastname($firstname, $lastname, $nameorder); - - return dol_trunc($ret,$maxlen); - } - - /** - * Return full address of contact - * - * @param int $withcountry 1=Add country into address string - * @param string $sep Separator to use to build string - * @param int $withregion 1=Add region into address string - * @return string Full address string - */ - function getFullAddress($withcountry=0,$sep="\n",$withregion=0) - { - if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) - { - require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; - $tmparray=getCountry($this->country_id,'all'); - $this->country_code=$tmparray['code']; - $this->country =$tmparray['label']; - } - - if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde))) - { - require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; - $tmparray=getState($this->state_id,'all',0,1); - $this->state_code =$tmparray['code']; - $this->state =$tmparray['label']; - $this->region_code =$tmparray['region_code']; - $this->region =$tmparray['region']; - } - - return dol_format_address($this, $withcountry, $sep); - } - - - /** - * Return full address for banner - * - * @param string $htmlkey HTML id to make banner content unique - * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member) - * @return string Full address string - */ - function getBannerAddress($htmlkey, $object) - { - global $conf, $langs; - - $countriesusingstate=array('AU','US','IN','GB','ES','UK','TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS - - $contactid=0; - $thirdpartyid=0; - if ($this->element == 'societe') - { - $thirdpartyid=$this->id; - } - if ($this->element == 'contact') - { - $contactid=$this->id; - $thirdpartyid=$object->fk_soc; - } - if ($this->element == 'user') - { - $contactid=$this->contact_id; - $thirdpartyid=$object->fk_soc; - } - - $out=''; - - $outdone=0; - $coords = $this->getFullAddress(1,', ',$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); - if ($coords) - { - if (! empty($conf->use_javascript_ajax)) - { - $namecoords = $this->getFullName($langs,1).'
'.$coords; - // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile - $out.=''; - $out.=img_picto($langs->trans("Address"), 'object_address.png'); - $out.=' '; - } - $out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++; - $outdone++; - } - - if (! in_array($this->country_code,$countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress - && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) - { - if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) { - $out.=($outdone?' - ':'').$this->region.' - '.$this->state; - } - else { - $out.=($outdone?' - ':'').$this->state; - } - $outdone++; - } - - if (! empty($this->phone) || ! empty($this->phone_pro) || ! empty($this->phone_mobile) || ! empty($this->phone_perso) || ! empty($this->fax) || ! empty($this->office_phone) || ! empty($this->user_mobile) || ! empty($this->office_fax)) $out.=($outdone?'
':''); - if (! empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone - $out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL',' ','phone',$langs->trans("PhonePro")); $outdone++; - } - if (! empty($this->phone_pro)) { - $out.=dol_print_phone($this->phone_pro,$this->country_code,$contactid,$thirdpartyid,'AC_TEL',' ','phone',$langs->trans("PhonePro")); $outdone++; - } - if (! empty($this->phone_mobile)) { - $out.=dol_print_phone($this->phone_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL',' ','mobile',$langs->trans("PhoneMobile")); $outdone++; - } - if (! empty($this->phone_perso)) { - $out.=dol_print_phone($this->phone_perso,$this->country_code,$contactid,$thirdpartyid,'AC_TEL',' ','phone',$langs->trans("PhonePerso")); $outdone++; - } - if (! empty($this->office_phone)) { - $out.=dol_print_phone($this->office_phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL',' ','phone',$langs->trans("PhonePro")); $outdone++; - } - if (! empty($this->user_mobile)) { - $out.=dol_print_phone($this->user_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL',' ','mobile',$langs->trans("PhoneMobile")); $outdone++; - } - if (! empty($this->fax)) { - $out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX',' ','fax',$langs->trans("Fax")); $outdone++; - } - if (! empty($this->office_fax)) { - $out.=dol_print_phone($this->office_fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX',' ','fax',$langs->trans("Fax")); $outdone++; - } - - $out.='
'; - $outdone=0; - if (! empty($this->email)) - { - $out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1); - $outdone++; - } - if (! empty($this->url)) - { - $out.=dol_print_url($this->url,'_goout',0,1); - $outdone++; - } - if (! empty($conf->skype->enabled)) - { - $out.='
'; - if ($this->skype) $out.=dol_print_skype($this->skype,$this->id,$object->id,'AC_SKYPE'); - $outdone++; - } - - $out.=''; - - return $out; - } - - /** - * Return the link of last main doc file for direct public download. - * - * @param string $modulepart Module related to document - * @param int $initsharekey Init the share key if it was not yet defined - * @return string Link or empty string if there is no download link - */ - function getLastMainDocLink($modulepart, $initsharekey=0) - { - global $user, $dolibarr_main_url_root; - - if (empty($this->last_main_doc)) - { - return ''; // No known last doc - } - - include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile=new EcmFiles($this->db); - $result = $ecmfile->fetch(0, '', $this->last_main_doc); - if ($result < 0) - { - $this->error = $ecmfile->error; - $this->errors = $ecmfile->errors; - return -1; - } - - if (empty($ecmfile->id)) - { - // Add entry into index - if ($initsharekey) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first - /* - $ecmfile->filepath = $rel_dir; - $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content - $ecmfile->fullpath_orig = ''; - $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $ecmfile->share = getRandomPassword(true); - $result = $ecmfile->create($user); - if ($result < 0) - { - $this->error = $ecmfile->error; - $this->errors = $ecmfile->errors; - } - */ - } - else return ''; - } - elseif (empty($ecmfile->share)) - { - // Add entry into index - if ($initsharekey) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $ecmfile->share = getRandomPassword(true); - $ecmfile->update($user); - } - else return ''; - } - - // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file - //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - - $forcedownload=0; - - $paramlink=''; - //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required. - //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required. - //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash - if (! empty($ecmfile->share)) $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share; // Hash for public share - if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1'; - - $fulllink=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:''); - - // Here $ecmfile->share is defined - return $fulllink; - } - - - /** - * Add a link between element $this->element and a contact - * - * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link - * @param int $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL - * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) - * @param int $notrigger Disable all triggers - * @return int <0 if KO, >0 if OK - */ - function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0) - { - global $user,$langs; - - - dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger"); - - // Check parameters - if ($fk_socpeople <= 0) - { - $langs->load("errors"); - $this->error=$langs->trans("ErrorWrongValueForParameterX","1"); - dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR); - return -1; - } - if (! $type_contact) - { - $langs->load("errors"); - $this->error=$langs->trans("ErrorWrongValueForParameterX","2"); - dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR); - return -2; - } - - $id_type_contact=0; - if (is_numeric($type_contact)) - { - $id_type_contact=$type_contact; - } - else - { - // On recherche id type_contact - $sql = "SELECT tc.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; - $sql.= " AND tc.source='".$this->db->escape($source)."'"; - $sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1"; - //print $sql; - $resql=$this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj) $id_type_contact=$obj->rowid; - } - } - - if ($id_type_contact == 0) - { - $this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT'; - dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT"); - return -3; - } - - $datecreate = dol_now(); - - // Socpeople must have already been added by some a trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error - $TListeContacts=$this->liste_contact(-1, $source); - $already_added=false; - if(!empty($TListeContacts)) { - foreach($TListeContacts as $array_contact) { - if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) { - $already_added=true; - break; - } - } - } - - if(!$already_added) { - - $this->db->begin(); - - // Insertion dans la base - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact"; - $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) "; - $sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ; - $sql.= "'".$this->db->idate($datecreate)."'"; - $sql.= ", 4, ". $id_type_contact; - $sql.= ")"; - - $resql=$this->db->query($sql); - if ($resql) - { - if (! $notrigger) - { - $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - } - - $this->db->commit(); - return 1; - } - else - { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $this->error=$this->db->errno(); - $this->db->rollback(); - echo 'err rollback'; - return -2; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -1; - } - } - } else return 0; - } - - /** - * Copy contact from one element to current - * - * @param CommonObject $objFrom Source element - * @param string $source Nature of contact ('internal' or 'external') - * @return int >0 if OK, <0 if KO - */ - function copy_linked_contact($objFrom, $source='internal') - { - $contacts = $objFrom->liste_contact(-1, $source); - foreach($contacts as $contact) - { - if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) - { - $this->error=$this->db->lasterror(); - return -1; - } - } - return 1; - } - - /** - * Update a link to contact line - * - * @param int $rowid Id of line contact-element - * @param int $statut New status of link - * @param int $type_contact_id Id of contact type (not modified if 0) - * @param int $fk_socpeople Id of soc_people to update (not modified if 0) - * @return int <0 if KO, >= 0 if OK - */ - function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0) - { - // Insertion dans la base - $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set"; - $sql.= " statut = ".$statut; - if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'"; - if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'"; - $sql.= " where rowid = ".$rowid; - $resql=$this->db->query($sql); - if ($resql) - { - return 0; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } - - /** - * Delete a link to contact line - * - * @param int $rowid Id of contact link line to delete - * @param int $notrigger Disable all triggers - * @return int >0 if OK, <0 if KO - */ - function delete_contact($rowid, $notrigger=0) - { - global $user; - - - $this->db->begin(); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; - $sql.= " WHERE rowid =".$rowid; - - dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG); - if ($this->db->query($sql)) - { - if (! $notrigger) - { - $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); - if ($result < 0) { $this->db->rollback(); return -1; } - } - - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } - - /** - * Delete all links between an object $this and all its contacts - * - * @param string $source '' or 'internal' or 'external' - * @param string $code Type of contact (code or id) - * @return int >0 if OK, <0 if KO - */ - function delete_linked_contact($source='',$code='') - { - $temp = array(); - $typeContact = $this->liste_type_contact($source,'',0,0,$code); - - foreach($typeContact as $key => $value) - { - array_push($temp,$key); - } - $listId = implode(",", $temp); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; - $sql.= " WHERE element_id = ".$this->id; - if ($listId) - $sql.= " AND fk_c_type_contact IN (".$listId.")"; - - dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG); - if ($this->db->query($sql)) - { - return 1; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } - - /** - * Get array of all contacts for an object - * - * @param int $statut Status of links to get (-1=all) - * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user) - * @param int $list 0:Return array contains all properties, 1:Return array contains just id - * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...) - * @return array Array of contacts - */ - function liste_contact($statut=-1,$source='external',$list=0,$code='') - { - global $langs; - - $tab=array(); - - $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user - if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo"; - if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact"; - $sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email"; - $sql.= ", tc.source, tc.element, tc.code, tc.libelle"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc"; - $sql.= ", ".MAIN_DB_PREFIX."element_contact ec"; - if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid"; - if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid"; - $sql.= " WHERE ec.element_id =".$this->id; - $sql.= " AND ec.fk_c_type_contact=tc.rowid"; - $sql.= " AND tc.element='".$this->db->escape($this->element)."'"; - if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'"; - if ($source == 'internal') $sql.= " AND tc.source = 'internal'"; - if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'"; - $sql.= " AND tc.active=1"; - if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'"; - $sql.=" ORDER BY t.lastname ASC"; - - dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - if (! $list) - { - $transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code; - $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); - $tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id, - 'nom'=>$obj->lastname, // For backward compatibility - 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact, - 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact); - } - else - { - $tab[$i]=$obj->id; - } - - $i++; - } - - return $tab; - } - else - { - $this->error=$this->db->lasterror(); - dol_print_error($this->db); - return -1; - } - } - - - /** - * Update status of a contact linked to object - * - * @param int $rowid Id of link between object and contact - * @return int <0 if KO, >=0 if OK - */ - function swapContactStatus($rowid) - { - $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,"; - $sql.= " tc.code, tc.libelle"; - //$sql.= ", s.fk_soc"; - $sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)"; - //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid"; // Si contact de type external, alors il est lie a une societe - $sql.= " WHERE ec.rowid =".$rowid; - $sql.= " AND ec.fk_c_type_contact=tc.rowid"; - $sql.= " AND tc.element = '".$this->db->escape($this->element)."'"; - - dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $newstatut = ($obj->statut == 4) ? 5 : 4; - $result = $this->update_contact($rowid, $newstatut); - $this->db->free($resql); - return $result; - } - else - { - $this->error=$this->db->error(); - dol_print_error($this->db); - return -1; - } - - } - - /** - * Return array with list of possible values for type of contacts - * - * @param string $source 'internal', 'external' or 'all' - * @param string $order Sort order by : 'position', 'code', 'rowid'... - * @param int $option 0=Return array id->label, 1=Return array code->label - * @param int $activeonly 0=all status of contact, 1=only the active - * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE') - * @return array Array list of type of contacts (id->label if option=0, code->label if option=1) - */ - function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='') - { - global $langs; - - if (empty($order)) $order='position'; - if ($order == 'position') $order.=',code'; - - $tab = array(); - $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; - if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types - if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'"; - if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'"; - $sql.= $this->db->order($order,'ASC'); - - //print "sql=".$sql; - $resql=$this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - $transkey="TypeContact_".$this->element."_".$source."_".$obj->code; - $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); - if (empty($option)) $tab[$obj->rowid]=$libelle_type; - else $tab[$obj->code]=$libelle_type; - $i++; - } - return $tab; - } - else - { - $this->error=$this->db->lasterror(); - //dol_print_error($this->db); - return null; - } - } - - /** - * Return id of contacts for a source and a contact code. - * Example: contact client de facturation ('external', 'BILLING') - * Example: contact client de livraison ('external', 'SHIPPING') - * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL') - * - * @param string $source 'external' or 'internal' - * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ... - * @param int $status limited to a certain status - * @return array List of id for such contacts - */ - function getIdContact($source,$code,$status=0) - { - global $conf; - - $result=array(); - $i=0; - //cas particulier pour les expeditions - if($this->element=='shipping' && $this->origin_id != 0) { - $id=$this->origin_id; - $element='commande'; - } else { - $id=$this->id; - $element=$this->element; - } - - $sql = "SELECT ec.fk_socpeople"; - $sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,"; - if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,"; - if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,"; - $sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE ec.element_id = ".$id; - $sql.= " AND ec.fk_socpeople = c.rowid"; - if ($source == 'internal') $sql.= " AND c.entity IN (0,".$conf->entity.")"; - if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")"; - $sql.= " AND ec.fk_c_type_contact = tc.rowid"; - $sql.= " AND tc.element = '".$element."'"; - $sql.= " AND tc.source = '".$source."'"; - $sql.= " AND tc.code = '".$code."'"; - $sql.= " AND tc.active = 1"; - if ($status) $sql.= " AND ec.statut = ".$status; - - dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - $result[$i]=$obj->fk_socpeople; - $i++; - } - } - else - { - $this->error=$this->db->error(); - return null; - } - - return $result; - } - - /** - * Load object contact with id=$this->contactid into $this->contact - * - * @param int $contactid Id du contact. Use this->contactid if empty. - * @return int <0 if KO, >0 if OK - */ - function fetch_contact($contactid=null) - { - if (empty($contactid)) $contactid=$this->contactid; - - if (empty($contactid)) return 0; - - require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - $contact = new Contact($this->db); - $result=$contact->fetch($contactid); - $this->contact = $contact; - return $result; - } - - /** - * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty - * - * @param int $force_thirdparty_id Force thirdparty id - * @return int <0 if KO, >0 if OK - */ - function fetch_thirdparty($force_thirdparty_id=0) - { - global $conf; - - if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) - return 0; - - require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; - - $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty); - if ($force_thirdparty_id) - $idtofetch = $force_thirdparty_id; - - if ($idtofetch) { - $thirdparty = new Societe($this->db); - $result = $thirdparty->fetch($idtofetch); - $this->thirdparty = $thirdparty; - - // Use first price level if level not defined for third party - if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) { - $this->thirdparty->price_level = 1; - } - - return $result; - } else - return -1; - } - - - /** - * Looks for an object with ref matching the wildcard provided - * It does only work when $this->table_ref_field is set - * - * @param string $ref Wildcard - * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO - */ - public function fetchOneLike($ref) - { - if (!$this->table_ref_field) { - return 0; - } - - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1'; - - $query = $this->db->query($sql); - - if (!$this->db->num_rows($query)) { - return 0; - } - - $result = $this->db->fetch_object($query); - - return $this->fetch($result->rowid); - } - - /** - * Load data for barcode into properties ->barcode_type* - * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but - * if it is not defined, ->element must be defined to know default barcode type. - * - * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded) - */ - function fetch_barcode() - { - global $conf; - - dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type); - - $idtype=$this->barcode_type; - if (empty($idtype) && $idtype != '0') // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined - { - if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; - else if ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY; - else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING); - } - - if ($idtype > 0) - { - if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) // If data not already loaded - { - $sql = "SELECT rowid, code, libelle as label, coder"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; - $sql.= " WHERE rowid = ".$idtype; - dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $this->barcode_type = $obj->rowid; - $this->barcode_type_code = $obj->code; - $this->barcode_type_label = $obj->label; - $this->barcode_type_coder = $obj->coder; - return 1; - } - else - { - dol_print_error($this->db); - return -1; - } - } - } - return 0; - } - - /** - * Charge le projet d'id $this->fk_project dans this->projet - * - * @return int <0 if KO, >=0 if OK - */ - function fetch_projet() - { - include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - - if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility - if (empty($this->fk_project)) return 0; - - $project = new Project($this->db); - $result = $project->fetch($this->fk_project); - - $this->projet = $project; // deprecated - $this->project = $project; - return $result; - } - - /** - * Charge le user d'id userid dans this->user - * - * @param int $userid Id du contact - * @return int <0 if KO, >0 if OK - */ - function fetch_user($userid) - { - $user = new User($this->db); - $result=$user->fetch($userid); - $this->user = $user; - return $result; - } - - /** - * Read linked origin object - * - * @return void - */ - function fetch_origin() - { - if ($this->origin == 'shipping') $this->origin = 'expedition'; - if ($this->origin == 'delivery') $this->origin = 'livraison'; - - $origin = $this->origin; - - $classname = ucfirst($origin); - $this->$origin = new $classname($this->db); - $this->$origin->fetch($this->origin_id); - } - - /** - * Load object from specific field - * - * @param string $table Table element or element line - * @param string $field Field selected - * @param string $key Import key - * @param string $element Element name - * @return int <0 if KO, >0 if OK - */ - function fetchObjectFrom($table, $field, $key, $element = null) - { - global $conf; - - $result=false; - - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE ".$field." = '".$key."'"; - if (! empty($element)) { - $sql.= " AND entity IN (".getEntity($element).")"; - } else { - $sql.= " AND entity = ".$conf->entity; - } - - dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - $result = $this->fetch($row[0]); - } - - return $result; - } - - /** - * Getter generic. Load value from a specific field - * - * @param string $table Table of element or element line - * @param int $id Element id - * @param string $field Field selected - * @return int <0 if KO, >0 if OK - */ - function getValueFrom($table, $id, $field) - { - $result=false; - if (!empty($id) && !empty($field) && !empty($table)) { - $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE rowid = ".$id; - - dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - $result = $row[0]; - } - } - return $result; - } - - /** - * Setter generic. Update a specific field into database. - * Warning: Trigger is run only if param trigkey is provided. - * - * @param string $field Field to update - * @param mixed $value New value - * @param string $table To force other table element or element line (should not be used) - * @param int $id To force other object id (should not be used) - * @param string $format Data format ('text', 'date'). 'text' is used if not defined - * @param string $id_field To force rowid field name. 'rowid' is used if not defined - * @param User|string $fuser Update the user of last update field with this user. If not provided, current user is used except if value is 'none' - * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY') - * @return int <0 if KO, >0 if OK - * @see updateExtraField - */ - function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='') - { - global $user,$langs,$conf; - - if (empty($table)) $table=$this->table_element; - if (empty($id)) $id=$this->id; - if (empty($format)) $format='text'; - if (empty($id_field)) $id_field='rowid'; - - $error=0; - - $this->db->begin(); - - // Special case - if ($table == 'product' && $field == 'note_private') $field='note'; - - $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; - if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'"; - else if ($format == 'int') $sql.= $field." = ".$this->db->escape($value); - else if ($format == 'date') $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); - if (! empty($fuser) && is_object($fuser)) $sql.=", fk_user_modif = ".$fuser->id; - elseif (empty($fuser) || $fuser != 'none') $sql.=", fk_user_modif = ".$user->id; - $sql.= " WHERE ".$id_field." = ".$id; - - dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($trigkey) - { - $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors - if ($result < 0) $error++; - } - - if (! $error) - { - if (property_exists($this, $field)) $this->$field = $value; - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -2; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } - - /** - * Load properties id_previous and id_next by comparing $fieldid with $this->ref - * - * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')" - * @param string $fieldid Name of field to use for the select MAX and MIN - * @param int $nodbprefix Do not include DB prefix to forge table name - * @return int <0 if KO, >0 if OK - */ - function load_previous_next_ref($filter, $fieldid, $nodbprefix=0) - { - global $user; - - if (! $this->table_element) - { - dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined"); - return -1; - } - if ($fieldid == 'none') return 1; - - // Security on socid - $socid = 0; - if ($user->societe_id > 0) $socid = $user->societe_id; - - // this->ismultientitymanaged contains - // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - $alias = 's'; - if ($this->element == 'societe') $alias = 'te'; - - $sql = "SELECT MAX(te.".$fieldid.")"; - $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid - else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid - if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; - $sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND sc.fk_user = " .$user->id; - if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)'; - if (! empty($filter)) - { - if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility - $sql.=$filter; - } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity - else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element).')'; - if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql.= ' AND te.fk_soc = ' . $socid; - if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)'; - if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql.= ' AND te.rowid = ' . $socid; - //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."
"; - - $result = $this->db->query($sql); - if (! $result) - { - $this->error=$this->db->lasterror(); - return -1; - } - $row = $this->db->fetch_row($result); - $this->ref_previous = $row[0]; - - - $sql = "SELECT MIN(te.".$fieldid.")"; - $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid - else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid - if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; - $sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND sc.fk_user = " .$user->id; - if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)'; - if (! empty($filter)) - { - if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility - $sql.=$filter; - } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity - else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element).')'; - if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql.= ' AND te.fk_soc = ' . $socid; - if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)'; - if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql.= ' AND te.rowid = ' . $socid; - //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."
"; - // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null - - $result = $this->db->query($sql); - if (! $result) - { - $this->error=$this->db->lasterror(); - return -2; - } - $row = $this->db->fetch_row($result); - $this->ref_next = $row[0]; - - return 1; - } - - - /** - * Return list of id of contacts of project - * - * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe) - * @return array Array of id of contacts (if source=external or internal) - * Array of id of third parties with at least one contact on project (if source=thirdparty) - */ - function getListContactId($source='external') - { - $contactAlreadySelected = array(); - $tab = $this->liste_contact(-1,$source); - $num=count($tab); - $i = 0; - while ($i < $num) - { - if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid']; - else $contactAlreadySelected[$i] = $tab[$i]['id']; - $i++; - } - return $contactAlreadySelected; - } - - - /** - * Link element with a project - * - * @param int $projectid Project id to link element to - * @return int <0 if KO, >0 if OK - */ - function setProject($projectid) - { - if (! $this->table_element) - { - dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - if ($this->table_element == 'actioncomm') - { - if ($projectid) $sql.= ' SET fk_project = '.$projectid; - else $sql.= ' SET fk_project = NULL'; - $sql.= ' WHERE id = '.$this->id; - } - else - { - if ($projectid) $sql.= ' SET fk_projet = '.$projectid; - else $sql.= ' SET fk_projet = NULL'; - $sql.= ' WHERE rowid = '.$this->id; - } - - dol_syslog(get_class($this)."::setProject", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->fk_project = $projectid; - return 1; - } - else - { - dol_print_error($this->db); - return -1; - } - } - - /** - * Change the payments methods - * - * @param int $id Id of new payment method - * @return int >0 if OK, <0 if KO - */ - function setPaymentMethods($id) - { - dol_syslog(get_class($this).'::setPaymentMethods('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - // TODO uniformize field name - $fieldname = 'fk_mode_reglement'; - if ($this->element == 'societe') $fieldname = 'mode_reglement'; - if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier'; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$id; - $sql .= ' WHERE rowid='.$this->id; - - if ($this->db->query($sql)) - { - $this->mode_reglement_id = $id; - // for supplier - if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id; - return 1; - } - else - { - dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } - - /** - * Change the multicurrency code - * - * @param string $code multicurrency code - * @return int >0 if OK, <0 if KO - */ - function setMulticurrencyCode($code) - { - dol_syslog(get_class($this).'::setMulticurrencyCode('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - $fieldname = 'multicurrency_code'; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'"; - $sql .= ' WHERE rowid='.$this->id; - - if ($this->db->query($sql)) - { - $this->multicurrency_code = $code; - - list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code); - if ($rate) $this->setMulticurrencyRate($rate); - - return 1; - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } - - /** - * Change the multicurrency rate - * - * @param double $rate multicurrency rate - * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency - * @return int >0 if OK, <0 if KO - */ - function setMulticurrencyRate($rate, $mode=1) - { - dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - $fieldname = 'multicurrency_tx'; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$rate; - $sql .= ' WHERE rowid='.$this->id; - - if ($this->db->query($sql)) - { - $this->multicurrency_tx = $rate; - - // Update line price - if (!empty($this->lines)) - { - foreach ($this->lines as &$line) - { - if($mode == 1) { - $line->subprice = 0; - } - - switch ($this->element) { - case 'propal': - $this->updateline($line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, ($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); - break; - case 'commande': - $this->updateline($line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); - break; - case 'facture': - $this->updateline($line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice); - break; - case 'supplier_proposal': - $this->updateline($line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, ($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options, $line->ref_fourn, $line->multicurrency_subprice); - break; - case 'order_supplier': - $this->updateline($line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); - break; - case 'invoice_supplier': - $this->updateline($line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); - break; - default: - dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG); - break; - } - - } - } - - return 1; - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } - - /** - * Change the payments terms - * - * @param int $id Id of new payment terms - * @return int >0 if OK, <0 if KO - */ - function setPaymentTerms($id) - { - dol_syslog(get_class($this).'::setPaymentTerms('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - // TODO uniformize field name - $fieldname = 'fk_cond_reglement'; - if ($this->element == 'societe') $fieldname = 'cond_reglement'; - if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier'; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$id; - $sql .= ' WHERE rowid='.$this->id; - - if ($this->db->query($sql)) - { - $this->cond_reglement_id = $id; - // for supplier - if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id; - $this->cond_reglement = $id; // for compatibility - return 1; - } - else - { - dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } - - /** - * Define delivery address - * @deprecated - * - * @param int $id Address id - * @return int <0 si ko, >0 si ok - */ - function setDeliveryAddress($id) - { - $fieldname = 'fk_delivery_address'; - if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address'; - - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - - if ($this->db->query($sql)) - { - $this->fk_delivery_address = $id; - return 1; - } - else - { - $this->error=$this->db->error(); - dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error); - return -1; - } - } - - - /** - * Change the shipping method - * - * @param int $shipping_method_id Id of shipping method - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @param User $userused Object user - * - * @return int 1 if OK, 0 if KO - */ - function setShippingMethod($shipping_method_id, $notrigger=false, $userused=null) - { - global $user; - - if (empty($userused)) $userused=$user; - - $error = 0; - - if (! $this->table_element) { - dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - - $this->db->begin(); - - if ($shipping_method_id<0) $shipping_method_id='NULL'; - dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')'); - - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_shipping_method = ".$shipping_method_id; - $sql.= " WHERE rowid=".$this->id; - $resql = $this->db->query($sql); - if (! $resql) { - dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG); - $this->error = $this->db->lasterror(); - $error++; - } else { - if (!$notrigger) - { - // Call trigger - $this->context=array('shippingmethodupdate'=>1); - $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused); - if ($result < 0) $error++; - // End call trigger - } - } - if ($error) - { - $this->db->rollback(); - return -1; - } else { - $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id; - $this->db->commit(); - return 1; - } - - } - - - /** - * Change the warehouse - * - * @param int $warehouse_id Id of warehouse - * @return int 1 if OK, 0 if KO - */ - function setWarehouse($warehouse_id) - { - if (! $this->table_element) { - dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - if ($warehouse_id<0) $warehouse_id='NULL'; - dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')'); - - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_warehouse = ".$warehouse_id; - $sql.= " WHERE rowid=".$this->id; - - if ($this->db->query($sql)) { - $this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id; - return 1; - } else { - dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG); - $this->error=$this->db->error(); - return 0; - } - } - - - /** - * Set last model used by doc generator - * - * @param User $user User object that make change - * @param string $modelpdf Modele name - * @return int <0 if KO, >0 if OK - */ - function setDocModel($user, $modelpdf) - { - if (! $this->table_element) - { - dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - - $newmodelpdf=dol_trunc($modelpdf,255); - - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'"; - $sql.= " WHERE rowid = ".$this->id; - // if ($this->element == 'facture') $sql.= " AND fk_statut < 2"; - // if ($this->element == 'propal') $sql.= " AND fk_statut = 0"; - - dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->modelpdf=$modelpdf; - return 1; - } - else - { - dol_print_error($this->db); - return 0; - } - } - - - /** - * Change the bank account - * - * @param int $fk_account Id of bank account - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @param User $userused Object user - * @return int 1 if OK, 0 if KO - */ - function setBankAccount($fk_account, $notrigger=false, $userused=null) - { - global $user; - - if (empty($userused)) $userused=$user; - - $error = 0; - - if (! $this->table_element) { - dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - $this->db->begin(); - - if ($fk_account<0) $fk_account='NULL'; - dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')'); - - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_account = ".$fk_account; - $sql.= " WHERE rowid=".$this->id; - - $resql = $this->db->query($sql); - if (! $resql) - { - dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error()); - $this->error = $this->db->lasterror(); - $error++; - } - else - { - if (!$notrigger) - { - // Call trigger - $this->context=array('bankaccountupdate'=>1); - $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused); - if ($result < 0) $error++; - // End call trigger - } - } - if ($error) - { - $this->db->rollback(); - return -1; - } - else - { - $this->fk_account = ($fk_account=='NULL')?null:$fk_account; - $this->db->commit(); - return 1; - } - } - - - // TODO: Move line related operations to CommonObjectLine? - - /** - * Save a new position (field rang) for details lines. - * You can choose to set position for lines with already a position or lines without any position defined. - * - * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines. - * @param string $rowidorder ASC or DESC - * @param boolean $fk_parent_line Table with fk_parent_line field or not - * @return int <0 if KO, >0 if OK - */ - function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true) - { - if (! $this->table_element_line) - { - dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR); - return -1; - } - if (! $this->fk_element) - { - dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR); - return -1; - } - - // Count number of lines to reorder (according to choice $renum) - $nl=0; - $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.'='.$this->id; - if (! $renum) $sql.= ' AND rang = 0'; - if ($renum) $sql.= ' AND rang <> 0'; - - dol_syslog(get_class($this)."::line_order", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - $nl = $row[0]; - } - else dol_print_error($this->db); - if ($nl > 0) - { - // The goal of this part is to reorder all lines, with all children lines sharing the same - // counter that parents. - $rows=array(); - - // We first search all lines that are parent lines (for multilevel details lines) - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - if ($fk_parent_line) $sql.= ' AND fk_parent_line IS NULL'; - $sql.= ' ORDER BY rang ASC, rowid '.$rowidorder; - - dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $i=0; - $num = $this->db->num_rows($resql); - while ($i < $num) - { - $row = $this->db->fetch_row($resql); - $rows[] = $row[0]; // Add parent line into array rows - $childrens = $this->getChildrenOfLine($row[0]); - if (! empty($childrens)) - { - foreach($childrens as $child) - { - array_push($rows, $child); - } - } - $i++; - } - - // Now we set a new number for each lines (parent and children with children included into parent tree) - if (! empty($rows)) - { - foreach($rows as $key => $row) - { - $this->updateRangOfLine($row, ($key+1)); - } - } - } - else - { - dol_print_error($this->db); - } - } - return 1; - } - - /** - * Get children of line - * - * @param int $id Id of parent line - * @return array Array with list of children lines id - */ - function getChildrenOfLine($id) - { - $rows=array(); - - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND fk_parent_line = '.$id; - $sql.= ' ORDER BY rang ASC'; - - dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $i=0; - $num = $this->db->num_rows($resql); - while ($i < $num) - { - $row = $this->db->fetch_row($resql); - $rows[$i] = $row[0]; - $i++; - } - } - - return $rows; - } - - /** - * Update a line to have a lower rank - * - * @param int $rowid Id of line - * @param boolean $fk_parent_line Table with fk_parent_line field or not - * @return void - */ - function line_up($rowid, $fk_parent_line=true) - { - $this->line_order(false, 'ASC', $fk_parent_line); - - // Get rang of line - $rang = $this->getRangOfLine($rowid); - - // Update position of line - $this->updateLineUp($rowid, $rang); - } - - /** - * Update a line to have a higher rank - * - * @param int $rowid Id of line - * @param boolean $fk_parent_line Table with fk_parent_line field or not - * @return void - */ - function line_down($rowid, $fk_parent_line=true) - { - $this->line_order(false, 'ASC', $fk_parent_line); - - // Get rang of line - $rang = $this->getRangOfLine($rowid); - - // Get max value for rang - $max = $this->line_max(); - - // Update position of line - $this->updateLineDown($rowid, $rang, $max); - } - - /** - * Update position of line (rang) - * - * @param int $rowid Id of line - * @param int $rang Position - * @return void - */ - function updateRangOfLine($rowid,$rang) - { - $fieldposition = 'rang'; - if ($this->table_element_line == 'ecm_files') $fieldposition = 'position'; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang; - $sql.= ' WHERE rowid = '.$rowid; - - dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG); - if (! $this->db->query($sql)) - { - dol_print_error($this->db); - } - } - - /** - * Update position of line with ajax (rang) - * - * @param array $rows Array of rows - * @return void - */ - function line_ajaxorder($rows) - { - $num = count($rows); - for ($i = 0 ; $i < $num ; $i++) - { - $this->updateRangOfLine($rows[$i], ($i+1)); - } - } - - /** - * Update position of line up (rang) - * - * @param int $rowid Id of line - * @param int $rang Position - * @return void - */ - function updateLineUp($rowid,$rang) - { - if ($rang > 1 ) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang ; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.($rang - 1); - if ($this->db->query($sql) ) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang - 1); - $sql.= ' WHERE rowid = '.$rowid; - if (! $this->db->query($sql) ) - { - dol_print_error($this->db); - } - } - else - { - dol_print_error($this->db); - } - } - } - - /** - * Update position of line down (rang) - * - * @param int $rowid Id of line - * @param int $rang Position - * @param int $max Max - * @return void - */ - function updateLineDown($rowid,$rang,$max) - { - if ($rang < $max) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.($rang+1); - if ($this->db->query($sql) ) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang+1); - $sql.= ' WHERE rowid = '.$rowid; - if (! $this->db->query($sql) ) - { - dol_print_error($this->db); - } - } - else - { - dol_print_error($this->db); - } - } - } - - /** - * Get position of line (rang) - * - * @param int $rowid Id of line - * @return int Value of rang in table of lines - */ - function getRangOfLine($rowid) - { - $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE rowid ='.$rowid; - - dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } - - /** - * Get rowid of the line relative to its position - * - * @param int $rang Rang value - * @return int Rowid of the line - */ - function getIdOfLine($rang) - { - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.$rang; - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } - - /** - * Get max value used for position of line (rang) - * - * @param int $fk_parent_line Parent line id - * @return int Max value of rang in table of lines - */ - function line_max($fk_parent_line=0) - { - // Search the last rang with fk_parent_line - if ($fk_parent_line) - { - $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND fk_parent_line = '.$fk_parent_line; - - dol_syslog(get_class($this)."::line_max", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - if (! empty($row[0])) - { - return $row[0]; - } - else - { - return $this->getRangOfLine($fk_parent_line); - } - } - } - // If not, search the last rang of element - else - { - $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - - dol_syslog(get_class($this)."::line_max", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } - } - - /** - * Update external ref of element - * - * @param string $ref_ext Update field ref_ext - * @return int <0 if KO, >0 if OK - */ - function update_ref_ext($ref_ext) - { - if (! $this->table_element) - { - dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'"; - $sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id; - - dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->ref_ext = $ref_ext; - return 1; - } - else - { - $this->error=$this->db->error(); - return -1; - } - } - - /** - * Update note of element - * - * @param string $note New value for note - * @param string $suffix '', '_public' or '_private' - * @return int <0 if KO, >0 if OK - */ - function update_note($note,$suffix='') - { - global $user; - - if (! $this->table_element) - { - dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - if (! in_array($suffix,array('','_public','_private'))) - { - dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR); - return -2; - } - // Special cas - //var_dump($this->table_element);exit; - if ($this->table_element == 'product') $suffix=''; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL"); - $sql.= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))?"fk_user_mod":"fk_user_modif")." = ".$user->id; - $sql.= " WHERE rowid =". $this->id; - - dol_syslog(get_class($this)."::update_note", LOG_DEBUG); - if ($this->db->query($sql)) - { - if ($suffix == '_public') $this->note_public = $note; - else if ($suffix == '_private') $this->note_private = $note; - else - { - $this->note = $note; // deprecated - $this->note_private = $note; - } - return 1; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } - - /** - * Update public note (kept for backward compatibility) - * - * @param string $note New value for note - * @return int <0 if KO, >0 if OK - * @deprecated - * @see update_note() - */ - function update_note_public($note) - { - return $this->update_note($note,'_public'); - } - - /** - * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines). - * Must be called at end of methods addline or updateline. - * - * @param int $exclspec >0 = Exclude special product (product_type=9) - * @param string $roundingadjust 'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode total of rounding, '1'=Force mode rounding of total - * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object. - * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object. - * @return int <0 if KO, >0 if OK - */ - function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null) - { - global $conf; - - // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield) - $MODULE = ""; - if ($this->element == 'propal') - $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL"; - elseif ($this->element == 'order') - $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER"; - elseif ($this->element == 'facture') - $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE"; - elseif ($this->element == 'facture_fourn') - $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE"; - elseif ($this->element == 'order_supplier') - $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER"; - elseif ($this->element == 'supplier_proposal') - $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL"; - - if (! empty($MODULE)) { - if (! empty($conf->global->$MODULE)) { - $modsactivated = explode(',', $conf->global->$MODULE); - foreach ($modsactivated as $mod) { - if ($conf->$mod->enabled) - return 1; // update was disabled by specific setup - } - } - } - - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - - if ($roundingadjust == '-1') $roundingadjust='auto'; // For backward compatibility - - $forcedroundingmode=$roundingadjust; - if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND; - elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0'; - - $error=0; - - $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1; - - // Define constants to find lines to sum - $fieldtva='total_tva'; - $fieldlocaltax1='total_localtax1'; - $fieldlocaltax2='total_localtax2'; - $fieldup='subprice'; - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') - { - $fieldtva='tva'; - $fieldup='pu_ht'; - } - if ($this->element == 'expensereport') - { - $fieldup='value_unit'; - } - - $sql = 'SELECT rowid, qty, '.$fieldup.' as up, remise_percent, total_ht, '.$fieldtva.' as total_tva, total_ttc, '.$fieldlocaltax1.' as total_localtax1, '.$fieldlocaltax2.' as total_localtax2,'; - $sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type'; - if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent'; - $sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; - $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - if ($exclspec) - { - $product_field='product_type'; - if ($this->table_element_line == 'contratdet') $product_field=''; // contratdet table has no product_type field - if ($product_field) $sql.= ' AND '.$product_field.' <> 9'; - } - $sql.= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used - - dol_syslog(get_class($this)."::update_price", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->total_ht = 0; - $this->total_tva = 0; - $this->total_localtax1 = 0; - $this->total_localtax2 = 0; - $this->total_ttc = 0; - $total_ht_by_vats = array(); - $total_tva_by_vats = array(); - $total_ttc_by_vats = array(); - $this->multicurrency_total_ht = 0; - $this->multicurrency_total_tva = 0; - $this->multicurrency_total_ttc = 0; - - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none' - if ($forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto' - { - $localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx); - $tmpcal=calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx); - $diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); - if ($diff) - { - $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid; - dol_syslog('We found unconsistent data into detailed line (difference of '.$diff.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); - $resqlfix=$this->db->query($sqlfix); - if (! $resqlfix) dol_print_error($this->db,'Failed to update line'); - $obj->total_tva = $tmpcal[1]; - $obj->total_ttc = $tmpcal[2]; - // - } - } - - $this->total_ht += $obj->total_ht; // The field visible at end of line detail - $this->total_tva += $obj->total_tva; - $this->total_localtax1 += $obj->total_localtax1; - $this->total_localtax2 += $obj->total_localtax2; - $this->total_ttc += $obj->total_ttc; - $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail - $this->multicurrency_total_tva += $obj->multicurrency_total_tva; - $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc; - - if (! isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate]=0; - if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0; - if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0; - $total_ht_by_vats[$obj->vatrate] += $obj->total_ht; - $total_tva_by_vats[$obj->vatrate] += $obj->total_tva; - $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc; - - if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency - { - $tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1); - $diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1); - //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."
\n"; - if ($diff) - { - if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; } - $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid; - dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); - $resqlfix=$this->db->query($sqlfix); - if (! $resqlfix) dol_print_error($this->db,'Failed to update line'); - $this->total_tva -= $diff; - $this->total_ttc -= $diff; - $total_tva_by_vats[$obj->vatrate] -= $diff; - $total_ttc_by_vats[$obj->vatrate] -= $diff; - - } - } - - $i++; - } - - // Add revenue stamp to total - $this->total_ttc += isset($this->revenuestamp)?$this->revenuestamp:0; - $this->multicurrency_total_ttc += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0; - - // Situations totals - if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits')) - { - $prev_sits = $this->get_prev_sits(); - - foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch. - $this->total_ht -= $sit->total_ht; - $this->total_tva -= $sit->total_tva; - $this->total_localtax1 -= $sit->total_localtax1; - $this->total_localtax2 -= $sit->total_localtax2; - $this->total_ttc -= $sit->total_ttc; - $this->multicurrency_total_ht -= $sit->multicurrency_total_ht; - $this->multicurrency_total_tva -= $sit->multicurrency_total_tva; - $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc; - } - } - - $this->db->free($resql); - - // Now update global field total_ht, total_ttc and tva - $fieldht='total_ht'; - $fieldtva='tva'; - $fieldlocaltax1='localtax1'; - $fieldlocaltax2='localtax2'; - $fieldttc='total_ttc'; - // Specific code for backward compatibility with old field names - if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht='total'; - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva'; - if ($this->element == 'propal') $fieldttc='total'; - if ($this->element == 'expensereport') $fieldtva='total_tva'; - if ($this->element == 'supplier_proposal') $fieldttc='total'; - - if (empty($nodatabaseupdate)) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; - $sql .= " ".$fieldht."='".price2num($this->total_ht)."',"; - $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',"; - $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',"; - $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',"; - $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'"; - $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'"; - $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'"; - $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'"; - $sql .= ' WHERE rowid = '.$this->id; - - //print "xx".$sql; - dol_syslog(get_class($this)."::update_price", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) - { - $error++; - $this->error=$this->db->lasterror(); - $this->errors[]=$this->db->lasterror(); - } - } - - if (! $error) - { - return 1; - } - else - { - return -1; - } - } - else - { - dol_print_error($this->db,'Bad request in update_price'); - return -1; - } - } - - /** - * Add objects linked in llx_element_element. - * - * @param string $origin Linked element type - * @param int $origin_id Linked element id - * @return int <=0 if KO, >0 if OK - * @see fetchObjectLinked, updateObjectLinked, deleteObjectLinked - */ - function add_object_linked($origin=null, $origin_id=null) - { - $origin = (! empty($origin) ? $origin : $this->origin); - $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id); - - // Special case - if ($origin == 'order') $origin='commande'; - if ($origin == 'invoice') $origin='facture'; - - $this->db->begin(); - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql.= "fk_source"; - $sql.= ", sourcetype"; - $sql.= ", fk_target"; - $sql.= ", targettype"; - $sql.= ") VALUES ("; - $sql.= $origin_id; - $sql.= ", '".$this->db->escape($origin)."'"; - $sql.= ", ".$this->id; - $sql.= ", '".$this->db->escape($this->element)."'"; - $sql.= ")"; - - dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return 0; - } - } - - /** - * Fetch array of objects linked to current object. Links are loaded into this->linkedObjects array and this->linkedObjectsIds - * Possible usage for parameters: - * - all parameters empty -> we look all link to current object (current object can be source or target) - * - source id+type -> will get target list linked to source - * - target id+type -> will get source list linked to target - * - source id+type + target type -> will get target list of the type - * - target id+type + target source -> will get source list of the type - * - * @param int $sourceid Object source id (if not defined, id of object) - * @param string $sourcetype Object source type (if not defined, element name of object) - * @param int $targetid Object target id (if not defined, id of object) - * @param string $targettype Object target type (if not defined, elemennt name of object) - * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided - * @param int $alsosametype 0=Return only links to object that differs from source. 1=Include also link to objects of same type. - * @return void - * @see add_object_linked, updateObjectLinked, deleteObjectLinked - */ - function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1) - { - global $conf; - - $this->linkedObjectsIds=array(); - $this->linkedObjects=array(); - - $justsource=false; - $justtarget=false; - $withtargettype=false; - $withsourcetype=false; - - if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid)) - { - $justsource=true; // the source (id and type) is a search criteria - if (! empty($targettype)) $withtargettype=true; - } - if (! empty($targetid) && ! empty($targettype) && empty($sourceid)) - { - $justtarget=true; // the target (id and type) is a search criteria - if (! empty($sourcetype)) $withsourcetype=true; - } - - $sourceid = (! empty($sourceid) ? $sourceid : $this->id); - $targetid = (! empty($targetid) ? $targetid : $this->id); - $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element); - $targettype = (! empty($targettype) ? $targettype : $this->element); - - /*if (empty($sourceid) && empty($targetid)) - { - dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR); - return -1; - }*/ - - // Links between objects are stored in table element_element - $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element'; - $sql.= " WHERE "; - if ($justsource || $justtarget) - { - if ($justsource) - { - $sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'"; - if ($withtargettype) $sql.= " AND targettype = '".$targettype."'"; - } - else if ($justtarget) - { - $sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'"; - if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'"; - } - } - else - { - $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')"; - $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')"; - } - $sql .= ' ORDER BY sourcetype'; - //print $sql; - - dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - if ($justsource || $justtarget) - { - if ($justsource) - { - $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; - } - else if ($justtarget) - { - $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; - } - } - else - { - if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) - { - $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; - } - if ($obj->fk_target == $targetid && $obj->targettype == $targettype) - { - $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; - } - } - $i++; - } - - if (! empty($this->linkedObjectsIds)) - { - foreach($this->linkedObjectsIds as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...) - { - // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...) - $module = $element = $subelement = $objecttype; - if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier' - && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs)) - { - $module = $element = $regs[1]; - $subelement = $regs[2]; - } - - $classpath = $element.'/class'; - // To work with non standard classpath or module name - if ($objecttype == 'facture') { - $classpath = 'compta/facture/class'; - } - else if ($objecttype == 'facturerec') { - $classpath = 'compta/facture/class'; $module = 'facture'; - } - else if ($objecttype == 'propal') { - $classpath = 'comm/propal/class'; - } - else if ($objecttype == 'supplier_proposal') { - $classpath = 'supplier_proposal/class'; - } - else if ($objecttype == 'shipping') { - $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon'; - } - else if ($objecttype == 'delivery') { - $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon'; - } - else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { - $classpath = 'fourn/class'; $module = 'fournisseur'; - } - else if ($objecttype == 'fichinter') { - $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter'; - } - else if ($objecttype == 'subscription') { - $classpath = 'adherents/class'; $module = 'adherent'; - } - - // Set classfile - $classfile = strtolower($subelement); $classname = ucfirst($subelement); - - if ($objecttype == 'order') { - $classfile = 'commande'; $classname = 'Commande'; - } - else if ($objecttype == 'invoice_supplier') { - $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur'; - } - else if ($objecttype == 'order_supplier') { - $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur'; - } - else if ($objecttype == 'supplier_proposal') { - $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; - } - else if ($objecttype == 'facturerec') { - $classfile = 'facture-rec'; $classname = 'FactureRec'; - } - else if ($objecttype == 'subscription') { - $classfile = 'subscription'; $classname = 'Subscription'; - } - - // Here $module, $classfile and $classname are set - if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) - { - dol_include_once('/'.$classpath.'/'.$classfile.'.class.php'); - //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname); - if (class_exists($classname)) - { - foreach($objectids as $i => $objectid) // $i is rowid into llx_element_element - { - $object = new $classname($this->db); - $ret = $object->fetch($objectid); - if ($ret >= 0) - { - $this->linkedObjects[$objecttype][$i] = $object; - } - } - } - } - } - } - } - else - { - dol_print_error($this->db); - } - } - - /** - * Update object linked of a current object - * - * @param int $sourceid Object source id - * @param string $sourcetype Object source type - * @param int $targetid Object target id - * @param string $targettype Object target type - * @return int >0 if OK, <0 if KO - * @see add_object_linked, fetObjectLinked, deleteObjectLinked - */ - function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='') - { - $updatesource=false; - $updatetarget=false; - - if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource=true; - else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $updatetarget=true; - - $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET "; - if ($updatesource) - { - $sql.= "fk_source = ".$sourceid; - $sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'"; - $sql.= " WHERE fk_target = ".$this->id; - $sql.= " AND targettype = '".$this->db->escape($this->element)."'"; - } - else if ($updatetarget) - { - $sql.= "fk_target = ".$targetid; - $sql.= ", targettype = '".$this->db->escape($targettype)."'"; - $sql.= " WHERE fk_source = ".$this->id; - $sql.= " AND sourcetype = '".$this->db->escape($this->element)."'"; - } - - dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG); - if ($this->db->query($sql)) - { - return 1; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } - - /** - * Delete all links between an object $this - * - * @param int $sourceid Object source id - * @param string $sourcetype Object source type - * @param int $targetid Object target id - * @param string $targettype Object target type - * @param int $rowid Row id of line to delete. If defined, other parameters are not used. - * @return int >0 if OK, <0 if KO - * @see add_object_linked, updateObjectLinked, fetchObjectLinked - */ - function deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='') - { - $deletesource=false; - $deletetarget=false; - - if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource=true; - else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $deletetarget=true; - - $sourceid = (! empty($sourceid) ? $sourceid : $this->id); - $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element); - $targetid = (! empty($targetid) ? $targetid : $this->id); - $targettype = (! empty($targettype) ? $targettype : $this->element); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element"; - $sql.= " WHERE"; - if ($rowid > 0) - { - $sql.=" rowid = ".$rowid; - } - else - { - if ($deletesource) - { - $sql.= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'"; - $sql.= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'"; - } - else if ($deletetarget) - { - $sql.= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'"; - $sql.= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'"; - } - else - { - $sql.= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')"; - $sql.= " OR"; - $sql.= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')"; - } - } - - dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG); - if ($this->db->query($sql)) - { - return 1; - } - else - { - $this->error=$this->db->lasterror(); - $this->errors[]=$this->error; - return -1; - } - } - - /** - * Set status of an object - * - * @param int $status Status to set - * @param int $elementId Id of element to force (use this->id by default) - * @param string $elementType Type of element to force (use this->table_element by default) - * @return int <0 if KO, >0 if OK - */ - function setStatut($status,$elementId=null,$elementType='') - { - global $user,$langs,$conf; - - $savElementId=$elementId; // To be used later to know if we were using the method using the id of this or not. - - $elementId = (!empty($elementId)?$elementId:$this->id); - $elementTable = (!empty($elementType)?$elementType:$this->table_element); - - $this->db->begin(); - - $fieldstatus="fk_statut"; - if ($elementTable == 'mailing') $fieldstatus="statut"; - if ($elementTable == 'user') $fieldstatus="statut"; - if ($elementTable == 'expensereport') $fieldstatus="fk_statut"; - if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus="status"; - - $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable; - $sql.= " SET ".$fieldstatus." = ".$status; - // If status = 1 = validated, update also fk_user_valid - if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id; - $sql.= " WHERE rowid=".$elementId; - - dol_syslog(get_class($this)."::setStatut", LOG_DEBUG); - if ($this->db->query($sql)) - { - $error = 0; - - $trigkey=''; - if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class - if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class - if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class - if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE'; - if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED'; - if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED'; - - if ($trigkey) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers($trigkey,$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers - } - - if (! $error) - { - $this->db->commit(); - - if (empty($savElementId)) // If the element we update was $this (so $elementId is null) - { - $this->statut = $status; - $this->status = $status; - } - - return 1; - } - else - { - $this->db->rollback(); - dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR); - return -1; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } - - - /** - * Load type of canvas of an object if it exists - * - * @param int $id Record id - * @param string $ref Record ref - * @return int <0 if KO, 0 if nothing done, >0 if OK - */ - function getCanvas($id=0,$ref='') - { - global $conf; - - if (empty($id) && empty($ref)) return 0; - if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default. - - // Clean parameters - $ref = trim($ref); - - $sql = "SELECT rowid, canvas"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " WHERE entity IN (".getEntity($this->element).")"; - if (! empty($id)) $sql.= " AND rowid = ".$id; - if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'"; - - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj) - { - $this->canvas = $obj->canvas; - return 1; - } - else return 0; - } - else - { - dol_print_error($this->db); - return -1; - } - } - - - /** - * Get special code of a line - * - * @param int $lineid Id of line - * @return int Special code - */ - function getSpecialCode($lineid) - { - $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE rowid = '.$lineid; - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } - - /** - * Function to check if an object is used by others. - * Check is done into this->childtables. There is no check into llx_element_element. - * - * @param int $id Force id of object - * @return int <0 if KO, 0 if not used, >0 if already used - */ - function isObjectUsed($id=0) - { - global $langs; - - if (empty($id)) $id=$this->id; - - // Check parameters - if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0) - { - dol_print_error('Called isObjectUsed on a class with property this->childtables not defined'); - return -1; - } - - $arraytoscan = $this->childtables; - // For backward compatibility, we check if array is old format array('table1', 'table2', ...) - $tmparray=array_keys($this->childtables); - if (is_numeric($tmparray[0])) - { - $arraytoscan = array_flip($this->childtables); - } - - // Test if child exists - $haschild=0; - foreach($arraytoscan as $table => $elementname) - { - //print $id.'-'.$table.'-'.$elementname.'
'; - // Check if third party can be deleted - $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE ".$this->fk_element." = ".$id; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - if ($obj->nb > 0) - { - $langs->load("errors"); - //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild; - $haschild += $obj->nb; - $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname)); - break; // We found at least one, we stop here - } - } - else - { - $this->errors[]=$this->db->lasterror(); - return -1; - } - } - if ($haschild > 0) - { - $this->errors[]="ErrorRecordHasChildren"; - return $haschild; - } - else return 0; - } - - /** - * Function to say how many lines object contains - * - * @param int $predefined -1=All, 0=Count free product/service only, 1=Count predefined product/service only, 2=Count predefined product, 3=Count predefined service - * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found - */ - function hasProductsOrServices($predefined=-1) - { - $nb=0; - - foreach($this->lines as $key => $val) - { - $qualified=0; - if ($predefined == -1) $qualified=1; - if ($predefined == 1 && $val->fk_product > 0) $qualified=1; - if ($predefined == 0 && $val->fk_product <= 0) $qualified=1; - if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1; - if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1; - if ($qualified) $nb++; - } - dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies'); - return $nb; - } - - /** - * Function that returns the total amount HT of discounts applied for all lines. - * - * @return float - */ - function getTotalDiscount() - { - $total_discount=0.00; - - $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det"; - $sql.= " WHERE ".$this->fk_element." = ".$this->id; - - dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - $pu_ht = $obj->pu_ht; - $qty= $obj->qty; - $total_ht = $obj->total_ht; - - $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT')); - $total_discount += $total_discount_line; - - $i++; - } - } - - //print $total_discount; exit; - return price2num($total_discount); - } - - - /** - * Return into unit=0, the calculated total of weight and volume of all lines * qty - * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line. - * - * @return array array('weight'=>...,'volume'=>...) - */ - function getTotalWeightVolume() - { - $totalWeight = 0; - $totalVolume = 0; - // defined for shipment only - $totalOrdered = ''; - // defined for shipment only - $totalToShip = ''; - - foreach ($this->lines as $line) - { - if (isset($line->qty_asked)) - { - if (empty($totalOrdered)) $totalOrdered=0; // Avoid warning because $totalOrdered is '' - $totalOrdered+=$line->qty_asked; // defined for shipment only - } - if (isset($line->qty_shipped)) - { - if (empty($totalToShip)) $totalToShip=0; // Avoid warning because $totalToShip is '' - $totalToShip+=$line->qty_shipped; // defined for shipment only - } - - // Define qty, weight, volume, weight_units, volume_units - if ($this->element == 'shipping') { - // for shipments - $qty = $line->qty_shipped ? $line->qty_shipped : 0; - } - else { - $qty = $line->qty ? $line->qty : 0; - } - - $weight = $line->weight ? $line->weight : 0; - $volume = $line->volume ? $line->volume : 0; - - $weight_units=$line->weight_units; - $volume_units=$line->volume_units; - - $weightUnit=0; - $volumeUnit=0; - if (! empty($weight_units)) $weightUnit = $weight_units; - if (! empty($volume_units)) $volumeUnit = $volume_units; - - if (empty($totalWeight)) $totalWeight=0; // Avoid warning because $totalWeight is '' - if (empty($totalVolume)) $totalVolume=0; // Avoid warning because $totalVolume is '' - - //var_dump($line->volume_units); - if ($weight_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) - { - $trueWeightUnit=pow(10, $weightUnit); - $totalWeight += $weight * $qty * $trueWeightUnit; - } - else { - if ($weight_units == 99) { - // conversion 1 Pound = 0.45359237 KG - $trueWeightUnit = 0.45359237; - $totalWeight += $weight * $qty * $trueWeightUnit; - } elseif ($weight_units == 98) { - // conversion 1 Ounce = 0.0283495 KG - $trueWeightUnit = 0.0283495; - $totalWeight += $weight * $qty * $trueWeightUnit; - } - else - $totalWeight += $weight * $qty; // This may be wrong if we mix different units - } - if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) - { - //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit; - $trueVolumeUnit=pow(10, $volumeUnit); - //print $line->volume; - $totalVolume += $volume * $qty * $trueVolumeUnit; - } - else - { - $totalVolume += $volume * $qty; // This may be wrong if we mix different units - } - } - - return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip); - } - - - /** - * Set extra parameters - * - * @return int <0 if KO, >0 if OK - */ - function setExtraParameters() - { - $this->db->begin(); - - $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null); - - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null"); - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - - - /** - * Return incoterms informations - * TODO Use a cache for label get - * - * @return string incoterms info - */ - function display_incoterms() - { - $out = ''; - $this->libelle_incoterms = ''; - if (!empty($this->fk_incoterms)) - { - $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; - $result = $this->db->query($sql); - if ($result) - { - $res = $this->db->fetch_object($result); - $out .= $res->code; - } - } - - $out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms; - - return $out; - } - - /** - * Return incoterms informations for pdf display - * - * @return string incoterms info - */ - function getIncotermsForPDF() - { - $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num > 0) - { - $res = $this->db->fetch_object($resql); - return 'Incoterm : '.$res->code.' - '.$this->location_incoterms; - } - else - { - return ''; - } - } - else - { - $this->errors[] = $this->db->lasterror(); - return false; - } - } - - /** - * Define incoterms values of current object - * - * @param int $id_incoterm Id of incoterm to set or '' to remove - * @param string $location location of incoterm - * @return int <0 if KO, >0 if OK - */ - function setIncoterms($id_incoterm, $location) - { - if ($this->id && $this->table_element) - { - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null"); - $sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null"); - $sql.= " WHERE rowid = " . $this->id; - dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->fk_incoterms = $id_incoterm; - $this->location_incoterms = $location; - - $sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; - $res = $this->db->query($sql); - if ($res) - { - $obj = $this->db->fetch_object($res); - $this->libelle_incoterms = $obj->libelle; - } - return 1; - } - else - { - $this->errors[] = $this->db->lasterror(); - return -1; - } - } - else return -1; - } - - - /** - * Return if a country is inside the EEC (European Economic Community) - * @deprecated - * - * @return boolean true = country inside EEC, false = country outside EEC - */ - function isInEEC() - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - return isInEEC($this); - } - - - // -------------------- - // TODO: All functions here must be redesigned and moved as they are not business functions but output functions - // -------------------- - - /* This is to show add lines */ - - /** - * Show add free and predefined products/services form - * - * @param int $dateSelector 1=Show also date range input fields - * @param Societe $seller Object thirdparty who sell - * @param Societe $buyer Object thirdparty who buy - * @return void - */ - function formAddObjectLine($dateSelector,$seller,$buyer) - { - global $conf,$user,$langs,$object,$hookmanager; - global $form,$bcnd,$var; - - //Line extrafield - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafieldsline = new ExtraFields($this->db); - $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line); - - // Output template part (modules that overwrite templates must declare this into descriptor) - // Use global variables + $dateSelector + $seller and $buyer - $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); - foreach($dirtpls as $reldir) - { - $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php'); - if (empty($conf->file->strict_mode)) { - $res=@include $tpl; - } else { - $res=include $tpl; // for debug - } - if ($res) break; - } - } - - - - /* This is to show array of line of details */ - - - /** - * Return HTML table for object lines - * TODO Move this into an output class file (htmlline.class.php) - * If lines are into a template, title must also be into a template - * But for the moment we don't know if it'st possible as we keep a method available on overloaded objects. - * - * @param string $action Action code - * @param string $seller Object of seller third party - * @param string $buyer Object of buyer third party - * @param int $selected Object line selected - * @param int $dateSelector 1=Show also date range input fields - * @return void - */ - function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0) - { - global $conf, $hookmanager, $langs, $user; - // TODO We should not use global var for this ! - global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax; - - // Define usemargins - $usemargins=0; - if (! empty($conf->margin->enabled) && ! empty($this->element) && in_array($this->element,array('facture','propal','commande'))) $usemargins=1; - - $num = count($this->lines); - - //Line extrafield - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafieldsline = new ExtraFields($this->db); - $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line); - - $parameters = array('num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline); - $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - print ''; - - if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ' '; - - // Description - print ''.$langs->trans('Description').''; - - if ($this->element == 'supplier_proposal' || $this->element == 'order_supplier' || $this->element == 'invoice_supplier') - { - print ''.$langs->trans("SupplierRef").''; - } - - // VAT - print ''.$langs->trans('VAT').''; - - // Price HT - print ''.$langs->trans('PriceUHT').''; - - // Multicurrency - if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''; - - if ($inputalsopricewithtax) print ''.$langs->trans('PriceUTTC').''; - - // Qty - print ''.$langs->trans('Qty').''; - - if($conf->global->PRODUCT_USE_UNITS) - { - print ''.$langs->trans('Unit').''; - } - - // Reduction short - print ''.$langs->trans('ReductionShort').''; - - if ($this->situation_cycle_ref) { - print '' . $langs->trans('Progress') . ''; - } - - if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id)) - { - if (!empty($user->rights->margins->creer)) - { - if ($conf->global->MARGIN_TYPE == "1") - print ''.$langs->trans('BuyingPrice').''; - else - print ''.$langs->trans('CostPrice').''; - } - - if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) - print ''.$langs->trans('MarginRate').''; - if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) - print ''.$langs->trans('MarkRate').''; - } - - // Total HT - print ''.$langs->trans('TotalHTShort').''; - - // Multicurrency - if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''; - - if ($outputalsopricetotalwithtax) print ''.$langs->trans('TotalTTCShort').''; - - print ''; // No width to allow autodim - - print ''; - - print ''; - - print "\n"; - } - - $var = true; - $i = 0; - - foreach ($this->lines as $line) - { - //Line extrafield - $line->fetch_optionals($line->id,$extralabelslines); - - - - //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) - if (is_object($hookmanager)) // Old code is commented on preceding line. - { - if (empty($line->fk_parent_line)) - { - $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline); - $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - } - else - { - $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline, 'fk_parent_line'=>$line->fk_parent_line); - $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - } - } - if (empty($reshook)) - { - $this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline); - } - - $i++; - } - } - - /** - * Return HTML content of a detail line - * TODO Move this into an output class file (htmlline.class.php) - * - * @param string $action GET/POST action - * @param CommonObjectLine $line Selected object line to output - * @param string $var Is it a an odd line (true) - * @param int $num Number of line (0) - * @param int $i I - * @param int $dateSelector 1=Show also date range input fields - * @param string $seller Object of seller third party - * @param string $buyer Object of buyer third party - * @param int $selected Object line selected - * @param int $extrafieldsline Object of extrafield line attribute - * @return void - */ - function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0) - { - global $conf,$langs,$user,$object,$hookmanager; - global $form,$bc,$bcdd; - global $object_rights, $disableedit, $disablemove; // TODO We should not use global var for this ! - - $object_rights = $this->getRights(); - - $element=$this->element; - - $text=''; $description=''; $type=0; - - // Show product and description - $type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type); - // Try to enhance type detection using date_start and date_end for free lines where type was not saved. - if (! empty($line->date_start)) $type=1; // deprecated - if (! empty($line->date_end)) $type=1; // deprecated - - // Ligne en mode visu - if ($action != 'editline' || $selected != $line->id) - { - // Product - if ($line->fk_product > 0) - { - $product_static = new Product($this->db); - $product_static->fetch($line->fk_product); - - $product_static->ref = $line->ref; //can change ref in hook - $product_static->label = $line->label; //can change label in hook - $text=$product_static->getNomUrl(1); - - // Define output language and label - if (! empty($conf->global->MAIN_MULTILANGS)) - { - if (! is_object($this->thirdparty)) - { - dol_print_error('','Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before'); - return; - } - - $prod = new Product($this->db); - $prod->fetch($line->fk_product); - - $outputlangs = $langs; - $newlang=''; - if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09'); - if (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) $newlang=$this->thirdparty->default_lang; // For language to language of customer - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); - } - - $label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label; - } - else - { - $label = $line->product_label; - } - - $text.= ' - '.(! empty($line->label)?$line->label:$label); - $description.=(! empty($conf->global->PRODUIT_DESC_IN_FORM)?'':dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc. - } - - $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU'); - - // Output template part (modules that overwrite templates must declare this into descriptor) - // Use global variables + $dateSelector + $seller and $buyer - $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); - foreach($dirtpls as $reldir) - { - $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php'); - if (empty($conf->file->strict_mode)) { - $res=@include $tpl; - } else { - $res=include $tpl; // for debug - } - if ($res) break; - } - } - - // Ligne en mode update - if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) - { - $label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : '')); - $placeholder=' placeholder="'.$langs->trans("Label").'"'; - - $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU'); - - // Output template part (modules that overwrite templates must declare this into descriptor) - // Use global variables + $dateSelector + $seller and $buyer - $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); - foreach($dirtpls as $reldir) - { - $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php'); - if (empty($conf->file->strict_mode)) { - $res=@include $tpl; - } else { - $res=include $tpl; // for debug - } - if ($res) break; - } - } - } - - - /* This is to show array of line of details of source object */ - - - /** - * Return HTML table table of source object lines - * TODO Move this and previous function into output html class file (htmlline.class.php). - * If lines are into a template, title must also be into a template - * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects. - * - * @param string $restrictlist ''=All lines, 'services'=Restrict to services only - * @return void - */ - function printOriginLinesList($restrictlist='') - { - global $langs, $hookmanager, $conf; - - print ''; - print ''.$langs->trans('Ref').''; - print ''.$langs->trans('Description').''; - print ''.$langs->trans('VATRate').''; - print ''.$langs->trans('PriceUHT').''; - if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency').''; - print ''.$langs->trans('Qty').''; - if($conf->global->PRODUCT_USE_UNITS) - { - print ''.$langs->trans('Unit').''; - } - print ''.$langs->trans('ReductionShort').''; - - $var = true; - $i = 0; - - foreach ($this->lines as $line) - { - if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) - { - if (empty($line->fk_parent_line)) - { - $parameters=array('line'=>$line,'var'=>$var,'i'=>$i); - $action=''; - $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - } - } - else - { - $this->printOriginLine($line, $var, $restrictlist); - } - - $i++; - } - } - - /** - * Return HTML with a line of table array of source object lines - * TODO Move this and previous function into output html class file (htmlline.class.php). - * If lines are into a template, title must also be into a template - * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. - * - * @param CommonObjectLine $line Line - * @param string $var Var - * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not) - * @return void - */ - function printOriginLine($line, $var, $restrictlist='') - { - global $langs, $conf; - - //var_dump($line); - if (!empty($line->date_start)) - { - $date_start=$line->date_start; - } - else - { - $date_start=$line->date_debut_prevue; - if ($line->date_debut_reel) $date_start=$line->date_debut_reel; - } - if (!empty($line->date_end)) - { - $date_end=$line->date_end; - } - else - { - $date_end=$line->date_fin_prevue; - if ($line->date_fin_reel) $date_end=$line->date_fin_reel; - } - - $this->tpl['label'] = ''; - if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow'); - - if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object - { - $discount=new DiscountAbsolute($this->db); - $discount->fk_soc = $this->socid; - $this->tpl['label'].= $discount->getNomUrl(0,'discount'); - } - else if (! empty($line->fk_product)) - { - $productstatic = new Product($this->db); - $productstatic->id = $line->fk_product; - $productstatic->ref = $line->ref; - $productstatic->type = $line->fk_product_type; - $this->tpl['label'].= $productstatic->getNomUrl(1); - $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label); - // Dates - if ($line->product_type == 1 && ($date_start || $date_end)) - { - $this->tpl['label'].= get_date_range($date_start,$date_end); - } - } - else - { - $this->tpl['label'].= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product'))); - if (!empty($line->desc)) { - $this->tpl['label'].=$line->desc; - }else { - $this->tpl['label'].= ($line->label ? ' '.$line->label : ''); - } - // Dates - if ($line->product_type == 1 && ($date_start || $date_end)) - { - $this->tpl['label'].= get_date_range($date_start,$date_end); - } - } - - if (! empty($line->desc)) - { - if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object - { - $discount=new DiscountAbsolute($this->db); - $discount->fetch($line->fk_remise_except); - $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0)); - } - elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object - { - $discount=new DiscountAbsolute($this->db); - $discount->fetch($line->fk_remise_except); - $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); - } - elseif ($line->desc == '(EXCESS RECEIVED)') - { - $discount=new DiscountAbsolute($this->db); - $discount->fetch($line->fk_remise_except); - $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } - else - { - $this->tpl['description'] = dol_trunc($line->desc,60); - } - } - else - { - $this->tpl['description'] = ' '; - } - - // VAT Rate - $this->tpl['vat_rate'] = vatrate($line->tva_tx, true); - $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : ''; - if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')'; - - $this->tpl['price'] = price($line->subprice); - $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice); - $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' '; - if ($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long')); - $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' '; - - // Is the line strike or not - $this->tpl['strike']=0; - if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1; - - // Output template part (modules that overwrite templates must declare this into descriptor) - // Use global variables + $dateSelector + $seller and $buyer - $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); - foreach($dirtpls as $reldir) - { - $tpl = dol_buildpath($reldir.'/originproductline.tpl.php'); - if (empty($conf->file->strict_mode)) { - $res=@include $tpl; - } else { - $res=include $tpl; // for debug - } - if ($res) break; - } - } - - - /** - * Add resources to the current object : add entry into llx_element_resources - * Need $this->element & $this->id - * - * @param int $resource_id Resource id - * @param string $resource_type 'resource' - * @param int $busy Busy or not - * @param int $mandatory Mandatory or not - * @return int <=0 if KO, >0 if OK - */ - function add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0) - { - $this->db->begin(); - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources ("; - $sql.= "resource_id"; - $sql.= ", resource_type"; - $sql.= ", element_id"; - $sql.= ", element_type"; - $sql.= ", busy"; - $sql.= ", mandatory"; - $sql.= ") VALUES ("; - $sql.= $resource_id; - $sql.= ", '".$this->db->escape($resource_type)."'"; - $sql.= ", '".$this->db->escape($this->id)."'"; - $sql.= ", '".$this->db->escape($this->element)."'"; - $sql.= ", '".$this->db->escape($busy)."'"; - $sql.= ", '".$this->db->escape($mandatory)."'"; - $sql.= ")"; - - dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return 0; - } - } - - /** - * Delete a link to resource line - * - * @param int $rowid Id of resource line to delete - * @param int $element element name (for trigger) TODO: use $this->element into commonobject class - * @param int $notrigger Disable all triggers - * @return int >0 if OK, <0 if KO - */ - function delete_resource($rowid, $element, $notrigger=0) - { - global $user; - - $this->db->begin(); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; - $sql.= " WHERE rowid=".$rowid; - - dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG); - - $resql=$this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - if (! $notrigger) - { - $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); - if ($result < 0) { $this->db->rollback(); return -1; } - } - $this->db->commit(); - return 1; - } - } - - - /** - * Overwrite magic function to solve problem of cloning object that are kept as references - * - * @return void - */ - function __clone() - { - // Force a copy of this->lines, otherwise it will point to same object. - if (isset($this->lines) && is_array($this->lines)) - { - $nboflines=count($this->lines); - for($i=0; $i < $nboflines; $i++) - { - $this->lines[$i] = clone $this->lines[$i]; - } - } - } - - /** - * Common function for all objects extending CommonObject for generating documents - * - * @param string $modelspath Relative folder where generators are placed - * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example. - * @param Translate $outputlangs Output language to use - * @param int $hidedetails 1 to hide details. 0 by default - * @param int $hidedesc 1 to hide product description. 0 by default - * @param int $hideref 1 to hide product reference. 0 by default - * @param null|array $moreparams Array to provide more information - * @return int >0 if OK, <0 if KO - */ - protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null) - { - global $conf, $langs, $user; - - $srctemplatepath=''; - - // Increase limit for PDF build - $err=error_reporting(); - error_reporting(0); - @set_time_limit(120); - error_reporting($err); - - // If selected model is a filename template (then $modele="modelname" or "modelname:filename") - $tmp=explode(':',$modele,2); - if (! empty($tmp[1])) - { - $modele=$tmp[0]; - $srctemplatepath=$tmp[1]; - } - - // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array('/'); - if (is_array($conf->modules_parts['models'])) $dirmodels=array_merge($dirmodels,$conf->modules_parts['models']); - foreach($dirmodels as $reldir) - { - foreach(array('doc','pdf') as $prefix) - { - if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php - else $file = $prefix."_".$modele.".modules.php"; - - // On verifie l'emplacement du modele - $file=dol_buildpath($reldir.$modelspath.$file,0); - if (file_exists($file)) - { - $filefound=1; - $classname=$prefix.'_'.$modele; - break; - } - } - if ($filefound) break; - } - - // If generator was found - if ($filefound) - { - global $db; // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db - - require_once $file; - - $obj = new $classname($this->db); - - // If generator is ODT, we must have srctemplatepath defined, if not we set it. - if ($obj->type == 'odt' && empty($srctemplatepath)) - { - $varfortemplatedir=$obj->scandir; - if ($varfortemplatedir && ! empty($conf->global->$varfortemplatedir)) - { - $dirtoscan=$conf->global->$varfortemplatedir; - - $listoffiles=array(); - - // Now we add first model found in directories scanned - $listofdir=explode(',',$dirtoscan); - foreach($listofdir as $key => $tmpdir) - { - $tmpdir=trim($tmpdir); - $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir); - if (! $tmpdir) { unset($listofdir[$key]); continue; } - if (is_dir($tmpdir)) - { - $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0); - if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles); - } - } - - if (count($listoffiles)) - { - foreach($listoffiles as $record) - { - $srctemplatepath=$record['fullname']; - break; - } - } - } - - if (empty($srctemplatepath)) - { - $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined'; - return -1; - } - } - - if ($obj->type == 'odt' && ! empty($srctemplatepath)) - { - if (! dol_is_file($srctemplatepath)) - { - $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; - return -1; - } - } - - // We save charset_output to restore it because write_file can change it if needed for - // output format that does not support UTF8. - $sav_charset_output=$outputlangs->charset_output; - - if (in_array(get_class($this), array('Adherent'))) - { - $arrayofrecords = array(); // The write_file of templates of adherent class need this var - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); - } - else - { - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); - } - // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index. - - if ($resultwritefile > 0) - { - $outputlangs->charset_output=$sav_charset_output; - - // We delete old preview - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - dol_delete_preview($this); - - // Index file in database - if (! empty($obj->result['fullpath'])) - { - $destfull = $obj->result['fullpath']; - $upload_dir = dirname($destfull); - $destfile = basename($destfull); - $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir); - - if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir - { - $filename = basename($destfile); - $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); - $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - - include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile=new EcmFiles($this->db); - $result = $ecmfile->fetch(0, '', ($rel_dir?$rel_dir.'/':'').$filename); - - // Set the public "share" key - $setsharekey = false; - if ($this->element == 'propal') - { - $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok - if ($useonlinesignature) $setsharekey=true; - if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; - } - if ($this->element == 'commande' && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; - if ($this->element == 'facture' && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; - if ($setsharekey) - { - if (empty($ecmfile->share)) // Because object not found or share not set yet - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $ecmfile->share = getRandomPassword(true); - } - } - - if ($result > 0) - { - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content - $ecmfile->fullpath_orig = ''; - $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $result = $ecmfile->update($user); - if ($result < 0) - { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } - else - { - $ecmfile->entity = $conf->entity; - $ecmfile->filepath = $rel_dir; - $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content - $ecmfile->fullpath_orig = ''; - $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $result = $ecmfile->create($user); - if ($result < 0) - { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } - - /*$this->result['fullname']=$destfull; - $this->result['filepath']=$ecmfile->filepath; - $this->result['filename']=$ecmfile->filename;*/ - //var_dump($obj->update_main_doc_field);exit; - - // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set) - $update_main_doc_field=0; - if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1; - if ($update_main_doc_field && ! empty($this->table_element)) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'"; - $sql.= ' WHERE rowid = '.$this->id; - $resql = $this->db->query($sql); - if (! $resql) dol_print_error($this->db); - } - } - } - else - { - dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING); - } - - // Success in building document. We build meta file. - dol_meta_create($this); - - return 1; - } - else - { - $outputlangs->charset_output=$sav_charset_output; - dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors); - return -1; - } - - } - else - { - $this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file); - dol_print_error('',$this->error); - return -1; - } - } - - /** - * Build thumb - * - * @param string $file Path file in UTF8 to original file to create thumbs from. - * @return void - */ - function addThumbs($file) - { - global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality; - - require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ... - - $file_osencoded=dol_osencode($file); - if (file_exists($file_osencoded)) - { - // Create small thumbs for company (Ratio is near 16/9) - // Used on logon for example - vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality); - - // Create mini thumbs for company (Ratio is near 16/9) - // Used on menu or for setup page for example - vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality); - } - } - - - /* Functions common to commonobject and commonobjectline */ - - /* For default values */ - - /** - * Return the default value to use for a field when showing the create form of object. - * Return values in this order: - * 1) If parameter is available into POST, we return it first. - * 2) If not but an alternate value was provided as parameter of function, we return it. - * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table). - * 4) Return value found into database (TODO No yet implemented) - * - * @param string $fieldname Name of field - * @param string $alternatevalue Alternate value to use - * @return string|string[] Default value (can be an array if the GETPOST return an array) - **/ - function getDefaultCreateValueFor($fieldname, $alternatevalue=null) - { - global $conf, $_POST; - - // If param here has been posted, we use this value first. - if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2); - - if (isset($alternatevalue)) return $alternatevalue; - - $newelement=$this->element; - if ($newelement == 'facture') $newelement='invoice'; - if ($newelement == 'commande') $newelement='order'; - if (empty($newelement)) - { - dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING); - return ''; - } - - $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname); - //var_dump($keyforfieldname); - if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname; - - // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname - - } - - - /* For triggers */ - - - /** - * Call trigger based on this instance. - * Some context information may also be provided into array property this->context. - * NB: Error from trigger are stacked in interface->errors - * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction. - * - * @param string $trigger_name trigger's name to execute - * @param User $user Object user - * @return int Result of run_triggers - */ - function call_trigger($trigger_name, $user) - { - global $langs,$conf; - - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf); - - if ($result < 0) - { - if (!empty($this->errors)) - { - $this->errors=array_unique(array_merge($this->errors,$interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice. - } - else - { - $this->errors=$interface->errors; - } - } - return $result; - } - - - /* Functions for extrafields */ - - - /** - * Function to get extra fields of an object into $this->array_options - * This method is in most cases called by method fetch of objects but you can call it separately. - * - * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters. - * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters. - * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded - */ - function fetch_optionals($rowid=null, $optionsArray=null) - { - if (empty($rowid)) $rowid=$this->id; - - // To avoid SQL errors. Probably not the better solution though - if (!$this->table_element) { - return 0; - } - - if (! is_array($optionsArray)) - { - // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page. - // TODO Use of existing extrafield is not yet ready (must mutualize code that use extrafields in form first) - // global $extrafields; - //if (! is_object($extrafields)) - //{ - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - //} - - // Load array of extrafields for elementype = $this->table_element - if (empty($extrafields->attributes[$this->table_element]['loaded'])) - { - $extrafields->fetch_name_optionals_label($this->table_element); - } - $optionsArray = $extrafields->attributes[$this->table_element]['label']; - } - - $table_element = $this->table_element; - if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility - - // Request to get complementary values - if (is_array($optionsArray) && count($optionsArray) > 0) - { - $sql = "SELECT rowid"; - foreach ($optionsArray as $name => $label) - { - if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') - { - $sql.= ", ".$name; - } - } - $sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; - $sql.= " WHERE fk_object = ".$rowid; - - dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $numrows=$this->db->num_rows($resql); - if ($numrows) - { - $tab = $this->db->fetch_array($resql); - - foreach ($tab as $key => $value) - { - // Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine) - if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key)) - { - // we can add this attribute to object - $this->array_options["options_".$key]=$value; - } - } - } - - $this->db->free($resql); - - if ($numrows) return $numrows; - else return 0; - } - else - { - dol_print_error($this->db); - return -1; - } - } - return 0; - } - - /** - * Delete all extra fields values for the current object. - * - * @return int <0 if KO, >0 if OK - */ - function deleteExtraFields() - { - $this->db->begin(); - - $table_element = $this->table_element; - if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility - - $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id; - dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG); - $resql=$this->db->query($sql_del); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - - /** - * Add/Update all extra fields values for the current object. - * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) - * This function delete record with all extrafields and insert them again from the array $this->array_options. - * - * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY) - * @param User $userused Object user - * @return int -1=error, O=did nothing, 1=OK - * @see updateExtraField, setValueFrom - */ - function insertExtraFields($trigger='', $userused=null) - { - global $conf,$langs,$user; - - if (empty($userused)) $userused=$user; - - $error=0; - - if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used - - if (! empty($this->array_options)) - { - // Check parameters - $langs->load('admin'); - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); - - //Eliminate copied source object extra_fields that do not exist in target object - $new_array_options=array(); - foreach ($this->array_options as $key => $value) { - if (in_array(substr($key,8), array_keys($target_extrafields))) // We remove the 'options_' from $key for test - $new_array_options[$key] = $value; - elseif (in_array($key, array_keys($target_extrafields))) // We test on $key that does not contains the 'options_' prefix - $new_array_options['options_'.$key] = $value; - } - - foreach($new_array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - $attributeType = $extrafields->attribute_type[$attributeKey]; - $attributeLabel = $extrafields->attribute_label[$attributeKey]; - $attributeParam = $extrafields->attribute_param[$attributeKey]; - $attributeRequired = $extrafields->attribute_required[$attributeKey]; - - if ($attributeRequired) - { - $mandatorypb=false; - if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true; - if ($this->array_options[$key] === '') $mandatorypb=true; - if ($mandatorypb) - { - $this->errors[]=$langs->trans('ErrorFieldRequired', $attributeLabel); - return -1; - } - } - - switch ($attributeType) - { - case 'int': - if (!is_numeric($value) && $value!='') - { - $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel); - return -1; - } - elseif ($value=='') - { - $new_array_options[$key] = null; - } - break; - /*case 'select': // Not required, we chosed value='0' for undefined values - if ($value=='-1') - { - $this->array_options[$key] = null; - } - break;*/ - case 'price': - $new_array_options[$key] = price2num($this->array_options[$key]); - break; - case 'date': - $new_array_options[$key] = $this->db->idate($this->array_options[$key]); - break; - case 'datetime': - $new_array_options[$key] = $this->db->idate($this->array_options[$key]); - break; - case 'link': - $param_list=array_keys($attributeParam['options']); - // 0 : ObjectName - // 1 : classPath - $InfoFieldList = explode(":", $param_list[0]); - dol_include_once($InfoFieldList[1]); - if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) - { - if ($value == '-1') // -1 is key for no defined in combo list of objects - { - $new_array_options[$key]=''; - } - elseif ($value) - { - $object = new $InfoFieldList[0]($this->db); - if (is_numeric($value)) $res=$object->fetch($value); - else $res=$object->fetch('',$value); - - if ($res > 0) $new_array_options[$key]=$object->id; - else - { - $this->error="Id/Ref '".$value."' for object '".$object->element."' not found"; - $this->db->rollback(); - return -1; - } - } - } - else - { - dol_syslog('Error bad setup of extrafield', LOG_WARNING); - } - break; - } - } - - $this->db->begin(); - - $table_element = $this->table_element; - if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility - - $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id; - dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG); - $this->db->query($sql_del); - - $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object"; - foreach($new_array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - // Add field of attribut - if ($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate - $sql.=",".$attributeKey; - } - $sql .= ") VALUES (".$this->id; - - foreach($new_array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - // Add field o fattribut - if($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate) - { - if ($new_array_options[$key] != '') - { - $sql.=",'".$this->db->escape($new_array_options[$key])."'"; - } - else - { - $sql.=",null"; - } - } - } - $sql.=")"; - - dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $error++; - } - - if (! $error && $trigger) - { - // Call trigger - $this->context=array('extrafieldaddupdate'=>1); - $result=$this->call_trigger($trigger, $userused); - if ($result < 0) $error++; - // End call trigger - } - - if ($error) - { - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - else return 0; - } - - /** - * Update an exta field value for the current object. - * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) - * - * @param string $key Key of the extrafield - * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY) - * @param User $userused Object user - * @return int -1=error, O=did nothing, 1=OK - * @see setValueFrom - */ - function updateExtraField($key, $trigger, $userused) - { - global $conf,$langs,$user; - - if (empty($userused)) $userused=$user; - - $error=0; - - if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used - - if (! empty($this->array_options) && isset($this->array_options["options_".$key])) - { - // Check parameters - $langs->load('admin'); - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); - - $value=$this->array_options["options_".$key]; - $attributeType = $extrafields->attribute_type[$key]; - $attributeLabel = $extrafields->attribute_label[$key]; - $attributeParam = $extrafields->attribute_param[$key]; - switch ($attributeType) - { - case 'int': - if (!is_numeric($value) && $value!='') - { - $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); - return -1; - } - elseif ($value=='') - { - $this->array_options["options_".$key] = null; - } - break; - /*case 'select': // Not required, we chosed value='0' for undefined values - if ($value=='-1') - { - $this->array_options[$key] = null; - } - break;*/ - case 'price': - $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]); - break; - case 'date': - $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); - break; - case 'datetime': - $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); - break; - case 'link': - $param_list=array_keys($attributeParam ['options']); - // 0 : ObjectName - // 1 : classPath - $InfoFieldList = explode(":", $param_list[0]); - dol_include_once($InfoFieldList[1]); - if ($value) - { - $object = new $InfoFieldList[0]($this->db); - $object->fetch(0,$value); - $this->array_options["options_".$key]=$object->id; - } - break; - } - - $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'"; - $sql .= " WHERE fk_object = ".$this->id; - $resql = $this->db->query($sql); - if (! $resql) - { - $error++; - $this->error=$this->db->lasterror(); - } - - if (! $error && $trigger) - { - // Call trigger - $this->context=array('extrafieldupdate'=>1); - $result=$this->call_trigger($trigger, $userused); - if ($result < 0) $error++; - // End call trigger - } - - if ($error) - { - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - else return 0; - } - - - /** - * Return HTML string to put an input field into a page - * Code very similar with showInputField of extra fields - * - * @param array $val Array of properties for field to show - * @param string $key Key of attribute - * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) - * @param string $moreparam To add more parametes on html input tag - * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) - * @param string|int $showsize Value for css to define size. May also be a numeric. - * @return string - */ - function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0) - { - global $conf,$langs,$form; - - if (! is_object($form)) - { - require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - $form=new Form($this->db); - } - - $objectid = $this->id; - - $label= $val['label']; - $type = $val['type']; - $size = $val['css']; - - // Convert var to be able to share same code than showInputField of extrafields - if (preg_match('/varchar\((\d+)\)/', $type, $reg)) - { - $type = 'varchar'; // convert varchar(xx) int varchar - $size = $reg[1]; - } - elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar - if (is_array($val['arrayofkeyval'])) $type='select'; - if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link'; - - //$elementtype=$this->attribute_elementtype[$key]; // seems to not be used - $default=$val['default']; - $computed=$val['computed']; - $unique=$val['unique']; - $required=$val['required']; - $param=$val['param']; - if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval']; - if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) - { - $type='link'; - $param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]); - } - $langfile=$val['langfile']; - $list=$val['list']; - $hidden=(abs($val['visible'])!=1 ? 1 : 0); - $help=$val['help']; - - if ($computed) - { - if (! preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; - else return ''; - } - - // Use in priorit showsize from parameters, then $val['css'] then autodefine - if (empty($showsize) && ! empty($val['css'])) - { - $showsize = $val['css']; - } - if (empty($showsize)) - { - if ($type == 'date') - { - //$showsize=10; - $showsize = 'minwidth100imp'; - } - elseif ($type == 'datetime') - { - //$showsize=19; - $showsize = 'minwidth200imp'; - } - elseif (in_array($type,array('int','double','price'))) - { - //$showsize=10; - $showsize = 'maxwidth75'; - } - elseif ($type == 'url') - { - $showsize='minwidth400'; - } - elseif ($type == 'boolean') - { - $showsize=''; - } - else - { - if (round($size) < 12) - { - $showsize = 'minwidth100'; - } - else if (round($size) <= 48) - { - $showsize = 'minwidth200'; - } - else - { - //$showsize=48; - $showsize = 'minwidth400'; - } - } - } - //var_dump($showsize.' '.$size); - - if (in_array($type,array('date','datetime'))) - { - $tmp=explode(',',$size); - $newsize=$tmp[0]; - - $showtime = in_array($type,array('datetime')) ? 1 : 0; - - // Do not show current date when field not required (see select_date() method) - if (!$required && $value == '') $value = '-1'; - - // TODO Must also support $moreparam - $out = $form->select_date($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, ($keyprefix != 'search_' ? 1 : 0), 1, 0, 1); - } - elseif (in_array($type,array('int','integer'))) - { - $tmp=explode(',',$size); - $newsize=$tmp[0]; - $out=''; - } - elseif (preg_match('/varchar/', $type)) - { - $out=''; - } - elseif (in_array($type, array('mail', 'phone', 'url'))) - { - $out=''; - } - elseif ($type == 'text') - { - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,0,ROWS_5,'90%'); - $out=$doleditor->Create(1); - } - elseif ($type == 'html') - { - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%'); - $out=$doleditor->Create(1); - } - elseif ($type == 'boolean') - { - $checked=''; - if (!empty($value)) { - $checked=' checked value="1" '; - } else { - $checked=' value="1" '; - } - $out=''; - } - elseif ($type == 'price') - { - if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. - $value=price($value); - } - $out=' '.$langs->getCurrencySymbol($conf->currency); - } - elseif ($type == 'double') - { - if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. - $value=price($value); - } - $out=' '; - } - elseif ($type == 'select') - { - $out = ''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) - { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); - } - - $out.=''; - } - elseif ($type == 'sellist') - { - $out = ''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) - { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); - } - - $out.=''; - } - elseif ($type == 'checkbox') - { - $value_arr=explode(',',$value); - $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); - } - elseif ($type == 'radio') - { - $out=''; - foreach ($param['options'] as $keyopt => $val) - { - $out.=''.$val.'
'; - } - } - elseif ($type == 'chkbxlst') - { - if (is_array($value)) { - $value_arr = $value; - } - else { - $value_arr = explode(',', $value); - } - - if (is_array($param['options'])) { - $param_list = array_keys($param['options']); - $InfoFieldList = explode(":", $param_list[0]); - // 0 : tableName - // 1 : label field name - // 2 : key fields name (if differ of rowid) - // 3 : key field parent (for dependent lists) - // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value - $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid'); - - if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) { - list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]); - $keyList .= ', ' . $parentField; - } - if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) { - if (strpos($InfoFieldList[4], 'extra.') !== false) { - $keyList = 'main.' . $InfoFieldList[2] . ' as rowid'; - } else { - $keyList = $InfoFieldList[2] . ' as rowid'; - } - } - - $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($fields_label)) { - $keyList .= ', '; - $keyList .= implode(', ', $fields_label); - } - - $sqlwhere = ''; - $sql = 'SELECT ' . $keyList; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0]; - if (! empty($InfoFieldList[4])) { - - // can use SELECT request - if (strpos($InfoFieldList[4], '$SEL$')!==false) { - $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]); - } - - // current object id can be use into filter - if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) { - $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]); - } else { - $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]); - } - - // We have to join on extrafield table - if (strpos($InfoFieldList[4], 'extra') !== false) { - $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra'; - $sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4]; - } else { - $sqlwhere .= ' WHERE ' . $InfoFieldList[4]; - } - } else { - $sqlwhere .= ' WHERE 1=1'; - } - // Some tables may have field, some other not. For the moment we disable it. - if (in_array($InfoFieldList[0], array ('tablewithentity'))) - { - $sqlwhere .= ' AND entity = ' . $conf->entity; - } - // $sql.=preg_replace('/^ AND /','',$sqlwhere); - // print $sql; - - $sql .= $sqlwhere; - dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - $i = 0; - - $data=array(); - - while ( $i < $num ) { - $labeltoshow = ''; - $obj = $this->db->fetch_object($resql); - - // Several field into label (eq table:code|libelle:rowid) - $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($fields_label)) { - $notrans = true; - foreach ( $fields_label as $field_toshow ) { - $labeltoshow .= $obj->$field_toshow . ' '; - } - } else { - $labeltoshow = $obj->{$InfoFieldList[1]}; - } - $labeltoshow = dol_trunc($labeltoshow, 45); - - if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { - foreach ( $fields_label as $field_toshow ) { - $translabel = $langs->trans($obj->$field_toshow); - if ($translabel != $obj->$field_toshow) { - $labeltoshow = dol_trunc($translabel, 18) . ' '; - } else { - $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' '; - } - } - - $data[$obj->rowid]=$labeltoshow; - - } else { - if (! $notrans) { - $translabel = $langs->trans($obj->{$InfoFieldList[1]}); - if ($translabel != $obj->{$InfoFieldList[1]}) { - $labeltoshow = dol_trunc($translabel, 18); - } else { - $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18); - } - } - if (empty($labeltoshow)) - $labeltoshow = '(not defined)'; - - if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { - $data[$obj->rowid]=$labeltoshow; - } - - if (! empty($InfoFieldList[3])) { - $parent = $parentName . ':' . $obj->{$parentField}; - } - - $data[$obj->rowid]=$labeltoshow; - } - - $i ++; - } - $this->db->free($resql); - - $out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); - - } else { - print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.
'; - } - } - $out .= ''; - } - elseif ($type == 'link') - { - $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' - $showempty=(($val['notnull'] == 1 && $val['default'] != '')?0:1); - $out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty); - } - elseif ($type == 'password') - { - // If prefix is 'search_', field is used as a filter, we use a common text field. - $out=''; - } - if (!empty($hidden)) { - $out=''; - } - /* Add comments - if ($type == 'date') $out.=' (YYYY-MM-DD)'; - elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)'; - */ - return $out; - } - - - /** - * Return HTML string to show a field into a page - * Code very similar with showOutputField of extra fields - * - * @param array $val Array of properties of field to show - * @param string $key Key of attribute - * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) - * @param string $moreparam To add more parametes on html input tag - * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) - * @param mixed $showsize Value for css to define size. May also be a numeric. - * @return string - */ - function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0) - { - global $conf,$langs,$form; - - if (! is_object($form)) - { - require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - $form=new Form($this->db); - } - - $objectid = $this->id; - $label = $val['label']; - $type = $val['type']; - $size = $val['css']; - - // Convert var to be able to share same code than showOutputField of extrafields - if (preg_match('/varchar\((\d+)\)/', $type, $reg)) - { - $type = 'varchar'; // convert varchar(xx) int varchar - $size = $reg[1]; - } - elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar - if (is_array($val['arrayofkeyval'])) $type='select'; - if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link'; - - //$elementtype=$this->attribute_elementtype[$key]; // seems to not be used - $default=$val['default']; - $computed=$val['computed']; - $unique=$val['unique']; - $required=$val['required']; - $param=$val['param']; - if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval']; - if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) - { - $type='link'; - $param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]); - } - $langfile=$val['langfile']; - $list=$val['list']; - $help=$val['help']; - $hidden=(($val['visible'] == 0) ? 1 : 0); // If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) - - if ($hidden) return ''; - - // If field is a computed field, value must become result of compute - if ($computed) - { - // Make the eval of compute string - //var_dump($computed); - $value = dol_eval($computed, 1, 0); - } - - if (empty($showsize)) - { - if ($type == 'date') - { - //$showsize=10; - $showsize = 'minwidth100imp'; - } - elseif ($type == 'datetime') - { - //$showsize=19; - $showsize = 'minwidth200imp'; - } - elseif (in_array($type,array('int','double','price'))) - { - //$showsize=10; - $showsize = 'maxwidth75'; - } - elseif ($type == 'url') - { - $showsize='minwidth400'; - } - elseif ($type == 'boolean') - { - $showsize=''; - } - else - { - if (round($size) < 12) - { - $showsize = 'minwidth100'; - } - else if (round($size) <= 48) - { - $showsize = 'minwidth200'; - } - else - { - //$showsize=48; - $showsize = 'minwidth400'; - } - } - } - - // Format output value differently according to properties of field - if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1); - elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3); - elseif ($type == 'date') - { - $value=dol_print_date($value,'day'); - } - elseif ($type == 'datetime') - { - $value=dol_print_date($value,'dayhour'); - } - elseif ($type == 'double') - { - if (!empty($value)) { - $value=price($value); - } - } - elseif ($type == 'boolean') - { - $checked=''; - if (!empty($value)) { - $checked=' checked '; - } - $value=''; - } - elseif ($type == 'mail') - { - $value=dol_print_email($value,0,0,0,64,1,1); - } - elseif ($type == 'url') - { - $value=dol_print_url($value,'_blank',32,1); - } - elseif ($type == 'phone') - { - $value=dol_print_phone($value, '', 0, 0, '', ' ', 1); - } - elseif ($type == 'price') - { - $value=price($value,0,$langs,0,0,-1,$conf->currency); - } - elseif ($type == 'select') - { - $value=$param['options'][$value]; - } - elseif ($type == 'sellist') - { - $param_list=array_keys($param['options']); - $InfoFieldList = explode(":", $param_list[0]); - - $selectkey="rowid"; - $keyList='rowid'; - - if (count($InfoFieldList)>=3) - { - $selectkey = $InfoFieldList[2]; - $keyList=$InfoFieldList[2].' as rowid'; - } - - $fields_label = explode('|',$InfoFieldList[1]); - if(is_array($fields_label)) { - $keyList .=', '; - $keyList .= implode(', ', $fields_label); - } - - $sql = 'SELECT '.$keyList; - $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0]; - if (strpos($InfoFieldList[4], 'extra')!==false) - { - $sql.= ' as main'; - } - if ($selectkey=='rowid' && empty($value)) { - $sql.= " WHERE ".$selectkey."=0"; - } elseif ($selectkey=='rowid') { - $sql.= " WHERE ".$selectkey."=".$this->db->escape($value); - }else { - $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'"; - } - - //$sql.= ' AND entity = '.$conf->entity; - - dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $value=''; // value was used, so now we reste it to use it to build final output - - $obj = $this->db->fetch_object($resql); - - // Several field into label (eq table:code|libelle:rowid) - $fields_label = explode('|',$InfoFieldList[1]); - - if(is_array($fields_label) && count($fields_label)>1) - { - foreach ($fields_label as $field_toshow) - { - $translabel=''; - if (!empty($obj->$field_toshow)) { - $translabel=$langs->trans($obj->$field_toshow); - } - if ($translabel!=$field_toshow) { - $value.=dol_trunc($translabel,18).' '; - }else { - $value.=$obj->$field_toshow.' '; - } - } - } - else - { - $translabel=''; - if (!empty($obj->{$InfoFieldList[1]})) { - $translabel=$langs->trans($obj->{$InfoFieldList[1]}); - } - if ($translabel!=$obj->{$InfoFieldList[1]}) { - $value=dol_trunc($translabel,18); - }else { - $value=$obj->{$InfoFieldList[1]}; - } - } - } - else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING); - } - elseif ($type == 'radio') - { - $value=$param['options'][$value]; - } - elseif ($type == 'checkbox') - { - $value_arr=explode(',',$value); - $value=''; - if (is_array($value_arr)) - { - foreach ($value_arr as $keyval=>$valueval) { - $toprint[]='
  • '.$param['options'][$valueval].'
  • '; - } - } - $value='
      '.implode(' ', $toprint).'
    '; - } - elseif ($type == 'chkbxlst') - { - $value_arr = explode(',', $value); - - $param_list = array_keys($param['options']); - $InfoFieldList = explode(":", $param_list[0]); - - $selectkey = "rowid"; - $keyList = 'rowid'; - - if (count($InfoFieldList) >= 3) { - $selectkey = $InfoFieldList[2]; - $keyList = $InfoFieldList[2] . ' as rowid'; - } - - $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($fields_label)) { - $keyList .= ', '; - $keyList .= implode(', ', $fields_label); - } - - $sql = 'SELECT ' . $keyList; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0]; - if (strpos($InfoFieldList[4], 'extra') !== false) { - $sql .= ' as main'; - } - // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'"; - // $sql.= ' AND entity = '.$conf->entity; - - dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $value = ''; // value was used, so now we reste it to use it to build final output - $toprint=array(); - while ( $obj = $this->db->fetch_object($resql) ) { - - // Several field into label (eq table:code|libelle:rowid) - $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { - if (is_array($fields_label) && count($fields_label) > 1) { - foreach ( $fields_label as $field_toshow ) { - $translabel = ''; - if (! empty($obj->$field_toshow)) { - $translabel = $langs->trans($obj->$field_toshow); - } - if ($translabel != $field_toshow) { - $toprint[]='
  • '.dol_trunc($translabel, 18).'
  • '; - } else { - $toprint[]='
  • '.$obj->$field_toshow.'
  • '; - } - } - } else { - $translabel = ''; - if (! empty($obj->{$InfoFieldList[1]})) { - $translabel = $langs->trans($obj->{$InfoFieldList[1]}); - } - if ($translabel != $obj->{$InfoFieldList[1]}) { - $toprint[]='
  • '.dol_trunc($translabel, 18).'
  • '; - } else { - $toprint[]='
  • '.$obj->{$InfoFieldList[1]}.'
  • '; - } - } - } - } - $value='
      '.implode(' ', $toprint).'
    '; - - } else { - dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING); - } - } - elseif ($type == 'link') - { - $out=''; - - // only if something to display (perf) - if ($value) - { - $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' - - $InfoFieldList = explode(":", $param_list[0]); - $classname=$InfoFieldList[0]; - $classpath=$InfoFieldList[1]; - if (! empty($classpath)) - { - dol_include_once($InfoFieldList[1]); - if ($classname && class_exists($classname)) - { - $object = new $classname($this->db); - $object->fetch($value); - $value=$object->getNomUrl(3); - } - } - else - { - dol_syslog('Error bad setup of extrafield', LOG_WARNING); - return 'Error bad setup of extrafield'; - } - } - } - elseif ($type == 'text' || $type == 'html') - { - $value=dol_htmlentitiesbr($value); - } - elseif ($type == 'password') - { - $value=preg_replace('/./i','*',$value); - } - - //print $type.'-'.$size; - $out=$value; - - return $out; - } - - - /** - * Function to show lines of extrafields with output datas - * - * @param Extrafields $extrafields Extrafield Object - * @param string $mode Show output (view) or input (edit) for extrafield - * @param array $params Optional parameters - * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names) - * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names) - * - * @return string - */ - function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='') - { - global $_POST, $conf, $langs, $action; - - $out = ''; - - if (count($extrafields->attribute_label) > 0) - { - $out .= "\n"; - $out .= ' '; - $out .= "\n"; - - $e = 0; - foreach($extrafields->attribute_label as $key=>$label) - { - if (empty($extrafields->attribute_list[$key])) continue; // 0 = Never visible field - if (($mode == 'create' || $mode == 'edit') && abs($extrafields->attribute_list[$key]) != 1 && abs($extrafields->attribute_list[$key]) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list - - // Load language if required - if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]); - - if (is_array($params) && count($params)>0) { - if (array_key_exists('colspan',$params)) { - $colspan=$params['colspan']; - } - }else { - $colspan='3'; - } - - switch($mode) { - case "view": - $value=$this->array_options["options_".$key.$keysuffix]; - break; - case "edit": - $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none'); // GETPOST can get value from GET, POST or setup of default values. - // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc') - if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) - { - if (is_array($getposttemp)) { - // $getposttemp is an array but following code expects a comma separated string - $value = implode(",", $getposttemp); - } else { - $value = $getposttemp; - } - } else { - $value = $this->array_options["options_" . $key]; // No GET, no POST, no default value, so we take value of object. - } - break; - } - //var_dump($value); - - if ($extrafields->attribute_type[$key] == 'separate') - { - $out .= $extrafields->showSeparator($key); - } - else - { - $csstyle=''; - $class=(!empty($extrafields->attribute_hidden[$key]) ? 'class="hideobject" ' : ''); - if (is_array($params) && count($params)>0) { - if (array_key_exists('style',$params)) { - $csstyle=$params['style']; - } - } - if ( !empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) - { - $out .= ''; - $colspan='0'; - } - else - { - $out .= ''; - } - // Convert date into timestamp format (value in memory must be a timestamp) - if (in_array($extrafields->attribute_type[$key],array('date','datetime'))) - { - $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min",'int',3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year",'int',3)):$this->db->jdate($this->array_options['options_'.$key]); - } - // Convert float submited string into real php numeric (value in memory must be a php numeric) - if (in_array($extrafields->attribute_type[$key],array('price','double'))) - { - $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix,'int',3)):$this->array_options['options_'.$key]; - } - - $labeltoshow = $langs->trans($label); - - if($extrafields->attribute_required[$key]) - { - $labeltoshow = ''.$labeltoshow.''; - } - $out .= ''.$labeltoshow.''; - - $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : ''; - $out .=''; - - switch($mode) { - case "view": - $out .= $extrafields->showOutputField($key, $value); - break; - case "edit": - $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id); - break; - } - - $out .= ''; - - if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= ''; - else $out .= ''; - $e++; - } - } - $out .= "\n"; - // Add code to manage list depending on others - if (! empty($conf->use_javascript_ajax)) { - $out .= ' - '."\n"; - $out .= ' '."\n"; - } - } - return $out; - } - - - /** - * Returns the rights used for this class - * @return stdClass - */ - public function getRights() - { - global $user; - - $element = $this->element; - if ($element == 'facturerec') $element='facture'; - - return $user->rights->{$element}; - } - - /** - * Function used to replace a thirdparty id with another one. - * This function is meant to be called from replaceThirdparty with the appropiate tables - * Column name fk_soc MUST be used to identify thirdparties - * - * @param DoliDB $db Database handler - * @param int $origin_id Old thirdparty id (the thirdparty to delete) - * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other) - * @param string[] $tables Tables that need to be changed - * @param int $ignoreerrors Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old thirdparty may already exists on new one) - * @return bool True if success, False if error - */ - public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0) - { - foreach ($tables as $table) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id; - - if (! $db->query($sql)) - { - if ($ignoreerrors) return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B. - //$this->errors = $db->lasterror(); - return false; - } - } - - return true; - } - - /** - * Get buy price to use for margin calculation. This function is called when buy price is unknown. - * Set buy price = sell price if ForceBuyingPriceIfNull configured, - * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice - * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice - * else set min buy price as buy price - * - * @param float $unitPrice Product unit price - * @param float $discountPercent Line discount percent - * @param int $fk_product Product id - * @return float <0 if KO, buyprice if OK - */ - public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0) - { - global $conf; - - $buyPrice = 0; - - if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false - { - $buyPrice = $unitPrice * (1 - $discountPercent / 100); - } - else - { - // Get cost price for margin calculation - if (! empty($fk_product)) - { - if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') - { - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $product = new Product($this->db); - $result = $product->fetch($fk_product); - if ($result <= 0) - { - $this->errors[] = 'ErrorProductIdDoesNotExists'; - return -1; - } - if ($product->cost_price > 0) - { - $buyPrice = $product->cost_price; - } - else if ($product->pmp > 0) - { - $buyPrice = $product->pmp; - } - } - else if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') - { - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $product = new Product($this->db); - $result = $product->fetch($fk_product); - if ($result <= 0) - { - $this->errors[] = 'ErrorProductIdDoesNotExists'; - return -1; - } - if ($product->pmp > 0) - { - $buyPrice = $product->pmp; - } - } - - if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1','pmp','costprice'))) - { - require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; - $productFournisseur = new ProductFournisseur($this->db); - if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) - { - $buyPrice = $productFournisseur->fourn_unitprice; - } - else if ($result < 0) - { - $this->errors[] = $productFournisseur->error; - return -2; - } - } - } - } - return $buyPrice; - } - - - - /** - * Function test if type is array - * - * @param array $info content informations of field - * @return bool - */ - protected function isArray($info) - { - if(is_array($info)) - { - if(isset($info['type']) && $info['type']=='array') return true; - else return false; - } - else return false; - } - - /** - * Function test if type is null - * - * @param array $info content informations of field - * @return bool - */ - protected function isNull($info) - { - if(is_array($info)) - { - if(isset($info['type']) && $info['type']=='null') return true; - else return false; - } - else return false; - } - - - /** - * Function test if type is date - * - * @param array $info content informations of field - * @return bool - */ - public function isDate($info) - { - if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true; - else return false; - } - - /** - * Function test if type is integer - * - * @param array $info content informations of field - * @return bool - */ - public function isInt($info) - { - if(is_array($info)) - { - if(isset($info['type']) && ($info['type']=='int' || $info['type']=='integer' )) return true; - else return false; - } - else return false; - } - - /** - * Function test if type is float - * - * @param array $info content informations of field - * @return bool - */ - public function isFloat($info) - { - if(is_array($info)) - { - if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true; - else return false; - } - else return false; - } - - /** - * Function test if type is text - * - * @param array $info content informations of field - * @return bool - */ - public function isText($info) - { - if(is_array($info)) - { - if(isset($info['type']) && $info['type']=='text') return true; - else return false; - } - else return false; - } - - /** - * Function test if is indexed - * - * @param array $info content informations of field - * @return bool - */ - protected function isIndex($info) - { - if(is_array($info)) - { - if(isset($info['index']) && $info['index']==true) return true; - else return false; - } - else return false; - } - - /** - * Function to prepare the values to insert. - * Note $this->${field} are set by the page that make the createCommon or the updateCommon. - * - * @return array - */ - private function set_save_query() - { - global $conf; - - $queryarray=array(); - foreach ($this->fields as $field=>$info) // Loop on definition of fields - { - // Depending on field type ('datetime', ...) - if($this->isDate($info)) - { - if(empty($this->{$field})) - { - $queryarray[$field] = NULL; - } - else - { - $queryarray[$field] = $this->db->idate($this->{$field}); - } - } - else if($this->isArray($info)) - { - $queryarray[$field] = serialize($this->{$field}); - } - else if($this->isInt($info)) - { - if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field]=$conf->entity; - else - { - $queryarray[$field] = (int) price2num($this->{$field}); - if (empty($queryarray[$field])) $queryarray[$field]=0; // May be reset to null later if property 'notnull' is -1 for this field. - } - } - else if($this->isFloat($info)) - { - $queryarray[$field] = (double) price2num($this->{$field}); - if (empty($queryarray[$field])) $queryarray[$field]=0; - } - else - { - $queryarray[$field] = $this->{$field}; - } - - if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]); - if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null; - } - - return $queryarray; - } - - /** - * Function to load data from a SQL pointer into properties of current object $this - * - * @param stdClass $obj Contain data of object from database - */ - private function setVarsFromFetchObj(&$obj) - { - foreach ($this->fields as $field => $info) - { - if($this->isDate($info)) - { - if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0; - else $this->{$field} = strtotime($obj->{$field}); - } - elseif($this->isArray($info)) - { - $this->{$field} = @unserialize($obj->{$field}); - // Hack for data not in UTF8 - if($this->{$field } === FALSE) @unserialize(utf8_decode($obj->{$field})); - } - elseif($this->isInt($info)) - { - if ($field == 'rowid') $this->id = (int) $obj->{$field}; - else $this->{$field} = (int) $obj->{$field}; - } - elseif($this->isFloat($info)) - { - $this->{$field} = (double) $obj->{$field}; - } - elseif($this->isNull($info)) - { - $val = $obj->{$field}; - // zero is not null - $this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val); - } - else - { - $this->{$field} = $obj->{$field}; - } - } - - // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions. - if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id; - } - - /** - * Function to concat keys of fields - * - * @return string - */ - private function get_field_list() - { - $keys = array_keys($this->fields); - return implode(',', $keys); - } - - /** - * Add quote to field value if necessary - * - * @param string|int $value Value to protect - * @param array $fieldsentry Properties of field - * @return string - */ - protected function quote($value, $fieldsentry) { - if (is_null($value)) return 'NULL'; - else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value"); - else return "'".$this->db->escape($value)."'"; - } - - - /** - * Create object into database - * - * @param User $user User that creates - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - public function createCommon(User $user, $notrigger = false) - { - global $langs; - - $error = 0; - - $now=dol_now(); - - $fieldvalues = $this->set_save_query(); - if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now); - if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id; - unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert. - - $keys=array(); - $values = array(); - foreach ($fieldvalues as $k => $v) { - $keys[$k] = $k; - $value = $this->fields[$k]; - $values[$k] = $this->quote($v, $value); - } - - // Clean and check mandatory - foreach($keys as $key) - { - // If field is an implicit foreign key field - if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]=''; - if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]=''; - - //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1)); - if ($this->fields[$key]['notnull'] == 1 && ! isset($values[$key])) - { - $error++; - $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']); - } - - // If field is an implicit foreign key field - if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null'; - if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null'; - } - - if ($error) return -1; - - $this->db->begin(); - - if (! $error) - { - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; - $sql.= ' ('.implode( ", ", $keys ).')'; - $sql.= ' VALUES ('.implode( ", ", $values ).')'; - - $res = $this->db->query($sql); - if ($res===false) { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } - - if (! $error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); - } - - // Create extrafields - if (! $error) - { - $result=$this->insertExtraFields(); - if ($result < 0) $error++; - } - - // Triggers - if (! $error && ! $notrigger) - { - // Call triggers - $result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } - - // Commit or rollback - if ($error) { - $this->db->rollback(); - return -1; - } else { - $this->db->commit(); - return $this->id; - } - } - - - /** - * Load object in memory from the database - * - * @param int $id Id object - * @param string $ref Ref - * @return int <0 if KO, 0 if not found, >0 if OK - */ - public function fetchCommon($id, $ref = null) - { - if (empty($id) && empty($ref)) return false; - - $sql = 'SELECT '.$this->get_field_list(); - $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element; - - if(!empty($id)) $sql.= ' WHERE rowid = '.$id; - else $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']); - - $res = $this->db->query($sql); - if ($res) - { - $obj = $this->db->fetch_object($res); - if ($obj) - { - $this->setVarsFromFetchObj($obj); - return $this->id; - } - else - { - return 0; - } - } - else - { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - return -1; - } - } - - /** - * Update object into database - * - * @param User $user User that modifies - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @return int <0 if KO, >0 if OK - */ - public function updateCommon(User $user, $notrigger = false) - { - global $conf, $langs; - - $error = 0; - - $now=dol_now(); - - $fieldvalues = $this->set_save_query(); - if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now); - if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id; - unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update. - - $keys=array(); - $values = array(); - foreach ($fieldvalues as $k => $v) { - $keys[$k] = $k; - $value = $this->fields[$k]; - $values[$k] = $this->quote($v, $value); - $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]); - } - - // Clean and check mandatory - foreach($keys as $key) - { - if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]=''; // This is an implicit foreign key field - if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]=''; // This is an explicit foreign key field - - //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1)); - /* - if ($this->fields[$key]['notnull'] == 1 && empty($values[$key])) - { - $error++; - $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']); - }*/ - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ; - - $this->db->begin(); - if (! $error) - { - $res = $this->db->query($sql); - if ($res===false) - { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } - - // Update extrafield - if (! $error) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - - // Triggers - if (! $error && ! $notrigger) - { - // Call triggers - $result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user); - if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail - // End call triggers - } - - // Commit or rollback - if ($error) { - $this->db->rollback(); - return -1; - } else { - $this->db->commit(); - return $this->id; - } - } - - /** - * Delete object in database - * - * @param User $user User that deletes - * @param bool $notrigger false=launch triggers after, true=disable triggers - * @return int <0 if KO, >0 if OK - */ - public function deleteCommon(User $user, $notrigger = false) - { - $error=0; - - $this->db->begin(); - - if (! $error) { - if (! $notrigger) { - // Call triggers - $result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user); - if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail - // End call triggers - } - } - - if (! $error) - { - $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element."_extrafields"; - $sql.= " WHERE fk_object=" . $this->id; - - $resql = $this->db->query($sql); - if (! $resql) - { - $this->errors[] = $this->db->lasterror(); - $error++; - } - } - - if (! $error) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; - - $res = $this->db->query($sql); - if($res===false) { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } - - // Commit or rollback - if ($error) { - $this->db->rollback(); - return -1; - } else { - $this->db->commit(); - return 1; - } - } - - /** - * Initialise object with example values - * Id must be 0 if object instance is a specimen - * - * @return void - */ - public function initAsSpecimenCommon() - { - $this->id = 0; - - // TODO... - } - - /** - * Load comments linked with current task - * @return boolean 1 if ok - */ - public function fetchComments() - { - require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php'; - - $comment = new Comment($this->db); - $this->comments = Comment::fetchAllFor($this->element, $this->id); - return 1; - } - - /** - * Return nb comments already posted - * - * @return int - */ - public function getNbComments() - { - return count($this->comments); - } - -} diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index b1255e10b9c..e17891dab06 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -117,6 +117,13 @@ class Societe extends CommonObject var $state_code; var $state; + /** + * Id of region + * @var int + */ + var $region_code; + var $region; + /** * State code * @var string @@ -3126,29 +3133,8 @@ class Societe extends CommonObject $this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS; $this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP; $this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN; - - // We define state_id, state_code and state - $state_id=$state_code=$state_label=''; - if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) - { - $tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_STATE); - $state_id=$tmp[0]; - if (! empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label" or "id:code:label:region_code:region" - { - $state_code=$tmp[1]; - $state_label=$tmp[2]; - } - else // For backward compatibility - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - $state_code=getState($state_id,2,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore - $state_label=getState($state_id,0,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore - } - } - $this->state_id=$state_id; - $this->state_code=$state_code; - $this->state=$state_label; - if (is_object($langs)) $this->state=($langs->trans('State'.$state_code)!='State'.$state_code)?$langs->trans('State'.$state_code):$state_label; + $this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE; + $this->region_code=empty($conf->global->MAIN_INFO_SOCIETE_REGION)?'':$conf->global->MAIN_INFO_SOCIETE_REGION; $this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE; From 3a7cb43ad5c6235b9436e34f9ddba9fd6b3e9a78 Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Wed, 7 Feb 2018 16:06:58 +0000 Subject: [PATCH 015/413] Forgot withregion condition if we want no state code --- htdocs/core/lib/company.lib.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index 710798331ac..d8b9d090473 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -518,7 +518,12 @@ function getState($id,$withcode='',$dbtouse=0,$withregion='',$outputlangs='',$en } } else { - return $label; + if ($withregion == 1) { + return $label = $obj->region_name . ' - ' . $label; + } + else { + return $label; + } } } else From ecea8d698c3c83e98588e9e8272642f8f574f86b Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Wed, 7 Feb 2018 16:07:33 +0000 Subject: [PATCH 016/413] Forgot that MAIN_SHOW_STATE_CODE is not just 0 or 1 --- htdocs/core/class/html.formcompany.class.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/core/class/html.formcompany.class.php b/htdocs/core/class/html.formcompany.class.php index 6d4547eb68c..7e69d7c7ca0 100644 --- a/htdocs/core/class/html.formcompany.class.php +++ b/htdocs/core/class/html.formcompany.class.php @@ -267,7 +267,8 @@ class FormCompany } // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - if(!empty($conf->global->MAIN_SHOW_STATE_CODE) && $conf->global->MAIN_SHOW_STATE_CODE == 1) { + if(!empty($conf->global->MAIN_SHOW_STATE_CODE) && + ($conf->global->MAIN_SHOW_STATE_CODE == 1 || $conf->global->MAIN_SHOW_STATE_CODE == 2 || $conf->global->MAIN_SHOW_STATE_CODE === 'all')) { if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1) { $out.= $obj->region_name . ' - ' . $obj->code . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); } From f52beef3eb31d7161049391557d9eee438c3f451 Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Wed, 7 Feb 2018 16:54:21 +0000 Subject: [PATCH 017/413] Added translation to company.php if MAIN_SHOW_REGION_IN_STATE_SELECT is activated --- htdocs/admin/company.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index 2b63bc7a4e8..dff69c08abe 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -729,7 +729,8 @@ else print ''; - print ''.$langs->trans("State").''; + if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) print ''.$langs->trans("Region-State").''; + else print ''.$langs->trans("State").''; if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) print getState($conf->global->MAIN_INFO_SOCIETE_STATE,$conf->global->MAIN_SHOW_STATE_CODE,0,$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); else print ' '; print ''; From fd594f7e749f0573e81aa9c59890084e79371a59 Mon Sep 17 00:00:00 2001 From: Rui Strecht Date: Wed, 7 Feb 2018 16:57:43 +0000 Subject: [PATCH 018/413] Fixed wrong global --- htdocs/admin/company.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index dff69c08abe..06fa93bfd2a 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -729,7 +729,7 @@ else print ''; - if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) print ''.$langs->trans("Region-State").''; + if (! empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT)) print ''.$langs->trans("Region-State").''; else print ''.$langs->trans("State").''; if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) print getState($conf->global->MAIN_INFO_SOCIETE_STATE,$conf->global->MAIN_SHOW_STATE_CODE,0,$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); else print ' '; From 40fe3849dc0df5f0bf1ece51a6ebc5794fd3687f Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Mon, 12 Feb 2018 08:21:35 +0100 Subject: [PATCH 019/413] Fix: avoid Warning: A non-numeric value encountered --- htdocs/product/class/product.class.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index e6439031146..06e234ff0c0 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -1649,7 +1649,7 @@ class Product extends CommonObject * @param string $newdefaultvatcode Default vat code * @return int <0 if KO, >0 if OK */ - function updatePrice($newprice, $newpricebase, $user, $newvat='',$newminprice='', $level=0, $newnpr=0, $newpbq=0, $ignore_autogen=0, $localtaxes_array=array(), $newdefaultvatcode='') + function updatePrice($newprice, $newpricebase, $user, $newvat='',$newminprice=0, $level=0, $newnpr=0, $newpbq=0, $ignore_autogen=0, $localtaxes_array=array(), $newdefaultvatcode='') { global $conf,$langs; @@ -1677,7 +1677,7 @@ class Product extends CommonObject return -1; } - if ($newprice!='' || $newprice==0) + if ($newprice != '' || $newprice == 0) { if ($newpricebase == 'TTC') { @@ -1685,7 +1685,7 @@ class Product extends CommonObject $price = price2num($newprice) / (1 + ($newvat / 100)); $price = price2num($price,'MU'); - if ($newminprice!='' || $newminprice==0) + if ($newminprice != '' || $newminprice == 0) { $price_min_ttc = price2num($newminprice,'MU'); $price_min = price2num($newminprice) / (1 + ($newvat / 100)); @@ -1703,7 +1703,7 @@ class Product extends CommonObject $price_ttc = ( $newnpr != 1 ) ? price2num($newprice) * (1 + ($newvat / 100)) : $price; $price_ttc = price2num($price_ttc,'MU'); - if ($newminprice!='' || $newminprice==0) + if ($newminprice != '' || $newminprice == 0) { $price_min = price2num($newminprice,'MU'); $price_min_ttc = price2num($newminprice) * (1 + ($newvat / 100)); From 4f9bb336009b16bf9d827138631cab35c81ba2ea Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 14 Feb 2018 10:47:10 +0100 Subject: [PATCH 020/413] NEW: supplier credit notes: convert to usable absolute discount + link/unlink to supplier invoice + create supplier credit note from excess paid --- htdocs/compta/facture/card.php | 8 +- htdocs/core/class/commoninvoice.class.php | 6 - htdocs/core/class/commonobject.class.php | 2 +- htdocs/core/class/discount.class.php | 64 +++- htdocs/core/class/html.form.class.php | 49 ++- htdocs/core/lib/doc.lib.php | 2 +- htdocs/core/lib/pdf.lib.php | 2 +- htdocs/core/tpl/objectline_view.tpl.php | 4 +- .../fourn/class/fournisseur.facture.class.php | 100 +++++ htdocs/fourn/facture/card.php | 343 +++++++++++++++++- htdocs/societe/class/societe.class.php | 5 +- htdocs/societe/consumption.php | 4 +- 12 files changed, 519 insertions(+), 70 deletions(-) diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 01ea8d93de3..df5e78b8712 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -2989,11 +2989,11 @@ else if ($id > 0 || ! empty($ref)) $resteapayeraffiche = $resteapayer; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this - $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filterabsolutediscount = "fk_facture IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%'))"; - $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + $filterabsolutediscount = "fk_facture IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 9d7ae9d0998..c629c6021b4 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -180,12 +180,6 @@ abstract class CommonInvoice extends CommonObject */ function getSumCreditNotesUsed($multicurrency=0) { - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') - { - // TODO - return 0; - } - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discountstatic=new DiscountAbsolute($this->db); diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 0dd9a245136..a320d102c4e 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -3955,7 +3955,7 @@ abstract class CommonObject $discount=new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } + } // TODO handle (EXCESS PAID) else { $this->tpl['description'] = dol_trunc($line->desc,60); diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index 37dedea8b6b..c8aa11996b6 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -60,16 +60,17 @@ class DiscountAbsolute /** * Load object from database into memory * - * @param int $rowid id discount to load - * @param int $fk_facture_source fk_facture_source - * @return int <0 if KO, =0 if not found, >0 if OK + * @param int $rowid id discount to load + * @param int $fk_facture_source fk_facture_source + * @param int $fk_invoice_supplier_source fk_invoice_supplier_source + * @return int <0 if KO, =0 if not found, >0 if OK */ - function fetch($rowid, $fk_facture_source=0) + function fetch($rowid, $fk_facture_source=0, $fk_invoice_supplier_source=0) { global $conf; // Check parameters - if (! $rowid && ! $fk_facture_source) + if (! $rowid && ! $fk_facture_source && ! $fk_invoice_supplier_source) { $this->error='ErrorBadParameters'; return -1; @@ -79,14 +80,16 @@ class DiscountAbsolute $sql.= " sr.fk_user,"; $sql.= " sr.amount_ht, sr.amount_tva, sr.amount_ttc, sr.tva_tx,"; $sql.= " sr.multicurrency_amount_ht, sr.multicurrency_amount_tva, sr.multicurrency_amount_ttc,"; - $sql.= " sr.fk_facture_line, sr.fk_facture, sr.fk_facture_source, sr.description,"; + $sql.= " sr.fk_facture_line, sr.fk_facture, sr.fk_facture_source, sr.fk_invoice_supplier_line, sr.fk_invoice_supplier, sr.fk_invoice_supplier_source, sr.description,"; $sql.= " sr.datec,"; - $sql.= " f.facnumber as ref_facture_source"; + $sql.= " f.facnumber as ref_facture_source, fsup.facnumber as ref_invoice_supplier_source"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON sr.fk_facture_source = f.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fsup ON sr.fk_invoice_supplier_source = fsup.rowid"; $sql.= " WHERE sr.entity = " . $conf->entity; if ($rowid) $sql.= " AND sr.rowid=".$rowid; if ($fk_facture_source) $sql.= " AND sr.fk_facture_source=".$fk_facture_source; + if ($fk_invoice_supplier_source) $sql.= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -113,6 +116,10 @@ class DiscountAbsolute $this->fk_facture = $obj->fk_facture; $this->fk_facture_source = $obj->fk_facture_source; // Id avoir source $this->ref_facture_source = $obj->ref_facture_source; // Ref avoir source + $this->fk_invoice_supplier_line = $obj->fk_invoice_supplier_line; + $this->fk_invoice_supplier = $obj->fk_invoice_supplier; + $this->fk_invoice_supplier_source = $obj->fk_invoice_supplier_source; // Id avoir source + $this->ref_invoice_supplier_source = $obj->ref_invoice_supplier_source; // Ref avoir source $this->description = $obj->description; $this->datec = $this->db->jdate($obj->datec); @@ -161,11 +168,12 @@ class DiscountAbsolute $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_except"; $sql.= " (entity, datec, fk_soc, fk_user, description,"; $sql.= " amount_ht, amount_tva, amount_ttc, tva_tx,"; - $sql.= " fk_facture_source"; + $sql.= " fk_facture_source, fk_invoice_supplier_source"; $sql.= ")"; $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".$user->id.", '".$this->db->escape($this->description)."',"; $sql.= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.","; - $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null"); + $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null").","; + $sql.= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'":"null"); $sql.= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); @@ -194,7 +202,7 @@ class DiscountAbsolute global $conf, $langs; // Check if we can remove the discount - if ($this->fk_facture_source) + if ($this->fk_facture_source) // TODO check { $sql="SELECT COUNT(rowid) as nb"; $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except"; @@ -278,9 +286,10 @@ class DiscountAbsolute * * @param int $rowidline Invoice line id (To use discount into invoice lines) * @param int $rowidinvoice Invoice id (To use discount as a credit note to reduc payment of invoice) + * @param string $mode 'supplier' to link to supplier invoice, 'customer' instead * @return int <0 if KO, >0 if OK */ - function link_to_invoice($rowidline,$rowidinvoice) + function link_to_invoice($rowidline,$rowidinvoice,$mode='customer') { // Check parameters if (! $rowidline && ! $rowidinvoice) @@ -295,16 +304,26 @@ class DiscountAbsolute } $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - if ($rowidline) $sql.=" SET fk_facture_line = ".$rowidline; - if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice; + if($mode == 'supplier') { + if ($rowidline) $sql.=" SET fk_invoice_supplier_line = ".$rowidline; + if ($rowidinvoice) $sql.=" SET fk_invoice_supplier = ".$rowidinvoice; + } else { + if ($rowidline) $sql.=" SET fk_facture_line = ".$rowidline; + if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice; + } $sql.=" WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::link_to_invoice", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $this->fk_facture_line=$rowidline; - $this->fk_facture=$rowidinvoice; + if($mode == 'supplier') { + $this->fk_invoice_supplier_line=$rowidline; + $this->fk_invoice_supplier=$rowidinvoice; + } else { + $this->fk_facture_line=$rowidline; + $this->fk_facture=$rowidinvoice; + } return 1; } else @@ -319,12 +338,17 @@ class DiscountAbsolute * Link the discount to a particular invoice line or a particular invoice. * Do not call this if discount is linked to a reconcialiated invoice * + * @param string $mode 'supplier' to unlink a supplier invoice, 'customer' instead * @return int <0 if KO, >0 if OK */ - function unlink_invoice() + function unlink_invoice($mode = 'customer') { $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - $sql.=" SET fk_facture_line = NULL, fk_facture = NULL"; + if($mode = 'supplier') { + $sql.=" SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL"; + } else { + $sql.=" SET fk_facture_line = NULL, fk_facture = NULL"; + } $sql.=" WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG); @@ -359,8 +383,8 @@ class DiscountAbsolute //$sql = "SELECT rc.amount_ttc as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; $sql.= " WHERE rc.entity = " . $conf->entity; - if ($mode != 'supplier') $sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available - else $sql.= " AND (rc.fk_suppler_invoice IS NULL AND rc.fk_supplier_invoice IS NULL)"; // Available + if ($mode == 'supplier') $sql.= " AND (rc.fk_facture_source IS NULL AND rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available + else $sql.= " AND (rc.fk_invoice_supplier_source IS NULL AND rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available if (is_object($company)) $sql.= " AND rc.fk_soc = ".$company->id; if (is_object($user)) $sql.= " AND rc.fk_user = ".$user->id; if ($filter) $sql.=' AND ('.$filter.')'; @@ -452,7 +476,7 @@ class DiscountAbsolute $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; $sql.= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id; - $sql.= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess received + $sql.= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess paid } else { diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 4e8f67d6552..8a1cc6ac33c 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -1236,6 +1236,7 @@ class Form if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc); if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc); if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc); + // TODO handle (EXCESS PAID) $selectstring=''; if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected'; @@ -4219,9 +4220,10 @@ class Form * @param int $maxvalue Max value for lines that can be selected * @param string $more More string to add * @param int $hidelist 1=Hide list + * @param string $mode 'supplier' to list available discounts for suppliers, 'customer' instead * @return void */ - function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0) + function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $mode='customer') { global $conf,$langs; if ($htmlname != "none") @@ -4230,28 +4232,51 @@ class Form print ''; print ''; print '
    '; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) - { - if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); - } - else - { - if (! $filter || $filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%'))") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + if($mode == 'supplier') { + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + { + if (! $filter || $filter=="fk_invoice_supplier IS NOT NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } + else + { + if (! $filter || $filter=="fk_invoice_supplier IS NOT NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } + } else { + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + { + if (! $filter || $filter=="fk_facture IS NOT NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } + else + { + if (! $filter || $filter=="fk_facture IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } } if (empty($hidelist)) print ': '; print '
    '; if (empty($hidelist)) { print '
    '; - $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles + if($mode == 'supplier') { + $newfilter = 'fk_facture_source IS NULL AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Exclude customer discounts + $newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available + } else { + $newfilter = 'fk_invoice_supplier_source IS NULL AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Exclude supplier discounts + $newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available + } if ($filter) $newfilter.=' AND ('.$filter.')'; $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue); if ($nbqualifiedlines > 0) { print '   '; } print '
    '; diff --git a/htdocs/core/lib/doc.lib.php b/htdocs/core/lib/doc.lib.php index 99e576ad057..20eaa9a71f7 100644 --- a/htdocs/core/lib/doc.lib.php +++ b/htdocs/core/lib/doc.lib.php @@ -88,7 +88,7 @@ function doc_getlinedesc($line,$outputlangs,$hideref=0,$hidedesc=0,$issupplierli $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source); - } + } // TODO handle (EXCESS PAID) else { if ($idprod) diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php index 377f2215b6d..0fb649506cb 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -1251,7 +1251,7 @@ function pdf_getlinedesc($object,$i,$outputlangs,$hideref=0,$hidedesc=0,$issuppl $discount=new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source); - } + } // TODO handle (EXCESS PAID) else { if ($idprod) diff --git a/htdocs/core/tpl/objectline_view.tpl.php b/htdocs/core/tpl/objectline_view.tpl.php index 8d5b13ece7c..bc5d950ab8e 100644 --- a/htdocs/core/tpl/objectline_view.tpl.php +++ b/htdocs/core/tpl/objectline_view.tpl.php @@ -72,7 +72,7 @@ if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0; $txt=''; print img_object($langs->trans("ShowReduc"),'reduc').' '; if ($line->description == '(DEPOSIT)') $txt=$langs->trans("Deposit"); - elseif ($line->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); + elseif ($line->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); // TODO handle (EXCESS PAID) //else $txt=$langs->trans("Discount"); print $txt; ?> @@ -100,7 +100,7 @@ if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0; $discount=new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); echo ($txt?' - ':'').$langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } + } // TODO handle (EXCESS PAID) else { echo ($txt?' - ':'').dol_htmlentitiesbr($line->description); diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 444eb5d200a..b23c9af5fce 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -897,6 +897,106 @@ class FactureFournisseur extends CommonInvoice } } + /** + * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount) + * + * @param int $idremise Id of absolute discount + * @return int >0 if OK, <0 if KO + */ + function insert_discount($idremise) + { + global $langs; + + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + + $this->db->begin(); + + $remise=new DiscountAbsolute($this->db); + $result=$remise->fetch($idremise); + + if ($result > 0) + { + if ($remise->fk_invoice_supplier) // Protection against multiple submission + { + $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); + $this->db->rollback(); + return -5; + } + + $facligne=new SupplierInvoiceLine($this->db); + $facligne->fk_facture=$this->id; + $facligne->fk_remise_except=$remise->id; + $facligne->desc=$remise->description; // Description ligne + $facligne->vat_src_code=$remise->vat_src_code; + $facligne->tva_tx=$remise->tva_tx; + $facligne->subprice = -$remise->amount_ht; + $facligne->fk_product=0; // Id produit predefini + $facligne->qty=1; + $facligne->remise_percent=0; + $facligne->rang=-1; + $facligne->info_bits=2; + + // Get buy/cost price of invoice that is source of discount + if ($remise->fk_invoice_supplier_source > 0) + { + $srcinvoice=new FactureFournisseur($this->db); + $srcinvoice->fetch($remise->fk_invoice_supplier_source); + $totalcostpriceofinvoice=0; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject + $formmargin=new FormMargin($this->db); + $arraytmp=$formmargin->getMarginInfosArray($srcinvoice, false); + $facligne->pa_ht = $arraytmp['pa_total']; + } + + $facligne->total_ht = -$remise->amount_ht; + $facligne->total_tva = -$remise->amount_tva; + $facligne->total_ttc = -$remise->amount_ttc; + + $facligne->multicurrency_subprice = -$remise->multicurrency_subprice; + $facligne->multicurrency_total_ht = -$remise->multicurrency_total_ht; + $facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva; + $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc; + + $lineid=$facligne->insert(); + if ($lineid > 0) + { + $result=$this->update_price(1); + if ($result > 0) + { + // Create link between discount and invoice line + $result=$remise->link_to_invoice($lineid,0,'supplier'); + if ($result < 0) + { + $this->error=$remise->error; + $this->db->rollback(); + return -4; + } + + $this->db->commit(); + return 1; + } + else + { + $this->error=$facligne->error; + $this->db->rollback(); + return -1; + } + } + else + { + $this->error=$facligne->error; + $this->db->rollback(); + return -2; + } + } + else + { + $this->db->rollback(); + return -3; + } + } + /** * Delete invoice from database diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 761d5d591e3..a397d40d147 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -36,6 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -265,6 +266,14 @@ if (empty($reshook)) $action=''; } } + + // Delete link of credit note to invoice + else if ($action == 'unlinkdiscount' && $user->rights->facture->creer) + { + $discount = new DiscountAbsolute($db); + $result = $discount->fetch(GETPOST("discountid")); + $discount->unlink_invoice('supplier'); + } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { @@ -376,6 +385,186 @@ if (empty($reshook)) $result=$object->update($user); if ($result < 0) dol_print_error($db,$object->error); } + elseif ($action == "setabsolutediscount" && $user->rights->facture->creer) + { + // POST[remise_id] or POST[remise_id_for_payment] + + // We use the credit to reduce amount of invoice + if (! empty($_POST["remise_id"])) { + $ret = $object->fetch($id); + if ($ret > 0) { + $result = $object->insert_discount($_POST["remise_id"]); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else { + dol_print_error($db, $object->error); + } + } + // We use the credit to reduce remain to pay + if (! empty($_POST["remise_id_for_payment"])) + { + require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php'; + $discount = new DiscountAbsolute($db); + $discount->fetch($_POST["remise_id_for_payment"]); + + //var_dump($object->getRemainToPay(0)); + //var_dump($discount->amount_ttc);exit; + if ($discount->amount_ttc > $object->getRemainToPay(0)) + { + // TODO Split the discount in 2 automatically + $error++; + setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors'); + } + + if (! $error) + { + $result = $discount->link_to_invoice(0, $id, 'supplier'); + if ($result < 0) { + setEventMessages($discount->error, $discount->errors, 'errors'); + } + } + } + + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $ret = $object->fetch($id); // Reload to get new records + + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + } + } + // Convertir en reduc + else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->rights->facture->creer) + { + $object->fetch($id); + $object->fetch_thirdparty(); + //$object->fetch_lines(); // Already done into fetch + + // Check if there is already a discount (protection to avoid duplicate creation when resubmit post) + $discountcheck=new DiscountAbsolute($db); + $result=$discountcheck->fetch(0,0,$object->id); + + $canconvert=0; + if ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discountcheck->id)) $canconvert=1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) + if (($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_STANDARD) && $object->paye == 0 && empty($discountcheck->id)) $canconvert=1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) + if ($canconvert) + { + $db->begin(); + + $amount_ht = $amount_tva = $amount_ttc = array(); + + // Loop on each vat rate + $i = 0; + foreach ($object->lines as $line) + { + if ($line->product_type < 9 && $line->total_ht != 0) // Remove lines with product_type greater than or equal to 9 + { // no need to create discount if amount is null + $amount_ht[$line->tva_tx] += $line->total_ht; + $amount_tva[$line->tva_tx] += $line->total_tva; + $amount_ttc[$line->tva_tx] += $line->total_ttc; + $i ++; + } + } + + // Insert one discount by VAT rate category + $discount = new DiscountAbsolute($db); + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) + $discount->description = '(CREDIT_NOTE)'; + elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) + $discount->description = '(DEPOSIT)'; + elseif ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) + $discount->description = '(EXCESS PAID)'; + else { + setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors'); + } + $discount->fk_soc = $object->socid; + $discount->fk_invoice_supplier_source = $object->id; + + $error = 0; + + if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) + { + // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT + + $sql = 'SELECT SUM(pf.amount) as total_paiements'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement') . ')'; + $sql.= ' WHERE pf.fk_facturefourn = '.$object->id; + $sql.= ' AND pf.fk_paiementfourn = p.rowid'; + $sql.= ' AND p.entity IN (' . getEntity('facture').')'; + $sql.= ' ORDER BY p.datep, p.tms'; + + $resql = $db->query($sql); + if (! $resql) dol_print_error($db); + + $res = $db->fetch_object($resql); + $total_paiements = $res->total_paiements; + + $discount->amount_ht = $discount->amount_ttc = $total_paiements - $object->total_ttc; + $discount->amount_tva = 0; + $discount->tva_tx = 0; + + $result = $discount->create($user); + if ($result < 0) + { + $error++; + } + + } + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) + { + foreach ($amount_ht as $tva_tx => $xxx) + { + $discount->amount_ht = abs($amount_ht[$tva_tx]); + $discount->amount_tva = abs($amount_tva[$tva_tx]); + $discount->amount_ttc = abs($amount_ttc[$tva_tx]); + $discount->tva_tx = abs($tva_tx); + + $result = $discount->create($user); + if ($result < 0) + { + $error++; + break; + } + } + + } + + if (empty($error)) + { + if($object->type != FactureFournisseur::TYPE_DEPOSIT) { + // Classe facture + $result = $object->set_paid($user); + if ($result >= 0) + { + $db->commit(); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); + } + } else { + $db->commit(); + } + } + else + { + setEventMessages($discount->error, $discount->errors, 'errors'); + $db->rollback(); + } + } + } + // Delete payment elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) @@ -464,6 +653,7 @@ if (empty($reshook)) // Credit note invoice if ($_POST['type'] == FactureFournisseur::TYPE_CREDIT_NOTE) { + $sourceinvoice = GETPOST('fac_avoir','int'); if (! ($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) { @@ -519,6 +709,10 @@ if (empty($reshook)) $id = $object->create($user); + if($id <= 0) { + $error++; + } + if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0) { $facture_source = new FactureFournisseur($db); // fetch origin object @@ -677,7 +871,7 @@ if (empty($reshook)) } $num=count($lines); - for ($i = 0; $i < $num; $i++) + for ($i = 0; $i < $num; $i++) // TODO handle subprice < 0 { $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); @@ -1485,6 +1679,7 @@ if ($action == 'create') if ($societe->id > 0) { + $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 'supplier'); print $societe->getNomUrl(1); print ''; } @@ -1717,22 +1912,22 @@ if ($action == 'create') print ''; - if ($socid > 0) + if ($societe->id > 0) { // Discounts for third party print '' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); + if ($societe->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); else print $langs->trans("CompanyHasNoRelativeDiscount"); - print ' (' . $langs->trans("EditRelativeDiscount") . ')'; + print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
    '; if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); + print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); else print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; + print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; print '.'; print ''; } @@ -1944,6 +2139,18 @@ else } $resteapayeraffiche = $resteapayer; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this + $filterabsolutediscount = "fk_invoice_supplier IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_invoice_supplier IS NOT NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; + } + + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 'supplier'); + $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 'supplier'); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); /* * View card @@ -1953,6 +2160,17 @@ else dol_fiche_head($head, 'card', $titre, -1, 'bill'); + $formconfirm = ''; + + // Confirmation de la conversion de l'avoir en reduc + if ($action == 'converttoreduc') { + if($object->type == FactureFournisseur::TYPE_STANDARD) $type_fac = 'ExcessReceived'; // TODO translation trop-perçu => trop-payé + elseif($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $type_fac = 'CreditNote'; + elseif($object->type == FactureFournisseur::TYPE_DEPOSIT) $type_fac = 'Deposit'; + $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac))); // TODO translation client => fournisseur + $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2); + } + // Clone confirmation if ($action == 'clone') { @@ -2189,7 +2407,88 @@ else print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')'; } print ''; - + + // Relative and absolute discounts + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; + + print '' . $langs->trans('Discounts'); + print ''; + if ($societe->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + // print ' ('.$addrelativediscount.')'; + + // Is there is commercial discount or down payment available ? + if ($absolute_discount > 0) { + print '. '; + if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + if ($object->statut == 0) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + print '. '; + } else { + if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + print '
    ' . $text . '.
    '; + } else { + $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + $text2 = $langs->trans("AbsoluteDiscountUse"); + print $form->textwithpicto($text, $text2); + } + } + } else { + // Discount available of type fixed amount (not credit note) + print '
    '; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 'supplier'); + } + } else { + if ($absolute_creditnote > 0) // If not, link will be added later + { + if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) + print ' (' . $addabsolutediscount . ')
    '; + else + print '. '; + } else + print '. '; + } + // Is there credit notes availables ? + if ($absolute_creditnote > 0) + { + // If validated, we show link "add credit note to payment" + if ($object->statut != FactureFournisseur::STATUS_VALIDATED || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + if ($object->statut == 0 && $object->type != FactureFournisseur::TYPE_DEPOSIT) { + $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); + print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); + } else { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; + } + } else { // We can add a credit note on a down payment or standard invoice or situation invoice + // There is credit notes discounts available + if (! $absolute_discount) print '
    '; + // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 'supplier'); + $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 'supplier'); // We allow credit note even if amount is higher + } + } + if (! $absolute_discount && ! $absolute_creditnote) { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) + print ' (' . $addabsolutediscount . ')
    '; + else + print '. '; + } + // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) + // { + // if (! $absolute_discount && ! $absolute_creditnote) print '
    '; + // print '   -   '; + // print $addabsolutediscount; + // print '   -   '.$addcreditnote; // We disbale link to credit note + // } + print ''; + // Label print ''; print ''.$form->editfieldkey("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).''; @@ -2539,18 +2838,19 @@ else print $langs->trans('AlreadyPaid'); print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' '; - $resteapayer = $object->total_ttc - $totalpaye; + //$resteapayer = $object->total_ttc - $totalpaye; $resteapayeraffiche = $resteapayer; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; // Loop on each credit note or deposit amount applied $creditnoteamount = 0; $depositamount = 0; - /* + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql .= " re.description, re.fk_facture_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except_supplier as re"; - $sql .= " WHERE fk_facture = " . $object->id; + $sql .= " re.description, re.fk_invoice_supplier_source"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; + $sql .= " WHERE fk_invoice_supplier = " . $object->id; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -2558,7 +2858,7 @@ else $invoice = new FactureFournisseur($db); while ($i < $num) { $obj = $db->fetch_object($resql); - $invoice->fetch($obj->fk_facture_source); + $invoice->fetch($obj->fk_invoice_supplier_source); print ''; if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) print $langs->trans("CreditNote") . ' '; @@ -2568,7 +2868,7 @@ else print ' :'; print '' . price($obj->amount_ttc) . ''; print ''; - print 'rowid . '">' . img_delete() . ''; + print 'rowid . '">' . img_delete() . ''; // TODO unlinkdiscount print ''; $i ++; if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) @@ -2579,7 +2879,7 @@ else } else { dol_print_error($db); } - */ + // Paye partiellement 'escompte' if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { @@ -2627,7 +2927,7 @@ else else print $langs->trans('ExcessReceived'); print ' :'; - print '' . price($resteapayeraffiche) . ''; + print '' . price($resteapayeraffiche) . ''; print ' '; } else // Credit note @@ -2649,7 +2949,7 @@ else else print $langs->trans('ExcessPaydBack'); print ' :'; - print '' . price($sign * $resteapayeraffiche) . ''; + print '' . price($sign * $resteapayeraffiche) . ''; print ' '; // Sold credit note @@ -2792,7 +3092,7 @@ else } // Reverse back money or convert to reduction - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) { // For credit note only if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) { @@ -2806,6 +3106,11 @@ else } } + // For standard invoice with excess paid + if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $user->rights->facture->creer && empty($discount->id)) + { + print ''; // TODO translation : trop-perçu => trop payé + } // For credit note if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->fournisseur->facture->creer && $object->getSommePaiement() == 0) { print ''; diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index b9b431f3e3e..4adfae72258 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1718,14 +1718,15 @@ class Societe extends CommonObject * @param User $user Filtre sur un user auteur des remises * @param string $filter Filtre autre * @param integer $maxvalue Filter on max value for discount + * @param string $mode 'supplier' to get available discounts for suppliers, 'customer' instead * @return int <0 if KO, Credit note amount otherwise */ - function getAvailableDiscounts($user='',$filter='',$maxvalue=0) + function getAvailableDiscounts($user='',$filter='',$maxvalue=0,$mode='customer') { require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discountstatic=new DiscountAbsolute($this->db); - $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue); + $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue,$mode); if ($result >= 0) { return $result; diff --git a/htdocs/societe/consumption.php b/htdocs/societe/consumption.php index ffb4cac77fa..1420562da19 100644 --- a/htdocs/societe/consumption.php +++ b/htdocs/societe/consumption.php @@ -490,7 +490,7 @@ if ($sql_select) $txt=''; print img_object($langs->trans("ShowReduc"),'reduc').' '; if ($objp->description == '(DEPOSIT)') $txt=$langs->trans("Deposit"); - elseif ($objp->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); + elseif ($objp->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); // TODO handle (EXCESS PAID) //else $txt=$langs->trans("Discount"); print $txt; ?> @@ -517,7 +517,7 @@ if ($sql_select) echo ($txt?' - ':'').$langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); // Add date of deposit if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec).')'; - } + } // TODO handle (EXCESS PAID) else { echo ($txt?' - ':'').dol_htmlentitiesbr($objp->description); From daca27b2ed8e8a2924105de16b32f7f8d894d117 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 14 Feb 2018 18:02:40 +0100 Subject: [PATCH 021/413] NEW: supplier credit notes: split display in thirdparty discount page + fixes + refactoring --- htdocs/comm/card.php | 2 +- htdocs/comm/remx.php | 372 +++++++++++++++++- htdocs/core/class/discount.class.php | 93 ++++- htdocs/core/class/html.form.class.php | 15 +- .../fourn/class/fournisseur.facture.class.php | 2 +- htdocs/fourn/facture/card.php | 21 +- .../install/mysql/migration/7.0.0-8.0.0.sql | 1 + .../tables/llx_societe_remise_except.key.sql | 1 + .../tables/llx_societe_remise_except.sql | 3 +- htdocs/societe/class/societe.class.php | 25 +- 10 files changed, 476 insertions(+), 59 deletions(-) diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index 81443f04d62..d732a10a347 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -392,7 +392,7 @@ if ($object->id > 0) print ''; print ''; print ''; - $amount_discount=$object->getAvailableDiscounts(); + $amount_discount=$object->getAvailableDiscounts(); // TODO adapt to supplier discounts if ($amount_discount < 0) dol_print_error($db,$object->error); if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; //else print $langs->trans("DiscountNone"); diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 0127b8f15be..072baa675fb 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -26,6 +26,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $langs->load("orders"); @@ -143,6 +144,7 @@ if ($action == 'setremise' && $user->rights->societe->creer) $amount_ht=GETPOST('amount_ht'); $desc=GETPOST('desc','alpha'); $tva_tx=GETPOST('tva_tx','alpha'); + $discount_type=! empty($_POST['discount_type'])?GETPOST('discount_type','alpha'):0; if (price2num($amount_ht) > 0) { @@ -157,7 +159,7 @@ if ($action == 'setremise' && $user->rights->societe->creer) { $soc = new Societe($db); $soc->fetch($id); - $discountid=$soc->set_remise_except($amount_ht,$user,$desc,$tva_tx); + $discountid=$soc->set_remise_except($amount_ht,$user,$desc,$tva_tx,$discount_type); if ($discountid > 0) { @@ -215,6 +217,7 @@ if (GETPOST('action','aZ09') == 'confirm_remove' && GETPOST("confirm")=='yes') $form=new Form($db); $facturestatic=new Facture($db); +$facturefournstatic=new FactureFournisseur($db); llxHeader('',$langs->trans("GlobalDiscount")); @@ -244,12 +247,13 @@ if ($socid > 0) print '
    '; print ''; - // Calcul avoirs en cours + // Calcul avoirs client en cours $remise_all=$remise_user=0; $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; $sql.= " WHERE rc.fk_soc = " . $object->id; $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND discount_type = 0"; // Exclude supplier discounts $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; $sql.= " GROUP BY rc.fk_user"; $resql=$db->query($sql); @@ -264,14 +268,47 @@ if ($socid > 0) dol_print_error($db); } - print ''; + print ''; // TODO adapt text print ''; if (! empty($user->fk_soc)) // No need to show this for external users { - print ''; + print ''; // TODO adapt text print ''; } + + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + // Calcul avoirs fournisseur en cours + $remise_all=$remise_user=0; + $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND discount_type = 1"; // Exclude customer discounts + $sql.= " AND (fk_invoice_supplier_line IS NULL AND fk_invoice_supplier IS NULL)"; + $sql.= " GROUP BY rc.fk_user"; + $resql=$db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $remise_all+=$obj->amount; + if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; + } + else + { + dol_print_error($db); + } + + print ''; // TODO adapt text + print ''; + + if (! empty($user->fk_soc)) // No need to show this for external users + { + print ''; // TODO adapt text + print ''; + } + } + print '
    '.$langs->trans("CustomerAbsoluteDiscountAllUsers").'
    '.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("CustomerAbsoluteDiscountMy").'
    '.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '; print '
    '; @@ -284,6 +321,11 @@ if ($socid > 0) print '
    '; print ''; + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print ''; + print ''; + } print ''; print ''; @@ -321,9 +363,18 @@ if ($socid > 0) print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.GETPOST('remid'), $langs->trans('RemoveDiscount'), $langs->trans('ConfirmRemoveDiscount'), 'confirm_remove', '', 0, 1); } + /* - * Liste remises fixes restant en cours (= liees a aucune facture ni ligne de facture) + * Liste remises fixes client restant en cours (= liees a aucune facture ni ligne de facture) */ + + print load_fiche_titre($langs->trans("DiscountStillRemaining")); + + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print '
    '; + print '
    '; + } + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; $sql.= " rc.datec as dc, rc.description,"; $sql.= " rc.fk_facture_source,"; @@ -334,13 +385,16 @@ if ($socid > 0) $sql.= " WHERE rc.fk_soc = " . $object->id; $sql.= " AND rc.entity = " . $conf->entity; $sql.= " AND u.rowid = rc.fk_user"; + $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)"; $sql.= " ORDER BY rc.datec DESC"; $resql=$db->query($sql); if ($resql) { - print load_fiche_titre($langs->trans("DiscountStillRemaining")); + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); // TODO translate + } print '
    '.$langs->trans('DiscountType').' '; + print '
    '.$langs->trans("AmountHT").''; print ' '.$langs->trans("Currency".$conf->currency).'
    '; print ''; print ''; // Need 120+ for format with AM/PM @@ -449,11 +503,157 @@ if ($socid > 0) dol_print_error($db); } + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print ''; // class="fichehalfleft" + print '
    '; + print '
    '; + + /* + * Liste remises fixes fournisseur restant en cours (= liees a aucune facture ni ligne de facture) + */ + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description,"; + $sql.= " rc.fk_invoice_supplier_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " fa.ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user"; + $sql.= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) + { + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); // TODO translate + print '
    '.$langs->trans("Date").'
    '; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $showconfirminfo=array(); + + $i = 0; + $num = $db->num_rows($resql); + if ($num > 0) + { + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS PAID\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + if ($user->rights->societe->creer || $user->rights->facture->creer) + { + print ''; + } + else print ''; + print ''; + + if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) + { + $showconfirminfo['rowid']=$obj->rowid; + $showconfirminfo['amount_ttc']=$obj->amount_ttc; + } + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
    '.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("DiscountOfferedBy").' 
    '.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(EXCESS PAID\)/',$langs->trans("ExcessPaid"),$obj->description).' '.$facturefournstatic->getNomURl(1); // TODO translate ExcessPaid + print ''; + print $obj->description; + print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ''; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; + print '   '; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; + print ' 
    '.$langs->trans("None").'
    "; + + if (count($showconfirminfo)) + { + $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT'); + $amount2=($showconfirminfo['amount_ttc']-$amount1); + $formquestion=array( + 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), + array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), + array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') + ); + $langs->load("dict"); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + } + } + else + { + dol_print_error($db); + } + + print ''; // class="ficheaddleft" + print ''; // class="fichehalfright" + print ''; // class="fichecenter" + } + print '
    '; /* * List discount consumed (=liees a une ligne de facture ou facture) */ + + print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); + + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print '
    '; + print '
    '; + } // Remises liees a lignes de factures $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; @@ -471,6 +671,7 @@ if ($socid > 0) $sql.= " AND rc.fk_facture_line = fc.rowid"; $sql.= " AND fc.fk_facture = f.rowid"; $sql.= " AND rc.fk_user = u.rowid"; + $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts $sql.= " ORDER BY dc DESC"; //$sql.= " UNION "; // Remises liees a factures @@ -487,7 +688,7 @@ if ($socid > 0) $sql2.= " WHERE rc.fk_soc =". $object->id; $sql2.= " AND rc.fk_facture = f.rowid"; $sql2.= " AND rc.fk_user = u.rowid"; - + $sql2.= " AND rc.discount_type = 0"; // Eliminate supplier discounts $sql2.= " ORDER BY dc DESC"; $resql=$db->query($sql); @@ -495,7 +696,9 @@ if ($socid > 0) if ($resql) $resql2=$db->query($sql2); if ($resql2) { - print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); // TODO translate + } print ''; print ''; print ''; // Need 120+ for format with AM/PM @@ -598,6 +801,159 @@ if ($socid > 0) dol_print_error($db); } + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print ''; // class="fichehalfleft" + print '
    '; + print '
    '; + + // Remises liees a lignes de factures + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,"; + $sql.= " rc.fk_invoice_supplier_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " f.rowid, f.ref as facnumber,"; + $sql.= " fa.ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql.= " , ".MAIN_DB_PREFIX."user as u"; + $sql.= " , ".MAIN_DB_PREFIX."facture_fourn_det as fc"; + $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc =". $object->id; + $sql.= " AND rc.fk_invoice_supplier_line = fc.rowid"; + $sql.= " AND fc.fk_facture_fourn = f.rowid"; + $sql.= " AND rc.fk_user = u.rowid"; + $sql.= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql.= " ORDER BY dc DESC"; + //$sql.= " UNION "; + // Remises liees a factures + $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql2.= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,"; + $sql2.= " rc.fk_invoice_supplier_source,"; + $sql2.= " u.login, u.rowid as user_id,"; + $sql2.= " f.rowid, f.ref as facnumber,"; + $sql2.= " fa.ref, fa.type as type"; + $sql2.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql2.= " , ".MAIN_DB_PREFIX."user as u"; + $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql2.= " WHERE rc.fk_soc =". $object->id; + $sql2.= " AND rc.fk_invoice_supplier = f.rowid"; + $sql2.= " AND rc.fk_user = u.rowid"; + $sql2.= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql2.= " ORDER BY dc DESC"; + + $resql=$db->query($sql); + $resql2=null; + if ($resql) $resql2=$db->query($sql2); + if ($resql2) + { + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); // TODO translate + print '
    '.$langs->trans("Date").'
    '; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $tab_sqlobj=array(); + $tab_sqlobjOrder=array(); + $num = $db->num_rows($resql); + if ($num > 0) + { + for ($i = 0;$i < $num; $i++) + { + $sqlobj = $db->fetch_object($resql); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); + } + } + $db->free($resql); + + $num = $db->num_rows($resql2); + for ($i = 0;$i < $num;$i++) + { + $sqlobj = $db->fetch_object($resql2); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); + } + $db->free($resql2); + array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj); + + $num = count($tab_sqlobj); + if ($num > 0) + { + $i = 0 ; + while ($i < $num ) + { + $obj = array_shift($tab_sqlobj); + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS PAID\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; // TODO adapt to supplier invoice of use getNomUrl + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + + print "
    '.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("Author").' 
    '.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(EXCESS PAID\)/',$langs->trans("Invoice"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + print $obj->description; + print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; // TODO getNomUrl ? + print ' 
    '.$langs->trans("None").'
    "; + } + else + { + dol_print_error($db); + } + + print '
    '; // class="ficheaddleft" + print '
    '; // class="fichehalfright" + print ''; // class="fichecenter" + } } llxFooter(); diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index c8aa11996b6..b62e35c183e 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -34,6 +34,7 @@ class DiscountAbsolute public $id; // Id discount public $fk_soc; + public $discount_type; // 0 => customer discount, 1 => supplier discount public $amount_ht; // public $amount_tva; // public $amount_ttc; // @@ -76,7 +77,7 @@ class DiscountAbsolute return -1; } - $sql = "SELECT sr.rowid, sr.fk_soc,"; + $sql = "SELECT sr.rowid, sr.fk_soc, sr.discount_type,"; $sql.= " sr.fk_user,"; $sql.= " sr.amount_ht, sr.amount_tva, sr.amount_ttc, sr.tva_tx,"; $sql.= " sr.multicurrency_amount_ht, sr.multicurrency_amount_tva, sr.multicurrency_amount_ttc,"; @@ -101,6 +102,7 @@ class DiscountAbsolute $this->id = $obj->rowid; $this->fk_soc = $obj->fk_soc; + $this->discount_type = $obj->discount_type; $this->amount_ht = $obj->amount_ht; $this->amount_tva = $obj->amount_tva; @@ -166,11 +168,11 @@ class DiscountAbsolute // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_except"; - $sql.= " (entity, datec, fk_soc, fk_user, description,"; + $sql.= " (entity, datec, fk_soc, discount_type, fk_user, description,"; $sql.= " amount_ht, amount_tva, amount_ttc, tva_tx,"; $sql.= " fk_facture_source, fk_invoice_supplier_source"; $sql.= ")"; - $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".$user->id.", '".$this->db->escape($this->description)."',"; + $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".(empty($this->discount_type)?0:intval($this->discount_type)).", ".$user->id.", '".$this->db->escape($this->description)."',"; $sql.= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.","; $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null").","; $sql.= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'":"null"); @@ -202,7 +204,7 @@ class DiscountAbsolute global $conf, $langs; // Check if we can remove the discount - if ($this->fk_facture_source) // TODO check + if ($this->fk_facture_source) { $sql="SELECT COUNT(rowid) as nb"; $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except"; @@ -228,15 +230,46 @@ class DiscountAbsolute return -1; } } + + // Check if we can remove the discount + if ($this->fk_invoice_supplier_source) + { + $sql="SELECT COUNT(rowid) as nb"; + $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except"; + $sql.=" WHERE (fk_invoice_supplier_line IS NOT NULL"; // Not used as absolute simple discount + $sql.=" OR fk_invoice_supplier IS NOT NULL)"; // Not used as credit note and not used as deposit + $sql.=" AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; + //$sql.=" AND rowid != ".$this->id; + + dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj->nb > 0) + { + $this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved'; + return -2; + } + } + else + { + dol_print_error($this->db); + return -1; + } + } $this->db->begin(); // Delete but only if not used $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except "; if ($this->fk_facture_source) $sql.= " WHERE fk_facture_source = ".$this->fk_facture_source; // Delete all lines of same serie + elseif ($this->fk_invoice_supplier_source) $sql.= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; // Delete all lines of same serie else $sql.= " WHERE rowid = ".$this->id; // Delete only line $sql.= " AND (fk_facture_line IS NULL"; // Not used as absolute simple discount $sql.= " AND fk_facture IS NULL)"; // Not used as credit note and not used as deposit + $sql.= " AND (fk_invoice_supplier_line IS NULL"; // Not used as absolute simple discount + $sql.= " AND fk_invoice_supplier IS NULL)"; // Not used as credit note and not used as deposit dol_syslog(get_class($this)."::delete Delete discount", LOG_DEBUG); $result=$this->db->query($sql); @@ -263,6 +296,26 @@ class DiscountAbsolute return -1; } } + elseif($this->fk_invoice_supplier_source) { + + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; + $sql.=" set paye=0, fk_statut=1"; + $sql.=" WHERE (type = 2 or type = 3) AND rowid=".$this->fk_invoice_supplier_source; + + dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } else { $this->db->commit(); @@ -286,10 +339,9 @@ class DiscountAbsolute * * @param int $rowidline Invoice line id (To use discount into invoice lines) * @param int $rowidinvoice Invoice id (To use discount as a credit note to reduc payment of invoice) - * @param string $mode 'supplier' to link to supplier invoice, 'customer' instead * @return int <0 if KO, >0 if OK */ - function link_to_invoice($rowidline,$rowidinvoice,$mode='customer') + function link_to_invoice($rowidline,$rowidinvoice) { // Check parameters if (! $rowidline && ! $rowidinvoice) @@ -304,7 +356,7 @@ class DiscountAbsolute } $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - if($mode == 'supplier') { + if(! empty($this->discount_type)) { if ($rowidline) $sql.=" SET fk_invoice_supplier_line = ".$rowidline; if ($rowidinvoice) $sql.=" SET fk_invoice_supplier = ".$rowidinvoice; } else { @@ -317,7 +369,7 @@ class DiscountAbsolute $resql = $this->db->query($sql); if ($resql) { - if($mode == 'supplier') { + if(! empty($this->discount_type)) { $this->fk_invoice_supplier_line=$rowidline; $this->fk_invoice_supplier=$rowidinvoice; } else { @@ -338,13 +390,12 @@ class DiscountAbsolute * Link the discount to a particular invoice line or a particular invoice. * Do not call this if discount is linked to a reconcialiated invoice * - * @param string $mode 'supplier' to unlink a supplier invoice, 'customer' instead * @return int <0 if KO, >0 if OK */ - function unlink_invoice($mode = 'customer') + function unlink_invoice() { $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - if($mode = 'supplier') { + if(! empty($this->discount_type)) { $sql.=" SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL"; } else { $sql.=" SET fk_facture_line = NULL, fk_facture = NULL"; @@ -368,14 +419,14 @@ class DiscountAbsolute /** * Return amount (with tax) of discounts currently available for a company, user or other criteria * - * @param Societe $company Object third party for filter - * @param User $user Filtre sur un user auteur des remises - * @param string $filter Filtre autre - * @param int $maxvalue Filter on max value for discount - * @param string $mode 'customer' = discounts the customer has, 'supplier' = discount i have at this supplier + * @param Societe $company Object third party for filter + * @param User $user Filtre sur un user auteur des remises + * @param string $filter Filtre autre + * @param int $maxvalue Filter on max value for discount + * @param int $discount_type 0 => customer discount, 1 => supplier discount * @return int <0 if KO, amount otherwise */ - function getAvailableDiscounts($company='', $user='',$filter='', $maxvalue=0, $mode='customer') + function getAvailableDiscounts($company='', $user='',$filter='', $maxvalue=0, $discount_type=0) { global $conf; @@ -383,8 +434,12 @@ class DiscountAbsolute //$sql = "SELECT rc.amount_ttc as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; $sql.= " WHERE rc.entity = " . $conf->entity; - if ($mode == 'supplier') $sql.= " AND (rc.fk_facture_source IS NULL AND rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available - else $sql.= " AND (rc.fk_invoice_supplier_source IS NULL AND rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available + $sql.= " AND rc.discount_type=".intval($discount_type); + if (! empty($discount_type)) { + $sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier + } else { + $sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer + } if (is_object($company)) $sql.= " AND rc.fk_soc = ".$company->id; if (is_object($user)) $sql.= " AND rc.fk_user = ".$user->id; if ($filter) $sql.=' AND ('.$filter.')'; diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 8a1cc6ac33c..e6ab69dff95 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -4220,10 +4220,10 @@ class Form * @param int $maxvalue Max value for lines that can be selected * @param string $more More string to add * @param int $hidelist 1=Hide list - * @param string $mode 'supplier' to list available discounts for suppliers, 'customer' instead + * @param int $discount_type 0 => customer discount, 1 => supplier discount * @return void */ - function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $mode='customer') + function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $discount_type=0) { global $conf,$langs; if ($htmlname != "none") @@ -4232,7 +4232,7 @@ class Form print ''; print ''; print '
    '; - if($mode == 'supplier') { + if(! empty($discount_type)) { if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { if (! $filter || $filter=="fk_invoice_supplier IS NOT NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice @@ -4260,11 +4260,10 @@ class Form if (empty($hidelist)) { print '
    '; - if($mode == 'supplier') { - $newfilter = 'fk_facture_source IS NULL AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Exclude customer discounts + $newfilter = 'discount_type='.intval($discount_type); + if(! empty($discount_type)) { $newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available } else { - $newfilter = 'fk_invoice_supplier_source IS NULL AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Exclude supplier discounts $newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available } if ($filter) $newfilter.=' AND ('.$filter.')'; @@ -4272,9 +4271,9 @@ class Form if ($nbqualifiedlines > 0) { print '   '; diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index b23c9af5fce..198954572d1 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -2672,7 +2672,7 @@ class SupplierInvoiceLine extends CommonObjectLine $this->error = $this->db->lasterror(); } } - + // TODO free discount linked to line as in customer invoice if (! $error) { $this->db->commit(); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index a397d40d147..e3c68177b41 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -133,7 +133,7 @@ if (empty($reshook)) $object->fetch_thirdparty(); $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder')); } - + var_dump($conf->global->MAIN_VERSION_LAST_UPGRADE, $conf->global->MAIN_VERSION_LAST_INSTALL); // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes') { @@ -272,7 +272,7 @@ if (empty($reshook)) { $discount = new DiscountAbsolute($db); $result = $discount->fetch(GETPOST("discountid")); - $discount->unlink_invoice('supplier'); + $discount->unlink_invoice(); } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) @@ -419,7 +419,7 @@ if (empty($reshook)) if (! $error) { - $result = $discount->link_to_invoice(0, $id, 'supplier'); + $result = $discount->link_to_invoice(0, $id); if ($result < 0) { setEventMessages($discount->error, $discount->errors, 'errors'); } @@ -486,6 +486,7 @@ if (empty($reshook)) else { setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors'); } + $discount->discount_type = 1; // Supplier discount $discount->fk_soc = $object->socid; $discount->fk_invoice_supplier_source = $object->id; @@ -1679,7 +1680,7 @@ if ($action == 'create') if ($societe->id > 0) { - $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 'supplier'); + $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); print $societe->getNomUrl(1); print ''; } @@ -2143,12 +2144,12 @@ else $filterabsolutediscount = "fk_invoice_supplier IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_invoice_supplier IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_invoice_supplier IS NOT NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filterabsolutediscount = "fk_invoice_supplier IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; $filtercreditnote = "fk_invoice_supplier IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } - $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 'supplier'); - $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 'supplier'); + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); @@ -2442,7 +2443,7 @@ else } else { // Discount available of type fixed amount (not credit note) print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 'supplier'); + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); } } else { if ($absolute_creditnote > 0) // If not, link will be added later @@ -2468,9 +2469,9 @@ else } else { // We can add a credit note on a down payment or standard invoice or situation invoice // There is credit notes discounts available if (! $absolute_discount) print '
    '; - // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 'supplier'); + // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 'supplier'); // We allow credit note even if amount is higher + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher } } if (! $absolute_discount && ! $absolute_creditnote) { diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 9bfe0bd2915..bfc2c79a679 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -35,3 +35,4 @@ ALTER TABLE llx_projet ADD COLUMN bill_time integer DEFAULT 0; ALTER TABLE llx_societe ADD COLUMN order_min_amount double(24,8) DEFAULT NULL AFTER outstanding_limit; ALTER TABLE llx_societe ADD COLUMN supplier_order_min_amount double(24,8) DEFAULT NULL AFTER order_min_amount; +ALTER TABLE llx_societe_remise_except ADD COLUMN discount_type integer DEFAULT 0 NOT NULL AFTER fk_soc; \ No newline at end of file diff --git a/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql b/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql index 148a8777915..525af592041 100644 --- a/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql +++ b/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql @@ -26,6 +26,7 @@ ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_fk_soc ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_fk_facture_line (fk_facture_line); ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_fk_facture (fk_facture); ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_fk_facture_source (fk_facture_source); +ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_discount_type (discount_type); ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_user FOREIGN KEY (fk_user) REFERENCES llx_user (rowid); diff --git a/htdocs/install/mysql/tables/llx_societe_remise_except.sql b/htdocs/install/mysql/tables/llx_societe_remise_except.sql index 3a19a026ca9..151e33d7f1e 100644 --- a/htdocs/install/mysql/tables/llx_societe_remise_except.sql +++ b/htdocs/install/mysql/tables/llx_societe_remise_except.sql @@ -23,7 +23,8 @@ create table llx_societe_remise_except ( rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id - fk_soc integer NOT NULL, -- client + fk_soc integer NOT NULL, -- customer or supplier + discount_type integer DEFAULT 0 NOT NULL, -- 0 => customer, 1 => supplier datec datetime, amount_ht double(24,8) NOT NULL, amount_tva double(24,8) DEFAULT 0 NOT NULL, diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 4adfae72258..2e980ba7ff8 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1661,13 +1661,14 @@ class Societe extends CommonObject /** * Add a discount for third party * - * @param float $remise Amount of discount - * @param User $user User adding discount - * @param string $desc Reason of discount - * @param float $tva_tx VAT rate + * @param float $remise Amount of discount + * @param User $user User adding discount + * @param string $desc Reason of discount + * @param float $tva_tx VAT rate + * @param int $discount_type 0 => customer discount, 1 => supplier discount * @return int <0 if KO, id of discount record if OK */ - function set_remise_except($remise, User $user, $desc, $tva_tx=0) + function set_remise_except($remise, User $user, $desc, $tva_tx=0, $discount_type=0) { global $langs; @@ -1693,11 +1694,13 @@ class Societe extends CommonObject $discount = new DiscountAbsolute($this->db); $discount->fk_soc=$this->id; + $discount->discount_type=$discount_type; $discount->amount_ht=price2num($remise,'MT'); $discount->amount_tva=price2num($remise*$tva_tx/100,'MT'); $discount->amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT'); $discount->tva_tx=price2num($tva_tx,'MT'); $discount->description=$desc; + $result=$discount->create($user); if ($result > 0) { @@ -1715,18 +1718,18 @@ class Societe extends CommonObject /** * Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe * - * @param User $user Filtre sur un user auteur des remises - * @param string $filter Filtre autre - * @param integer $maxvalue Filter on max value for discount - * @param string $mode 'supplier' to get available discounts for suppliers, 'customer' instead + * @param User $user Filtre sur un user auteur des remises + * @param string $filter Filtre autre + * @param integer $maxvalue Filter on max value for discount + * @param int $discount_type 0 => customer discount, 1 => supplier discount * @return int <0 if KO, Credit note amount otherwise */ - function getAvailableDiscounts($user='',$filter='',$maxvalue=0,$mode='customer') + function getAvailableDiscounts($user='',$filter='',$maxvalue=0,$discount_type=0) { require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discountstatic=new DiscountAbsolute($this->db); - $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue,$mode); + $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue,$discount_type); if ($result >= 0) { return $result; From bd486e4cabae60ec559f12a6b88495efc8081df2 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 10:29:36 +0100 Subject: [PATCH 022/413] FIX: remove var_dump --- htdocs/fourn/facture/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index e3c68177b41..3ab9e4e684c 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -133,7 +133,7 @@ if (empty($reshook)) $object->fetch_thirdparty(); $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder')); } - var_dump($conf->global->MAIN_VERSION_LAST_UPGRADE, $conf->global->MAIN_VERSION_LAST_INSTALL); + // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes') { From 905adab5176331c11b9936e06f8815723a06a272 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 11:23:59 +0100 Subject: [PATCH 023/413] NEW: supplier credit notes: display supplier discounts in supplier order card --- htdocs/commande/card.php | 7 ++-- htdocs/fourn/commande/card.php | 62 ++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 6e1d411d55e..a56dc6cd5ac 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -2038,8 +2038,7 @@ if ($action == 'create' && $user->rights->commande->creer) // Relative and absolute discounts if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final - // invoice + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; @@ -2056,8 +2055,8 @@ if ($action == 'create' && $user->rights->commande->creer) else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; - $absolute_discount = $soc->getAvailableDiscounts('', 'fk_facture_source IS NULL'); - $absolute_creditnote = $soc->getAvailableDiscounts('', 'fk_facture_source IS NOT NULL'); + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); if ($absolute_discount) { diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 81ea1a0f951..5c632530a8e 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1477,6 +1477,29 @@ if ($action=='create') } print ''; + if ($societe->id > 0) + { + // Discounts for third party + print '' . $langs->trans('Discounts') . ''; + if ($fourn->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print ' (' . $langs->trans("EditRelativeDiscount") . ')'; + print '. '; + print '
    '; + + $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); + + if ($absolute_discount) + print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); + else + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; + print '.'; + print ''; + } + // Ref supplier print ''.$langs->trans('RefSupplier').''; print ''; @@ -1857,6 +1880,45 @@ elseif (! empty($object->id)) print ''.$author->getNomUrl(1, '', 0, 0, 0).''; print ''; + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + } + + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + + print '' . $langs->trans('Discounts') . ''; + if ($societe->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print '. '; + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + if ($absolute_discount) { + if ($object->statut > CommandeFournisseur::STATUS_DRAFT) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + } else { + // Remise dispo de type remise fixe (not credit note) + print '
    '; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + } + } + if ($absolute_creditnote) { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; + } + if (! $absolute_discount && ! $absolute_creditnote) + print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + print ''; + // Conditions de reglement par defaut $langs->load('bills'); print ''; From d2bb6a790b2bc98a36ecc05012362dc4656be75d Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 11:45:57 +0100 Subject: [PATCH 024/413] NEW: supplier credit notes: display supplier discounts in supplier proposal card --- htdocs/fourn/commande/card.php | 2 +- htdocs/supplier_proposal/card.php | 62 +++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 5c632530a8e..798c6219356 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1481,7 +1481,7 @@ if ($action=='create') { // Discounts for third party print '' . $langs->trans('Discounts') . ''; - if ($fourn->remise_percent) + if ($societe->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); else print $langs->trans("CompanyHasNoRelativeDiscount"); diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index a5488959016..dcd15b61469 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1048,6 +1048,29 @@ if ($action == 'create') } print '' . "\n"; + if ($soc->id > 0) + { + // Discounts for third party + print '' . $langs->trans('Discounts') . ''; + if ($fourn->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print ' (' . $langs->trans("EditRelativeDiscount") . ')'; + print '. '; + print '
    '; + + $absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1); + + if ($absolute_discount) + print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); + else + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; + print '.'; + print ''; + } + // Terms of payment print '' . $langs->trans('PaymentConditionsShort') . ''; $form->select_conditions_paiements(GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $cond_reglement_id, 'cond_reglement_id', -1, 1); @@ -1387,6 +1410,45 @@ if ($action == 'create') print ''; + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + } + + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + + print ''; + // Payment term print ''; } + $remise_percent = $buyer->remise_percent; + if($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') { + $remise_percent = $seller->remise_supplier_percent; + } ?> - + situation_cycle_ref) { $coldisplay++; diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 60f745d95c7..1929c11a464 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -257,6 +257,19 @@ if ($object->id > 0) print ''; if($conf->global->MAIN_FEATURES_LEVEL > 0) { + // Relative discounts (Discounts-Drawbacks-Rebates) + print ''; + print ''; + // Absolute discounts (Discounts-Drawbacks-Rebates) print '\n"; - $stripeaccount = $stripe->GetStripeAccount($conf->entity); + $stripeaccount = $stripe->getStripeAccount($service); $txn = \Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripeaccount)); From 7a277a8d2b649d9ae98d18c58b28e35a410c6723 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 21:32:52 +0100 Subject: [PATCH 087/413] Debug list of charges. Compatible with the metadata FULLTAG used by dolibarr native online payment page. --- htdocs/langs/en_US/stripe.lang | 5 ++- htdocs/stripe/charge.php | 82 +++++++++++++++++++++++----------- 2 files changed, 61 insertions(+), 26 deletions(-) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 5c7b782f593..782c49ce61e 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -46,4 +46,7 @@ ExampleOfTestCreditCard=Example of credit card for test: %s (valid), %s (error C StripeGateways=Stripe gateways OAUTH_STRIPE_TEST_ID=Stripe Connect Client ID (ca_...) OAUTH_STRIPE_LIVE_ID=Stripe Connect Client ID (ca_...) -BankAccountForBankTransfer=Bank account for fund payouts \ No newline at end of file +BankAccountForBankTransfer=Bank account for fund payouts +StripeAccount=Stripe account +StripeChargeList=List of Stripe charges +StripeCustomer=Stripe customer id \ No newline at end of file diff --git a/htdocs/stripe/charge.php b/htdocs/stripe/charge.php index 9ba246cf9a8..2c937e318a4 100644 --- a/htdocs/stripe/charge.php +++ b/htdocs/stripe/charge.php @@ -18,6 +18,8 @@ // Put here all includes required by your class file require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; //require_once DOL_DOCUMENT_ROOT.'/core/lib/stripe.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; @@ -55,7 +57,8 @@ $pagenext = $page + 1; llxHeader('', $langs->trans("StripeChargeList")); $form = new Form($db); -$societestatic = new societe($db); +$societestatic = new Societe($db); +$memberstatic = new Adherent($db); $acc = new Account($db); $stripe=new Stripe($db); if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) @@ -92,12 +95,13 @@ if (!$rowid && $stripeaccount) print ''; print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); + print_liste_field_titre("StripeCustomer",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); print_liste_field_titre("Customer",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); print_liste_field_titre("Origin",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"","","",'align="center"',$sortfield,$sortorder); - print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"","","",'align="left"'); print_liste_field_titre("Type",$_SERVER["PHP_SELF"],"","","",'align="left"',$sortfield,$sortorder); print_liste_field_titre("Paid",$_SERVER["PHP_SELF"],"","","",'align="right"',$sortfield,$sortorder); + print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"","","",'align="left"'); print "\n"; print "\n"; @@ -107,21 +111,48 @@ if (!$rowid && $stripeaccount) //print $list; foreach ($list->data as $charge) { + // The metadata FULLTAG is defined by the online payment page + $FULLTAG=$charge->metadata->FULLTAG; + + // Save into $tmparray all metadata + $tmparray = dolExplodeIntoArray($FULLTAG,'.','='); + // Load origin object according to metadata + if (! empty($tmparray['CUS'])) + { + $societestatic->fetch($tmparray['CUS']); + } + else + { + $societestatic->id = 0; + } + if (! empty($tmparray['MEM'])) + { + $memberstatic->fetch($tmparray['MEM']); + } + else + { + $memberstatic->id = 0; + } + print ''; - $societestatic->fetch($charge->metadata->idcustomer); - $societestatic->id=$charge->metadata->idcustomer; - $societestatic->lastname=$obj->lastname; - $societestatic->firstname=$obj->firstname; - $societestatic->admin=$obj->admin; - $societestatic->login=$obj->login; - $societestatic->email=$obj->email; - $societestatic->societe_id=$obj->fk_soc; // Ref print "\n"; + // Stripe customer + print "\n"; // Employee - print "\n"; + print "\n"; // Origine print "\n"; - // Date payment + // Date payment print '\n"; - // Label payment - print "\n"; // Type print ''; // Amount print ""; + // Status + print "\n"; + print "\n"; } } else { From 489dde4db4c70c9555c9bd7d46ace9a03c447abe Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 22:26:42 +0100 Subject: [PATCH 088/413] Prepare database to store payment modes of customers --- .../install/mysql/migration/7.0.0-8.0.0.sql | 20 +++++++++ .../install/mysql/tables/llx_societe_rib.sql | 28 ++++++++++-- .../canvas/company/tpl/card_view.tpl.php | 2 +- .../canvas/individual/tpl/card_view.tpl.php | 2 +- htdocs/societe/class/societe.class.php | 20 ++++----- htdocs/societe/paymentmodes.php | 45 +++++++++++-------- htdocs/stripe/class/stripe.class.php | 6 ++- 7 files changed, 88 insertions(+), 35 deletions(-) diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index eb3c865c106..227562ea9bc 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -97,3 +97,23 @@ ALTER TABLE llx_c_payment_term CHANGE COLUMN rowid rowid INTEGER AUTO_INCREMENT ALTER TABLE llx_c_payment_term ADD UNIQUE INDEX uk_c_payment_term_code(entity, code); ALTER TABLE llx_oauth_token ADD COLUMN tokenstring text; + +-- Add field for payment modes +ALTER TABLE llx_societe_rib ADD COLUMN type varchar(32) DEFAULT 'ban' after rowid; +ALTER TABLE llx_societe_rib ADD COLUMN last_four varchar(4); +ALTER TABLE llx_societe_rib ADD COLUMN card_type varchar(255); +ALTER TABLE llx_societe_rib ADD COLUMN cvn varchar(255); +ALTER TABLE llx_societe_rib ADD COLUMN exp_date_month INTEGER; +ALTER TABLE llx_societe_rib ADD COLUMN exp_date_year INTEGER; +ALTER TABLE llx_societe_rib ADD COLUMN country_code varchar(10); +ALTER TABLE llx_societe_rib ADD COLUMN approved integer DEFAULT 0; +ALTER TABLE llx_societe_rib ADD COLUMN email varchar(255); +ALTER TABLE llx_societe_rib ADD COLUMN ending_date date; +ALTER TABLE llx_societe_rib ADD COLUMN max_total_amount_of_all_payments double(24,8); +ALTER TABLE llx_societe_rib ADD COLUMN preapproval_key varchar(255); +ALTER TABLE llx_societe_rib ADD COLUMN starting_date date; +ALTER TABLE llx_societe_rib ADD COLUMN total_amount_of_all_payments double(24,8); +ALTER TABLE llx_societe_rib ADD COLUMN stripe_card_ref varchar(128); +ALTER TABLE llx_societe_rib ADD COLUMN status integer NOT NULL DEFAULT 1; + + diff --git a/htdocs/install/mysql/tables/llx_societe_rib.sql b/htdocs/install/mysql/tables/llx_societe_rib.sql index 168a2803c9d..6157af37830 100644 --- a/htdocs/install/mysql/tables/llx_societe_rib.sql +++ b/htdocs/install/mysql/tables/llx_societe_rib.sql @@ -17,15 +17,19 @@ -- You should have received a copy of the GNU General Public License -- along with this program. If not, see . -- +-- Table with the payment modes of a thirdparty (BAN, Paypal, Card, ...) -- ============================================================================= create table llx_societe_rib ( rowid integer AUTO_INCREMENT PRIMARY KEY, + type varchar(32) DEFAULT 'ban', -- 'ban' or 'paypal' or 'card' or 'stripe' + label varchar(30), fk_soc integer NOT NULL, datec datetime, tms timestamp, - label varchar(30), + + -- For BAN bank varchar(255), -- bank name code_banque varchar(128), -- bank code code_guichet varchar(6), -- desk code @@ -37,10 +41,28 @@ create table llx_societe_rib proprio varchar(60), owner_address varchar(255), default_rib smallint NOT NULL DEFAULT 0, - + -- For BAN direct debit feature rum varchar(32), -- RUM value to use for SEPA generation date_rum date, -- Date of mandate frstrecur varchar(16) default 'FRST', -- 'FRST' or 'RECUR' - + --For credit card + last_four varchar(4), -- last 4 + card_type varchar(255), -- card type 'VISA', 'MC' , ... + cvn varchar(255), + exp_date_month INTEGER, + exp_date_year INTEGER, + country_code varchar(10), + --For Paypal + approved INTEGER DEFAULT 0, + email varchar(255), + ending_date date, + max_total_amount_of_all_payments double(24,8), + preapproval_key varchar(255), + starting_date date, + total_amount_of_all_payments double(24,8), + --For Stripe + stripe_card_ref varchar(128), -- 'card_...' + + status integer NOT NULL DEFAULT 1, -- 1=ACTIVE, 0=IN_TRASH import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/societe/canvas/company/tpl/card_view.tpl.php b/htdocs/societe/canvas/company/tpl/card_view.tpl.php index 3865e9b95a0..24ddfbaaaac 100644 --- a/htdocs/societe/canvas/company/tpl/card_view.tpl.php +++ b/htdocs/societe/canvas/company/tpl/card_view.tpl.php @@ -185,7 +185,7 @@ for ($i=1; $i<=4; $i++) { '; print '
    ' . $langs->trans('Discounts') . ''; + if ($soc->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print '. '; + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + if ($absolute_discount) { + if ($object->statut > SupplierProposal::STATUS_DRAFT) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + } else { + // Remise dispo de type remise fixe (not credit note) + print '
    '; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + } + } + if ($absolute_creditnote) { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; + } + if (! $absolute_discount && ! $absolute_creditnote) + print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + print '
    '; print ''; // TODO adapt text + print ''; print ''; if (! empty($user->fk_soc)) // No need to show this for external users { - print ''; // TODO adapt text + print ''; print ''; } @@ -307,12 +307,12 @@ if ($socid > 0) dol_print_error($db); } - print ''; // TODO adapt text + print ''; print ''; if (! empty($user->fk_soc)) // No need to show this for external users { - print ''; // TODO adapt text + print ''; print ''; } } @@ -330,9 +330,10 @@ if ($socid > 0) print '
    '; print '
    '; From 7367769ec36f96be619cc950cc3e5d6c14c64b61 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 11:59:51 +0100 Subject: [PATCH 025/413] FIX: supplier credit notes: use correct rights in supplier invoice card --- htdocs/fourn/facture/card.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 3ab9e4e684c..ace7ce0b1b7 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -268,7 +268,7 @@ if (empty($reshook)) } // Delete link of credit note to invoice - else if ($action == 'unlinkdiscount' && $user->rights->facture->creer) + else if ($action == 'unlinkdiscount' && $user->rights->fournisseur->facture->creer) { $discount = new DiscountAbsolute($db); $result = $discount->fetch(GETPOST("discountid")); @@ -326,12 +326,12 @@ if (empty($reshook)) } // Multicurrency Code - else if ($action == 'setmulticurrencycode' && $user->rights->facture->creer) { + else if ($action == 'setmulticurrencycode' && $user->rights->fournisseur->facture->creer) { $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha')); } // Multicurrency rate - else if ($action == 'setmulticurrencyrate' && $user->rights->facture->creer) { + else if ($action == 'setmulticurrencyrate' && $user->rights->fournisseur->facture->creer) { $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx', 'alpha'))); } @@ -385,7 +385,7 @@ if (empty($reshook)) $result=$object->update($user); if ($result < 0) dol_print_error($db,$object->error); } - elseif ($action == "setabsolutediscount" && $user->rights->facture->creer) + elseif ($action == "setabsolutediscount" && $user->rights->fournisseur->facture->creer) { // POST[remise_id] or POST[remise_id_for_payment] @@ -443,7 +443,7 @@ if (empty($reshook)) } } // Convertir en reduc - else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->rights->facture->creer) + else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { $object->fetch($id); $object->fetch_thirdparty(); @@ -3108,7 +3108,7 @@ else } // For standard invoice with excess paid - if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $user->rights->facture->creer && empty($discount->id)) + if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $user->rights->fournisseur->facture->creer && empty($discount->id)) { print ''; // TODO translation : trop-perçu => trop payé } From fa0c65e37ee1f35d1282ff8029616fd82d65186a Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 12:05:36 +0100 Subject: [PATCH 026/413] FIX: supplier credit notes: correctly handle discount split --- htdocs/comm/remx.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 072baa675fb..ad6c1f33a97 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -93,6 +93,12 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes') $newdiscount2->fk_facture=$discount->fk_facture; $newdiscount1->fk_facture_line=$discount->fk_facture_line; $newdiscount2->fk_facture_line=$discount->fk_facture_line; + $newdiscount1->fk_invoice_supplier_source=$discount->fk_invoice_supplier_source; + $newdiscount2->fk_invoice_supplier_source=$discount->fk_invoice_supplier_source; + $newdiscount1->fk_invoice_supplier=$discount->fk_invoice_supplier; + $newdiscount2->fk_invoice_supplier=$discount->fk_invoice_supplier; + $newdiscount1->fk_invoice_supplier_line=$discount->fk_invoice_supplier_line; + $newdiscount2->fk_invoice_supplier_line=$discount->fk_invoice_supplier_line; if ($discount->description == '(CREDIT_NOTE)' || $discount->description == '(DEPOSIT)') { $newdiscount1->description=$discount->description; @@ -107,6 +113,8 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes') $newdiscount2->fk_user=$discount->fk_user; $newdiscount1->fk_soc=$discount->fk_soc; $newdiscount2->fk_soc=$discount->fk_soc; + $newdiscount1->discount_type=$discount->discount_type; + $newdiscount2->discount_type=$discount->discount_type; $newdiscount1->datec=$discount->datec; $newdiscount2->datec=$discount->datec; $newdiscount1->tva_tx=$discount->tva_tx; From 924a9c392cd5cecf4c9e7666a9df38cf1e7f2037 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 12:30:32 +0100 Subject: [PATCH 027/413] FIX: supplier credit notes: hide relative discounts until supported --- htdocs/fourn/commande/card.php | 7 +++++-- htdocs/fourn/facture/card.php | 19 +++++++++++-------- htdocs/supplier_proposal/card.php | 9 ++++++--- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 798c6219356..c65b7d6cf60 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1479,6 +1479,7 @@ if ($action=='create') if ($societe->id > 0) { +/* // TODO handle supplier relative discount // Discounts for third party print '
    ' . $langs->trans('Discounts') . ''; if ($societe->remise_percent) @@ -1488,7 +1489,7 @@ if ($action=='create') print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
    '; - +*/ $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); if ($absolute_discount) @@ -1894,11 +1895,13 @@ elseif (! empty($object->id)) $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print '
    ' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount if ($societe->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; +*/ $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); @@ -1908,7 +1911,7 @@ elseif (! empty($object->id)) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); } else { // Remise dispo de type remise fixe (not credit note) - print '
    '; +// print '
    '; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); } } diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index ace7ce0b1b7..255c917b6a9 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1917,6 +1917,7 @@ if ($action == 'create') { // Discounts for third party print '
    ' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount if ($societe->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); else @@ -1924,6 +1925,7 @@ if ($action == 'create') print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
    '; +*/ if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); else @@ -2417,15 +2419,16 @@ else print '
    ' . $langs->trans('Discounts'); print ''; +/* // TODO handle supplier relative discount if ($societe->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); // print ' ('.$addrelativediscount.')'; - +*/ // Is there is commercial discount or down payment available ? if ($absolute_discount > 0) { - print '. '; +// print '. '; if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { if ($object->statut == 0) { print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); @@ -2433,7 +2436,7 @@ else } else { if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '
    ' . $text . '.
    '; + print '' . $text . '.
    '; } else { $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); $text2 = $langs->trans("AbsoluteDiscountUse"); @@ -2442,7 +2445,7 @@ else } } else { // Discount available of type fixed amount (not credit note) - print '
    '; +// print '
    '; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); } } else { @@ -2450,10 +2453,10 @@ else { if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) print ' (' . $addabsolutediscount . ')
    '; - else - print '. '; +// else +// print '. '; } else - print '. '; + print '. '; } // Is there credit notes availables ? if ($absolute_creditnote > 0) @@ -2468,7 +2471,7 @@ else } } else { // We can add a credit note on a down payment or standard invoice or situation invoice // There is credit notes discounts available - if (! $absolute_discount) print '
    '; +// if (! $absolute_discount) print '
    '; // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index dcd15b61469..ba78c78dade 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1050,16 +1050,17 @@ if ($action == 'create') if ($soc->id > 0) { +/* // TODO handle supplier relative discount // Discounts for third party print '
    ' . $langs->trans('Discounts') . ''; - if ($fourn->remise_percent) + if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); else print $langs->trans("CompanyHasNoRelativeDiscount"); print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
    '; - +*/ $absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1); if ($absolute_discount) @@ -1424,11 +1425,13 @@ if ($action == 'create') $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print '
    ' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; +*/ $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); @@ -1438,7 +1441,7 @@ if ($action == 'create') print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); } else { // Remise dispo de type remise fixe (not credit note) - print '
    '; +// print '
    '; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); } } From f5ad93b272cfcc0d699ee3b9130640520ff5b6d3 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 19 Feb 2018 15:52:07 +0100 Subject: [PATCH 028/413] NEW: supplier credit notes: handle Excess Paid + translation --- htdocs/comm/remx.php | 29 ++++++++++--------- htdocs/core/class/commonobject.class.php | 8 ++++- htdocs/core/class/discount.class.php | 6 ++-- htdocs/core/class/html.form.class.php | 2 +- htdocs/core/lib/doc.lib.php | 12 ++++++-- htdocs/core/lib/pdf.lib.php | 14 +++++++-- htdocs/core/tpl/objectline_view.tpl.php | 11 +++++-- .../fourn/class/fournisseur.facture.class.php | 2 ++ htdocs/fourn/facture/card.php | 10 +++---- htdocs/langs/en_US/bills.lang | 9 +++++- htdocs/langs/en_US/companies.lang | 6 ++-- htdocs/societe/consumption.php | 11 +++++-- 12 files changed, 85 insertions(+), 35 deletions(-) diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index ad6c1f33a97..177b4456912 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -276,12 +276,12 @@ if ($socid > 0) dol_print_error($db); } - print '
    '.$langs->trans("CustomerAbsoluteDiscountAllUsers").'
    '.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("CustomerAbsoluteDiscountMy").'
    '.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("CustomerAbsoluteDiscountAllUsers").'
    '.$langs->trans("SupplierAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("CustomerAbsoluteDiscountMy").'
    '.$langs->trans("SupplierAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '; if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print ''; - print ''; + print ''; + print ''; } print ''; print ''; - } - $db->free($resql); - print "
    '.$langs->trans('DiscountType').' '; - print '
    '.$langs->trans('DiscountType').' '; + print ' '; + print '
    '.$langs->trans("AmountHT").''; @@ -401,7 +402,7 @@ if ($socid > 0) if ($resql) { if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); // TODO translate + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); } print ''; print ''; @@ -536,7 +537,7 @@ if ($socid > 0) $resql=$db->query($sql); if ($resql) { - print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); // TODO translate + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); print '
    '; print ''; print ''; // Need 120+ for format with AM/PM @@ -585,7 +586,7 @@ if ($socid > 0) $facturefournstatic->id=$obj->fk_invoice_supplier_source; $facturefournstatic->ref=$obj->ref; $facturefournstatic->type=$obj->type; - print preg_replace('/\(EXCESS PAID\)/',$langs->trans("ExcessPaid"),$obj->description).' '.$facturefournstatic->getNomURl(1); // TODO translate ExcessPaid + print preg_replace('/\(EXCESS PAID\)/',$langs->trans("ExcessPaid"),$obj->description).' '.$facturefournstatic->getNomURl(1); print ''; } else @@ -705,7 +706,7 @@ if ($socid > 0) if ($resql2) { if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); // TODO translate + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); } print '
    '.$langs->trans("Date").'
    '; print ''; @@ -855,7 +856,7 @@ if ($socid > 0) if ($resql) $resql2=$db->query($sql2); if ($resql2) { - print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); // TODO translate + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); print '
    '; print ''; print ''; // Need 120+ for format with AM/PM @@ -934,12 +935,12 @@ if ($socid > 0) print $obj->description; print ''; } - print ''; // TODO adapt to supplier invoice of use getNomUrl + print ''; print ''; print ''; print ''; print ''; print ''; print ''; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index e45acea7675..5abf5e3a0e1 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -3963,7 +3963,13 @@ abstract class CommonObject $discount=new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } // TODO handle (EXCESS PAID) + } + elseif ($line->desc == '(EXCESS PAID)') + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0)); + } else { $this->tpl['description'] = dol_trunc($line->desc,60); diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index b62e35c183e..b71d84130a1 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -46,6 +46,7 @@ class DiscountAbsolute public $fk_facture; // Id invoice when a discount line is used into an invoice (for credit note) public $fk_facture_source; // Id facture avoir a l'origine de la remise public $ref_facture_source; // Ref facture avoir a l'origine de la remise + public $ref_invoive_supplier_source; /** * Constructor @@ -568,10 +569,11 @@ class DiscountAbsolute $result=''; if ($option == 'invoice') { + $facid=! empty($this->discount_type)?$this->fk_invoice_supplier_source:$this->fk_facture_source; $label=$langs->trans("ShowDiscount").': '.$this->ref_facture_source; - $link = ''; + $link = ''; $linkend=''; - $ref=$this->ref_facture_source; + $ref=! empty($this->discount_type)?$this->ref_invoice_supplier_source:$this->ref_facture_source; $picto='bill'; } if ($option == 'discount') { diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index e6ab69dff95..f65a3bec36c 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -1236,7 +1236,7 @@ class Form if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc); if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc); if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc); - // TODO handle (EXCESS PAID) + if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc=preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc); $selectstring=''; if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected'; diff --git a/htdocs/core/lib/doc.lib.php b/htdocs/core/lib/doc.lib.php index 20eaa9a71f7..447c7c2149e 100644 --- a/htdocs/core/lib/doc.lib.php +++ b/htdocs/core/lib/doc.lib.php @@ -73,13 +73,15 @@ function doc_getlinedesc($line,$outputlangs,$hideref=0,$hidedesc=0,$issupplierli { $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); - $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$discount->ref_facture_source); + $sourceref=!empty($discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$sourceref); } elseif ($desc == '(DEPOSIT)' && $line->fk_remise_except) { $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$discount->ref_facture_source); + $sourceref=!empty($discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; // Add date of deposit if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) $libelleproduitservice.=' ('.dol_print_date($discount->datec,'day','',$outputlangs).')'; } @@ -88,7 +90,13 @@ function doc_getlinedesc($line,$outputlangs,$hideref=0,$hidedesc=0,$issupplierli $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source); - } // TODO handle (EXCESS PAID) + } + elseif ($desc == '(EXCESS PAID)' && $line->fk_remise_except) + { + $discount=new DiscountAbsolute($db); + $discount->fetch($line->fk_remise_except); + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid",$discount->ref_invoice_supplier_source); + } else { if ($idprod) diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php index 0fb649506cb..31fcc519051 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -1236,13 +1236,15 @@ function pdf_getlinedesc($object,$i,$outputlangs,$hideref=0,$hidedesc=0,$issuppl { $discount=new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); - $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$discount->ref_facture_source); + $sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$sourceref); } elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except) { $discount=new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); - $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$discount->ref_facture_source); + $sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$sourceref); // Add date of deposit if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec,'day','',$outputlangs).')'; } @@ -1251,7 +1253,13 @@ function pdf_getlinedesc($object,$i,$outputlangs,$hideref=0,$hidedesc=0,$issuppl $discount=new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source); - } // TODO handle (EXCESS PAID) + } + elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except) + { + $discount=new DiscountAbsolute($db); + $discount->fetch($object->lines[$i]->fk_remise_except); + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid",$discount->ref_invoice_supplier_source); + } else { if ($idprod) diff --git a/htdocs/core/tpl/objectline_view.tpl.php b/htdocs/core/tpl/objectline_view.tpl.php index bc5d950ab8e..6371e289207 100644 --- a/htdocs/core/tpl/objectline_view.tpl.php +++ b/htdocs/core/tpl/objectline_view.tpl.php @@ -72,7 +72,8 @@ if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0; $txt=''; print img_object($langs->trans("ShowReduc"),'reduc').' '; if ($line->description == '(DEPOSIT)') $txt=$langs->trans("Deposit"); - elseif ($line->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); // TODO handle (EXCESS PAID) + elseif ($line->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); + elseif ($line->description == '(EXCESS PAID)') $txt=$langs->trans("ExcessPaid"); //else $txt=$langs->trans("Discount"); print $txt; ?> @@ -100,7 +101,13 @@ if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0; $discount=new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); echo ($txt?' - ':'').$langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } // TODO handle (EXCESS PAID) + } + elseif ($line->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + echo ($txt?' - ':'').$langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0)); + } else { echo ($txt?' - ':'').dol_htmlentitiesbr($line->description); diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 3fe59d66ff7..4ebab7d0bc4 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -1049,6 +1049,8 @@ class FactureFournisseur extends CommonInvoice } } + // TODO Delete related discounts + if (! $error) { // Delete linked object diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 255c917b6a9..ca29e7299a6 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2167,10 +2167,10 @@ else // Confirmation de la conversion de l'avoir en reduc if ($action == 'converttoreduc') { - if($object->type == FactureFournisseur::TYPE_STANDARD) $type_fac = 'ExcessReceived'; // TODO translation trop-perçu => trop-payé + if($object->type == FactureFournisseur::TYPE_STANDARD) $type_fac = 'ExcessPaid'; elseif($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $type_fac = 'CreditNote'; elseif($object->type == FactureFournisseur::TYPE_DEPOSIT) $type_fac = 'Deposit'; - $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac))); // TODO translation client => fournisseur + $text = $langs->trans('ConfirmConvertToReducSupplier', strtolower($langs->transnoentities($type_fac))); $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2); } @@ -2872,7 +2872,7 @@ else print ' :'; print ''; print ''; $i ++; if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) @@ -2929,7 +2929,7 @@ else if ($resteapayeraffiche >= 0) print $langs->trans('RemainderToPay'); else - print $langs->trans('ExcessReceived'); + print $langs->trans('ExcessPaid'); print ' :'; print ''; print ''; @@ -3113,7 +3113,7 @@ else // For standard invoice with excess paid if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $user->rights->fournisseur->facture->creer && empty($discount->id)) { - print ''; // TODO translation : trop-perçu => trop payé + print ''; } // For credit note if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->fournisseur->facture->creer && $object->getSommePaiement() == 0) { diff --git a/htdocs/langs/en_US/bills.lang b/htdocs/langs/en_US/bills.lang index 668090129ff..62386adbe99 100644 --- a/htdocs/langs/en_US/bills.lang +++ b/htdocs/langs/en_US/bills.lang @@ -67,6 +67,7 @@ PaidBack=Paid back DeletePayment=Delete payment ConfirmDeletePayment=Are you sure you want to delete this payment? ConfirmConvertToReduc=Do you want to convert this %s into an absolute discount ?
    The amount will so be saved among all discounts and could be used as a discount for a current or a future invoice for this customer. +ConfirmConvertToReducSupplier=Do you want to convert this %s into an absolute discount ?
    The amount will so be saved among all discounts and could be used as a discount for a current or a future invoice for this supplier. SupplierPayments=Suppliers payments ReceivedPayments=Received payments ReceivedCustomersPayments=Payments received from customers @@ -91,7 +92,7 @@ PaymentAmount=Payment amount ValidatePayment=Validate payment PaymentHigherThanReminderToPay=Payment higher than reminder to pay HelpPaymentHigherThanReminderToPay=Attention, the payment amount of one or more bills is higher than the rest to pay.
    Edit your entry, otherwise confirm and think about creating a credit note of the excess received for each overpaid invoices. -HelpPaymentHigherThanReminderToPaySupplier=Attention, the payment amount of one or more bills is higher than the rest to pay.
    Edit your entry, otherwise confirm. +HelpPaymentHigherThanReminderToPaySupplier=Attention, the payment amount of one or more bills is higher than the rest to pay.
    Edit your entry, otherwise confirm and think about creating a credit note of the excess paid for each overpaid invoice. ClassifyPaid=Classify 'Paid' ClassifyPaidPartially=Classify 'Paid partially' ClassifyCanceled=Classify 'Abandoned' @@ -110,6 +111,7 @@ DoPayment=Enter payment DoPaymentBack=Enter refund ConvertToReduc=Convert into future discount ConvertExcessReceivedToReduc=Convert excess received into future discount +ConvertExcessPaidToReduc=Convert excess paid into future discount EnterPaymentReceivedFromCustomer=Enter payment received from customer EnterPaymentDueToCustomer=Make payment due to customer DisabledBecauseRemainderToPayIsZero=Disabled because remaining unpaid is zero @@ -220,6 +222,7 @@ RemainderToPayBack=Remaining amount to refund Rest=Pending AmountExpected=Amount claimed ExcessReceived=Excess received +ExcessPaid=Excess paid EscompteOffered=Discount offered (payment before term) EscompteOfferedShort=Discount SendBillRef=Submission of invoice %s @@ -284,15 +287,19 @@ Deposits=Down payments DiscountFromCreditNote=Discount from credit note %s DiscountFromDeposit=Down payments from invoice %s DiscountFromExcessReceived=Payments from excess received of invoice %s +DiscountFromExcessPaid=Payments from excess paid of invoice %s AbsoluteDiscountUse=This kind of credit can be used on invoice before its validation CreditNoteDepositUse=Invoice must be validated to use this kind of credits NewGlobalDiscount=New absolute discount NewRelativeDiscount=New relative discount +DiscountType=Discount type NoteReason=Note/Reason ReasonDiscount=Reason DiscountOfferedBy=Granted by DiscountStillRemaining=Discounts available DiscountAlreadyCounted=Discounts already consumed +CustomerDiscounts=Customer discounts +SupplierDiscounts=Supplier discounts BillAddress=Bill address HelpEscompte=This discount is a discount granted to customer because its payment was made before term. HelpAbandonBadCustomer=This amount has been abandoned (customer said to be a bad customer) and is considered as an exceptional loose. diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index 7d2b878c5cc..2eb1ba88e57 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -271,8 +271,10 @@ CompanyHasAbsoluteDiscount=This customer has discount available (credits notes o CompanyHasDownPaymentOrCommercialDiscount=This customer has discount available (commercial, down payments) for %s %s CompanyHasCreditNote=This customer still has credit notes for %s %s CompanyHasNoAbsoluteDiscount=This customer has no discount credit available -CustomerAbsoluteDiscountAllUsers=Absolute discounts (granted by all users) -CustomerAbsoluteDiscountMy=Absolute discounts (granted by yourself) +CustomerAbsoluteDiscountAllUsers=Absolute customer discounts (granted by all users) +CustomerAbsoluteDiscountMy=Absolute customer discounts (granted by yourself) +SupplierAbsoluteDiscountAllUsers=Absolute supplier discounts (granted by all users) +SupplierAbsoluteDiscountMy=Absolute supplier discounts (granted by yourself) DiscountNone=None Supplier=Supplier AddContact=Create contact diff --git a/htdocs/societe/consumption.php b/htdocs/societe/consumption.php index 1420562da19..1a6a4be6199 100644 --- a/htdocs/societe/consumption.php +++ b/htdocs/societe/consumption.php @@ -490,7 +490,8 @@ if ($sql_select) $txt=''; print img_object($langs->trans("ShowReduc"),'reduc').' '; if ($objp->description == '(DEPOSIT)') $txt=$langs->trans("Deposit"); - elseif ($objp->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); // TODO handle (EXCESS PAID) + elseif ($objp->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); + elseif ($objp->description == '(EXCESS PAID)') $txt=$langs->trans("ExcessPaid"); //else $txt=$langs->trans("Discount"); print $txt; ?> @@ -510,6 +511,12 @@ if ($sql_select) $discount->fetch($objp->fk_remise_except); echo ($txt?' - ':'').$langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); } + elseif ($objp->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) + { + $discount=new DiscountAbsolute($db); + $discount->fetch($objp->fk_remise_except); + echo ($txt?' - ':'').$langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0)); + } elseif ($objp->description == '(DEPOSIT)' && $objp->fk_remise_except > 0) { $discount=new DiscountAbsolute($db); @@ -517,7 +524,7 @@ if ($sql_select) echo ($txt?' - ':'').$langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); // Add date of deposit if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec).')'; - } // TODO handle (EXCESS PAID) + } else { echo ($txt?' - ':'').dol_htmlentitiesbr($objp->description); From 57b8df400806f726946cb4ccca55f44dac548dc8 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 19 Feb 2018 17:32:11 +0100 Subject: [PATCH 029/413] FIX: supplier credit notes: delete discount when deleting linked invoice/invoice line --- .../fourn/class/fournisseur.facture.class.php | 68 +++++++++++++++++-- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 4ebab7d0bc4..570966d8600 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -925,13 +925,14 @@ class FactureFournisseur extends CommonInvoice } $facligne=new SupplierInvoiceLine($this->db); - $facligne->fk_facture=$this->id; + $facligne->fk_facture_fourn=$this->id; $facligne->fk_remise_except=$remise->id; $facligne->desc=$remise->description; // Description ligne $facligne->vat_src_code=$remise->vat_src_code; $facligne->tva_tx=$remise->tva_tx; $facligne->subprice = -$remise->amount_ht; $facligne->fk_product=0; // Id produit predefini + $facligne->product_type=0; $facligne->qty=1; $facligne->remise_percent=0; $facligne->rang=-1; @@ -1030,6 +1031,33 @@ class FactureFournisseur extends CommonInvoice // Fin appel triggers } + if (! $error) { + // If invoice was converted into a discount not yet consumed, we remove discount + $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . 'societe_remise_except'; + $sql .= ' WHERE fk_invoice_supplier_source = ' . $rowid; + $sql .= ' AND fk_invoice_supplier_line IS NULL'; + $resql = $this->db->query($sql); + + // If invoice has consumned discounts + $this->fetch_lines(); + $list_rowid_det = array (); + foreach ($this->lines as $key => $invoiceline) { + $list_rowid_det[] = $invoiceline->rowid; + } + + // Consumned discounts are freed + if (count($list_rowid_det)) { + $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'societe_remise_except'; + $sql .= ' SET fk_invoice_supplier = NULL, fk_invoice_supplier_line = NULL'; + $sql .= ' WHERE fk_invoice_supplier_line IN (' . join(',', $list_rowid_det) . ')'; + + dol_syslog(get_class($this) . "::delete", LOG_DEBUG); + if (! $this->db->query($sql)) { + $error ++; + } + } + } + if (! $error) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';'; @@ -1049,8 +1077,6 @@ class FactureFournisseur extends CommonInvoice } } - // TODO Delete related discounts - if (! $error) { // Delete linked object @@ -1769,6 +1795,22 @@ class FactureFournisseur extends CommonInvoice $rowid = $this->id; } + $this->db->begin(); + + // Libere remise liee a ligne de facture + $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'societe_remise_except'; + $sql .= ' SET fk_invoice_supplier_line = NULL'; + $sql .= ' WHERE fk_invoice_supplier_line = ' . $rowid; + + dol_syslog(get_class($this) . "::deleteline", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) + { + $this->error = $this->db->error(); + $this->db->rollback(); + return - 2; + } + $line = new SupplierInvoiceLine($this->db); if ($line->fetch($rowid) < 1) { @@ -1778,12 +1820,24 @@ class FactureFournisseur extends CommonInvoice $res = $line->delete($notrigger); if ($res < 1) { - $this->errors[] = $line->error; + $this->errors[] = $line->error; + $this->db->rollback(); + return - 3; } else { - $res = $this->update_price(); - } + $res = $this->update_price(); - return $res; + if ($res > 0) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + return - 4; + } + } } From a66f7b8bc84428b5c285b46cb2d93d4779226558 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 19 Feb 2018 17:32:59 +0100 Subject: [PATCH 030/413] FIX: supplier credit notes: wrong discount filters --- htdocs/compta/facture/card.php | 8 ++++---- htdocs/fourn/facture/card.php | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index df5e78b8712..ab75eaa86de 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -2989,11 +2989,11 @@ else if ($id > 0 || ! empty($ref)) $resteapayeraffiche = $resteapayer; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this - $filterabsolutediscount = "fk_facture IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_facture IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_facture IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; - $filtercreditnote = "fk_facture IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index ca29e7299a6..fa046a7a97c 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2143,11 +2143,11 @@ else $resteapayeraffiche = $resteapayer; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this - $filterabsolutediscount = "fk_invoice_supplier IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_invoice_supplier IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_invoice_supplier IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; - $filtercreditnote = "fk_invoice_supplier IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source NOT IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); From bcb39e57fb45ad0a85875e4bcae6eba18cef1799 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Tue, 20 Feb 2018 10:08:55 +0100 Subject: [PATCH 031/413] FIX: supplier credit notes: wrong credit note filter --- htdocs/fourn/facture/card.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index fa046a7a97c..d9fcf57a4a6 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2147,7 +2147,7 @@ else $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; - $filtercreditnote = "fk_invoice_supplier_source NOT IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); @@ -2426,6 +2426,7 @@ else print $langs->trans("CompanyHasNoRelativeDiscount"); // print ' ('.$addrelativediscount.')'; */ + // Is there is commercial discount or down payment available ? if ($absolute_discount > 0) { // print '. '; From a4f2a2532de1a07670e6b1662b062deb353a92ca Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Tue, 20 Feb 2018 11:41:57 +0100 Subject: [PATCH 032/413] FIX: supplier credit notes: use MAIN_FEATURES_LEVEL --- htdocs/fourn/commande/card.php | 77 ++++++----- htdocs/fourn/facture/card.php | 217 +++++++++++++++--------------- htdocs/supplier_proposal/card.php | 81 +++++------ 3 files changed, 193 insertions(+), 182 deletions(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index c65b7d6cf60..6cd17690c24 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1477,7 +1477,7 @@ if ($action=='create') } print ''; - if ($societe->id > 0) + if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $societe->id > 0) { /* // TODO handle supplier relative discount // Discounts for third party @@ -1881,46 +1881,49 @@ elseif (! empty($object->id)) print ''; print ''; - // Relative and absolute discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; - } + if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - - print ''; } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; - print ''; // Conditions de reglement par defaut $langs->load('bills'); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index d9fcf57a4a6..0344890458b 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1913,7 +1913,7 @@ if ($action == 'create') print ''; - if ($societe->id > 0) + if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $societe->id > 0) { // Discounts for third party print ''; - - // Relative and absolute discounts - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; - - print ''; - + // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) + // { + // if (! $absolute_discount && ! $absolute_creditnote) print '
    '; + // print '   -   '; + // print $addabsolutediscount; + // print '   -   '.$addcreditnote; // We disbale link to credit note + // } + print ''; + } + // Label print ''; print ''; @@ -2852,37 +2855,39 @@ else $creditnoteamount = 0; $depositamount = 0; - $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql .= " re.description, re.fk_invoice_supplier_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; - $sql .= " WHERE fk_invoice_supplier = " . $object->id; - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - $invoice = new FactureFournisseur($db); - while ($i < $num) { - $obj = $db->fetch_object($resql); - $invoice->fetch($obj->fk_invoice_supplier_source); - print ''; - print ''; - print ''; - $i ++; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - $creditnoteamount += $obj->amount_ttc; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) - $depositamount += $obj->amount_ttc; + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; + $sql .= " re.description, re.fk_invoice_supplier_source"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; + $sql .= " WHERE fk_invoice_supplier = " . $object->id; + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + $invoice = new FactureFournisseur($db); + while ($i < $num) { + $obj = $db->fetch_object($resql); + $invoice->fetch($obj->fk_invoice_supplier_source); + print ''; + print ''; + print ''; + $i ++; + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + $creditnoteamount += $obj->amount_ttc; + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + $depositamount += $obj->amount_ttc; + } + } else { + dol_print_error($db); } - } else { - dol_print_error($db); } @@ -3097,7 +3102,7 @@ else } // Reverse back money or convert to reduction - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) { + if ($conf->global->MAIN_FEATURES_LEVEL > 0 && ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD)) { // For credit note only if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) { diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index ba78c78dade..17e5a2be199 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1048,11 +1048,11 @@ if ($action == 'create') } print '' . "\n"; - if ($soc->id > 0) + if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $soc->id > 0) { -/* // TODO handle supplier relative discount // Discounts for third party - print ''; print ''; + dol_print_error($db); } - - print "
    '.$langs->trans("Date").''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; - print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; // TODO getNomUrl ? + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; print ' 
    ' . price($obj->amount_ttc) . ''; - print 'rowid . '">' . img_delete() . ''; // TODO unlinkdiscount + print 'rowid . '">' . img_delete() . ''; print '
    ' . price($resteapayeraffiche) . ' 
    '.$author->getNomUrl(1, '', 0, 0, 0).'
    ' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; -*/ - $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); - $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); - $absolute_discount = price2num($absolute_discount, 'MT'); - $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > CommandeFournisseur::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - // Remise dispo de type remise fixe (not credit note) -// print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; } + + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + + print '
    ' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount + if ($societe->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print '. '; +*/ + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + if ($absolute_discount) { + if ($object->statut > CommandeFournisseur::STATUS_DRAFT) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + } else { + // Remise dispo de type remise fixe (not credit note) +// print '
    '; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + } + } + if ($absolute_creditnote) { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; + } + if (! $absolute_discount && ! $absolute_creditnote) + print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + print '
    ' . $langs->trans('Discounts') . ''; @@ -2410,90 +2410,93 @@ else print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')'; } print '
    ' . $langs->trans('Discounts'); - print ''; -/* // TODO handle supplier relative discount - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - // print ' ('.$addrelativediscount.')'; -*/ - // Is there is commercial discount or down payment available ? - if ($absolute_discount > 0) { -// print '. '; - if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - if ($object->statut == 0) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '. '; - } else { - if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '' . $text . '.
    '; + if ($conf->global->MAIN_FEATURES_LEVEL > 0) { + + // Relative and absolute discounts + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; + + print '
    ' . $langs->trans('Discounts'); + print ''; +/* // TODO handle supplier relative discount + if ($societe->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print ' ('.$addrelativediscount.')'; +*/ + + // Is there is commercial discount or down payment available ? + if ($absolute_discount > 0) { +// print '. '; + if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + if ($object->statut == 0) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + print '. '; } else { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - $text2 = $langs->trans("AbsoluteDiscountUse"); - print $form->textwithpicto($text, $text2); + if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + print '' . $text . '.
    '; + } else { + $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + $text2 = $langs->trans("AbsoluteDiscountUse"); + print $form->textwithpicto($text, $text2); + } } + } else { + // Discount available of type fixed amount (not credit note) +// print '
    '; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); } } else { - // Discount available of type fixed amount (not credit note) -// print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); + if ($absolute_creditnote > 0) // If not, link will be added later + { + if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) + print ' (' . $addabsolutediscount . ')
    '; +// else +// print '. '; + } else + print '. '; } - } else { - if ($absolute_creditnote > 0) // If not, link will be added later + // Is there credit notes availables ? + if ($absolute_creditnote > 0) { + // If validated, we show link "add credit note to payment" + if ($object->statut != FactureFournisseur::STATUS_VALIDATED || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + if ($object->statut == 0 && $object->type != FactureFournisseur::TYPE_DEPOSIT) { + $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); + print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); + } else { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; + } + } else { // We can add a credit note on a down payment or standard invoice or situation invoice + // There is credit notes discounts available +// if (! $absolute_discount) print '
    '; + // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); + $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher + } + } + if (! $absolute_discount && ! $absolute_creditnote) { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) print ' (' . $addabsolutediscount . ')
    '; -// else -// print '. '; - } else - print '. '; - } - // Is there credit notes availables ? - if ($absolute_creditnote > 0) - { - // If validated, we show link "add credit note to payment" - if ($object->statut != FactureFournisseur::STATUS_VALIDATED || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { - if ($object->statut == 0 && $object->type != FactureFournisseur::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); - print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); - } else { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; - } - } else { // We can add a credit note on a down payment or standard invoice or situation invoice - // There is credit notes discounts available -// if (! $absolute_discount) print '
    '; - // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); - $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher + else + print '. '; } - } - if (! $absolute_discount && ! $absolute_creditnote) { - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
    '; - else - print '. '; - } - // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) - // { - // if (! $absolute_discount && ! $absolute_creditnote) print '
    '; - // print '   -   '; - // print $addabsolutediscount; - // print '   -   '.$addcreditnote; // We disbale link to credit note - // } - print '
    '.$form->editfieldkey("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).'
    '; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - print $langs->trans("CreditNote") . ' '; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) - print $langs->trans("Deposit") . ' '; - print $invoice->getNomUrl(0); - print ' :' . price($obj->amount_ttc) . ''; - print 'rowid . '">' . img_delete() . ''; - print '
    '; + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + print $langs->trans("CreditNote") . ' '; + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + print $langs->trans("Deposit") . ' '; + print $invoice->getNomUrl(0); + print ' :' . price($obj->amount_ttc) . ''; + print 'rowid . '">' . img_delete() . ''; + print '
    ' . $langs->trans('Discounts') . ''; + print '
    ' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); else @@ -1411,46 +1411,49 @@ if ($action == 'create') print ''; - // Relative and absolute discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; - } + if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - - print ''; } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; - print ''; // Payment term print '
    ' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; -*/ - $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); - $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); - $absolute_discount = price2num($absolute_discount, 'MT'); - $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > SupplierProposal::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - // Remise dispo de type remise fixe (not credit note) -// print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; } + + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + + print '
    ' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount + if ($soc->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print '. '; +*/ + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + if ($absolute_discount) { + if ($object->statut > SupplierProposal::STATUS_DRAFT) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + } else { + // Remise dispo de type remise fixe (not credit note) +// print '
    '; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + } + } + if ($absolute_creditnote) { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; + } + if (! $absolute_discount && ! $absolute_creditnote) + print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + print '
    '; From 95be1550100ff94cc1a1529c21dccbb536f5452f Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Tue, 20 Feb 2018 12:26:29 +0100 Subject: [PATCH 033/413] FIX: supplier credit notes: harmonize discount filters --- htdocs/comm/card.php | 2 +- htdocs/comm/propal/card.php | 15 +++++++++++---- htdocs/commande/card.php | 4 ++-- htdocs/compta/facture/prelevement.php | 16 ++++++++++++---- htdocs/core/class/html.form.class.php | 12 ++++++------ htdocs/expedition/shipment.php | 14 +++++++++++--- htdocs/fourn/commande/card.php | 4 ++-- htdocs/societe/class/api_thirdparties.class.php | 10 ++++++++-- htdocs/supplier_proposal/card.php | 4 ++-- 9 files changed, 55 insertions(+), 26 deletions(-) diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index d732a10a347..81443f04d62 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -392,7 +392,7 @@ if ($object->id > 0) print '
    '; print '
    '; - $amount_discount=$object->getAvailableDiscounts(); // TODO adapt to supplier discounts + $amount_discount=$object->getAvailableDiscounts(); if ($amount_discount < 0) dol_print_error($db,$object->error); if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; //else print $langs->trans("DiscountNone"); diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 54e3cf36c45..4291b22508d 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -1873,14 +1873,22 @@ if ($action == 'create') print ''; // Link for thirdparty discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + } + print ''; - } - $db->free($resql); - print "
    ' . $langs->trans('Discounts') . ''; if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; - $absolute_discount = $soc->getAvailableDiscounts('', 'fk_facture_source IS NULL'); - $absolute_creditnote = $soc->getAvailableDiscounts('', 'fk_facture_source IS NOT NULL'); + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); if ($absolute_discount) { @@ -1888,9 +1896,8 @@ if ($action == 'create') print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount, 0, $langs, 0, 0, -1, $conf->currency)); } else { // Remise dispo de type non avoir - $filter = 'fk_facture_source IS NULL'; print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filter, 0, '', 1); + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1); } } if ($absolute_creditnote) { diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index a56dc6cd5ac..6cd21df9c78 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -2041,8 +2041,8 @@ if ($action == 'create' && $user->rights->commande->creer) $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_facture_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 989e742afee..6065ad9cd6f 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -140,8 +140,16 @@ if ($object->id > 0) if ($object->paye) $resteapayer=0; $resteapayeraffiche=$resteapayer; - $absolute_discount=$object->thirdparty->getAvailableDiscounts('','fk_facture_source IS NULL'); - $absolute_creditnote=$object->thirdparty->getAvailableDiscounts('','fk_facture_source IS NOT NULL'); + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + } + + $absolute_discount=$object->thirdparty->getAvailableDiscounts('',$filterabsolutediscount); + $absolute_creditnote=$object->thirdparty->getAvailableDiscounts('',$filtercreditnote); $absolute_discount=price2num($absolute_discount,'MT'); $absolute_creditnote=price2num($absolute_creditnote,'MT'); @@ -282,7 +290,7 @@ if ($object->id > 0) else { // Remise dispo de type non avoir - $filter='fk_facture_source IS NULL'; + $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NULL':"fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; print '
    '; $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$object->thirdparty->id,$absolute_discount,$filter,$resteapayer,'',1); } @@ -302,7 +310,7 @@ if ($object->id > 0) else { // Remise dispo de type avoir - $filter='fk_facture_source IS NOT NULL'; + $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NOT NULL':"fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; if (! $absolute_discount) print '
    '; $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id_for_payment',$object->thirdparty->id,$absolute_creditnote,$filter,$resteapayer,'',1); } diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index f65a3bec36c..aafe9b81cc1 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -4235,23 +4235,23 @@ class Form if(! empty($discount_type)) { if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - if (! $filter || $filter=="fk_invoice_supplier IS NOT NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice + if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); } else { - if (! $filter || $filter=="fk_invoice_supplier IS NOT NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); } } else { if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - if (! $filter || $filter=="fk_facture IS NOT NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice + if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); } else { - if (! $filter || $filter=="fk_facture IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); } } @@ -4271,9 +4271,9 @@ class Form if ($nbqualifiedlines > 0) { print '   '; diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index a358d349531..cf0cc1d6d24 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -329,12 +329,20 @@ if ($id > 0 || ! empty($ref)) print ''; // Discounts for third party + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + } + print '"; print ''; + + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + // Absolute discounts (Discounts-Drawbacks-Rebates) + print ''; + print ''; + print ''; + } print ''; print ''; if ($conf->global->MAIN_FEATURES_LEVEL > 0) { From 876ea3198f735e511a8d1aa47680a908c256065e Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 21 Feb 2018 17:51:44 +0100 Subject: [PATCH 037/413] FIX: handle type in supplier invoice list --- htdocs/fourn/facture/list.php | 49 ++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index 31d6ba2f183..75dee1422d2 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -76,6 +76,7 @@ $search_amount_all_tax = GETPOST("search_amount_all_tax","alpha"); $search_product_category=GETPOST('search_product_category','int'); $search_ref=GETPOST('sf_ref')?GETPOST('sf_ref','alpha'):GETPOST('search_ref','alpha'); $search_refsupplier=GETPOST('search_refsupplier','alpha'); +$search_type=GETPOST('search_type','int'); $search_project=GETPOST('search_project','alpha'); $search_societe=GETPOST('search_societe','alpha'); $search_montant_ht=GETPOST('search_montant_ht','alpha'); @@ -148,6 +149,7 @@ $checkedtypetiers=0; $arrayfields=array( 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'f.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), + 'f.type'=>array('label'=>$langs->trans("Type"), 'checked'=>0), 'f.label'=>array('label'=>$langs->trans("Label"), 'checked'=>0), 'f.datef'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), @@ -203,6 +205,7 @@ if (empty($reshook)) $search_product_category=''; $search_ref=""; $search_refsupplier=""; + $search_type=""; $search_label=""; $search_project=''; $search_societe=""; @@ -261,7 +264,7 @@ llxHeader('',$langs->trans("SuppliersInvoices"),'EN:Suppliers_Invoices|FR:Factur $sql = "SELECT"; if ($search_all || $search_product_category > 0) $sql = 'SELECT DISTINCT'; -$sql.= " f.rowid as facid, f.ref, f.ref_supplier, f.datef, f.date_lim_reglement as datelimite, f.fk_mode_reglement,"; +$sql.= " f.rowid as facid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement as datelimite, f.fk_mode_reglement,"; $sql.= " f.total_ht, f.total_ttc, f.total_tva as total_vat, f.paye as paye, f.fk_statut as fk_statut, f.libelle as label, f.datec as date_creation, f.tms as date_update,"; $sql.= " f.localtax1 as total_localtax1, f.localtax2 as total_localtax2,"; $sql.= " s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta as code_compta_client, s.code_compta_fournisseur,"; @@ -307,6 +310,15 @@ if ($search_ref) } if ($search_ref) $sql .= natural_search('f.ref', $search_ref); if ($search_refsupplier) $sql .= natural_search('f.ref_supplier', $search_refsupplier); +if ($search_type != '' && $search_type >= 0) +{ + if ($search_type == '0') $sql.=" AND f.type = 0"; // standard + if ($search_type == '1') $sql.=" AND f.type = 1"; // replacement + if ($search_type == '2') $sql.=" AND f.type = 2"; // credit note + if ($search_type == '3') $sql.=" AND f.type = 3"; // deposit + //if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma + //if ($search_type == '5') $sql.=" AND f.type = 5"; // situation +} if ($search_project) $sql .= natural_search('p.ref', $search_project); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); if ($search_town) $sql.= natural_search('s.town', $search_town); @@ -377,7 +389,7 @@ $sql.=$hookmanager->resPrint; if (! $search_all) { - $sql.= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.datef, f.date_lim_reglement, f.fk_mode_reglement,"; + $sql.= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement, f.fk_mode_reglement,"; $sql.= " f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut, f.libelle, f.datec, f.tms,"; $sql.= " f.localtax1, f.localtax2,"; $sql.= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,'; @@ -434,6 +446,7 @@ if ($resql) if ($year_lim) $param.='&year_lim=' .urlencode($year_lim); if ($search_ref) $param.='&search_ref='.urlencode($search_ref); if ($search_refsupplier) $param.='&search_refsupplier='.urlencode($search_refsupplier); + if ($search_type != '') $param.='&search_type='.urlencode($search_type); if ($search_label) $param.='&search_label='.urlencode($search_label); if ($search_company) $param.='&search_company='.urlencode($search_company); if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); @@ -590,6 +603,26 @@ if ($resql) print ''; print ''; } + // Type + if (! empty($arrayfields['f.type']['checked'])) + { + print ''; + } // Label if (! empty($arrayfields['f.label']['checked'])) { @@ -741,6 +774,7 @@ if ($resql) print ''; if (! empty($arrayfields['f.ref']['checked'])) print_liste_field_titre($arrayfields['f.ref']['label'],$_SERVER['PHP_SELF'],'f.ref,f.rowid','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['f.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['f.ref_supplier']['label'],$_SERVER["PHP_SELF"],'f.ref_supplier','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'],$_SERVER["PHP_SELF"],'f.type','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['f.label']['checked'])) print_liste_field_titre($arrayfields['f.label']['label'],$_SERVER['PHP_SELF'],"f.libelle,f.rowid",'',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['f.datef']['checked'])) print_liste_field_titre($arrayfields['f.datef']['label'],$_SERVER['PHP_SELF'],'f.datef,f.rowid','',$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'],$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); @@ -767,7 +801,7 @@ if ($resql) print $hookmanager->resPrint; if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye,type","",$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); print "\n"; @@ -843,6 +877,15 @@ if ($resql) print ''; if (! $i) $totalarray['nbfield']++; } + + // Type + if (! empty($arrayfields['f.type']['checked'])) + { + print '"; + if (! $i) $totalarray['nbfield']++; + } // Label if (! empty($arrayfields['f.label']['checked'])) From 7ca5ac03ccb5a758434b70b7537bf8676dcda968 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 26 Feb 2018 17:40:31 +0100 Subject: [PATCH 038/413] FIX: discount card: only display relevant discounts types (customer/supplier) --- htdocs/comm/remx.php | 663 ++++++++++++++++-------------- htdocs/langs/en_US/companies.lang | 1 + 2 files changed, 351 insertions(+), 313 deletions(-) diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 177b4456912..92e2f1d5d71 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -235,12 +235,17 @@ if ($socid > 0) $object = new Societe($db); $object->fetch($socid); + $isCustomer = $object->client == 1 || $object->client == 3; + $isSupplier = $object->fournisseur == 1; + + $displayCustomer = $conf->global->MAIN_FEATURES_LEVEL <= 0 || $isCustomer; + $displaySupplier = $conf->global->MAIN_FEATURES_LEVEL > 0 && $isSupplier; + /* * Display tabs */ $head = societe_prepare_head($object); - print ''; print ''; print ''; @@ -253,39 +258,54 @@ if ($socid > 0) print '
    '; print '
    '; + + if(! $displayCustomer && ! $displaySupplier) { + print '

    '.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

    '; + + dol_fiche_end(); + + print ''; + + llxFooter(); + $db->close(); + exit; + } + + print '
    '.$langs->trans('Discounts').''; if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; - $absolute_discount=$soc->getAvailableDiscounts('','fk_facture_source IS NULL'); - $absolute_creditnote=$soc->getAvailableDiscounts('','fk_facture_source IS NOT NULL'); + $absolute_discount=$soc->getAvailableDiscounts('',$filterabsolutediscount); + $absolute_creditnote=$soc->getAvailableDiscounts('',$filtercreditnote); $absolute_discount=price2num($absolute_discount,'MT'); $absolute_creditnote=price2num($absolute_creditnote,'MT'); if ($absolute_discount) @@ -346,7 +354,7 @@ if ($id > 0 || ! empty($ref)) else { // Remise dispo de type non avoir - $filter='fk_facture_source IS NULL'; + $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NULL':"fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; print '
    '; $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$soc->id,$absolute_discount,$filter, 0, '', 1); } diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 6cd17690c24..0111a8d11c7 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1888,8 +1888,8 @@ elseif (! empty($object->id)) $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index fa52c73f597..49901c420f0 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -83,8 +83,14 @@ class Thirdparties extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%'))"; - $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + } + $absolute_discount = $this->company->getAvailableDiscounts('', $filterabsolutediscount); $absolute_creditnote = $this->company->getAvailableDiscounts('', $filtercreditnote); $this->company->absolute_discount = price2num($absolute_discount, 'MT'); diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 17e5a2be199..259d3d0a5ca 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1418,8 +1418,8 @@ if ($action == 'create') $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; From d3f848b7bc7b3a957bc522eba8aecd934467033e Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 21 Feb 2018 09:30:39 +0100 Subject: [PATCH 034/413] FIX: supplier credit notes: harmonize discount filters part 2 --- htdocs/compta/facture/prelevement.php | 6 ++---- htdocs/expedition/shipment.php | 3 +-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 6065ad9cd6f..01f2ff6aa27 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -290,9 +290,8 @@ if ($object->id > 0) else { // Remise dispo de type non avoir - $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NULL':"fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$object->thirdparty->id,$absolute_discount,$filter,$resteapayer,'',1); + $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$object->thirdparty->id,$absolute_discount,$filterabsolutediscount,$resteapayer,'',1); } } if ($absolute_creditnote > 0) @@ -310,9 +309,8 @@ if ($object->id > 0) else { // Remise dispo de type avoir - $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NOT NULL':"fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; if (! $absolute_discount) print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id_for_payment',$object->thirdparty->id,$absolute_creditnote,$filter,$resteapayer,'',1); + $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id_for_payment',$object->thirdparty->id,$absolute_creditnote,$filtercreditnote,$resteapayer,'',1); } } if (! $absolute_discount && ! $absolute_creditnote) print $langs->trans("CompanyHasNoAbsoluteDiscount").'.'; diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index cf0cc1d6d24..7b0cca64a30 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -354,9 +354,8 @@ if ($id > 0 || ! empty($ref)) else { // Remise dispo de type non avoir - $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NULL':"fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$soc->id,$absolute_discount,$filter, 0, '', 1); + $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$soc->id,$absolute_discount,$filterabsolutediscount, 0, '', 1); } } if ($absolute_creditnote) From cfdbef6bc30f38b8a945bb9e5a826d05854b66d0 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 21 Feb 2018 09:31:01 +0100 Subject: [PATCH 035/413] NEW: supplier credit notes: display supplier discounts in supplier card --- htdocs/fourn/card.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 588c13ca849..60f745d95c7 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -255,6 +255,28 @@ if ($object->id > 0) } print "
    '; + print ''; + print '
    '; + print $langs->trans("CustomerAbsoluteDiscountShort"); + print ''; + if ($user->rights->societe->creer && !$user->societe_id > 0) + { + print ''.img_edit($langs->trans("Modify")).''; + } + print '
    '; + print '
    '; + $amount_discount=$object->getAvailableDiscounts('', '', 0, 1); + if ($amount_discount < 0) dol_print_error($db,$object->error); + if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; + //else print $langs->trans("DiscountNone"); + print '
    '; From 34d84c6d5dde9c664fed7c8726f9df75ed8be61a Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 21 Feb 2018 17:15:16 +0100 Subject: [PATCH 036/413] FIX: supplier credit notes: display link to discount in supplier credit note card --- htdocs/fourn/facture/card.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 0344890458b..c1c04489f1d 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2409,6 +2409,13 @@ else $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')'; } + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + $discount = new DiscountAbsolute($db); + $result = $discount->fetch(0, 0, $object->id); + if ($result > 0){ + print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(), $discount->getNomUrl(1, 'discount')).'
    '; + } + } print '
    '; + $listtype=array( + FactureFournisseur::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), + FactureFournisseur::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), + FactureFournisseur::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), + FactureFournisseur::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), + ); +/* + if (! empty($conf->global->INVOICE_USE_SITUATION)) + { + $listtype[Facture::TYPE_SITUATION] = $langs->trans("InvoiceSituation"); + } +*/ + //$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma"); // A proformat invoice is not an invoice but must be an order. + print $form->selectarray('search_type', $listtype, $search_type, 1, 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth100'); + print '
    '; + print $facturestatic->getLibType(); + print "
    '; - // Calcul avoirs client en cours - $remise_all=$remise_user=0; - $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND discount_type = 0"; // Exclude supplier discounts - $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; - $sql.= " GROUP BY rc.fk_user"; - $resql=$db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $remise_all+=$obj->amount; - if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; - } - else - { - dol_print_error($db); + if($displayCustomer) { // Calcul avoirs client en cours + $remise_all=$remise_user=0; + $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND discount_type = 0"; // Exclude supplier discounts + $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; + $sql.= " GROUP BY rc.fk_user"; + $resql=$db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $remise_all+=$obj->amount; + if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; + } + else + { + dol_print_error($db); + } + + print ''; + print ''; + + if (! empty($user->fk_soc)) // No need to show this for external users + { + print ''; + print ''; + } } - print ''; - print ''; - - if (! empty($user->fk_soc)) // No need to show this for external users - { - print ''; - print ''; - } - - if($conf->global->MAIN_FEATURES_LEVEL > 0) { + if($displaySupplier) { // Calcul avoirs fournisseur en cours $remise_all=$remise_user=0; $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; @@ -328,9 +348,18 @@ if ($socid > 0) print load_fiche_titre($langs->trans("NewGlobalDiscount"),'',''); print '
    '; + + if($conf->global->MAIN_FEATURES_LEVEL <= 0 || ($isCustomer && ! $isSupplier)) { + print ''; + } + + if($conf->global->MAIN_FEATURES_LEVEL > 0 && (! $isCustomer && $isSupplier)) { + print ''; + } + print '
    '.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
    '; - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print ''; + if($conf->global->MAIN_FEATURES_LEVEL > 0 && $isCustomer && $isSupplier) { + print ''; print ''; @@ -378,144 +407,147 @@ if ($socid > 0) */ print load_fiche_titre($langs->trans("DiscountStillRemaining")); - - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print '
    '; - print '
    '; - } - $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql.= " rc.datec as dc, rc.description,"; - $sql.= " rc.fk_facture_source,"; - $sql.= " u.login, u.rowid as user_id,"; - $sql.= " fa.facnumber as ref, fa.type as type"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND u.rowid = rc.fk_user"; - $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts - $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)"; - $sql.= " ORDER BY rc.datec DESC"; - - $resql=$db->query($sql); - if ($resql) - { - if($conf->global->MAIN_FEATURES_LEVEL > 0) { + if($displayCustomer) { + if($displaySupplier) { + print '
    '; + print '
    '; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); } - print '
    '.$langs->trans('DiscountType').'
    '.$langs->trans('DiscountType').' '; print ' '; print '
    '; - print ''; - print ''; // Need 120+ for format with AM/PM - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $showconfirminfo=array(); - - $i = 0; - $num = $db->num_rows($resql); - if ($num > 0) + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description,"; + $sql.= " rc.fk_facture_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " fa.facnumber as ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user"; + $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) { - while ($i < $num) - { - $obj = $db->fetch_object($resql); - - print ''; - print ''; - if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) - { - print ''; - } - else - { - print ''; - } - print ''; - print ''; - print ''; - print ''; - print ''; - if ($user->rights->societe->creer || $user->rights->facture->creer) - { - print ''; - } - else print ''; - print ''; - - if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) - { - $showconfirminfo['rowid']=$obj->rowid; - $showconfirminfo['amount_ttc']=$obj->amount_ttc; - } - $i++; - } + print '
    '.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("DiscountOfferedBy").' 
    '.dol_print_date($db->jdate($obj->dc),'dayhour').''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("ExcessReceived"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - print $obj->description; - print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; - print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; - print ''; - print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; - print '   '; - print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; - print ' 
    '; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $showconfirminfo=array(); + + $i = 0; + $num = $db->num_rows($resql); + if ($num > 0) + { + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + if ($user->rights->societe->creer || $user->rights->facture->creer) + { + print ''; + } + else print ''; + print ''; + + if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) + { + $showconfirminfo['rowid']=$obj->rowid; + $showconfirminfo['amount_ttc']=$obj->amount_ttc; + } + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
    '.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("DiscountOfferedBy").' 
    '.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("ExcessReceived"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + print $obj->description; + print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ''; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; + print '   '; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; + print ' 
    '.$langs->trans("None").'
    "; + + if (count($showconfirminfo)) + { + $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT'); + $amount2=($showconfirminfo['amount_ttc']-$amount1); + $formquestion=array( + 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), + array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), + array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') + ); + $langs->load("dict"); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + } } else { - print '
    '.$langs->trans("None").'
    "; - - if (count($showconfirminfo)) - { - $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT'); - $amount2=($showconfirminfo['amount_ttc']-$amount1); - $formquestion=array( - 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), - array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), - array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') - ); - $langs->load("dict"); - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + dol_print_error($db); } } - else - { - dol_print_error($db); - } - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print ''; // class="fichehalfleft" - print '
    '; - print '
    '; + if($displaySupplier) { + if($displayCustomer) { + print '
    '; // class="fichehalfleft" + print '
    '; + print '
    '; + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); + } /* * Liste remises fixes fournisseur restant en cours (= liees a aucune facture ni ligne de facture) @@ -537,7 +569,6 @@ if ($socid > 0) $resql=$db->query($sql); if ($resql) { - print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); print ''; print ''; print ''; // Need 120+ for format with AM/PM @@ -646,9 +677,11 @@ if ($socid > 0) dol_print_error($db); } - print ''; // class="ficheaddleft" - print ''; // class="fichehalfright" - print ''; // class="fichecenter" + if($displayCustomer) { + print ''; // class="ficheaddleft" + print ''; // class="fichehalfright" + print ''; // class="fichecenter" + } } print '
    '; @@ -659,161 +692,164 @@ if ($socid > 0) print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print '
    '; - print '
    '; - } - - // Remises liees a lignes de factures - $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; - $sql.= " rc.fk_facture_source,"; - $sql.= " u.login, u.rowid as user_id,"; - $sql.= " f.rowid, f.facnumber,"; - $sql.= " fa.facnumber as ref, fa.type as type"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= " , ".MAIN_DB_PREFIX."user as u"; - $sql.= " , ".MAIN_DB_PREFIX."facturedet as fc"; - $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql.= " WHERE rc.fk_soc =". $object->id; - $sql.= " AND rc.fk_facture_line = fc.rowid"; - $sql.= " AND fc.fk_facture = f.rowid"; - $sql.= " AND rc.fk_user = u.rowid"; - $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts - $sql.= " ORDER BY dc DESC"; - //$sql.= " UNION "; - // Remises liees a factures - $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql2.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; - $sql2.= " rc.fk_facture_source,"; - $sql2.= " u.login, u.rowid as user_id,"; - $sql2.= " f.rowid, f.facnumber,"; - $sql2.= " fa.facnumber as ref, fa.type as type"; - $sql2.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql2.= " , ".MAIN_DB_PREFIX."user as u"; - $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql2.= " WHERE rc.fk_soc =". $object->id; - $sql2.= " AND rc.fk_facture = f.rowid"; - $sql2.= " AND rc.fk_user = u.rowid"; - $sql2.= " AND rc.discount_type = 0"; // Eliminate supplier discounts - $sql2.= " ORDER BY dc DESC"; - - $resql=$db->query($sql); - $resql2=null; - if ($resql) $resql2=$db->query($sql2); - if ($resql2) - { - if($conf->global->MAIN_FEATURES_LEVEL > 0) { + if($displayCustomer) { + if($displaySupplier) { + print '
    '; + print '
    '; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); } - print '
    '.$langs->trans("Date").'
    '; - print ''; - print ''; // Need 120+ for format with AM/PM - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $tab_sqlobj=array(); - $tab_sqlobjOrder=array(); - $num = $db->num_rows($resql); - if ($num > 0) + // Remises liees a lignes de factures + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; + $sql.= " rc.fk_facture_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " f.rowid, f.facnumber,"; + $sql.= " fa.facnumber as ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql.= " , ".MAIN_DB_PREFIX."user as u"; + $sql.= " , ".MAIN_DB_PREFIX."facturedet as fc"; + $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc =". $object->id; + $sql.= " AND rc.fk_facture_line = fc.rowid"; + $sql.= " AND fc.fk_facture = f.rowid"; + $sql.= " AND rc.fk_user = u.rowid"; + $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql.= " ORDER BY dc DESC"; + //$sql.= " UNION "; + // Remises liees a factures + $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql2.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; + $sql2.= " rc.fk_facture_source,"; + $sql2.= " u.login, u.rowid as user_id,"; + $sql2.= " f.rowid, f.facnumber,"; + $sql2.= " fa.facnumber as ref, fa.type as type"; + $sql2.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql2.= " , ".MAIN_DB_PREFIX."user as u"; + $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql2.= " WHERE rc.fk_soc =". $object->id; + $sql2.= " AND rc.fk_facture = f.rowid"; + $sql2.= " AND rc.fk_user = u.rowid"; + $sql2.= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql2.= " ORDER BY dc DESC"; + + $resql=$db->query($sql); + $resql2=null; + if ($resql) $resql2=$db->query($sql2); + if ($resql2) { - for ($i = 0;$i < $num; $i++) - { - $sqlobj = $db->fetch_object($resql); - $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); - } - } - $db->free($resql); - - $num = $db->num_rows($resql2); - for ($i = 0;$i < $num;$i++) - { - $sqlobj = $db->fetch_object($resql2); - $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); - } - $db->free($resql2); - array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj); - - $num = count($tab_sqlobj); - if ($num > 0) - { - $i = 0 ; - while ($i < $num ) - { - $obj = array_shift($tab_sqlobj); - print ''; - print ''; - if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) - { - print ''; - } - else - { - print ''; - } - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $i++; - } + print '
    '.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("Author").' 
    '.dol_print_date($db->jdate($obj->dc),'dayhour').''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("Invoice"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - print $obj->description; - print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; - print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; - print ' 
    '; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $tab_sqlobj=array(); + $tab_sqlobjOrder=array(); + $num = $db->num_rows($resql); + if ($num > 0) + { + for ($i = 0;$i < $num; $i++) + { + $sqlobj = $db->fetch_object($resql); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); + } + } + $db->free($resql); + + $num = $db->num_rows($resql2); + for ($i = 0;$i < $num;$i++) + { + $sqlobj = $db->fetch_object($resql2); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); + } + $db->free($resql2); + array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj); + + $num = count($tab_sqlobj); + if ($num > 0) + { + $i = 0 ; + while ($i < $num ) + { + $obj = array_shift($tab_sqlobj); + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + + print "
    '.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("Author").' 
    '.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("Invoice"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + print $obj->description; + print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ' 
    '.$langs->trans("None").'
    "; } else { - print '
    '.$langs->trans("None").'
    "; - } - else - { - dol_print_error($db); } - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print ''; // class="fichehalfleft" - print '
    '; - print '
    '; + if($displaySupplier) { + if($displayCustomer) { + print '
    '; // class="fichehalfleft" + print '
    '; + print '
    '; + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); + } // Remises liees a lignes de factures $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; @@ -856,7 +892,6 @@ if ($socid > 0) if ($resql) $resql2=$db->query($sql2); if ($resql2) { - print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); print ''; print ''; print ''; // Need 120+ for format with AM/PM @@ -958,10 +993,12 @@ if ($socid > 0) { dol_print_error($db); } - - print ''; // class="ficheaddleft" - print ''; // class="fichehalfright" - print ''; // class="fichecenter" + + if($displayCustomer) { + print ''; // class="ficheaddleft" + print ''; // class="fichehalfright" + print ''; // class="fichecenter" + } } } diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index 2eb1ba88e57..dde515c0223 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -79,6 +79,7 @@ VATIsUsed=Sales tax is used VATIsNotUsed=Sales tax is not used CopyAddressFromSoc=Fill address with third party address ThirdpartyNotCustomerNotSupplierSoNoRef=Thirdparty neither customer nor supplier, no available refering objects +ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts=Thirdparty neither customer nor supplier, discounts are not available PaymentBankAccount=Payment bank account OverAllProposals=Proposals OverAllOrders=Orders From 239e83491333c71d705f6666818a98352e7a86b1 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Tue, 27 Feb 2018 10:03:51 +0100 Subject: [PATCH 039/413] FIX: supplier credit notes: remove handled TODO --- htdocs/fourn/class/fournisseur.facture.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 570966d8600..7c0159c814f 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -2730,7 +2730,7 @@ class SupplierInvoiceLine extends CommonObjectLine $this->error = $this->db->lasterror(); } } - // TODO free discount linked to line as in customer invoice + if (! $error) { $this->db->commit(); From 9cf45266f5e7849e9b3c3827b7ff9255ddb5901e Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Tue, 27 Feb 2018 16:30:39 +0100 Subject: [PATCH 040/413] NEW: supplier relative discounts --- htdocs/comm/remise.php | 219 ++++++++++++++---- htdocs/core/tpl/objectline_create.tpl.php | 6 +- htdocs/fourn/card.php | 13 ++ htdocs/fourn/commande/card.php | 25 +- htdocs/fourn/facture/card.php | 43 ++-- .../install/mysql/migration/7.0.0-8.0.0.sql | 15 +- htdocs/install/mysql/tables/llx_societe.sql | 1 + .../tables/llx_societe_remise_supplier.sql | 34 +++ htdocs/langs/en_US/companies.lang | 2 + htdocs/societe/card.php | 2 +- .../societe/class/api_thirdparties.class.php | 2 +- htdocs/societe/class/societe.class.php | 65 +++++- htdocs/supplier_proposal/card.php | 24 +- 13 files changed, 351 insertions(+), 100 deletions(-) create mode 100644 htdocs/install/mysql/tables/llx_societe_remise_supplier.sql diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php index 1ad4612d879..bc87c2e65fc 100644 --- a/htdocs/comm/remise.php +++ b/htdocs/comm/remise.php @@ -56,7 +56,14 @@ if (GETPOST('action','aZ09') == 'setremise') { $object = new Societe($db); $object->fetch($id); - $result=$object->set_remise_client(price2num(GETPOST("remise")),GETPOST("note"),$user); + + $discount_type = GETPOST('discount_type', 'int'); + + if(! empty($discount_type)) { + $result=$object->set_remise_supplier(price2num(GETPOST("remise")),GETPOST("note"),$user); + } else { + $result=$object->set_remise_client(price2num(GETPOST("remise")),GETPOST("note"),$user); + } if ($result > 0) { @@ -100,6 +107,11 @@ if ($socid > 0) $head = societe_prepare_head($object); + $isCustomer = $object->client == 1 || $object->client == 3; + $isSupplier = $object->fournisseur == 1; + + $displayCustomer = $conf->global->MAIN_FEATURES_LEVEL <= 0 || $isCustomer; + $displaySupplier = $conf->global->MAIN_FEATURES_LEVEL > 0 && $isSupplier; print '
    '; @@ -114,20 +126,58 @@ if ($socid > 0) print '
    '; print '
    '; + + if(! $displayCustomer && ! $displaySupplier) { + print '

    '.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

    '; + + dol_fiche_end(); + + print ''; + + llxFooter(); + $db->close(); + exit; + } + print '
    '.$langs->trans("Date").'
    '; - // Discount - print '"; + if($displayCustomer) { + // Customer discount + print '"; + } + + if($displaySupplier) { + // Supplier discount + print '"; + } + print '
    '; - print $langs->trans("CustomerRelativeDiscount").''.price2num($object->remise_percent)."%
    '; + print $langs->trans("CustomerRelativeDiscount").''.price2num($object->remise_percent)."%
    '; + print $langs->trans("SupplierRelativeDiscount").''.price2num($object->remise_supplier_percent)."%
    '; print '
    '; print load_fiche_titre($langs->trans("NewRelativeDiscount"),'',''); print '
    '; + + if($conf->global->MAIN_FEATURES_LEVEL <= 0 || ($isCustomer && ! $isSupplier)) { + print ''; + } + + if($conf->global->MAIN_FEATURES_LEVEL > 0 && (! $isCustomer && $isSupplier)) { + print ''; + } print ''; + if($conf->global->MAIN_FEATURES_LEVEL > 0 && $isCustomer && $isSupplier) { + // Discount type + print ''; + print ''; + } + // New value print ''; @@ -155,57 +205,128 @@ if ($socid > 0) print '
    '; + if($displayCustomer) { + if($displaySupplier) { + print '
    '; + print '
    '; + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); + } - /* - * List log of all percent discounts - */ - $sql = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,"; - $sql.= " u.login, u.rowid as user_id"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND u.rowid = rc.fk_user_author"; - $sql.= " ORDER BY rc.datec DESC"; - - $resql=$db->query($sql); - if ($resql) - { - print '
    '.$langs->trans('DiscountType').' '; + print ' '; + print '
    '; print $langs->trans("NewValue").'%
    '; - $tag = !$tag; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $num = $db->num_rows($resql); - if ($num > 0) - { - $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $i++; - } + /* + * List log of all customer percent discounts + */ + $sql = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,"; + $sql.= " u.login, u.rowid as user_id"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user_author"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) + { + print '
    '.$langs->trans("Date").''.$langs->trans("CustomerRelativeDiscountShort").''.$langs->trans("NoteReason").''.$langs->trans("User").'
    '.dol_print_date($db->jdate($obj->dc),"dayhour").''.price2num($obj->remise_percent).'%'.$obj->note.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
    '; + $tag = !$tag; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $num = $db->num_rows($resql); + if ($num > 0) + { + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
    '.$langs->trans("Date").''.$langs->trans("CustomerRelativeDiscountShort").''.$langs->trans("NoteReason").''.$langs->trans("User").'
    '.dol_print_date($db->jdate($obj->dc),"dayhour").''.price2num($obj->remise_percent).'%'.$obj->note.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
    '.$langs->trans("None").'
    "; } else { - print '
    '.$langs->trans("None").'
    "; - } - else - { - dol_print_error($db); + dol_print_error($db); + } } + if($displaySupplier) { + if($displayCustomer) { + print ''; // class="fichehalfleft" + print '
    '; + print '
    '; + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); + } + + /* + * List log of all supplier percent discounts + */ + $sql = "SELECT rc.rowid, rc.remise_supplier as remise_percent, rc.note, rc.datec as dc,"; + $sql.= " u.login, u.rowid as user_id"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_supplier as rc, ".MAIN_DB_PREFIX."user as u"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user_author"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) + { + print ''; + $tag = !$tag; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $num = $db->num_rows($resql); + if ($num > 0) + { + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
    '.$langs->trans("Date").''.$langs->trans("CustomerRelativeDiscountShort").''.$langs->trans("NoteReason").''.$langs->trans("User").'
    '.dol_print_date($db->jdate($obj->dc),"dayhour").''.price2num($obj->remise_percent).'%'.$obj->note.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
    '.$langs->trans("None").'
    "; + } + else + { + dol_print_error($db); + } + + if($displayCustomer) { + print '
    '; // class="ficheaddleft" + print '
    '; // class="fichehalfright" + print ''; // class="fichecenter" + } + } } llxFooter(); diff --git a/htdocs/core/tpl/objectline_create.tpl.php b/htdocs/core/tpl/objectline_create.tpl.php index d26a31b3cd2..103e557eb7c 100644 --- a/htdocs/core/tpl/objectline_create.tpl.php +++ b/htdocs/core/tpl/objectline_create.tpl.php @@ -322,8 +322,12 @@ else { print $form->selectUnits($line->fk_unit, "units"); print '
    remise_percent); ?>">%">%
    '; + print '
    '; + print $langs->trans("CustomerRelativeDiscountShort"); + print ''; + if ($user->rights->societe->creer && !$user->societe_id > 0) + { + print ''.img_edit($langs->trans("Modify")).''; + } + print '
    '; + print '
    '.($object->remise_supplier_percent?''.$object->remise_supplier_percent.'%':'').'
    '; print ''; diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 0111a8d11c7..88d654a8924 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1398,7 +1398,7 @@ if ($action=='create') $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); $demand_reason_id = (!empty($objectsrc->demand_reason_id)?$objectsrc->demand_reason_id:(!empty($soc->demand_reason_id)?$soc->demand_reason_id:0)); - $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); + $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; @@ -1436,7 +1436,7 @@ if ($action=='create') print ''; print ''; print '' . "\n"; - print ''; + print ''; print ''; print ''; if (!empty($currency_tx)) print ''; @@ -1479,17 +1479,16 @@ if ($action=='create') if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $societe->id > 0) { -/* // TODO handle supplier relative discount // Discounts for third party print ''; } - + // Label print ''; print ''; diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index bfc2c79a679..4071356c982 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -35,4 +35,17 @@ ALTER TABLE llx_projet ADD COLUMN bill_time integer DEFAULT 0; ALTER TABLE llx_societe ADD COLUMN order_min_amount double(24,8) DEFAULT NULL AFTER outstanding_limit; ALTER TABLE llx_societe ADD COLUMN supplier_order_min_amount double(24,8) DEFAULT NULL AFTER order_min_amount; -ALTER TABLE llx_societe_remise_except ADD COLUMN discount_type integer DEFAULT 0 NOT NULL AFTER fk_soc; \ No newline at end of file +ALTER TABLE llx_societe_remise_except ADD COLUMN discount_type integer DEFAULT 0 NOT NULL AFTER fk_soc; +ALTER TABLE llx_societe ADD COLUMN remise_supplier real DEFAULT 0 AFTER remise_client; +CREATE TABLE llx_societe_remise_supplier +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1 NOT NULL, -- multi company id + fk_soc integer NOT NULL, + tms timestamp, + datec datetime, -- creation date + fk_user_author integer, -- creation user + remise_supplier double(6,3) DEFAULT 0 NOT NULL, -- discount + note text + +)ENGINE=innodb; \ No newline at end of file diff --git a/htdocs/install/mysql/tables/llx_societe.sql b/htdocs/install/mysql/tables/llx_societe.sql index 9ffb9734d7f..f1714021fb8 100644 --- a/htdocs/install/mysql/tables/llx_societe.sql +++ b/htdocs/install/mysql/tables/llx_societe.sql @@ -78,6 +78,7 @@ create table llx_societe customer_rate real DEFAULT 0, -- taux fiabilite client (0 a 1) supplier_rate real DEFAULT 0, -- taux fiabilite fournisseur (0 a 1) remise_client real DEFAULT 0, -- remise systematique pour le client + remise_supplier real DEFAULT 0, -- remise systematique auprès du fournisseur mode_reglement tinyint, -- mode de reglement cond_reglement tinyint, -- condition de reglement mode_reglement_supplier tinyint, -- mode de reglement fournisseur diff --git a/htdocs/install/mysql/tables/llx_societe_remise_supplier.sql b/htdocs/install/mysql/tables/llx_societe_remise_supplier.sql new file mode 100644 index 00000000000..c1b56f225c7 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_societe_remise_supplier.sql @@ -0,0 +1,34 @@ +-- ======================================================================== +-- Copyright (C) 2000-2004 Rodolphe Quiedeville +-- Copyright (C) 2011-2016 Regis Houssin +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- +-- Historique evolution de la remise relative des tiers +-- ======================================================================== + +create table llx_societe_remise_supplier +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1 NOT NULL, -- multi company id + fk_soc integer NOT NULL, + tms timestamp, + datec datetime, -- creation date + fk_user_author integer, -- creation user + remise_supplier double(6,3) DEFAULT 0 NOT NULL, -- discount + note text + +)ENGINE=innodb; + diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index dde515c0223..aab3ee183da 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -268,6 +268,8 @@ CustomerRelativeDiscountShort=Relative discount CustomerAbsoluteDiscountShort=Absolute discount CompanyHasRelativeDiscount=This customer has a default discount of %s%% CompanyHasNoRelativeDiscount=This customer has no relative discount by default +HasRelativeDiscountFromSupplier=You have a default discount of %s%% from this supplier +HasNoRelativeDiscountFromSupplier=You have no default relative discount from this supplier CompanyHasAbsoluteDiscount=This customer has discount available (credits notes or down payments) for %s %s CompanyHasDownPaymentOrCommercialDiscount=This customer has discount available (commercial, down payments) for %s %s CompanyHasCreditNote=This customer still has credit notes for %s %s diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index dcacf89d643..94fe7436041 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -149,7 +149,7 @@ if (empty($reshook)) $listofproperties=array( 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'url', 'barcode', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', - 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis', + 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis', 'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency', 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur', 'model_pdf', 'fk_projet' diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index 49901c420f0..1cdfabf7fca 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -314,7 +314,7 @@ class Thirdparties extends DolibarrApi $listofproperties=array( 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'url', 'barcode', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', - 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis', + 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis', 'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency', 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur', 'model_pdf', 'fk_projet' diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 4bf2dbd0dab..ddf6f5c509a 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -234,6 +234,7 @@ class Societe extends CommonObject var $forme_juridique; var $remise_percent; + var $remise_supplier_percent; var $mode_reglement_supplier_id; var $cond_reglement_supplier_id; var $fk_prospectlevel; @@ -1143,7 +1144,7 @@ class Societe extends CommonObject $sql .= ', s.fk_forme_juridique as forme_juridique_code'; $sql .= ', s.webservices_url, s.webservices_key'; $sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode'; - $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj'; + $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.remise_supplier, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj'; $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo'; $sql .= ', s.fk_shipping_method'; $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms'; @@ -1275,6 +1276,7 @@ class Societe extends CommonObject $this->prefix_comm = $obj->prefix_comm; $this->remise_percent = $obj->remise_client; + $this->remise_supplier_percent = $obj->remise_supplier; $this->mode_reglement_id = $obj->mode_reglement; $this->cond_reglement_id = $obj->cond_reglement; $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier; @@ -1657,6 +1659,67 @@ class Societe extends CommonObject return 1; } } + + /** + * Definit la societe comme un client + * + * @param float $remise Valeur en % de la remise + * @param string $note Note/Motif de modification de la remise + * @param User $user Utilisateur qui definie la remise + * @return int <0 if KO, >0 if OK + */ + function set_remise_supplier($remise, $note, User $user) + { + global $conf, $langs; + + // Nettoyage parametres + $note=trim($note); + if (! $note) + { + $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason")); + return -2; + } + + dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id); + + if ($this->id) + { + $this->db->begin(); + + $now=dol_now(); + + // Positionne remise courante + $sql = "UPDATE ".MAIN_DB_PREFIX."societe "; + $sql.= " SET remise_supplier = '".$this->db->escape($remise)."'"; + $sql.= " WHERE rowid = " . $this->id; + $resql=$this->db->query($sql); + if (! $resql) + { + $this->db->rollback(); + $this->error=$this->db->error(); + return -1; + } + + // Ecrit trace dans historique des remises + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier"; + $sql.= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)"; + $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',"; + $sql.= " '".$this->db->escape($note)."',"; + $sql.= " ".$user->id; + $sql.= ")"; + + $resql=$this->db->query($sql); + if (! $resql) + { + $this->db->rollback(); + $this->error=$this->db->lasterror(); + return -1; + } + + $this->db->commit(); + return 1; + } + } /** * Add a discount for third party diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 259d3d0a5ca..93bf576ef71 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -995,7 +995,7 @@ if ($action == 'create') $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); + $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); // Replicate extrafields @@ -1052,15 +1052,15 @@ if ($action == 'create') { // Discounts for third party print ''; print ""; - print '"; + print '"; print '"; print ""; //} @@ -972,7 +972,7 @@ if (empty($action) || $action == 'view') { print "'; print ""; - print '"; + print '"; print '"; print ""; } From e07177fec2367c56ad60ee2980993625d81b05dd Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Thu, 1 Mar 2018 12:31:33 +0100 Subject: [PATCH 042/413] FIX: supplier relativ discounts: pre-fill newlines with qty/discount --- htdocs/core/class/html.form.class.php | 4 ++++ htdocs/core/tpl/objectline_create.tpl.php | 11 +++++------ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 8648787bedf..16f72b2d837 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -2482,6 +2482,10 @@ class Form $opt = ''; } @@ -1884,29 +1880,17 @@ if ($action == 'create') } print ''; // Date of proposal diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index dabd44ae448..cf70d422130 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -1558,17 +1558,14 @@ if ($action == 'create' && $user->rights->commande->creer) // Ligne info remises tiers print ''; } // Date @@ -2052,29 +2049,17 @@ if ($action == 'create' && $user->rights->commande->creer) $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print ''; // Date diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 5062bc88f99..4ee9658c456 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -2699,19 +2699,12 @@ if ($action == 'create') { // Discounts for third party print ''; } @@ -3363,84 +3356,14 @@ else if ($id > 0 || ! empty($ref)) print ''; // Relative and absolute discounts - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; - print ''; // Date invoice diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 01f2ff6aa27..e665eaf77d1 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -261,59 +261,13 @@ if ($object->id > 0) // Discounts print ''; // Date invoice diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 16f72b2d837..a98729ac055 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -4239,26 +4239,27 @@ class Form if(! empty($discount_type)) { if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice + else $translationKey = 'HasCreditNoteFromSupplier'; } else { - if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier'; + else $translationKey = 'HasCreditNoteFromSupplier'; } } else { if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice + else $translationKey = 'CompanyHasCreditNote'; } else { - if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount'; + else $translationKey = 'CompanyHasCreditNote'; } } + print $langs->trans($translationKey,price($amount,0,$langs,0,0,-1,$conf->currency)); if (empty($hidelist)) print ': '; print ''; if (empty($hidelist)) diff --git a/htdocs/core/tpl/object_discounts.tpl.php b/htdocs/core/tpl/object_discounts.tpl.php new file mode 100644 index 00000000000..e8accdc4d26 --- /dev/null +++ b/htdocs/core/tpl/object_discounts.tpl.php @@ -0,0 +1,104 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Needs the following variables defined: + * $object Proposal, order, invoice (including supplier versions) + * $thirdparty Thirdparty of object + * $absolute_discount Amount of fixed discounts available + * $absolute_creditnote Amount of credit notes available + * $discount_type 0 => Customer discounts, 1 => Supplier discounts + * $cannotApplyDiscount Set it to prevent form to apply discount + * $backtopage URL to come back to from discount modification pages + */ + +$classname = get_class($object); +$isInvoice = in_array($object->element, array('facture', 'invoice', 'facture_fourn', 'invoice_supplier')); +$isNewObject = empty($object->id) && empty($object->rowid); + +// Relative and absolute discounts +$addrelativediscount = '' . $langs->trans("EditRelativeDiscount") . ''; +$addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; +$viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; + +$fixedDiscount = $thirdparty->remise_percent; + +if(! empty($discount_type)) { + $fixedDiscount = $thirdparty->remise_supplier_percent; +} + +$translationKey = ! empty($discount_type) ? 'HasRelativeDiscountFromSupplier' : 'CompanyHasRelativeDiscount'; +if ($fixedDiscount > 0) + print $langs->trans($translationKey, $fixedDiscount).'.'; +else + print $langs->trans($translationKey).'.'; +if($isNewObject) print ' ('.$addrelativediscount.')'; + +// Is there is commercial discount or down payment available ? +if ($absolute_discount > 0) { + + if ($cannotApplyDiscount || ! $isInvoice || $isNewObject || $object->statut > $classname::STATUS_DRAFT || $object->type == $classname::TYPE_CREDIT_NOTE || $object->type == $classname::TYPE_DEPOSIT) { + $translationKey = ! empty($discount_type) ? 'HasAbsoluteDiscountFromSupplier' : 'CompanyHasAbsoluteDiscount'; + $text = $langs->trans($translationKey, price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)).'.'; + + if ($isInvoice && ! $isNewObject && $object->statut > $classname::STATUS_DRAFT && $object->type != $classname::TYPE_CREDIT_NOTE && $object->type != $classname::TYPE_DEPOSIT) { + $text = $form->textwithpicto($text, $langs->trans('AbsoluteDiscountUse')); + } + + if ($isNewObject) { + $text.= ' ('.$addabsolutediscount.')'; + } + + print '
    '.$text; + } else { + // Discount available of type fixed amount (not credit note) + $more = '(' . $addabsolutediscount . ')'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $thirdparty->id, $absolute_discount, $filterabsolutediscount, $resteapayer, $more, 0, $discount_type); + } +} + +// Is there credit notes availables ? +if ($absolute_creditnote > 0) { + + // If validated, we show link "add credit note to payment" + if ($cannotApplyDiscount || ! $isInvoice || $isNewObject || $object->statut != $classname::STATUS_VALIDATED || $object->type == $classname::TYPE_CREDIT_NOTE) { + $translationKey = ! empty($discount_type) ? 'HasCreditNoteFromSupplier' : 'CompanyHasCreditNote'; + $text = $langs->trans($translationKey, price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; + + if ($isInvoice && ! $isNewObject && $object->statut == $classname::STATUS_DRAFT && $object->type != $classname::TYPE_DEPOSIT) { + $text = $form->textwithpicto($text, $langs->trans('CreditNoteDepositUse')); + } + + if ($absolute_discount <= 0 || $isNewObject) { + $text.= '('.$addabsolutediscount.')'; + } + + print '
    '.$text; + } else { // We can add a credit note on a down payment or standard invoice or situation invoice + // There is credit notes discounts available + $more = $isInvoice && ! $isNewObject ? ' (' . $viewabsolutediscount . ')' : ''; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $thirdparty->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, $discount_type); // We allow credit note even if amount is higher + } +} + +if($absolute_discount <= 0 && $absolute_creditnote <= 0) { + $translationKey = ! empty($discount_type) ? 'HasNoAbsoluteDiscountFromSupplier' : 'CompanyHasNoAbsoluteDiscount'; + print '
    '.$langs->trans($translationKey).'.'; + + if ($isInvoice && $object->statut == $classname::STATUS_DRAFT && $object->type != $classname::TYPE_CREDIT_NOTE && $object->type != $classname::TYPE_DEPOSIT) { + print ' (' . $addabsolutediscount . ')'; + } +} + diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index f16ee1eac48..a9bb706c4d8 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -340,31 +340,17 @@ if ($id > 0 || ! empty($ref)) } print '
    '; // Date diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 0026bfe8fe7..c7487f4cc51 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1483,22 +1483,14 @@ if ($action=='create') { // Discounts for third party print ''; } @@ -1892,37 +1884,19 @@ elseif (! empty($object->id)) $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } - - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - - print ''; } diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 9f2610d093b..14909a1fc2e 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1920,20 +1920,11 @@ if ($action == 'create') // Discounts for third party print ''; } @@ -2421,89 +2412,15 @@ else print ''; if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - // Relative and absolute discounts - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; - print ''; } diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index aab3ee183da..5a6d2d1fc52 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -273,6 +273,10 @@ HasNoRelativeDiscountFromSupplier=You have no default relative discount from thi CompanyHasAbsoluteDiscount=This customer has discount available (credits notes or down payments) for %s %s CompanyHasDownPaymentOrCommercialDiscount=This customer has discount available (commercial, down payments) for %s %s CompanyHasCreditNote=This customer still has credit notes for %s %s +HasNoAbsoluteDiscountFromSupplier=You have no discount credit available from this supplier +HasAbsoluteDiscountFromSupplier=You have discounts available (credits notes or down payments) for %s %s from this supplier +HasDownPaymentOrCommercialDiscountFromSupplier=You have discounts available (commercial, down payments) for %s %s from this supplier +HasCreditNoteFromSupplier=You have credit notes for %s %s from this supplier CompanyHasNoAbsoluteDiscount=This customer has no discount credit available CustomerAbsoluteDiscountAllUsers=Absolute customer discounts (granted by all users) CustomerAbsoluteDiscountMy=Absolute customer discounts (granted by yourself) diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 75575bf087b..4e4611d4fd5 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1055,22 +1055,13 @@ if ($action == 'create') // Discounts for third party print ''; } @@ -1423,37 +1414,19 @@ if ($action == 'create') $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } - - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - - print ''; } From 6a4a3c9e824dc3ca2596929a9e5391589ea46085 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 5 Mar 2018 10:58:19 +0100 Subject: [PATCH 044/413] NEW: supplier credit notes: remove MAIN_FEATURES_LEVEL --- htdocs/comm/remise.php | 26 ++-- htdocs/comm/remx.php | 35 +++--- htdocs/fourn/card.php | 64 +++++----- htdocs/fourn/commande/card.php | 47 ++++---- htdocs/fourn/facture/card.php | 194 +++++++++++++++--------------- htdocs/supplier_proposal/card.php | 47 ++++---- 6 files changed, 196 insertions(+), 217 deletions(-) diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php index c961f6f43a7..8fb75c908d4 100644 --- a/htdocs/comm/remise.php +++ b/htdocs/comm/remise.php @@ -109,10 +109,6 @@ if ($socid > 0) $isCustomer = $object->client == 1 || $object->client == 3; $isSupplier = $object->fournisseur == 1; - - $displayCustomer = $conf->global->MAIN_FEATURES_LEVEL <= 0 || $isCustomer; - $displaySupplier = $conf->global->MAIN_FEATURES_LEVEL > 0 && $isSupplier; - print '
    '; print ''; @@ -127,7 +123,7 @@ if ($socid > 0) print '
    '; - if(! $displayCustomer && ! $displaySupplier) { + if(! $isCustomer && ! $isSupplier) { print '

    '.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

    '; dol_fiche_end(); @@ -141,13 +137,13 @@ if ($socid > 0) print '
    ' . $langs->trans('Discounts') . ''; - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); + if ($societe->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", '' . $societe->remise_supplier_percent . ''); else - print $langs->trans("CompanyHasNoRelativeDiscount"); + print $langs->trans("HasNoRelativeDiscountFromSupplier"); print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
    '; -*/ + $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); if ($absolute_discount) @@ -1897,13 +1896,13 @@ elseif (! empty($object->id)) $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print '
    ' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + + if ($societe->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", $societe->remise_supplier_percent); else - print $langs->trans("CompanyHasNoRelativeDiscount"); + print $langs->trans("HasNoRelativeDiscountFromSupplier"); print '. '; -*/ + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); @@ -1913,7 +1912,7 @@ elseif (! empty($object->id)) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); } else { // Remise dispo de type remise fixe (not credit note) -// print '
    '; + print '
    '; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); } } diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index c1c04489f1d..b1efc5cbfa5 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1625,7 +1625,7 @@ if ($action == 'create') $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:1)); $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); - $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); + $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; @@ -1917,15 +1917,15 @@ if ($action == 'create') { // Discounts for third party print '
    ' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); + + if ($societe->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", '' . $societe->remise_supplier_percent . ''); else - print $langs->trans("CompanyHasNoRelativeDiscount"); + print $langs->trans("HasNoRelativeDiscountFromSupplier"); print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
    '; -*/ + if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); else @@ -2428,17 +2428,17 @@ else print '
    ' . $langs->trans('Discounts'); print ''; -/* // TODO handle supplier relative discount - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + + if ($societe->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", $societe->remise_supplier_percent); else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print ' ('.$addrelativediscount.')'; -*/ + print $langs->trans("HasNoRelativeDiscountFromSupplier"); + // print ' ('.$addrelativediscount.')'; + // Is there is commercial discount or down payment available ? if ($absolute_discount > 0) { -// print '. '; + print '. '; if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { if ($object->statut == 0) { print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); @@ -2446,7 +2446,7 @@ else } else { if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '' . $text . '.
    '; + print '
    ' . $text . '.
    '; } else { $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); $text2 = $langs->trans("AbsoluteDiscountUse"); @@ -2455,7 +2455,7 @@ else } } else { // Discount available of type fixed amount (not credit note) -// print '
    '; + print '
    '; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); } } else { @@ -2463,10 +2463,11 @@ else { if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) print ' (' . $addabsolutediscount . ')
    '; -// else -// print '. '; - } else - print '. '; + else + print '. '; + } + else + print '. '; } // Is there credit notes availables ? if ($absolute_creditnote > 0) @@ -2481,7 +2482,7 @@ else } } else { // We can add a credit note on a down payment or standard invoice or situation invoice // There is credit notes discounts available -// if (! $absolute_discount) print '
    '; + if (! $absolute_discount) print '
    '; // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher @@ -2503,7 +2504,7 @@ else // } print '
    '.$form->editfieldkey("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).'
    ' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); + + if ($soc->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", '' . $soc->remise_supplier_percent . ''); else - print $langs->trans("CompanyHasNoRelativeDiscount"); + print $langs->trans("HasNoRelativeDiscountFromSupplier"); print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
    '; -*/ + $absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1); if ($absolute_discount) @@ -1427,13 +1427,13 @@ if ($action == 'create') $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print '
    ' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); + + if ($soc->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", $soc->remise_supplier_percent); else - print $langs->trans("CompanyHasNoRelativeDiscount"); + print $langs->trans("HasNoRelativeDiscountFromSupplier"); print '. '; -*/ + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); @@ -1443,7 +1443,7 @@ if ($action == 'create') print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); } else { // Remise dispo de type remise fixe (not credit note) -// print '
    '; + print '
    '; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); } } From 24ffce0be5393216186470e168db83be8371ec9b Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Thu, 1 Mar 2018 11:20:42 +0100 Subject: [PATCH 041/413] FIX: supplier credit notes: accounting display in purchases journal --- htdocs/accountancy/journal/purchasesjournal.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/accountancy/journal/purchasesjournal.php b/htdocs/accountancy/journal/purchasesjournal.php index ec21937c8ff..698b121ea7c 100644 --- a/htdocs/accountancy/journal/purchasesjournal.php +++ b/htdocs/accountancy/journal/purchasesjournal.php @@ -878,7 +878,7 @@ if (empty($action) || $action == 'view') { else print $accountoshow; print '
    " . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->ref_supplier . ' - ' . $langs->trans("SubledgerAccount") . "' . ($mt < 0 ? - price(- $mt) : '') . "'. ($mt < 0 ? price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
    "; print '" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->ref_supplier . ' - ' . $langs->trans("VAT") . " NPR (counterpart)' . ($mt < 0 ? - price(- $mt) : '') . "' . ($mt < 0 ? price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
    ' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); + $absolute_discount = $soc->getAvailableDiscounts(); - print '. '; - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount, 0, $langs, 1, -1, -1, $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
    ' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > Propal::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount, 0, $langs, 0, 0, -1, $conf->currency)); - } else { - // Remise dispo de type non avoir - print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1); - } - } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote, 0, $langs, 0, 0, -1, $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
    ' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; + $absolute_discount = $soc->getAvailableDiscounts(); - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
    ' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > Commande::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - } else { - // Remise dispo de type remise fixe (not credit note) - print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1); - } - } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
    ' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print ' (' . $langs->trans("EditRelativeDiscount") . ')'; - print '. '; - print '
    '; - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; - print '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
    ' . $langs->trans('Discounts'); - print ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - // print ' ('.$addrelativediscount.')'; - // Is there is commercial discount or down payment available ? - if ($absolute_discount > 0) { - print '. '; - if ($object->statut > 0 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) { - if ($object->statut == 0) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '. '; - } else { - if ($object->statut < 1 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '
    ' . $text . '.
    '; - } else { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - $text2 = $langs->trans("AbsoluteDiscountUse"); - print $form->textwithpicto($text, $text2); - } - } - } else { - // Discount available of type fixed amount (not credit note) - print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')'); - } - } else { - if ($absolute_creditnote > 0) // If not, link will be added later - { - if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
    '; - else - print '. '; - } else - print '. '; - } - // Is there credit notes availables ? - if ($absolute_creditnote > 0) - { - // If validated, we show link "add credit note to payment" - if ($object->statut != Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_CREDIT_NOTE) { - if ($object->statut == 0 && $object->type != Facture::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); - print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); - } else { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; - } - } else { // We can add a credit note on a down payment or standard invoice or situation invoice - // There is credit notes discounts available - if (! $absolute_discount) print '
    '; - // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer); - $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0, $more); // We allow credit note even if amount is higher - } - } - if (! $absolute_discount && ! $absolute_creditnote) { - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
    '; - else - print '. '; - } - // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) - // { - // if (! $absolute_discount && ! $absolute_creditnote) print '
    '; - // print '   -   '; - // print $addabsolutediscount; - // print '   -   '.$addcreditnote; // We disbale link to credit note - // } + print '
    '; + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
    '.$langs->trans('Discounts').''; - if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; - if ($absolute_discount > 0) - { - if ($object->statut > Facture::STATUS_DRAFT || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) - { - if ($object->statut == Facture::STATUS_DRAFT) - { - print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)).'. '; - } - else - { - if ($object->statut < Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) - { - $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)); - print '
    '.$text.'.
    '; - } - else - { - $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)); - $text2=$langs->trans("AbsoluteDiscountUse"); - print $form->textwithpicto($text,$text2); - } - } - } - else - { - // Remise dispo de type non avoir - print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$object->thirdparty->id,$absolute_discount,$filterabsolutediscount,$resteapayer,'',1); - } - } - if ($absolute_creditnote > 0) - { - // If validated, we show link "add credit note to payment" - if ($object->statut != Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_CREDIT_NOTE) - { - if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_DEPOSIT) - { - $text=$langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)); - print $form->textwithpicto($text,$langs->trans("CreditNoteDepositUse")); - } - else print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'.'; - } - else - { - // Remise dispo de type avoir - if (! $absolute_discount) print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id_for_payment',$object->thirdparty->id,$absolute_creditnote,$filtercreditnote,$resteapayer,'',1); - } - } - if (! $absolute_discount && ! $absolute_creditnote) print $langs->trans("CompanyHasNoAbsoluteDiscount").'.'; + + $thirdparty = $object->thirdparty; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + $cannotApplyDiscount = 1; + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
    '.$langs->trans('Discounts').''; - if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; + $absolute_discount=$soc->getAvailableDiscounts('',$filterabsolutediscount); $absolute_creditnote=$soc->getAvailableDiscounts('',$filtercreditnote); $absolute_discount=price2num($absolute_discount,'MT'); $absolute_creditnote=price2num($absolute_creditnote,'MT'); - if ($absolute_discount) - { - if ($object->statut > Commande::STATUS_DRAFT) - { - print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)); - } - else - { - // Remise dispo de type non avoir - print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$soc->id,$absolute_discount,$filterabsolutediscount, 0, '', 1); - } - } - if ($absolute_creditnote) - { - print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'. '; - } - if (! $absolute_discount && ! $absolute_creditnote) print $langs->trans("CompanyHasNoAbsoluteDiscount").'.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + $cannotApplyDiscount = 1; + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
    ' . $langs->trans('Discounts') . ''; - if ($societe->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", '' . $societe->remise_supplier_percent . ''); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - print ' (' . $langs->trans("EditRelativeDiscount") . ')'; - print '. '; - print '
    '; $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; - print '.'; + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
    ' . $langs->trans('Discounts') . ''; - - if ($societe->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", $societe->remise_supplier_percent); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - print '. '; $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > CommandeFournisseur::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - } else { - // Remise dispo de type remise fixe (not credit note) - print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); - } - } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + + print '
    ' . $langs->trans('Discounts') . ''; + + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
    ' . $langs->trans('Discounts') . ''; - if ($societe->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", '' . $societe->remise_supplier_percent . ''); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - print ' (' . $langs->trans("EditRelativeDiscount") . ')'; - print '. '; - print '
    '; + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $societe->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; - print '.'; print '
    ' . $langs->trans('Discounts'); print ''; - if ($societe->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", $societe->remise_supplier_percent); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - // print ' ('.$addrelativediscount.')'; + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; - - // Is there is commercial discount or down payment available ? - if ($absolute_discount > 0) { - print '. '; - if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - if ($object->statut == 0) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '. '; - } else { - if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '
    ' . $text . '.
    '; - } else { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - $text2 = $langs->trans("AbsoluteDiscountUse"); - print $form->textwithpicto($text, $text2); - } - } - } else { - // Discount available of type fixed amount (not credit note) - print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); - } - } else { - if ($absolute_creditnote > 0) // If not, link will be added later - { - if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
    '; - else - print '. '; - } - else - print '. '; - } - // Is there credit notes availables ? - if ($absolute_creditnote > 0) - { - // If validated, we show link "add credit note to payment" - if ($object->statut != FactureFournisseur::STATUS_VALIDATED || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { - if ($object->statut == 0 && $object->type != FactureFournisseur::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); - print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); - } else { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; - } - } else { // We can add a credit note on a down payment or standard invoice or situation invoice - // There is credit notes discounts available - if (! $absolute_discount) print '
    '; - // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); - $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher - } - } - if (! $absolute_discount && ! $absolute_creditnote) { - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
    '; - else - print '. '; - } - // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) - // { - // if (! $absolute_discount && ! $absolute_creditnote) print '
    '; - // print '   -   '; - // print $addabsolutediscount; - // print '   -   '.$addcreditnote; // We disbale link to credit note - // } print '
    ' . $langs->trans('Discounts') . ''; - if ($soc->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", '' . $soc->remise_supplier_percent . ''); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - print ' (' . $langs->trans("EditRelativeDiscount") . ')'; - print '. '; - print '
    '; - $absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1); - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; - print '.'; + $thirdparty = $soc; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
    ' . $langs->trans('Discounts') . ''; - if ($soc->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", $soc->remise_supplier_percent); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - print '. '; + print '
    ' . $langs->trans('Discounts') . ''; $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > SupplierProposal::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - } else { - // Remise dispo de type remise fixe (not credit note) - print '
    '; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); - } - } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + + $thirdparty = $soc; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
    '; - if($displayCustomer) { + if($isCustomer) { // Customer discount print '"; } - if($displaySupplier) { + if($isSupplier) { // Supplier discount print '"; @@ -160,17 +156,17 @@ if ($socid > 0) print '
    '; - if($conf->global->MAIN_FEATURES_LEVEL <= 0 || ($isCustomer && ! $isSupplier)) { + if($isCustomer && ! $isSupplier) { print ''; } - if($conf->global->MAIN_FEATURES_LEVEL > 0 && (! $isCustomer && $isSupplier)) { + if(! $isCustomer && $isSupplier) { print ''; } print '
    '; print $langs->trans("CustomerRelativeDiscount").''.price2num($object->remise_percent)."%
    '; print $langs->trans("SupplierRelativeDiscount").''.price2num($object->remise_supplier_percent)."%
    '; - if($conf->global->MAIN_FEATURES_LEVEL > 0 && $isCustomer && $isSupplier) { + if($isCustomer && $isSupplier) { // Discount type print ''; print '\n"; + // Type + print ''; + // Amount + print ""; + print ""; + print "\n"; + } + print "
    '.$langs->trans('DiscountType').' '; @@ -205,8 +201,8 @@ if ($socid > 0) print '
    '; - if($displayCustomer) { - if($displaySupplier) { + if($isCustomer) { + if($isSupplier) { print '
    '; print '
    '; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); @@ -263,8 +259,8 @@ if ($socid > 0) } } - if($displaySupplier) { - if($displayCustomer) { + if($isSupplier) { + if($isCustomer) { print '
    '; // class="fichehalfleft" print '
    '; print '
    '; @@ -321,7 +317,7 @@ if ($socid > 0) dol_print_error($db); } - if($displayCustomer) { + if($isCustomer) { print '
    '; // class="ficheaddleft" print '
    '; // class="fichehalfright" print '
    '; // class="fichecenter" diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 92e2f1d5d71..b580684af7e 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -238,9 +238,6 @@ if ($socid > 0) $isCustomer = $object->client == 1 || $object->client == 3; $isSupplier = $object->fournisseur == 1; - $displayCustomer = $conf->global->MAIN_FEATURES_LEVEL <= 0 || $isCustomer; - $displaySupplier = $conf->global->MAIN_FEATURES_LEVEL > 0 && $isSupplier; - /* * Display tabs */ @@ -259,7 +256,7 @@ if ($socid > 0) print '
    '; - if(! $displayCustomer && ! $displaySupplier) { + if(! $isCustomer && ! $isSupplier) { print '

    '.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

    '; dol_fiche_end(); @@ -274,7 +271,7 @@ if ($socid > 0) print ''; - if($displayCustomer) { // Calcul avoirs client en cours + if($isCustomer) { // Calcul avoirs client en cours $remise_all=$remise_user=0; $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; @@ -305,7 +302,7 @@ if ($socid > 0) } } - if($displaySupplier) { + if($isSupplier) { // Calcul avoirs fournisseur en cours $remise_all=$remise_user=0; $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; @@ -349,16 +346,16 @@ if ($socid > 0) print '
    '; - if($conf->global->MAIN_FEATURES_LEVEL <= 0 || ($isCustomer && ! $isSupplier)) { + if($isCustomer && ! $isSupplier) { print ''; } - if($conf->global->MAIN_FEATURES_LEVEL > 0 && (! $isCustomer && $isSupplier)) { + if(! $isCustomer && $isSupplier) { print ''; } print '
    '; - if($conf->global->MAIN_FEATURES_LEVEL > 0 && $isCustomer && $isSupplier) { + if($isCustomer && $isSupplier) { print ''; print '"; print ''; - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - // Relative discounts (Discounts-Drawbacks-Rebates) - print ''; - print ''; - - // Absolute discounts (Discounts-Drawbacks-Rebates) - print ''; - print ''; - print ''; + // Relative discounts (Discounts-Drawbacks-Rebates) + print ''; + print ''; + + // Absolute discounts (Discounts-Drawbacks-Rebates) + print ''; + print ''; + print ''; print ''; print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $societe->id > 0) + if ($societe->id > 0) { // Discounts for third party print ''; print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - - // Relative and absolute discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; - } - - $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); - $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); - $absolute_discount = price2num($absolute_discount, 'MT'); - $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - - print ''; + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + + print ''; + // Conditions de reglement par defaut $langs->load('bills'); print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $societe->id > 0) + if ($societe->id > 0) { // Discounts for third party print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - // Relative and absolute discounts - print ''; - } + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + + print ''; // Label print ''; @@ -2782,41 +2778,39 @@ else $creditnoteamount = 0; $depositamount = 0; - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql .= " re.description, re.fk_invoice_supplier_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; - $sql .= " WHERE fk_invoice_supplier = " . $object->id; - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - $invoice = new FactureFournisseur($db); - while ($i < $num) { - $obj = $db->fetch_object($resql); - $invoice->fetch($obj->fk_invoice_supplier_source); - print ''; - print ''; - print ''; - $i ++; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - $creditnoteamount += $obj->amount_ttc; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) - $depositamount += $obj->amount_ttc; - } - } else { - dol_print_error($db); - } - } + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; + $sql .= " re.description, re.fk_invoice_supplier_source"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; + $sql .= " WHERE fk_invoice_supplier = " . $object->id; + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + $invoice = new FactureFournisseur($db); + while ($i < $num) { + $obj = $db->fetch_object($resql); + $invoice->fetch($obj->fk_invoice_supplier_source); + print ''; + print ''; + print ''; + $i ++; + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + $creditnoteamount += $obj->amount_ttc; + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + $depositamount += $obj->amount_ttc; + } + } else { + dol_print_error($db); + } // Paye partiellement 'escompte' if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { @@ -3029,7 +3023,7 @@ else } // Reverse back money or convert to reduction - if ($conf->global->MAIN_FEATURES_LEVEL > 0 && ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD)) { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) { // For credit note only if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) { diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 4e4611d4fd5..e906fea4041 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1050,7 +1050,7 @@ if ($action == 'create') } print '' . "\n"; - if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $soc->id > 0) + if ($soc->id > 0) { // Discounts for third party print ''; -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // autodecrement selected web stock when generate invoice or paid an order->generate linked invoice as in a POS module for a full automatic functionality (useful when there is a lot of payment) -{ - // Stock for automatic decrement - print ''; +print ''; - if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ? - { - print ''; - } +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ? +{ + print ''; } if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ? @@ -297,7 +283,7 @@ print ''; +print ''; // Payment token for URL print '\n"; print "\n"; - -$list=\Stripe\Charge::all(array("limit" => $limit),array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); -//print $list; -foreach ($list->data as $charge) { - print ''; - $societestatic->fetch($charge->metadata->idcustomer); - $societestatic->id=$charge->metadata->idcustomer; - $societestatic->lastname=$obj->lastname; - $societestatic->firstname=$obj->firstname; - $societestatic->admin=$obj->admin; - $societestatic->login=$obj->login; - $societestatic->email=$obj->email; - $societestatic->societe_id=$obj->fk_soc; - // Ref + + $list=\Stripe\Charge::all(array("limit" => $limit), array("stripe_account" => $stripeaccount)); + + //print $list; + foreach ($list->data as $charge) + { + print ''; + $societestatic->fetch($charge->metadata->idcustomer); + $societestatic->id=$charge->metadata->idcustomer; + $societestatic->lastname=$obj->lastname; + $societestatic->firstname=$obj->firstname; + $societestatic->admin=$obj->admin; + $societestatic->login=$obj->login; + $societestatic->email=$obj->email; + $societestatic->societe_id=$obj->fk_soc; + // Ref print "\n"; // Employee print "\n"; - // Origine + // Origine print "\n"; - // Date payment - print '\n"; - // Label payment - print "\n"; - // Type - print ''; - // Amount - print ""; - print "\n"; - } + if ($charge->metadata->source=="order"){ + $object = new Commande($db); + $object->fetch($charge->metadata->idsource); + print "".img_picto('', 'object_order')." ".$object->ref.""; + } elseif ($charge->metadata->source=="invoice"){ + $object = new Facture($db); + $object->fetch($charge->metadata->idsource); + print "".img_picto('', 'object_invoice')." ".$object->ref.""; + } + print "\n"; + // Date payment + print '\n"; + // Label payment + print "\n"; + // Type + print ''; + // Amount + print ""; + print "\n"; + } } else { -} +} llxFooter(); $db->close(); diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index a1eefd6ecb7..4ea45b7a4b3 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -21,23 +21,24 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; -/** - * \class Rewards - * \brief Class for Rewards + + +/** + * Stripe class */ class Stripe extends CommonObject { public $rowid; - public $fk_soc; - public $fk_key; - public $id; - public $mode; - public $entity; - public $statut; - public $type; - public $code; - public $message; - + public $fk_soc; + public $fk_key; + public $id; + public $mode; + public $entity; + public $statut; + public $type; + public $code; + public $message; + /** * Constructor * @@ -48,273 +49,306 @@ class Stripe extends CommonObject $this->db = $db; } - -public function GetStripeAccount($id) // TODO: move /transforme optimize function/data + + /** + * GetStripeAccount + * + * @param string $mode 'StripeTest' or 'StripeLive' + * @return int ??? + */ + public function GetStripeAccount($mode='StripeTest') { global $conf; - $sql = "SELECT key_account"; - $sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity"; - $sql.= " WHERE entity = ".$id.""; + $sql = "SELECT tokenstring"; + $sql.= " FROM ".MAIN_DB_PREFIX."oauth_token"; + $sql.= " WHERE entity = ".$conf->entity; + $sql.= " AND service = '".$mode."'"; dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) + if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - $key=$obj->key_account; - } - else {$key=0;} - } - else {$key=0;} - -return $key; - } - -public function GetStripeCustomerAccount($id) + $tokenstring=$obj->tokenstring; + + $tmparray = dol_json_decode($tokenstring); + $key = $tmparray->stripe_user_id; + } + else { + $tokenstring=''; + } + } + else { + dol_print_error($this->db); + } + + return $key; + } + + /** + * GetStripeCustomerAccount + * + * @param int $id ??? + * @return int ??? + */ + public function GetStripeCustomerAccount($id) { global $conf; $sql = "SELECT s.key_account as key_account, s.entity, e.fk_object"; - $sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity as s"; - $sql.= " JOIN ".MAIN_DB_PREFIX."entity_extrafields as e ON s.entity=e.fk_object"; - $sql.= " WHERE e.fk_soc=".$id." "; + $sql .= " FROM " . MAIN_DB_PREFIX . "stripe_entity as s"; + $sql .= " JOIN " . MAIN_DB_PREFIX . "entity_extrafields as e ON s.entity=e.fk_object"; + $sql .= " WHERE e.fk_soc=" . $id . " "; dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - $key=$obj->key_account; - } - else {$key=NULL;} - } - else {$key=NULL;} - -return $key; - } - -public function CustomerStripe($id,$key) + $key = $obj->key_account; + } else { + $key = NULL; + } + } else { + $key = NULL; + } + + return $key; + } + + + /** + * CustomerStripe + * + * @param int $id ??? + * @param string $key ??? + * @return \Stripe\StripeObject|\Stripe\ApiResource + */ + public function CustomerStripe($id,$key) { -global $conf; -if (empty($conf->global->STRIPECONNECT_LIVE)) -{ -$mode=0; -} -else -{ -if (empty($conf->global->STRIPE_LIVE)) -{ -$mode=0; -} -else -{ -$mode=$conf->global->STRIPE_LIVE; -} -} + global $conf; + if (empty($conf->global->STRIPECONNECT_LIVE)) { + $mode = 0; + } else { + if (empty($conf->global->STRIPE_LIVE)) { + $mode = 0; + } else { + $mode = $conf->global->STRIPE_LIVE; + } + } $sql = "SELECT rowid,fk_soc,fk_key,mode,entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_stripe"; - $sql.= " WHERE fk_soc = ".$id." "; - $sql.= " AND mode=".$mode." AND entity IN (" . getEntity('stripe') . ")"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe"; + $sql .= " WHERE fk_soc = " . $id . " "; + $sql .= " AND mode=" . $mode . " AND entity IN (" . getEntity('stripe') . ")"; dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $soc = new Societe($this->db); - $soc->fetch($id); - $num=$this->db->num_rows($resql); + $soc = new Societe($this->db); + $soc->fetch($id); + $num = $this->db->num_rows($resql); if ($num) { - $obj = $this->db->fetch_object($resql); - $tiers = $obj->fk_key; - if ($conf->entity==1){ - $customer = \Stripe\Customer::retrieve("$tiers"); - }else{ - $customer = \Stripe\Customer::retrieve("$tiers",array("stripe_account" => $key)); - }} - else { - if ($conf->entity==1){ - $customer = \Stripe\Customer::create(array( - "email" => $soc->email, - "description" => $soc->name - )); - }else{ - $customer = \Stripe\Customer::create(array( - "email" => $soc->email, - "description" => $soc->name - ), array("stripe_account" => $key)); - } - $customer_id = "".$customer->id.""; - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_stripe (fk_soc,fk_key,mode,entity)"; - $sql .= " VALUES ($id,'$customer_id',".$mode.",".$conf->entity.")"; - dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); - $resql = $this->db->query($sql); - }} -return $customer; + $obj = $this->db->fetch_object($resql); + $tiers = $obj->fk_key; + if ($conf->entity == 1) { + $customer = \Stripe\Customer::retrieve("$tiers"); + } else { + $customer = \Stripe\Customer::retrieve("$tiers", array( + "stripe_account" => $key + )); + } + } else { + if ($conf->entity == 1) { + $customer = \Stripe\Customer::create(array( + "email" => $soc->email, + "description" => $soc->name + )); + } else { + $customer = \Stripe\Customer::create(array( + "email" => $soc->email, + "description" => $soc->name + ), array( + "stripe_account" => $key + )); + } + $customer_id = "" . $customer->id . ""; + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_stripe (fk_soc,fk_key,mode,entity)"; + $sql .= " VALUES ($id,'$customer_id'," . $mode . "," . $conf->entity . ")"; + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + } + } + return $customer; } - -public function CreatePaymentStripe($amount,$currency,$origin,$item,$source,$customer,$account) -{ -global $conf; -if (empty($conf->global->STRIPECONNECT_LIVE)) -{ -$mode=0; -} -else -{ -if (empty($conf->global->STRIPE_LIVE)) -{ -$mode=0; -} -else -{ -$mode=$conf->global->STRIPE_LIVE; -} -} + + /** + * CreatePaymentStripe + * + * @param unknown $amount ??? + * @param unknown $currency ??? + * @param unknown $origin ??? + * @param unknown $item ??? + * @param unknown $source ??? + * @param unknown $customer ??? + * @param unknown $account ??? + * @return Stripe + */ + public function CreatePaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) + { + global $conf; + if (empty($conf->global->STRIPECONNECT_LIVE)) { + $mode = 0; + } else { + if (empty($conf->global->STRIPE_LIVE)) { + $mode = 0; + } else { + $mode = $conf->global->STRIPE_LIVE; + } + } $sql = "SELECT fk_soc,fk_key,mode,entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_stripe"; - $sql.= " WHERE fk_key = '$customer' "; - $sql.= " AND mode=".$mode." "; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe"; + $sql .= " WHERE fk_key = '$customer' "; + $sql .= " AND mode=" . $mode . " "; dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - $entite=$obj->entity; - $fksoc=$obj->fk_soc; - } - } -$stripeamount=round($amount*100); -$societe = new Societe($this->db); -$societe->fetch($fksoc); + $entite = $obj->entity; + $fksoc = $obj->fk_soc; + } + } + $stripeamount = round($amount * 100); + $societe = new Societe($this->db); + $societe->fetch($fksoc); -if ($origin==order){ -$order=new Commande($this->db); -$order->fetch($item); -$ref=$order->ref; -$description="ORD=".$ref.".CUS=".$societe->code_client; -} -elseif ($origin==invoice) { -$invoice=new Facture($this->db); -$invoice->fetch($item); -$ref=$invoice->ref; -$description="INV=".$ref.".CUS=".$societe->code_client; -} + if ($origin == order) { + $order = new Commande($this->db); + $order->fetch($item); + $ref = $order->ref; + $description = "ORD=" . $ref . ".CUS=" . $societe->code_client; + } elseif ($origin == invoice) { + $invoice = new Facture($this->db); + $invoice->fetch($item); + $ref = $invoice->ref; + $description = "INV=" . $ref . ".CUS=" . $societe->code_client; + } -$metadata = array( - "source" => "".$origin."", - "idsource" => "".$item."", - "idcustomer" => "".$societe->id."" - ); -$return = new Stripe($this->db); -try { -if ($stripeamount>=100) { -if ($entite=='1' or empty($conf->stripeconnect->enabled)){ -if (preg_match('/acct_/i',$source)){ - $charge = \Stripe\Charge::create(array( - "amount" => "$stripeamount", - "currency" => "$currency", -// "statement_descriptor" => " ", - "metadata" => $metadata, - "source" => "$source" -) -); -} else { -$charge = \Stripe\Charge::create(array( - "amount" => "$stripeamount", - "currency" => "$currency", -// "statement_descriptor" => " ", - "description" => "$description", - "metadata" => $metadata, - "receipt_email" => $societe->email, - "source" => "$source", - "customer" => "$customer") - ,array("idempotency_key" => "$ref") -); -}}else{ -$fee=round(($amount*($conf->global->STRIPE_APPLICATION_FEE_PERCENT/100)+$conf->global->STRIPE_APPLICATION_FEE)*100); -if ($fee<($conf->global->STRIPE_APPLICATION_FEE_MINIMAL*100)){ -$fee=round($conf->global->STRIPE_APPLICATION_FEE_MINIMAL*100); -} -$charge = \Stripe\Charge::create(array( - "amount" => "$stripeamount", - "currency" => "$currency", -// "statement_descriptor" => " ", - "description" => "$description", - "metadata" => $metadata, - "source" => "$source", - "customer" => "$customer", - "application_fee" => "$fee" -), array("idempotency_key" => "$ref","stripe_account" => "$account")); -} -if (isset($charge->id)){ + $metadata = array( + "source" => "" . $origin . "", + "idsource" => "" . $item . "", + "idcustomer" => "" . $societe->id . "" + ); + $return = new Stripe($this->db); + try { + if ($stripeamount >= 100) { + if ($entite == '1' or empty($conf->stripeconnect->enabled)) { + if (preg_match('/acct_/i', $source)) { + $charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", + // "statement_descriptor" => " ", + "metadata" => $metadata, + "source" => "$source" + )); + } else { + $charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", + // "statement_descriptor" => " ", + "description" => "$description", + "metadata" => $metadata, + "receipt_email" => $societe->email, + "source" => "$source", + "customer" => "$customer" + ), array( + "idempotency_key" => "$ref" + )); + } + } else { + $fee = round(($amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE) * 100); + if ($fee < ($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100)) { + $fee = round($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100); + } + $charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", + // "statement_descriptor" => " ", + "description" => "$description", + "metadata" => $metadata, + "source" => "$source", + "customer" => "$customer", + "application_fee" => "$fee" + ), array( + "idempotency_key" => "$ref", + "stripe_account" => "$account" + )); + } + if (isset($charge->id)) {} + } + + $return->statut = 'success'; + $return->id = $charge->id; + if ($charge->source->type == 'card') { + $return->message = $charge->source->card->brand . " ****" . $charge->source->card->last4; + } elseif ($charge->source->type == 'three_d_secure') { + $stripe = new Stripe($this->db); + $src = \Stripe\Source::retrieve("" . $charge->source->three_d_secure->card . "", array( + "stripe_account" => $stripe->GetStripeAccount($conf->entity) + )); + $return->message = $src->card->brand . " ****" . $src->card->last4; + } else { + $return->message = $charge->id; + } + } catch (\Stripe\Error\Card $e) { + // Since it's a decline, \Stripe\Error\Card will be caught + $body = $e->getJsonBody(); + $err = $body['error']; + + $return->statut = 'error'; + $return->id = $err['charge']; + $return->type = $err['type']; + $return->code = $err['code']; + $return->message = $err['message']; + $body = "Une erreur de paiement est survenue. Voici le code d'erreur:
    " . $return->id . " " . $return->message . " "; + $subject = '[NOTIFICATION] Erreur de paiement'; + $headers = 'From: "ptibogxiv.net" <' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '>'; + mail('' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '', $subject, $body, $headers); + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\RateLimit $e) { + // Too many requests made to the API too quickly + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\InvalidRequest $e) { + // Invalid parameters were supplied to Stripe's API + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\Authentication $e) { + // Authentication with Stripe's API failed + // (maybe you changed API keys recently) + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\ApiConnection $e) { + // Network communication with Stripe failed + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\Base $e) { + // Display a very generic error to the user, and maybe send + // yourself an email + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (Exception $e) { + // Something else happened, completely unrelated to Stripe + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } + return $return; + } } -} - -$return->statut = 'success'; -$return->id = $charge->id; -if ($charge->source->type=='card'){ -$return->message = $charge->source->card->brand." ****".$charge->source->card->last4; -}elseif ($charge->source->type=='three_d_secure'){ -$stripe=new Stripe($this->db); -$src = \Stripe\Source::retrieve("".$charge->source->three_d_secure->card."",array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); -$return->message = $src->card->brand." ****".$src->card->last4; -}else { -$return->message = $charge->id; -} - -} catch(\Stripe\Error\Card $e) { - // Since it's a decline, \Stripe\Error\Card will be caught - $body = $e->getJsonBody(); - $err = $body['error']; - -$return->statut = 'error'; -$return->id = $err['charge']; -$return->type = $err['type']; -$return->code = $err['code']; -$return->message = $err['message']; -$body = "Une erreur de paiement est survenue. Voici le code d'erreur:
    ".$return->id." ".$return->message." "; -$subject = '[NOTIFICATION] Erreur de paiement'; -$headers = 'From: "ptibogxiv.net" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; -mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\RateLimit $e) { - // Too many requests made to the API too quickly - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\InvalidRequest $e) { - // Invalid parameters were supplied to Stripe's API - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\Authentication $e) { - // Authentication with Stripe's API failed - // (maybe you changed API keys recently) - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\ApiConnection $e) { - // Network communication with Stripe failed - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\Base $e) { - // Display a very generic error to the user, and maybe send - // yourself an email - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (Exception $e) { - // Something else happened, completely unrelated to Stripe - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } - return $return; -} - -} diff --git a/htdocs/stripe/transaction.php b/htdocs/stripe/transaction.php index 2a37b5a55a5..143c34f7530 100644 --- a/htdocs/stripe/transaction.php +++ b/htdocs/stripe/transaction.php @@ -46,94 +46,109 @@ $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -/* -* View -*/ + /* + * View + */ llxHeader('', $langs->trans("StripeTransactionList")); $form = new Form($db); $societestatic = new societe($db); $acc = new Account($db); -$stripe=new Stripe($db); -if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) +$stripe = new Stripe($db); + +if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox', 'alpha'))) { - dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); + $service = 'StripeTest'; + dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); +} +else +{ + $servie = 'StripeLive'; } -if (!$rowid){ - print ''; - if ($optioncss != '') print ''; - print ''; +$stripeaccount = $stripe->GetStripeAccount($service); +if (empty($stripeaccount)) +{ + print $langs->trans('ErrorStripeAccountNotDefined'); +} + +if (! $rowid && $stripeaccount) { + + print ''; + if ($optioncss != '') + print ''; + print ''; print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print_barre_liste($langs->trans("StripeTransactionList"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit); + print_barre_liste($langs->trans("StripeTransactionList"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit); - print '
    '; - print '
    '.$langs->trans('DiscountType').' '; print ' '; @@ -408,8 +405,8 @@ if ($socid > 0) print load_fiche_titre($langs->trans("DiscountStillRemaining")); - if($displayCustomer) { - if($displaySupplier) { + if($isCustomer) { + if($isSupplier) { print '
    '; print '
    '; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); @@ -541,8 +538,8 @@ if ($socid > 0) } } - if($displaySupplier) { - if($displayCustomer) { + if($isSupplier) { + if($isCustomer) { print '
    '; // class="fichehalfleft" print '
    '; print '
    '; @@ -677,7 +674,7 @@ if ($socid > 0) dol_print_error($db); } - if($displayCustomer) { + if($isCustomer) { print '
    '; // class="ficheaddleft" print '
    '; // class="fichehalfright" print '
    '; // class="fichecenter" @@ -692,8 +689,8 @@ if ($socid > 0) print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); - if($displayCustomer) { - if($displaySupplier) { + if($isCustomer) { + if($isSupplier) { print '
    '; print '
    '; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); @@ -843,8 +840,8 @@ if ($socid > 0) } } - if($displaySupplier) { - if($displayCustomer) { + if($isSupplier) { + if($isCustomer) { print '
    '; // class="fichehalfleft" print '
    '; print '
    '; @@ -994,7 +991,7 @@ if ($socid > 0) dol_print_error($db); } - if($displayCustomer) { + if($isCustomer) { print '
    '; // class="ficheaddleft" print '
    '; // class="fichehalfright" print '
    '; // class="fichecenter" diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index a5d5490e660..877ba0f6e14 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -258,40 +258,38 @@ if ($object->id > 0) print "
    '; - print '
    '; - print $langs->trans("CustomerRelativeDiscountShort"); - print ''; - if ($user->rights->societe->creer && !$user->societe_id > 0) - { - print ''.img_edit($langs->trans("Modify")).''; - } - print '
    '; - print '
    '.($object->remise_supplier_percent?''.$object->remise_supplier_percent.'%':'').'
    '; - print ''; - print '
    '; - print $langs->trans("CustomerAbsoluteDiscountShort"); - print ''; - if ($user->rights->societe->creer && !$user->societe_id > 0) - { - print ''.img_edit($langs->trans("Modify")).''; - } - print '
    '; - print '
    '; - $amount_discount=$object->getAvailableDiscounts('', '', 0, 1); - if ($amount_discount < 0) dol_print_error($db,$object->error); - if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; - //else print $langs->trans("DiscountNone"); - print '
    '; + print '
    '; + print $langs->trans("CustomerRelativeDiscountShort"); + print ''; + if ($user->rights->societe->creer && !$user->societe_id > 0) + { + print ''.img_edit($langs->trans("Modify")).''; } + print '
    '; + print '
    '.($object->remise_supplier_percent?''.$object->remise_supplier_percent.'%':'').'
    '; + print ''; + print '
    '; + print $langs->trans("CustomerAbsoluteDiscountShort"); + print ''; + if ($user->rights->societe->creer && !$user->societe_id > 0) + { + print ''.img_edit($langs->trans("Modify")).''; + } + print '
    '; + print '
    '; + $amount_discount=$object->getAvailableDiscounts('', '', 0, 1); + if ($amount_discount < 0) dol_print_error($db,$object->error); + if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; + //else print $langs->trans("DiscountNone"); + print '
    '; diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index c7487f4cc51..4225646a3af 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1479,7 +1479,7 @@ if ($action=='create') } print '
    ' . $langs->trans('Discounts') . ''; @@ -1874,32 +1874,29 @@ elseif (! empty($object->id)) print ''.$author->getNomUrl(1, '', 0, 0, 0).'
    ' . $langs->trans('Discounts') . ''; - - $thirdparty = $societe; - $discount_type = 1; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); - include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; - - print '
    ' . $langs->trans('Discounts') . ''; + + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + + print '
    '; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 14909a1fc2e..8069f6cf520 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1848,74 +1848,71 @@ if ($action == 'create') if (empty($origin)) { - if ($conf->global->MAIN_FEATURES_LEVEL > 0) // Need to fix reports of standard accounting module to manage supplier credit note + if ($societe->id > 0) { - if ($societe->id > 0) - { - // Credit note - if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) - { - print '
    '; - $tmp=' - jQuery(document).ready(function() { - if (! jQuery("#radio_creditnote").is(":checked")) - { - jQuery("#credit_note_options").hide(); - } - jQuery("#radio_creditnote").click(function() { - jQuery("#credit_note_options").show(); - }); - jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() { - jQuery("#credit_note_options").hide(); - }); - }); - '; - $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; - // $text.=''; - $text .= ''; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); - print $desc; - - print '
    '; - print '    0 ? 'checked':'').' /> "; - print '
        0 ? 'checked':'').' /> "; - print '
    '; - - print '
    '; - } - } - else + // Credit note + if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) { print '
    '; - $tmp=' '; - $text = $tmp.$langs->trans("InvoiceAvoir") . ' '; - $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; + $tmp=' + jQuery(document).ready(function() { + if (! jQuery("#radio_creditnote").is(":checked")) + { + jQuery("#credit_note_options").hide(); + } + jQuery("#radio_creditnote").click(function() { + jQuery("#credit_note_options").show(); + }); + jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() { + jQuery("#credit_note_options").hide(); + }); + }); + '; + $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; + // $text.=''; + $text .= ''; $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); print $desc; - print '
    ' . "\n"; + + print '
    '; + print '    0 ? 'checked':'').' /> "; + print '
        0 ? 'checked':'').' /> "; + print '
    '; + + print ''; } } + else + { + print '
    '; + $tmp=' '; + $text = $tmp.$langs->trans("InvoiceAvoir") . ' '; + $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); + print $desc; + print '
    ' . "\n"; + } } print ''; print '
    ' . $langs->trans('Discounts') . ''; @@ -2411,18 +2408,17 @@ else } print '
    ' . $langs->trans('Discounts'); - print ''; - $thirdparty = $societe; - $discount_type = 1; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); - include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + // Relative and absolute discounts + print '
    ' . $langs->trans('Discounts'); + print ''; - print '
    '; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - print $langs->trans("CreditNote") . ' '; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) - print $langs->trans("Deposit") . ' '; - print $invoice->getNomUrl(0); - print ' :' . price($obj->amount_ttc) . ''; - print 'rowid . '">' . img_delete() . ''; - print '
    '; + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + print $langs->trans("CreditNote") . ' '; + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + print $langs->trans("Deposit") . ' '; + print $invoice->getNomUrl(0); + print ' :' . price($obj->amount_ttc) . ''; + print 'rowid . '">' . img_delete() . ''; + print '
    ' . $langs->trans('Discounts') . ''; @@ -1404,32 +1404,29 @@ if ($action == 'create') print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - - // Relative and absolute discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; - } - - print ''; + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } + print ''; + // Payment term print ''; + $thirdpartystatic->fetch($objp->socid); - $invoice=new Facture($db); - $invoice->fetch($objp->facid); - $paiement = $invoice->getSommePaiement(); - $creditnotes=$invoice->getSumCreditNotesUsed(); - $deposits=$invoice->getSumDepositsUsed(); - $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT'); - $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); + $invoice=new Facture($db); + $invoice->fetch($objp->facid); + + $paiement = $invoice->getSommePaiement(); + $creditnotes=$invoice->getSumCreditNotesUsed(); + $deposits=$invoice->getSumDepositsUsed(); + $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT'); + $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); + + print ''; // Invoice print ''; From 78259db0ee701f9f97a732297a111f84c38bf566 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 17:22:38 +0100 Subject: [PATCH 061/413] Intorduce dolDecodeBlockedData --- htdocs/blockedlog/admin/blockedlog_list.php | 2 +- htdocs/blockedlog/ajax/block-info.php | 6 +++ htdocs/blockedlog/class/blockedlog.class.php | 41 +++++++++++++++++++- 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/htdocs/blockedlog/admin/blockedlog_list.php b/htdocs/blockedlog/admin/blockedlog_list.php index 9410ef9be5e..e8b2dc8b73b 100644 --- a/htdocs/blockedlog/admin/blockedlog_list.php +++ b/htdocs/blockedlog/admin/blockedlog_list.php @@ -196,7 +196,7 @@ else if (GETPOST('downloadcsv','alpha')) $block_static->user_fullname = $obj->user_fullname; $block_static->fk_user = $obj->fk_user; $block_static->signature = $obj->signature; - $block_static->object_data = unserialize($obj->object_data); + $block_static->object_data = $block_static->dolDecodeBlockedData($obj->object_data); $checksignature = $block_static->checkSignature($previoushash); // If $previoushash is not defined, checkSignature will search it diff --git a/htdocs/blockedlog/ajax/block-info.php b/htdocs/blockedlog/ajax/block-info.php index a092b13ca99..d4d4eef4e07 100644 --- a/htdocs/blockedlog/ajax/block-info.php +++ b/htdocs/blockedlog/ajax/block-info.php @@ -85,10 +85,16 @@ function formatObject($objtoshow, $prefix) { if (! is_object($val) && ! is_array($val)) { + // TODO $val can be '__PHP_Incomplete_Class', the is_object return false $s.=''; $s.=''; } diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index fae976dec80..5a713168c48 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -686,6 +686,35 @@ if ($massaction == 'confirm_createbills') { $db->commit(); setEventMessage($langs->trans('BillCreated', $nb_bills_created)); + + // Make a redirect to avoid to bill twice if we make a refresh or back + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); + if ($sall) $param.='&sall='.urlencode($sall); + if ($socid > 0) $param.='&socid='.urlencode($socid); + if ($viewstatut != '') $param.='&viewstatut='.urlencode($viewstatut); + if ($search_orderday) $param.='&search_orderday='.urlencode($search_orderday); + if ($search_ordermonth) $param.='&search_ordermonth='.urlencode($search_ordermonth); + if ($search_orderyear) $param.='&search_orderyear='.urlencode($search_orderyear); + if ($search_deliveryday) $param.='&search_deliveryday='.urlencode($search_deliveryday); + if ($search_deliverymonth) $param.='&search_deliverymonth='.urlencode($search_deliverymonth); + if ($search_deliveryyear) $param.='&search_deliveryyear='.urlencode($search_deliveryyear); + if ($search_ref) $param.='&search_ref='.urlencode($search_ref); + if ($search_company) $param.='&search_company='.urlencode($search_company); + if ($search_ref_customer) $param.='&search_ref_customer='.urlencode($search_ref_customer); + if ($search_user > 0) $param.='&search_user='.urlencode($search_user); + if ($search_sale > 0) $param.='&search_sale='.urlencode($search_sale); + if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht); + if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat); + if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc); + if ($search_project_ref >= 0) $param.="&search_project_ref=".urlencode($search_project_ref); + if ($show_files) $param.='&show_files=' .urlencode($show_files); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + if ($billed != '') $param.='&billed='.urlencode($billed); + + header("Location: ".$_SERVER['PHP_SELF'].'?'.$param); + exit; } else { From cab61724f28e044922309ee1cfc14f407b4a9452 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 19:33:43 +0100 Subject: [PATCH 063/413] Fix phpcs --- htdocs/blockedlog/class/blockedlog.class.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index ee41a139152..8c35ec11834 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -675,8 +675,9 @@ class BlockedLog /** * Decode data * + * @param string $data Data to unserialize * @param string $mode 0=unserialize, 1=json_decode - * @return string Value unserialized + * @return string Value unserialized */ public function dolDecodeBlockedData($data, $mode=0) { From a0b587acc0766502a53031e3d83c916bcc3a1c26 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Wed, 7 Mar 2018 20:04:13 +0100 Subject: [PATCH 064/413] NEW introduce stripe.class.php TODO: more powerful saving infos ? --- htdocs/stripe/class/stripe.class.php | 320 +++++++++++++++++++++++++++ 1 file changed, 320 insertions(+) create mode 100644 htdocs/stripe/class/stripe.class.php diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php new file mode 100644 index 00000000000..c3fded06264 --- /dev/null +++ b/htdocs/stripe/class/stripe.class.php @@ -0,0 +1,320 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; +/** + * \class Rewards + * \brief Class for Rewards + */ +class Stripe extends CommonObject +{ + public $rowid; + public $fk_soc; + public $fk_key; + public $id; + public $mode; + public $entity; + public $statut; + public $type; + public $code; + public $message; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + + } + + +public function GetStripeAccount($id) // TODO: move /transforme optimize function/data + { + global $conf; + + $sql = "SELECT key_account"; + $sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity"; + $sql.= " WHERE entity = ".$id.""; + + dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $key=$obj->key_account; + } + else {$key=0;} + } + else {$key=0;} + +return $key; + } + +public function GetStripeCustomerAccount($id) + { + global $conf; + + $sql = "SELECT s.key_account as key_account, s.entity, e.fk_object"; + $sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity as s"; + $sql.= " JOIN ".MAIN_DB_PREFIX."entity_extrafields as e ON s.entity=e.fk_object"; + $sql.= " WHERE e.fk_soc=".$id." "; + + dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $key=$obj->key_account; + } + else {$key=NULL;} + } + else {$key=NULL;} + +return $key; + } + +public function CustomerStripe($id,$key) + { +global $conf; +if (empty($conf->global->STRIPECONNECT_LIVE)) +{ +$mode=0; +} +else +{ +if (empty($conf->global->STRIPE_LIVE)) +{ +$mode=0; +} +else +{ +$mode=$conf->global->STRIPE_LIVE; +} +} + $sql = "SELECT rowid,fk_soc,fk_key,mode,entity"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_stripe"; + $sql.= " WHERE fk_soc = ".$id." "; + $sql.= " AND mode=".$mode." AND entity IN (" . getEntity('stripe') . ")"; + + dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $soc = new Societe($this->db); + $soc->fetch($id); + $num=$this->db->num_rows($resql); + if ($num) { + $obj = $this->db->fetch_object($resql); + $tiers = $obj->fk_key; + if ($conf->entity==1){ + $customer = \Stripe\Customer::retrieve("$tiers"); + }else{ + $customer = \Stripe\Customer::retrieve("$tiers",array("stripe_account" => $key)); + }} + else { + if ($conf->entity==1){ + $customer = \Stripe\Customer::create(array( + "email" => $soc->email, + "description" => $soc->name + )); + }else{ + $customer = \Stripe\Customer::create(array( + "email" => $soc->email, + "description" => $soc->name + ), array("stripe_account" => $key)); + } + $customer_id = "".$customer->id.""; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_stripe (fk_soc,fk_key,mode,entity)"; + $sql .= " VALUES ($id,'$customer_id',".$mode.",".$conf->entity.")"; + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + }} +return $customer; + } + +public function CreatePaymentStripe($amount,$currency,$origin,$item,$source,$customer,$account) +{ +global $conf; +if (empty($conf->global->STRIPECONNECT_LIVE)) +{ +$mode=0; +} +else +{ +if (empty($conf->global->STRIPE_LIVE)) +{ +$mode=0; +} +else +{ +$mode=$conf->global->STRIPE_LIVE; +} +} + $sql = "SELECT fk_soc,fk_key,mode,entity"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_stripe"; + $sql.= " WHERE fk_key = '$customer' "; + $sql.= " AND mode=".$mode." "; + + dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $entite=$obj->entity; + $fksoc=$obj->fk_soc; + } + } +$stripeamount=round($amount*100); +$societe = new Societe($this->db); +$societe->fetch($fksoc); + +if ($origin==order){ +$order=new Commande($this->db); +$order->fetch($item); +$ref=$order->ref; +$description="ORD=".$ref.".CUS=".$societe->code_client; +} +elseif ($origin==invoice) { +$invoice=new Facture($this->db); +$invoice->fetch($item); +$ref=$invoice->ref; +$description="INV=".$ref.".CUS=".$societe->code_client; +} + +$metadata = array( + "source" => "".$origin."", + "idsource" => "".$item."", + "idcustomer" => "".$societe->id."" + ); +$return = new StripeConnexion($this->db); +try { +if ($stripeamount>=100) { +if ($entite=='1' or empty($conf->stripeconnect->enabled)){ +if (preg_match('/acct_/i',$source)){ + $charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", +// "statement_descriptor" => " ", + "metadata" => $metadata, + "source" => "$source" +) +); +} else { +$charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", +// "statement_descriptor" => " ", + "description" => "$description", + "metadata" => $metadata, + "receipt_email" => $societe->email, + "source" => "$source", + "customer" => "$customer") + ,array("idempotency_key" => "$ref") +); +}}else{ +$fee=round(($amount*($conf->global->STRIPE_APPLICATION_FEE_PERCENT/100)+$conf->global->STRIPE_APPLICATION_FEE)*100); +if ($fee<($conf->global->STRIPE_APPLICATION_FEE_MINIMAL*100)){ +$fee=round($conf->global->STRIPE_APPLICATION_FEE_MINIMAL*100); +} +$charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", +// "statement_descriptor" => " ", + "description" => "$description", + "metadata" => $metadata, + "source" => "$source", + "customer" => "$customer", + "application_fee" => "$fee" +), array("idempotency_key" => "$ref","stripe_account" => "$account")); +} +if (isset($charge->id)){ + +} +} + +$return->statut = 'success'; +$return->id = $charge->id; +if ($charge->source->type=='card'){ +$return->message = $charge->source->card->brand." ****".$charge->source->card->last4; +}elseif ($charge->source->type=='three_d_secure'){ +$stripeconnect=new StripeConnexion($this->db); +$src = \Stripe\Source::retrieve("".$charge->source->three_d_secure->card."",array("stripe_account" => $stripeconnect->GetStripeAccount($conf->entity))); +$return->message = $src->card->brand." ****".$src->card->last4; +}else { +$return->message = $charge->id; +} + +} catch(\Stripe\Error\Card $e) { + // Since it's a decline, \Stripe\Error\Card will be caught + $body = $e->getJsonBody(); + $err = $body['error']; + +$return->statut = 'error'; +$return->id = $err['charge']; +$return->type = $err['type']; +$return->code = $err['code']; +$return->message = $err['message']; +$body = "Une erreur de paiement est survenue. Voici le code d'erreur:
    ".$return->id." ".$return->message." "; +$subject = '[NOTIFICATION] Erreur de paiement'; +$headers = 'From: "ptibogxiv.net" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; +mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\RateLimit $e) { + // Too many requests made to the API too quickly + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\InvalidRequest $e) { + // Invalid parameters were supplied to Stripe's API + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\Authentication $e) { + // Authentication with Stripe's API failed + // (maybe you changed API keys recently) + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\ApiConnection $e) { + // Network communication with Stripe failed + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\Base $e) { + // Display a very generic error to the user, and maybe send + // yourself an email + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (Exception $e) { + // Something else happened, completely unrelated to Stripe + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } + return $return; +} + +} From d8dcebfa9aec5eb867bf9ff3d679019c50c3ceef Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 20:12:40 +0100 Subject: [PATCH 065/413] FIX Do not lose filter when editing comment of a time spent in task view --- htdocs/projet/tasks/time.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/htdocs/projet/tasks/time.php b/htdocs/projet/tasks/time.php index cbfdc48eae9..79ff8f9d9b0 100644 --- a/htdocs/projet/tasks/time.php +++ b/htdocs/projet/tasks/time.php @@ -987,13 +987,14 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) { if ($task_time->fk_user == $user->id || in_array($task_time->fk_user, $childids) || $user->rights->projet->all->creer) { + //$param = ($projectidforalltimes?'projectid='.$projectidforalltimes.'&':'').'.($withproject?'&withproject=1':''); print ' '; - print 'rowid.($withproject?'&withproject=1':'').'">'; + print 'rowid.$param.'">'; print img_edit(); print ''; print ' '; - print 'rowid.($withproject?'&withproject=1':'').'">'; + print 'rowid.$param.'">'; print img_delete(); print ''; } From 197ce2fc3d3b240a6d1e7da82e25f874a125cd51 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Thu, 8 Mar 2018 02:08:14 +0100 Subject: [PATCH 066/413] Fix set default --- htdocs/societe/paymentmodes.php | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 7f969f64e56..cbafeb68a09 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -272,13 +272,13 @@ if (empty($reshook)) } } - if ($action == 'setasdefault') + if ($action == 'setasbankdefault') { $account = new CompanyBankAccount($db); $res = $account->setAsDefault(GETPOST('ribid','int')); if ($res) { - $url=DOL_URL_ROOT.'/societe/gateway.php?socid='.$object->id; + $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; header('Location: '.$url); exit; } @@ -337,19 +337,20 @@ if (class_exists('Stripe')) $stripe=new Stripe($db); $customerstripe=$stripe->CustomerStripe($socid,$stripe->GetStripeAccount($conf->entity)); if ($customerstripe->id) { - $cu = \Stripe\Customer::retrieve("".$customerstripe->id."",array("stripe_account" => $stripe->GetStripeAccount($conf->entity)));} + $cu = \Stripe\Customer::retrieve("".$customerstripe->id."");} + $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; - if ($action == 'setasdefault') + if ($action == 'setassourcedefault') { $cu->default_source = "$source"; // obtained with Stripe.js $cu->save(); - - header('Location: '.$url); - exit; + + //header('Location: '.$url); + //exit; } elseif ($action == 'delete') { - $cu->sources->retrieve("$source")->delete(); + $cu->sources->retrieve("$source")->detach(); header('Location: '.$url); exit; @@ -365,8 +366,9 @@ $form = new Form($db); $formfile = new FormFile($db); llxHeader(); - + $head=societe_prepare_head($object); + if (! $id) { $account->fetch(0,$object->id); @@ -505,7 +507,7 @@ if ($socid && $action != 'edit' && $action != "create") print '
    '; print ''; diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index 8aa7f0ce54e..40274b00b76 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -148,16 +148,19 @@ class FormMail extends Form * Add a file into the list of attached files (stored in SECTION array) * * @param string $path Full absolute path on filesystem of file, including file name - * @param string $file Only filename - * @param string $type Mime type + * @param string $file Only filename (can be basename($path)) + * @param string $type Mime type (can be dol_mimetype($file)) * @return void */ - function add_attached_files($path,$file,$type) + function add_attached_files($path, $file='', $type='') { $listofpaths=array(); $listofnames=array(); $listofmimes=array(); + if (empty($file)) $file=basename($path); + if (empty($type)) $type=dol_mimetype($file); + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); diff --git a/htdocs/langs/en_US/members.lang b/htdocs/langs/en_US/members.lang index 2a98f700027..bfa338605f2 100644 --- a/htdocs/langs/en_US/members.lang +++ b/htdocs/langs/en_US/members.lang @@ -176,4 +176,7 @@ VATToUseForSubscriptions=VAT rate to use for subscriptions NoVatOnSubscription=No TVA for subscriptions MEMBER_PAYONLINE_SENDEMAIL=Email to use for email warning when Dolibarr receive a confirmation of a validated payment for a subscription (Example: paymentdone@example.com) ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS=Product used for subscription line into invoice: %s -NameOrCompany=Name or company \ No newline at end of file +NameOrCompany=Name or company +SubscriptionRecorded=Subscription recorded +NoEmailSentToMember=No email sent to member +EmailSentToMember=Email sent to member at %s \ No newline at end of file diff --git a/htdocs/public/payment/paymentok.php b/htdocs/public/payment/paymentok.php index 83b672604cc..285bf2920eb 100644 --- a/htdocs/public/payment/paymentok.php +++ b/htdocs/public/payment/paymentok.php @@ -374,6 +374,8 @@ if ($ispaymentok) if ($option == 'bankdirect') $postactionmessages[] = 'Bank record created'; if ($option == 'invoiceonly') $postactionmessages[] = 'Invoice recorded'; $ispostactionok = 1; + + // If an invoice was created, it is into $object->invoice } } @@ -395,13 +397,34 @@ if ($ispaymentok) $subjecttosend=$object->makeSubstitution($conf->global->ADHERENT_MAIL_COTIS_SUBJECT); $texttosend=$object->makeSubstitution($adht->getMailOnSubscription()); - $result=$object->send_an_email($texttosend,$subjecttosend,array(),array(),array(),"","",0,-1); + // Attach a file ? + $file=''; + $listofpaths=array(); + $listofnames=array(); + $listofmimes=array(); + if (is_object($object->invoice)) + { + $invoicediroutput = $conf->facture->dir_output; + $fileparams = dol_most_recent_file($invoicediroutput . '/' . $object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+'); + $file = $fileparams['fullname']; + + $listofpaths=array($file); + $listofnames=array(basename($file)); + $listofmimes=array(dol_mimetype($file)); + } + + $result=$object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofnames, $listofmimes, "", "", 0, -1); if ($result < 0) { $errmsg=$object->error; $postactionmessages[] = $errmsg; $ispostactionok = -1; } + else + { + if ($file) $postactionmessages[] = 'Email sent to member (with invoice document attached)'; + else $postactionmessages[] = 'Email sent to member (without any attached document)'; + } } } } @@ -601,7 +624,7 @@ if ($ispaymentok) $content=""; if (in_array('MEM', array_keys($tmptag))) { - $url=$urlwithroot."/adherents/card_subscriptions.php?rowid=".$tmptag['MEM']; + $url=$urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content.=''.$companylangs->trans("PaymentSubscription")."

    \n"; $content.=$companylangs->trans("MemberId").': '.$tmptag['MEM']."
    \n"; $content.=$companylangs->trans("Link").': '.$url.''."
    \n"; diff --git a/htdocs/public/paypal/paymentok.php b/htdocs/public/paypal/paymentok.php index 80ec1d8ec2b..d50dd66d903 100644 --- a/htdocs/public/paypal/paymentok.php +++ b/htdocs/public/paypal/paymentok.php @@ -212,7 +212,7 @@ if ($PAYPALTOKEN) if (! empty($tmptag['MEM'])) { $langs->load("members"); - $url=$urlwithroot."/adherents/card_subscriptions.php?rowid=".$tmptag['MEM']; + $url=$urlwithroot."/adherents/subscriptions/card.php?rowid=".$tmptag['MEM']; $content.=$langs->trans("PaymentSubscription")."
    \n"; $content.=$langs->trans("MemberId").': '.$tmptag['MEM']."
    \n"; $content.=$langs->trans("Link").': '.$url.''."
    \n"; From 88e47e11a4a254fda2bb201f07b7f2940e0a931c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 17:44:51 +0100 Subject: [PATCH 077/413] Fix rename file --- htdocs/stripe/{charge => charge.php} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename htdocs/stripe/{charge => charge.php} (100%) diff --git a/htdocs/stripe/charge b/htdocs/stripe/charge.php similarity index 100% rename from htdocs/stripe/charge rename to htdocs/stripe/charge.php From 235db1f40515758acf6d616b6c5b1def855374d1 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 19:50:41 +0100 Subject: [PATCH 078/413] Enhance OAuth module to store the stripe account in llx_oauth_token --- htdocs/admin/oauth.php | 1 + htdocs/admin/oauthlogintokens.php | 32 +- htdocs/core/lib/oauth.lib.php | 23 +- .../modules/oauth/github_oauthcallback.php | 6 +- .../modules/oauth/google_oauthcallback.php | 2 +- .../oauth/stripetest_oauthcallback.php | 180 ++++++ .../install/mysql/migration/7.0.0-8.0.0.sql | 2 + .../install/mysql/tables/llx_oauth_token.sql | 5 +- htdocs/langs/en_US/stripe.lang | 4 +- htdocs/stripe/admin/stripe.php | 116 ++-- htdocs/stripe/charge.php | 137 +++-- htdocs/stripe/class/stripe.class.php | 528 ++++++++++-------- htdocs/stripe/transaction.php | 157 +++--- 13 files changed, 728 insertions(+), 465 deletions(-) create mode 100644 htdocs/core/modules/oauth/stripetest_oauthcallback.php diff --git a/htdocs/admin/oauth.php b/htdocs/admin/oauth.php index 3e6f165161c..99ade75fdfe 100644 --- a/htdocs/admin/oauth.php +++ b/htdocs/admin/oauth.php @@ -95,6 +95,7 @@ print '
    ' . $langs->trans('Discounts') . ''; - - $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); - $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); - $absolute_discount = price2num($absolute_discount, 'MT'); - $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - - $thirdparty = $soc; - $discount_type = 1; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); - include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; - - print '
    ' . $langs->trans('Discounts') . ''; + + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + + $thirdparty = $soc; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + + print '
    '; print ''; +print ''; print ''; @@ -201,32 +201,36 @@ print '   '.$langs->trans("Example").': sk_live_xxxxxxxxxxxxxxxxxxxxxxxx'; print ''; print ''; } else { -print ''; -print ''; +print ''; +print ''; } -if (! empty($conf->banque->enabled)) +if (! empty($conf->banque->enabled)) //deplace here for separate stripe setting of general and common online payment settings { -print ''; - -print ''; + print ''; + + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // real bank account : automatic banktransfert with stripe webhook from stripe account (receiving funds, payment, debit fee/application fee, payment dispute) to real bank account + { + print ''; + } } print '
    '; From 480d756090a06699a47f61cd89e807a61c8c69ce Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 5 Mar 2018 11:30:18 +0100 Subject: [PATCH 045/413] FIX: supplier discounts: typo --- htdocs/core/class/discount.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index b71d84130a1..c8237a839c7 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -46,7 +46,7 @@ class DiscountAbsolute public $fk_facture; // Id invoice when a discount line is used into an invoice (for credit note) public $fk_facture_source; // Id facture avoir a l'origine de la remise public $ref_facture_source; // Ref facture avoir a l'origine de la remise - public $ref_invoive_supplier_source; + public $ref_invoice_supplier_source; /** * Constructor From f1faf155fc8d3154cb6a06fba3d3036e85a1639d Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 5 Mar 2018 11:41:06 +0100 Subject: [PATCH 046/413] FIX: supplier discounts: wrong link to source supplier invoice --- htdocs/core/class/discount.class.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index c8237a839c7..2813a0d46b1 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -570,8 +570,9 @@ class DiscountAbsolute if ($option == 'invoice') { $facid=! empty($this->discount_type)?$this->fk_invoice_supplier_source:$this->fk_facture_source; + $link=! empty($this->discount_type)?'/fourn/facture/card.php':'/compta/facture/card.php'; $label=$langs->trans("ShowDiscount").': '.$this->ref_facture_source; - $link = ''; + $link = ''; $linkend=''; $ref=! empty($this->discount_type)?$this->ref_invoice_supplier_source:$this->ref_facture_source; $picto='bill'; From c4950d4f0c193fe7618a434ee5ea0078054f3a37 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 5 Mar 2018 11:49:04 +0100 Subject: [PATCH 047/413] FIX: supplier discounts: wrong source invoice ref in DOCs --- htdocs/core/lib/doc.lib.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/core/lib/doc.lib.php b/htdocs/core/lib/doc.lib.php index 447c7c2149e..ae8410bd188 100644 --- a/htdocs/core/lib/doc.lib.php +++ b/htdocs/core/lib/doc.lib.php @@ -73,15 +73,15 @@ function doc_getlinedesc($line,$outputlangs,$hideref=0,$hidedesc=0,$issupplierli { $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); - $sourceref=!empty($discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$sourceref); } elseif ($desc == '(DEPOSIT)' && $line->fk_remise_except) { $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); - $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$discount->ref_facture_source); - $sourceref=!empty($discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$sourceref); // Add date of deposit if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) $libelleproduitservice.=' ('.dol_print_date($discount->datec,'day','',$outputlangs).')'; } From fad521d66cbc76ee1fc8f0f302714ac67b9d3e03 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 5 Mar 2018 12:09:13 +0100 Subject: [PATCH 048/413] FIX: supplier disocunts: add forgotten index to migration script --- htdocs/install/mysql/migration/7.0.0-8.0.0.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 08d7d362ec5..f23c095dca6 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -59,6 +59,7 @@ ALTER TABLE llx_c_type_container ADD UNIQUE INDEX uk_c_type_container_id (code, ALTER TABLE llx_societe_remise_except ADD COLUMN discount_type integer DEFAULT 0 NOT NULL AFTER fk_soc; +ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_discount_type (discount_type); ALTER TABLE llx_societe ADD COLUMN remise_supplier real DEFAULT 0 AFTER remise_client; CREATE TABLE llx_societe_remise_supplier ( From 0f574579eb71e95969d6dd2b645162016f0c8f1b Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Wed, 7 Mar 2018 12:27:13 +0100 Subject: [PATCH 049/413] Fix: avoid error if type is not numeric --- htdocs/categories/class/categorie.class.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 46063c0f8c4..a8018e2c104 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -1201,6 +1201,8 @@ class Categorie extends CommonObject */ function get_all_categories($type=null, $parent=false) { + if (! is_numeric($type)) $type = $this->MAP_ID[$type]; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie"; $sql.= " WHERE entity IN (".getEntity('category').")"; if (! is_null($type)) From a0774d523d234e83ef7fb26b3100ae94275c852d Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Wed, 7 Mar 2018 15:24:23 +0100 Subject: [PATCH 050/413] Fix: avoid conflict between invoice and invoicenumber sharings --- htdocs/core/lib/functions2.lib.php | 11 +++++++---- htdocs/core/modules/facture/mod_facture_mars.php | 4 ++-- htdocs/core/modules/facture/mod_facture_terre.php | 4 ++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php index 3cbef60f5fd..49a2f12db03 100644 --- a/htdocs/core/lib/functions2.lib.php +++ b/htdocs/core/lib/functions2.lib.php @@ -715,9 +715,12 @@ function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$m global $conf,$user; if (! is_object($objsoc)) $valueforccc=$objsoc; - else if($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur; + else if ($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur; else $valueforccc=$objsoc->code_client; + $sharetable = $table; + if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function + // Clean parameters if ($date == '') $date=dol_now(); // We use local year and month of PHP server to search numbers // but we should use local year and month of user @@ -979,7 +982,7 @@ function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$m $sql.= " WHERE ".$field." LIKE '".$maskLike."'"; $sql.= " AND ".$field." NOT LIKE '(PROV%)'"; if ($bentityon) // only if entity enable - $sql.= " AND entity IN (".getEntity($table, 1).")"; + $sql.= " AND entity IN (".getEntity($sharetable).")"; if ($where) $sql.=$where; if ($sqlwhere) $sql.=' AND '.$sqlwhere; @@ -1027,7 +1030,7 @@ function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$m $sql.= " WHERE ".$field." LIKE '".$maskLike."'"; $sql.= " AND ".$field." NOT LIKE '%PROV%'"; if ($bentityon) // only if entity enable - $sql.= " AND entity IN (".getEntity($table, 1).")"; + $sql.= " AND entity IN (".getEntity($sharetable).")"; if ($where) $sql.=$where; if ($sqlwhere) $sql.=' AND '.$sqlwhere; @@ -1081,7 +1084,7 @@ function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$m //$sql.= " WHERE ".$field." not like '(%'"; $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'"; if ($bentityon) // only if entity enable - $maskrefclient_sql.= " AND entity IN (".getEntity($table, 1).")"; + $maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")"; if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')"; diff --git a/htdocs/core/modules/facture/mod_facture_mars.php b/htdocs/core/modules/facture/mod_facture_mars.php index 85dff1aa0e1..831dce5d3e4 100644 --- a/htdocs/core/modules/facture/mod_facture_mars.php +++ b/htdocs/core/modules/facture/mod_facture_mars.php @@ -153,7 +153,7 @@ class mod_facture_mars extends ModeleNumRefFactures $sql = "SELECT MAX(CAST(SUBSTRING(facnumber FROM ".$posindice.") AS SIGNED)) as max"; // This is standard SQL $sql.= " FROM ".MAIN_DB_PREFIX."facture"; $sql.= " WHERE facnumber LIKE '".$prefix."____-%'"; - $sql.= " AND entity IN (".getEntity('facture').")"; + $sql.= " AND entity IN (".getEntity('invoicenumber').")"; $resql=$db->query($sql); dol_syslog(get_class($this)."::getNextValue", LOG_DEBUG); @@ -177,7 +177,7 @@ class mod_facture_mars extends ModeleNumRefFactures $sql = "SELECT facnumber as ref"; $sql.= " FROM ".MAIN_DB_PREFIX."facture"; $sql.= " WHERE facnumber LIKE '".$prefix."____-".$num."'"; - $sql.= " AND entity IN (".getEntity('facture').")"; + $sql.= " AND entity IN (".getEntity('invoicenumber').")"; dol_syslog(get_class($this)."::getNextValue", LOG_DEBUG); $resql=$db->query($sql); diff --git a/htdocs/core/modules/facture/mod_facture_terre.php b/htdocs/core/modules/facture/mod_facture_terre.php index 4c27340f270..174d8314784 100644 --- a/htdocs/core/modules/facture/mod_facture_terre.php +++ b/htdocs/core/modules/facture/mod_facture_terre.php @@ -169,7 +169,7 @@ class mod_facture_terre extends ModeleNumRefFactures $sql = "SELECT MAX(CAST(SUBSTRING(facnumber FROM ".$posindice.") AS SIGNED)) as max"; // This is standard SQL $sql.= " FROM ".MAIN_DB_PREFIX."facture"; $sql.= " WHERE facnumber LIKE '".$prefix."____-%'"; - $sql.= " AND entity IN (".getEntity('facture').")"; + $sql.= " AND entity IN (".getEntity('invoicenumber').")"; $resql=$db->query($sql); dol_syslog(get_class($this)."::getNextValue", LOG_DEBUG); @@ -193,7 +193,7 @@ class mod_facture_terre extends ModeleNumRefFactures $sql = "SELECT facnumber as ref"; $sql.= " FROM ".MAIN_DB_PREFIX."facture"; $sql.= " WHERE facnumber LIKE '".$prefix."____-".$num."'"; - $sql.= " AND entity IN (".getEntity('facture').")"; + $sql.= " AND entity IN (".getEntity('invoicenumber').")"; dol_syslog(get_class($this)."::getNextValue", LOG_DEBUG); $resql=$db->query($sql); From b2f6105ae251221a1c291ace826e8f5bca521a1c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 15:52:58 +0100 Subject: [PATCH 051/413] FIX #8277 --- htdocs/core/actions_sendmails.inc.php | 1 - htdocs/societe/card.php | 4 +++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index eea69e37c13..8a29a268e68 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -319,7 +319,6 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $filename = $attachedfiles['names']; $mimetype = $attachedfiles['mimes']; - // Feature to push mail sent into Sent folder if (! empty($conf->dolimail->enabled)) { diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index 217a5367ecf..bfe7db71aca 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -790,8 +790,10 @@ if (empty($reshook)) $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); } - // Actions to send emails $id=$socid; + $object->fetch($socid); + + // Actions to send emails $trigger_name='COMPANY_SENTBYMAIL'; $paramname='socid'; $mode='emailfromthirdparty'; From f4f009d877dfcda54b5ba6ce9870f72698acf4f0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 16:10:40 +0100 Subject: [PATCH 052/413] FIX #8269 --- htdocs/fourn/facture/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 5b1148cd885..99a50e08af8 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2928,7 +2928,7 @@ else } // Presend form - $modelmail='supplier_order_send'; + $modelmail='order_supplier_send'; $defaulttopic='SendBillRef'; $diroutput = $conf->fournisseur->facture->dir_output; $trackid = 'sin'.$object->id; From 39749a0a2ce890022277b725b46b2fa9eba9e3af Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Wed, 7 Mar 2018 16:13:49 +0100 Subject: [PATCH 053/413] NEW function and update comment --- htdocs/stripe/admin/stripe.php | 61 +++++++++++++++++----------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/htdocs/stripe/admin/stripe.php b/htdocs/stripe/admin/stripe.php index 544764b4c11..7a418a695dc 100644 --- a/htdocs/stripe/admin/stripe.php +++ b/htdocs/stripe/admin/stripe.php @@ -49,26 +49,26 @@ if ($action == 'setvalue' && $user->admin) $result=dolibarr_set_const($db, "STRIPE_LIVE",GETPOST('STRIPE_LIVE','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; -if (empty($conf->stripeconnect->enabled)) { +if (empty($conf->stripeconnect->enabled)) { $result=dolibarr_set_const($db, "STRIPE_TEST_PUBLISHABLE_KEY",GETPOST('STRIPE_TEST_PUBLISHABLE_KEY','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; $result=dolibarr_set_const($db, "STRIPE_TEST_SECRET_KEY",GETPOST('STRIPE_TEST_SECRET_KEY','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; $result=dolibarr_set_const($db, "STRIPE_TEST_WEBHOOK_KEY",GETPOST('STRIPE_TEST_WEBHOOK_KEY','alpha'),'chaine',0,'',$conf->entity); - if (! $result > 0) $error++; + if (! $result > 0) $error++; $result=dolibarr_set_const($db, "STRIPE_LIVE_PUBLISHABLE_KEY",GETPOST('STRIPE_LIVE_PUBLISHABLE_KEY','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; $result=dolibarr_set_const($db, "STRIPE_LIVE_SECRET_KEY",GETPOST('STRIPE_LIVE_SECRET_KEY','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; $result=dolibarr_set_const($db, "STRIPE_LIVE_WEBHOOK_KEY",GETPOST('STRIPE_LIVE_WEBHOOK_KEY','alpha'),'chaine',0,'',$conf->entity); - if (! $result > 0) $error++; -} + if (! $result > 0) $error++; +} $result=dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR",GETPOST('ONLINE_PAYMENT_CREDITOR','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; $result=dolibarr_set_const($db, "STRIPE_BANK_ACCOUNT_FOR_PAYMENTS",GETPOST('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS','int'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; $result=dolibarr_set_const($db, "STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS",GETPOST('STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS','int'),'chaine',0,'',$conf->entity); - if (! $result > 0) $error++; + if (! $result > 0) $error++; $result=dolibarr_set_const($db, "ONLINE_PAYMENT_CSS_URL",GETPOST('ONLINE_PAYMENT_CSS_URL','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; $result=dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_FORM",GETPOST('ONLINE_PAYMENT_MESSAGE_FORM','alpha'),'chaine',0,'',$conf->entity); @@ -114,7 +114,7 @@ if ($action=="setlive") setEventMessages($langs->trans("Error"), null, 'errors'); } } - +//TODO: import script for stripe account saving in alone or connect mode for stripe.class.php /* * View @@ -180,10 +180,10 @@ print '
    '; print ''.$langs->trans("STRIPE_TEST_SECRET_KEY").''; print ''; print '   '.$langs->trans("Example").': sk_test_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
    '; -print ''.$langs->trans("STRIPE_TEST_WEBHOOK_KEY").''; +print ''.$langs->trans("STRIPE_TEST_WEBHOOK_KEY").''; print ''; print '   '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; print '
    '; -print ''.$langs->trans("STRIPE_LIVE_WEBHOOK_KEY").''; +print ''.$langs->trans("STRIPE_LIVE_WEBHOOK_KEY").''; print ''; print '   '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; print '
    '.$langs->trans("STRIPECONNECT").'Ce module est configuré en mode marketplace
    '.$langs->trans("StripeConnect").''.$langs->trans("StripeConnect_Mode").'
    '; -print $langs->trans("BankAccount").''; -print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS, 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1); -print '
    '; -print $langs->trans("BankAccount").''; -print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1); -print '
    '; + print $langs->trans("BankAccount").''; + print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS, 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1); + print '
    '; + print $langs->trans("BankAccountForBankTransfer").''; + print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1); + print '
    '; print '
    '; + print ''; print ''; print ''; @@ -239,11 +243,12 @@ print 'name; print ''; -if (! empty($conf->banque->enabled)) +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // autodecrement selected web stock when generate invoice or paid an order->generate linked invoice as in a POS module for a full automatic functionality (useful when there is a lot of payment) { + // Stock for automatic decrement print ''; } @@ -275,13 +280,7 @@ print ''; - -// stock for automatic decrement -print ''; +print ''; // Payment token for URL print ''; print ''; From 884b74a6bb322a44e129ea54cf77e4399ad54536 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 7 Mar 2018 17:12:59 +0100 Subject: [PATCH 056/413] FIX: warning when adding ECM files using old photo path --- htdocs/core/class/html.formfile.class.php | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index a48ae7477fc..d84357c3559 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -1018,7 +1018,17 @@ class FormFile // Get list of files stored into database for same relative directory if ($relativedir) { - $filearrayindatabase = dol_dir_list_in_database($relativedir, '', null, 'name', SORT_ASC); + $filearrayindatabase = dol_dir_list_in_database($relativedir, '', null, 'name', SORT_ASC); + + if($modulepart == 'produit' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && ! empty($object->id)) { + if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos"; + else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos"; + + $relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dirold); + $relativedirold = preg_replace('/^[\\/]/','',$relativedirold); + + $filearrayindatabase = array_merge($filearrayindatabase, dol_dir_list_in_database($relativedirold, '', null, 'name', SORT_ASC)); + } //var_dump($filearray); //var_dump($filearrayindatabase); From 1ba6de7ec7b5cda981578ee26ed1d4d5ad157a8f Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Wed, 7 Mar 2018 17:26:49 +0100 Subject: [PATCH 057/413] FIX call stripe.class.php --- htdocs/stripe/charge | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/htdocs/stripe/charge b/htdocs/stripe/charge index 28b990fe811..aaa0b0475f8 100644 --- a/htdocs/stripe/charge +++ b/htdocs/stripe/charge @@ -1,5 +1,5 @@ +/* Copyright (C) 2018 PtibogXIV * * 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 @@ -53,7 +53,7 @@ llxHeader('', $langs->trans("StripeChargeList")); $form = new Form($db); $societestatic = new societe($db); $acc = new Account($db); -$stripeconnect=new StripeConnexion($db); +$stripe=new Stripe($db); if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); @@ -86,7 +86,7 @@ if (!$rowid){ print "\n"; -$list=\Stripe\Charge::all(array("limit" => $limit),array("stripe_account" => $stripeconnect->GetStripeAccount($conf->entity))); +$list=\Stripe\Charge::all(array("limit" => $limit),array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); //print $list; foreach ($list->data as $charge) { print ''; @@ -131,7 +131,10 @@ $label.="Statut: ".$langs->trans("".$charge->outcome->seller_message.""); print "\n"; // Type print '\n"; -$txn=\Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripeconnect->GetStripeAccount($conf->entity))); +$txn=\Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); foreach ($txn->data as $txn) { print ''; $societestatic->fetch($charge->metadata->idcustomer); @@ -119,16 +119,7 @@ $object->fetch($txn->metadata->idsource); print '\n"; // Label payment print "\n"; // Type print ''; From c02e8e9831d6920132356b3c06bce20439f05019 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 19:13:15 +0100 Subject: [PATCH 059/413] Css --- htdocs/core/lib/functions.lib.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 7fffee21b05..7cb2236524a 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -1226,7 +1226,7 @@ function dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $pi $tabsname=str_replace("@", "", $picto); $out.='
    '; - $out.=''.$langs->trans("More").'... ('.$nbintab.')'; + $out.=''.$langs->trans("More").'... ('.$nbintab.')'; $out.='
    '; $out.=$outmore; $out.='
    '; @@ -3733,7 +3733,7 @@ function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', } if (dol_strlen($morehtmlright)) { - $return.= '
    '; + $return.= ''; } $return.= '
    '.$langs->trans("UsageParameter").'
    '; - print $langs->trans("BankAccount").''; - print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS, 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1); + print $langs->trans("ONLINE_PAYMENT_WAREHOUSE").''; + print $formproduct->selectWarehouses($conf->global->ONLINE_PAYMENT_WAREHOUSE,'ONLINE_PAYMENT_WAREHOUSE','',1,$disabled); print '
    '; print $langs->trans("ONLINE_PAYMENT_SENDEMAIL").''; print ''; print '   '.$langs->trans("Example").': myemail@myserver.com'; -print '
    '; -print $langs->trans("ONLINE_PAYMENT_WAREHOUSE").''; -print $formproduct->selectWarehouses($conf->global->ONLINE_PAYMENT_WAREHOUSE,'ONLINE_PAYMENT_WAREHOUSE','',1,$disabled); -print '
    '; From d791b014a5089833400f2c3eb2da390a6064ca03 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Wed, 7 Mar 2018 16:17:25 +0100 Subject: [PATCH 054/413] update comment and class --- htdocs/societe/paymentmodes.php | 1006 +++++++++++++++++++++++++++++++ 1 file changed, 1006 insertions(+) create mode 100644 htdocs/societe/paymentmodes.php diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php new file mode 100644 index 00000000000..7f969f64e56 --- /dev/null +++ b/htdocs/societe/paymentmodes.php @@ -0,0 +1,1006 @@ + + * Copyright (C) 2003 Jean-Louis Bergamo + * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2005-2009 Regis Houssin + * Copyright (C) 2013 Peter Fontaine + * Copyright (C) 2015-2016 Marcos García + * Copyright (C) 2017 Ferran Marcet + * Copyright (C) 2018 ptibogxiv + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/societe/rib.php + * \ingroup societe + * \brief BAN tab for companies + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; +require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; + +$langs->load("companies"); +$langs->load("commercial"); +$langs->load("banks"); +$langs->load("bills"); + +// Security check +$socid = GETPOST("socid","int"); +if ($user->societe_id) $socid=$user->societe_id; +$result = restrictedArea($user, 'societe','',''); + +$id=GETPOST("id","int"); +$source=GETPOST("source","alpha"); +$ribid=GETPOST("ribid","int"); +$action=GETPOST("action", 'alpha', 3); + +$object = new Societe($db); +$object->fetch($socid); + +$account = new CompanyBankAccount($db); +$prelevement = new BonPrelevement($db); + +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('thirdpartybancard','globalcard')); + + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('thirdpartybancard')); + + + +/* + * Actions + */ + +$parameters=array('id'=>$socid, 'objcanvas'=>$objcanvas); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) +{ + if ($cancel) + { + $action=''; + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + } + + + if ($action == 'update' && ! $_POST["cancel"]) + { + // Modification + if (! GETPOST('label')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + $action='edit'; + $error++; + } + if (! GETPOST('bank')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + $action='edit'; + $error++; + } + if ($account->needIBAN() == 1) + { + if (! GETPOST('iban')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); + $action='edit'; + $error++; + } + if (! GETPOST('bic')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); + $action='edit'; + $error++; + } + } + + $account->fetch($id); + if (! $error) + { + $account->socid = $object->id; + + $account->bank = GETPOST('bank','alpha'); + $account->label = GETPOST('label','alpha'); + $account->courant = GETPOST('courant','alpha'); + $account->clos = GETPOST('clos','alpha'); + $account->code_banque = GETPOST('code_banque','alpha'); + $account->code_guichet = GETPOST('code_guichet','alpha'); + $account->number = GETPOST('number','alpha'); + $account->cle_rib = GETPOST('cle_rib','alpha'); + $account->bic = GETPOST('bic','alpha'); + $account->iban = GETPOST('iban','alpha'); + $account->domiciliation = GETPOST('domiciliation','alpha'); + $account->proprio = GETPOST('proprio','alpha'); + $account->owner_address = GETPOST('owner_address','alpha'); + $account->frstrecur = GETPOST('frstrecur','alpha'); + $account->rum = GETPOST('rum','alpha'); + if (empty($account->rum)) + { + $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); + $account->date_rum = dol_now(); + } + + $result = $account->update($user); + if (! $result) + { + setEventMessages($account->error, $account->errors, 'errors'); + } + else + { + // If this account is the default bank account, we disable others + if ($account->default_rib) + { + $account->setAsDefault($id); // This will make sure there is only one default rib + } + + $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + } + } + + if ($action == 'add' && ! $_POST["cancel"]) + { + $error=0; + + if (! GETPOST('label')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + $action='create'; + $error++; + } + if (! GETPOST('bank')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + $action='create'; + $error++; + } + + if (! $error) + { + // Ajout + $account = new CompanyBankAccount($db); + + $account->socid = $object->id; + + $account->bank = GETPOST('bank','alpha'); + $account->label = GETPOST('label','alpha'); + $account->courant = GETPOST('courant','alpha'); + $account->clos = GETPOST('clos','alpha'); + $account->code_banque = GETPOST('code_banque','alpha'); + $account->code_guichet = GETPOST('code_guichet','alpha'); + $account->number = GETPOST('number','alpha'); + $account->cle_rib = GETPOST('cle_rib','alpha'); + $account->bic = GETPOST('bic','alpha'); + $account->iban = GETPOST('iban','alpha'); + $account->domiciliation = GETPOST('domiciliation','alpha'); + $account->proprio = GETPOST('proprio','alpha'); + $account->owner_address = GETPOST('owner_address','alpha'); + $account->frstrecur = GETPOST('frstrecur'); + $account->rum = GETPOST('rum','alpha'); + $account->datec = dol_now(); + + $db->begin(); + + // This test can be done only once properties were set + if ($account->needIBAN() == 1) + { + if (! GETPOST('iban')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); + $action='create'; + $error++; + } + if (! GETPOST('bic')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); + $action='create'; + $error++; + } + } + + if (! $error) + { + $result = $account->create($user); + if ($result < 0) + { + $error++; + setEventMessages($account->error, $account->errors, 'errors'); + $action='create'; // Force chargement page création + } + + if (empty($account->rum)) + { + $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); + $account->date_rum = dol_now(); + } + } + + if (! $error) + { + $result = $account->update($user); // This will set the UMR number. + if ($result < 0) + { + $error++; + setEventMessages($account->error, $account->errors, 'errors'); + $action='create'; + } + } + + if (! $error) + { + $db->commit(); + + $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + else + { + $db->rollback(); + } + } + } + + if ($action == 'setasdefault') + { + $account = new CompanyBankAccount($db); + $res = $account->setAsDefault(GETPOST('ribid','int')); + if ($res) + { + $url=DOL_URL_ROOT.'/societe/gateway.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + else + { + setEventMessages($db->lasterror, null, 'errors'); + } + } + + if ($action == 'confirm_delete' && $_GET['confirm'] == 'yes') + { + $account = new CompanyBankAccount($db); + if ($account->fetch($ribid?$ribid:$id)) + { + $result = $account->delete($user); + if ($result > 0) + { + $url = $_SERVER['PHP_SELF']."?socid=".$object->id; + header('Location: '.$url); + exit; + } + else + { + setEventMessages($account->error, $account->errors, 'errors'); + } + } + else + { + setEventMessages($account->error, $account->errors, 'errors'); + } + } + + $savid=$id; + + // Actions to build doc + if ($action == 'builddocrib') + { + $action = 'builddoc'; + $moreparams = array( + 'use_companybankid'=>GETPOST('companybankid'), + 'force_dir_output'=>$conf->societe->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->id) + ); + $_POST['lang_id'] = GETPOST('lang_idrib'.GETPOST('companybankid')); + $_POST['model'] = GETPOST('modelrib'.GETPOST('companybankid')); + } + $id = $socid; + $upload_dir = $conf->societe->multidir_output[$object->entity]; + $permissioncreate=$user->rights->societe->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + + $id = $savid; +} + +if (class_exists('Stripe')) +{ + $stripe=new Stripe($db); + $customerstripe=$stripe->CustomerStripe($socid,$stripe->GetStripeAccount($conf->entity)); + if ($customerstripe->id) { + $cu = \Stripe\Customer::retrieve("".$customerstripe->id."",array("stripe_account" => $stripe->GetStripeAccount($conf->entity)));} + $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; + if ($action == 'setasdefault') + { + $cu->default_source = "$source"; // obtained with Stripe.js + $cu->save(); + + header('Location: '.$url); + exit; + } + elseif ($action == 'delete') + { + $cu->sources->retrieve("$source")->delete(); + + header('Location: '.$url); + exit; + } +} + + +/* + * View + */ + +$form = new Form($db); +$formfile = new FormFile($db); + +llxHeader(); + +$head=societe_prepare_head($object); +if (! $id) +{ + $account->fetch(0,$object->id); +} +else +{ + $account->fetch($id); +} +if (empty($account->socid)) $account->socid=$object->id; + +if ($socid && $action == 'edit' && $user->rights->societe->creer) +{ + print ''; + print ''; + print ''; + print ''; +} +if ($socid && $action == 'create' && $user->rights->societe->creer) +{ + print ''; + print ''; + print ''; +} + + +// View +if ($socid && $action != 'edit' && $action != "create") +{ + dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"), -1, 'company'); + + // Confirm delete third party + if ($action == 'delete') + { + print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $account->getRibLabel()), "confirm_delete", '', 0, 1); + } + + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); + + + if (! (empty($conf->stripe->enabled))) + { + print load_fiche_titre($langs->trans('StripeGateways'), '', ''); + + if (is_object($stripe) && $stripe->GetStripeAccount($conf->entity)) + { + $customerstripe=$stripe->CustomerStripe($object->id,$stripe->GetStripeAccount($conf->entity)); + } + + if ($customerstripe->id) { + $input=$customerstripe->sources->data; + } + + print ''."\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + if (is_array($input)) + { + foreach ($input as $src) + { + print ''; + print ''; + // Default + print ''; + print ''; + } + } + if (empty($input)) + { + print ''; + } + print "
    '.$langs->trans('Type').''.$langs->trans('Informations').''.$langs->trans('Default').'
    '; + if ($src->object=='card') + { + if ($src->brand == 'Visa') {$brand='cc-visa';} + elseif ($src->brand == 'MasterCard') {$brand='cc-mastercard';} + elseif ($src->brand == 'American Express') {$brand='cc-amex';} + elseif ($src->brand == 'Discover') {$brand='cc-discover';} + elseif ($src->brand == 'JCB') {$brand='cc-jcb';} + elseif ($src->brand == 'Diners Club') {$brand='cc-diners-club';} + else {$brand='credit-card';} + print ''; + } + elseif ($src->object=='source' && $src->type=='card') + { + if ($src->card->brand == 'Visa') {$brand='cc-visa';} + elseif ($src->card->brand == 'MasterCard') {$brand='cc-mastercard';} + elseif ($src->card->brand == 'American Express') {$brand='cc-amex';} + elseif ($src->card->brand == 'Discover') {$brand='cc-discover';} + elseif ($src->card->brand == 'JCB') {$brand='cc-jcb';} + elseif ($src->card->brand == 'Diners Club') {$brand='cc-diners-club';} + else {$brand='credit-card';} + print ''; + } + elseif ($src->object=='source' && $src->type=='sepa_debit') + { + print ''; + } + + print''; + if ($src->object=='card') + { + print '**** '.$src->last4.' - '.$src->exp_month.'/'.$src->exp_year.''; + print ''; + if ($src->country) + { + $img=picto_from_langcode($src->country); + print $img?$img.' ':''; + print getCountry($src->country,1); + } + else print img_warning().' '.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("CompanyCountry")).''; + } + elseif ($src->object=='source' && $src->type=='card') + { + print $src->owner->name.'
    **** '.$src->card->last4.' - '.$src->card->exp_month.'/'.$src->card->exp_year.''; + print '
    '; + + if ($src->card->country) + { + $img=picto_from_langcode($src->card->country); + print $img?$img.' ':''; + print getCountry($src->card->country,1); + } + else print img_warning().' '.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("CompanyCountry")).''; + } + elseif ($src->object=='source' && $src->type=='sepa_debit') + { + print 'info sepa'; + print ''; + if ($src->sepa_debit->country) + { + $img=picto_from_langcode($src->sepa_debit->country); + print $img?$img.' ':''; + print getCountry($src->sepa_debit->country,1); + } + else print img_warning().' '.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("CompanyCountry")).''; + } + print ''; + if (($cu->default_source!=$src->id)) + { + print ''; + print ""; + print ''; + } else { + print ""; + } + print ''; + if ($user->rights->societe->creer) + { + // print ''; + // print img_picto($langs->trans("Modify"),'edit'); + // print ''; + // print ' '; + print ''; + print ""; + print ''; + } + print '
    '.$langs->trans("NoSource").'
    "; + } + + + // List of bank accounts + + $morehtmlright=''.$langs->trans("Add").''; + + print load_fiche_titre($langs->trans("AllRIB"), $morehtmlright, ''); + + $rib_list = $object->get_all_rib(); + $var = false; + if (is_array($rib_list)) + { + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print ''; + + print ''; + print_liste_field_titre("LabelRIB"); + print_liste_field_titre("Bank"); + print_liste_field_titre("RIB"); + print_liste_field_titre("IBAN"); + print_liste_field_titre("BIC"); + if (! empty($conf->prelevement->enabled)) + { + print print_liste_field_titre("RUM"); + print print_liste_field_titre("WithdrawMode"); + } + print_liste_field_titre("DefaultRIB", '', '', '', '', 'align="center"'); + print_liste_field_titre('', '', '', '', '', 'align="center"'); + print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch '); + print "\n"; + + foreach ($rib_list as $rib) + { + print ''; + // Label + print ''; + // Bank name + print ''; + // Account number + print ''; + // IBAN + print ''; + // BIC + print ''; + + if (! empty($conf->prelevement->enabled)) + { + // RUM + //print ''; + print ''; + + // FRSTRECUR + print ''; + } + + // Default + print ''; + + // Generate doc + print ''; + + // Edit/Delete + print ''; + + print ''; + } + + if (count($rib_list) == 0) + { + $colspan=8; + if (! empty($conf->prelevement->enabled)) $colspan+=2; + print ''; + } + + print '
    '.$rib->label.''.$rib->bank.''; + $string=''; + foreach ($rib->getFieldsToShow() as $val) { + + if ($val == 'BankCode') { + $string .= $rib->code_banque.' '; + } elseif ($val == 'BankAccountNumber') { + $string .= $rib->number.' '; + } elseif ($val == 'DeskCode') { + $string .= $rib->code_guichet.' '; + } elseif ($val == 'BankAccountNumberKey') { + $string .= $rib->cle_rib.' '; + /* Already output after + }elseif ($val == 'BIC') { + $string .= $rib->bic.' '; + }elseif ($val == 'IBAN') { + $string .= $rib->iban.' ';*/ + } + } + if (! empty($rib->label) && $rib->number) { + if (! checkBanForAccount($rib)) { + $string.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); + } else { + $string.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); + } + } + + print $string; + print ''.$rib->iban; + if (! empty($rib->iban)) { + if (! checkIbanForAccount($rib)) { + print ' '.img_picto($langs->trans("IbanNotValid"),'warning'); + } else { + print ' '.img_picto($langs->trans("IbanValid"),'info'); + } + } + print ''.$rib->bic; + if (! empty($rib->bic)) { + if (! checkSwiftForAccount($rib)) { + print ' '.img_picto($langs->trans("SwiftNotValid"),'warning'); + } else { + print ' '.img_picto($langs->trans("SwiftValid"),'info'); + } + } + print ''.$prelevement->buildRumNumber($object->code_client, $rib->datec, $rib->id).''.$rib->rum.''.$rib->frstrecur.''; + if (!$rib->default_rib) { + print ''; + print img_picto($langs->trans("Disabled"),'off'); + print ''; + } else { + print img_picto($langs->trans("Enabled"),'on'); + } + print ''; + + $buttonlabel = $langs->trans("BuildDoc"); + $forname='builddocrib'.$rib->id; + + include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php'; + $modellist=ModeleBankAccountDoc::liste_modeles($db); + + $out = ''; + if (is_array($modellist) && count($modellist)) + { + $out.= ''; + $out.= ''; + $out.= ''; + $out.= ''; + $out.= ''; + + if (is_array($modellist) && count($modellist) == 1) // If there is only one element + { + $arraykeys=array_keys($modellist); + $modelselected=$arraykeys[0]; + } + if (! empty($conf->global->BANKADDON_PDF)) $modelselected = $conf->global->BANKADDON_PDF; + + $out.= $form->selectarray('modelrib'.$rib->id, $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100'); + $out.= ajax_combobox('modelrib'.$rib->id); + + // Language code (if multilang) + if ($conf->global->MAIN_MULTILANGS) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; + $formadmin=new FormAdmin($db); + $defaultlang=$codelang?$codelang:$langs->getDefaultLang(); + $morecss='maxwidth150'; + if (! empty($conf->browser->phone)) $morecss='maxwidth100'; + $out.= $formadmin->select_language($defaultlang, 'lang_idrib'.$rib->id, 0, 0, 0, 0, 0, $morecss); + } + // Button + $genbutton = 'dol_no_mouse_hover) && $modulepart != 'unpaid') + { + $langs->load("errors"); + $genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated")); + } + if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton=''; + if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton=''; + $out.= $genbutton; + $out.= ''; + } + print $out; + print ''; + if ($user->rights->societe->creer) + { + print ''; + print img_picto($langs->trans("Modify"),'edit'); + print ''; + + print ' '; + + print ''; + print img_picto($langs->trans("Delete"),'delete'); + print ''; + } + print '
    '.$langs->trans("NoBANRecord").'
    '; + print '
    '; + } else { + dol_print_error($db); + } + + dol_fiche_end(); +/* + if ($socid && $action != 'edit' && $action != 'create') + { + // Barre d'actions + print '
    '; + + if ($user->rights->societe->creer) + { + print ''.$langs->trans("Add").''; + } + + print '
    '; + } +*/ + if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC)) + { + print '
    '; + print ''; // ancre + + /* + * Documents generes + */ + $filedir=$conf->societe->multidir_output[$object->entity].'/'.$object->id; + $urlsource=$_SERVER["PHP_SELF"]."?socid=".$object->id; + $genallowed=$user->rights->societe->lire; + $delallowed=$user->rights->societe->creer; + + $var=true; + + print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang); + + print '
    '; + + + print '
    '; + + print '
    '; + } + /* + include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php'; + $modellist=ModeleBankAccountDoc::liste_modeles($db); + //print '
    '; + if (is_array($modellist) && count($modellist) == 1) // If there is only one element + { + $arraykeys=array_keys($modellist); + $modelselected=$arraykeys[0]; + } + $out.= $form->selectarray('model', $modellist, $modelselected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100'); + $out.= ajax_combobox('model'); + //print $out; + $buttonlabel=$langs->trans("Generate"); + $genbutton = ''; // TODO Add link to generate doc + */ +} + +// Edit +if ($socid && $action == 'edit' && $user->rights->societe->creer) +{ + dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); + + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); + + print '
    '; + + print '
    '; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + // Show fields of bank account + foreach ($account->getFieldsToShow(1) as $val) { + + $require=false; + if ($val == 'BankCode') { + $name = 'code_banque'; + $size = 8; + $content = $account->code_banque; + } elseif ($val == 'DeskCode') { + $name = 'code_guichet'; + $size = 8; + $content = $account->code_guichet; + } elseif ($val == 'BankAccountNumber') { + $name = 'number'; + $size = 18; + $content = $account->number; + } elseif ($val == 'BankAccountNumberKey') { + $name = 'cle_rib'; + $size = 3; + $content = $account->cle_rib; + } elseif ($val == 'IBAN') { + $name = 'iban'; + $size = 30; + $content = $account->iban; + if ($account->needIBAN()) $require=true; + } elseif ($val == 'BIC') { + $name = 'bic'; + $size = 12; + $content = $account->bic; + if ($account->needIBAN()) $require=true; + } + + print ''.$langs->trans($val).''; + print ''; + print ''; + } + + print '"; + + print ''; + print ''; + print "\n"; + + print '"; + + print '
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("BankName").'
    '.$langs->trans("BankAccountDomiciliation").''; + print '
    '.$langs->trans("BankAccountOwner").'
    '.$langs->trans("BankAccountOwnerAddress").''; + print '
    '; + + if ($conf->prelevement->enabled) + { + print '
    '; + + print ''; + + if (empty($account->rum)) $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); + + // RUM + print ''; + print ''; + + print ''; + + print '
    '.$langs->trans("RUM").'
    '.$langs->trans("WithdrawMode").''; + $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); + print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur')?GETPOST('frstrecur'):$account->frstrecur), 0); + print '
    '; + } + + print '
    '; + + dol_fiche_end(); + + print '
    '; + print ''; + print '     '; + print ''; + print '
    '; +} + + +// Create +if ($socid && $action == 'create' && $user->rights->societe->creer) +{ + dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); + + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); + + print '
    '; + + print '
    '; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + // Show fields of bank account + foreach ($account->getFieldsToShow(1) as $val) { + + $require=false; + if ($val == 'BankCode') { + $name = 'code_banque'; + $size = 8; + } elseif ($val == 'DeskCode') { + $name = 'code_guichet'; + $size = 8; + } elseif ($val == 'BankAccountNumber') { + $name = 'number'; + $size = 18; + } elseif ($val == 'BankAccountNumberKey') { + $name = 'cle_rib'; + $size = 3; + } elseif ($val == 'IBAN') { + $name = 'iban'; + $size = 30; + if ($account->needIBAN()) $require=true; + } elseif ($val == 'BIC') { + $name = 'bic'; + $size = 12; + if ($account->needIBAN()) $require=true; + } + + print ''.$langs->trans($val).''; + print ''; + print ''; + } + + print '"; + + print ''; + print ''; + print "\n"; + + print '"; + + print '
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("Bank").'
    '.$langs->trans("BankAccountDomiciliation").''; + print '
    '.$langs->trans("BankAccountOwner").'
    '.$langs->trans("BankAccountOwnerAddress").''; + print '
    '; + + if ($conf->prelevement->enabled) + { + print '
    '; + + print ''; + + // RUM + print ''; + print ''; + + print ''; + + print '
    '.$langs->trans("RUM").'
    '.$langs->trans("RUMWillBeGenerated").'
    '.$langs->trans("WithdrawMode").''; + $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); + print $form->selectarray("frstrecur", $tblArraychoice, (isset($_POST['frstrecur'])?GETPOST('frstrecur'):'FRST'), 0); + print '
    '; + } + + print '
    '; + + dol_fiche_end(); + + print '
    '; + print ''; + print '     '; + print ''; + print '
    '; +} + +if ($socid && $action == 'edit' && $user->rights->societe->creer) +{ + print ''; +} +if ($socid && $action == 'create' && $user->rights->societe->creer) +{ + print ''; +} + + +llxFooter(); + +$db->close(); From acc29ea1639ac0daa4f31f98822422e8b97abc8b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 16:19:13 +0100 Subject: [PATCH 055/413] FIX #8219 --- htdocs/fourn/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 8d10d55b3bd..817eb99d8f7 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -587,7 +587,7 @@ if ($object->id > 0) print '
    '; print ''; - print ''; + print ''; print ''; print '
    '.$langs->trans("LastSupplierOrders",($num<$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllOrders").' '.$num.''.$langs->trans("AllOrders").' '.$num.''.img_picto($langs->trans("Statistics"),'stats').'
    '; print '
    '; -if ($charge->source->type=='card'){ +if ($charge->source->object=='card'){ + print $langs->trans("card"); +} +elseif ($charge->source->type=='card'){ print $langs->trans("card"); } elseif ($charge->source->type=='three_d_secure'){ print $langs->trans("card3DS"); From 7edec37b286b4c10050a34ff2e2fc16acb7817e0 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Wed, 7 Mar 2018 17:27:45 +0100 Subject: [PATCH 058/413] FIx call stripe.class.php --- htdocs/stripe/transaction.php | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/htdocs/stripe/transaction.php b/htdocs/stripe/transaction.php index b350154bee9..2a37b5a55a5 100644 --- a/htdocs/stripe/transaction.php +++ b/htdocs/stripe/transaction.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2018 PtibogXIV * * 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 @@ -53,7 +53,7 @@ llxHeader('', $langs->trans("StripeTransactionList")); $form = new Form($db); $societestatic = new societe($db); $acc = new Account($db); -$stripeconnect=new StripeConnexion($db); +$stripe=new Stripe($db); if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); @@ -87,7 +87,7 @@ if (!$rowid){ print "
    '.dol_print_date($txn->created,'%d/%m/%Y %H:%M').""; -if ($charge->refunded=='1'){ - print $langs->trans("refunded"); -} elseif ($charge->paid=='1'){ - print $langs->trans("".$charge->status.""); -} else { -$label="Message: ".$charge->failure_message."
    "; -$label.="Réseau: ".$charge->outcome->network_status."
    "; -$label.="Statut: ".$langs->trans("".$charge->outcome->seller_message.""); - print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1); -} + print "
    '.$txn->type.''.$morehtmlright.''.$morehtmlright.'
    '."\n"; From 69ef6a9316363895c8708b4fe2d0529daa823cbe Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 18:32:25 +0100 Subject: [PATCH 060/413] Fix data on thirdparty tooltip --- htdocs/compta/paiement/card.php | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/htdocs/compta/paiement/card.php b/htdocs/compta/paiement/card.php index 6179fb9ac22..3a6727b4299 100644 --- a/htdocs/compta/paiement/card.php +++ b/htdocs/compta/paiement/card.php @@ -338,15 +338,18 @@ if ($resql) { $objp = $db->fetch_object($resql); - print '
    '; @@ -355,8 +358,6 @@ if ($resql) // Third party print ''; - $thirdpartystatic->id=$objp->socid; - $thirdpartystatic->name=$objp->name; print $thirdpartystatic->getNomUrl(1); print '
    '.($prefix?$prefix.' > ':'').$key.''; if (in_array($key, array('date','datef','dateh','datec','datem','datep'))) { + /*var_dump(is_object($val)); + var_dump(is_array($val)); + var_dump(is_array($val)); + var_dump(@get_class($val)); + var_dump($val);*/ $s.=dol_print_date($val, 'dayhour'); } else diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 13a2840e360..ee41a139152 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -18,10 +18,23 @@ * See https://medium.com/@lhartikk/a-blockchain-in-200-lines-of-code-963cc1cc0e54 */ + + + +/*ini_set('unserialize_callback_func', 'mycallback'); + +function mycallback($classname) +{ + //var_dump($classname); + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + +}*/ + + + /** * Class to manage Blocked Log */ - class BlockedLog { /** @@ -636,7 +649,7 @@ class BlockedLog $this->fk_user = $obj->fk_user; $this->user_fullname = $obj->user_fullname; - $this->object_data = unserialize($obj->object_data); + $this->object_data = $this->dolDecodeBlockedData($obj->object_data); $this->signature = $obj->signature; $this->signature_line = $obj->signature_line; @@ -658,6 +671,30 @@ class BlockedLog } + + /** + * Decode data + * + * @param string $mode 0=unserialize, 1=json_decode + * @return string Value unserialized + */ + public function dolDecodeBlockedData($data, $mode=0) + { + try + { + //include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + //include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $aaa = unserialize($data); + //$aaa = unserialize($data); + } + catch(Exception $e) + { + //print $e->getErrs); + } + return $aaa; + } + + /** * Set block certified by authority * From 317a5f5b2f3aa109fbfb22d9e0b7cd737868c111 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 14:33:29 +0100 Subject: [PATCH 062/413] Fix by adding a redirect to avoid the order2billing being done twice. --- htdocs/commande/list.php | 2 +- htdocs/core/actions_massactions.inc.php | 29 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 29590820b72..4e589aa6529 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -670,7 +670,7 @@ if ($resql) // Status billed if (! empty($arrayfields['c.facture']['checked'])) { - print ''; + print ''; print $form->selectyesno('billed', $billed, 1, 0, 1); print ''; if (($cu->default_source!=$src->id)) { - print ''; + print ''; print ""; print ''; } else { @@ -515,7 +517,7 @@ if ($socid && $action != 'edit' && $action != "create") print ''; if ($user->rights->societe->creer) { - // print ''; + // print ''; // print img_picto($langs->trans("Modify"),'edit'); // print ''; // print ' '; @@ -634,7 +636,7 @@ if ($socid && $action != 'edit' && $action != "create") // Default print ''; if (!$rib->default_rib) { - print ''; + print ''; print img_picto($langs->trans("Disabled"),'off'); print ''; } else { From c3e211f3f78d2ff2e4ea7185fc0871c402c1d788 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Thu, 8 Mar 2018 02:08:43 +0100 Subject: [PATCH 067/413] Delete gateway.php --- htdocs/societe/gateway.php | 985 ------------------------------------- 1 file changed, 985 deletions(-) delete mode 100644 htdocs/societe/gateway.php diff --git a/htdocs/societe/gateway.php b/htdocs/societe/gateway.php deleted file mode 100644 index 79a9a60bb96..00000000000 --- a/htdocs/societe/gateway.php +++ /dev/null @@ -1,985 +0,0 @@ - - * Copyright (C) 2003 Jean-Louis Bergamo - * Copyright (C) 2004-2016 Laurent Destailleur - * Copyright (C) 2005-2009 Regis Houssin - * Copyright (C) 2013 Peter Fontaine - * Copyright (C) 2015-2016 Marcos García - * Copyright (C) 2017 Ferran Marcet - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/societe/rib.php - * \ingroup societe - * \brief BAN tab for companies - */ - -require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; -require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; - -$langs->load("companies"); -$langs->load("commercial"); -$langs->load("banks"); -$langs->load("bills"); - -// Security check -$socid = GETPOST("socid","int"); -if ($user->societe_id) $socid=$user->societe_id; -$result = restrictedArea($user, 'societe','',''); - -$id=GETPOST("id","int"); -$source=GETPOST("source","alpha"); -$ribid=GETPOST("ribid","int"); -$action=GETPOST("action", 'alpha', 3); - -$object = new Societe($db); -$object->fetch($socid); - -$account = new CompanyBankAccount($db); -$prelevement = new BonPrelevement($db); - -$extrafields = new ExtraFields($db); - -// fetch optionals attributes and labels -$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); - -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('thirdpartybancard','globalcard')); - - -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('thirdpartybancard')); - - - -/* - * Actions - */ - -$parameters=array('id'=>$socid, 'objcanvas'=>$objcanvas); -$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - -if (empty($reshook)) -{ - if ($cancel) - { - $action=''; - if (! empty($backtopage)) - { - header("Location: ".$backtopage); - exit; - } - } - - - if ($action == 'update' && ! $_POST["cancel"]) - { - // Modification - if (! GETPOST('label')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $action='edit'; - $error++; - } - if (! GETPOST('bank')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); - $action='edit'; - $error++; - } - if ($account->needIBAN() == 1) - { - if (! GETPOST('iban')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); - $action='edit'; - $error++; - } - if (! GETPOST('bic')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); - $action='edit'; - $error++; - } - } - - $account->fetch($id); - if (! $error) - { - $account->socid = $object->id; - - $account->bank = GETPOST('bank','alpha'); - $account->label = GETPOST('label','alpha'); - $account->courant = GETPOST('courant','alpha'); - $account->clos = GETPOST('clos','alpha'); - $account->code_banque = GETPOST('code_banque','alpha'); - $account->code_guichet = GETPOST('code_guichet','alpha'); - $account->number = GETPOST('number','alpha'); - $account->cle_rib = GETPOST('cle_rib','alpha'); - $account->bic = GETPOST('bic','alpha'); - $account->iban = GETPOST('iban','alpha'); - $account->domiciliation = GETPOST('domiciliation','alpha'); - $account->proprio = GETPOST('proprio','alpha'); - $account->owner_address = GETPOST('owner_address','alpha'); - $account->frstrecur = GETPOST('frstrecur','alpha'); - $account->rum = GETPOST('rum','alpha'); - if (empty($account->rum)) - { - $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - $account->date_rum = dol_now(); - } - - $result = $account->update($user); - if (! $result) - { - setEventMessages($account->error, $account->errors, 'errors'); - } - else - { - // If this account is the default bank account, we disable others - if ($account->default_rib) - { - $account->setAsDefault($id); // This will make sure there is only one default rib - } - - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - } - } - - if ($action == 'add' && ! $_POST["cancel"]) - { - $error=0; - - if (! GETPOST('label')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $action='create'; - $error++; - } - if (! GETPOST('bank')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); - $action='create'; - $error++; - } - - if (! $error) - { - // Ajout - $account = new CompanyBankAccount($db); - - $account->socid = $object->id; - - $account->bank = GETPOST('bank','alpha'); - $account->label = GETPOST('label','alpha'); - $account->courant = GETPOST('courant','alpha'); - $account->clos = GETPOST('clos','alpha'); - $account->code_banque = GETPOST('code_banque','alpha'); - $account->code_guichet = GETPOST('code_guichet','alpha'); - $account->number = GETPOST('number','alpha'); - $account->cle_rib = GETPOST('cle_rib','alpha'); - $account->bic = GETPOST('bic','alpha'); - $account->iban = GETPOST('iban','alpha'); - $account->domiciliation = GETPOST('domiciliation','alpha'); - $account->proprio = GETPOST('proprio','alpha'); - $account->owner_address = GETPOST('owner_address','alpha'); - $account->frstrecur = GETPOST('frstrecur'); - $account->rum = GETPOST('rum','alpha'); - $account->datec = dol_now(); - - $db->begin(); - - // This test can be done only once properties were set - if ($account->needIBAN() == 1) - { - if (! GETPOST('iban')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); - $action='create'; - $error++; - } - if (! GETPOST('bic')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); - $action='create'; - $error++; - } - } - - if (! $error) - { - $result = $account->create($user); - if ($result < 0) - { - $error++; - setEventMessages($account->error, $account->errors, 'errors'); - $action='create'; // Force chargement page création - } - - if (empty($account->rum)) - { - $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - $account->date_rum = dol_now(); - } - } - - if (! $error) - { - $result = $account->update($user); // This will set the UMR number. - if ($result < 0) - { - $error++; - setEventMessages($account->error, $account->errors, 'errors'); - $action='create'; - } - } - - if (! $error) - { - $db->commit(); - - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - else - { - $db->rollback(); - } - } - } - - if ($action == 'setasdefault') - { - $account = new CompanyBankAccount($db); - $res = $account->setAsDefault(GETPOST('ribid','int')); - if ($res) - { - $url=DOL_URL_ROOT.'/societe/gateway.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - else - { - setEventMessages($db->lasterror, null, 'errors'); - } - } - - if ($action == 'confirm_delete' && $_GET['confirm'] == 'yes') - { - $account = new CompanyBankAccount($db); - if ($account->fetch($ribid?$ribid:$id)) - { - $result = $account->delete($user); - if ($result > 0) - { - $url = $_SERVER['PHP_SELF']."?socid=".$object->id; - header('Location: '.$url); - exit; - } - else - { - setEventMessages($account->error, $account->errors, 'errors'); - } - } - else - { - setEventMessages($account->error, $account->errors, 'errors'); - } - } - - $savid=$id; - - // Actions to build doc - if ($action == 'builddocrib') - { - $action = 'builddoc'; - $moreparams = array( - 'use_companybankid'=>GETPOST('companybankid'), - 'force_dir_output'=>$conf->societe->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->id) - ); - $_POST['lang_id'] = GETPOST('lang_idrib'.GETPOST('companybankid')); - $_POST['model'] = GETPOST('modelrib'.GETPOST('companybankid')); - } - $id = $socid; - $upload_dir = $conf->societe->multidir_output[$object->entity]; - $permissioncreate=$user->rights->societe->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - - $id = $savid; -} - -$stripeconnect=new StripeConnexion($db); -$customer=$stripeconnect->CustomerStripe($socid,$stripeconnect->GetStripeAccount($conf->entity)); -if ($customer->id) { -$cu = \Stripe\Customer::retrieve("".$customer->id."",array("stripe_account" => $stripeconnect->GetStripeAccount($conf->entity)));} -$url=DOL_URL_ROOT.'/societe/gateway.php?socid='.$object->id; -if ($action == 'setasdefault') -{ -$cu->default_source = "$source"; // obtained with Stripe.js -$cu->save(); - -header('Location: '.$url); -exit; -} -elseif ($action == 'delete') -{ -$cu->sources->retrieve("$source")->delete(); - -header('Location: '.$url); -exit; -} - - -/* - * View - */ - -$form = new Form($db); -$formfile = new FormFile($db); - -llxHeader(); - -$head=societe_prepare_head($object); -if (! $id) -{ - $account->fetch(0,$object->id); -} -else -{ - $account->fetch($id); -} -if (empty($account->socid)) $account->socid=$object->id; - -if ($socid && $action == 'edit' && $user->rights->societe->creer) -{ - print '
    '; - print ''; - print ''; - print ''; -} -if ($socid && $action == 'create' && $user->rights->societe->creer) -{ - print ''; - print ''; - print ''; -} - - -// View -if ($socid && $action != 'edit' && $action != "create") -{ - dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"), -1, 'company'); - - // Confirm delete third party - if ($action == 'delete') - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $account->getRibLabel()), "confirm_delete", '', 0, 1); - } - - $linkback = ''.$langs->trans("BackToList").''; - - dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); - -if (! (empty($conf->stripe->enabled))){ -print '
    '; -print $langs->trans('StripeGateways').''; -if ($stripeconnect->GetStripeAccount($conf->entity)) { -$customer=$stripeconnect->CustomerStripe($object->id,$stripeconnect->GetStripeAccount($conf->entity)); -} - -if ($customer->id) { -$input=$customer->sources->data; -} -print ''."\n"; -print ''; -print ''; -print ''; -print ''; -print ''; -print "\n"; - -foreach ($input as $src) { -print ''; -print ''; - // Default - print ''; -print ''; -} -if (empty($input)) -{ -print ''; -} -print "
    '.$langs->trans('Type').''.$langs->trans('Informations').''.$langs->trans('Default').'
    '; -if ($src->object=='card'){ -if ($src->brand == 'Visa') {$brand='cc-visa';} -elseif ($src->brand == 'MasterCard') {$brand='cc-mastercard';} -elseif ($src->brand == 'American Express') {$brand='cc-amex';} -elseif ($src->brand == 'Discover') {$brand='cc-discover';} -elseif ($src->brand == 'JCB') {$brand='cc-jcb';} -elseif ($src->brand == 'Diners Club') {$brand='cc-diners-club';} -else {$brand='credit-card';} -print ''; -} -elseif ($src->object=='source' && $src->type=='card'){ -if ($src->card->brand == 'Visa') {$brand='cc-visa';} -elseif ($src->card->brand == 'MasterCard') {$brand='cc-mastercard';} -elseif ($src->card->brand == 'American Express') {$brand='cc-amex';} -elseif ($src->card->brand == 'Discover') {$brand='cc-discover';} -elseif ($src->card->brand == 'JCB') {$brand='cc-jcb';} -elseif ($src->card->brand == 'Diners Club') {$brand='cc-diners-club';} -else {$brand='credit-card';} - -print ''; -} -elseif ($src->object=='source' && $src->type=='sepa_debit'){ -print ''; -} -print''; -if ($src->object=='card'){ -print '**** '.$src->last4.' - '.$src->exp_month.'/'.$src->exp_year.''; -print ''; - if ($src->country) - { - $img=picto_from_langcode($src->country); - print $img?$img.' ':''; - print getCountry($src->country,1); - } - else print img_warning().' '.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("CompanyCountry")).''; -} -elseif ($src->object=='source' && $src->type=='card'){ -print $src->owner->name.'
    **** '.$src->card->last4.' - '.$src->card->exp_month.'/'.$src->card->exp_year.''; -print '
    '; - if ($src->card->country) - { - $img=picto_from_langcode($src->card->country); - print $img?$img.' ':''; - print getCountry($src->card->country,1); - } - else print img_warning().' '.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("CompanyCountry")).''; -} -elseif ($src->object=='source' && $src->type=='sepa_debit'){ -print 'info sepa'; -print ''; - if ($src->sepa_debit->country) - { - $img=picto_from_langcode($src->sepa_debit->country); - print $img?$img.' ':''; - print getCountry($src->sepa_debit->country,1); - } - else print img_warning().' '.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("CompanyCountry")).''; -} -print ''; - if (($cu->default_source!=$src->id)) { - print ''; - print ""; - print ''; - } else { - print ""; - } - print ''; - if ($user->rights->societe->creer) - { -// print ''; -// print img_picto($langs->trans("Modify"),'edit'); -// print ''; -// print ' '; - print ''; - print ""; - print ''; - } -print '
    '.$langs->trans("NoSource").'
    "; -} - - // List of bank accounts - - $morehtmlright=''.$langs->trans("Add").''; - - print load_fiche_titre($langs->trans("AllRIB"), $morehtmlright, ''); - - $rib_list = $object->get_all_rib(); - $var = false; - if (is_array($rib_list)) - { - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print ''; - - print ''; - print_liste_field_titre("LabelRIB"); - print_liste_field_titre("Bank"); - print_liste_field_titre("RIB"); - print_liste_field_titre("IBAN"); - print_liste_field_titre("BIC"); - if (! empty($conf->prelevement->enabled)) - { - print print_liste_field_titre("RUM"); - print print_liste_field_titre("WithdrawMode"); - } - print_liste_field_titre("DefaultRIB", '', '', '', '', 'align="center"'); - print_liste_field_titre('', '', '', '', '', 'align="center"'); - print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; - - foreach ($rib_list as $rib) - { - print ''; - // Label - print ''; - // Bank name - print ''; - // Account number - print ''; - // IBAN - print ''; - // BIC - print ''; - - if (! empty($conf->prelevement->enabled)) - { - // RUM - //print ''; - print ''; - - // FRSTRECUR - print ''; - } - - // Default - print ''; - - // Generate doc - print ''; - - // Edit/Delete - print ''; - - print ''; - } - - if (count($rib_list) == 0) - { - $colspan=8; - if (! empty($conf->prelevement->enabled)) $colspan+=2; - print ''; - } - - print '
    '.$rib->label.''.$rib->bank.''; - $string=''; - foreach ($rib->getFieldsToShow() as $val) { - - if ($val == 'BankCode') { - $string .= $rib->code_banque.' '; - } elseif ($val == 'BankAccountNumber') { - $string .= $rib->number.' '; - } elseif ($val == 'DeskCode') { - $string .= $rib->code_guichet.' '; - } elseif ($val == 'BankAccountNumberKey') { - $string .= $rib->cle_rib.' '; - /* Already output after - }elseif ($val == 'BIC') { - $string .= $rib->bic.' '; - }elseif ($val == 'IBAN') { - $string .= $rib->iban.' ';*/ - } - } - if (! empty($rib->label) && $rib->number) { - if (! checkBanForAccount($rib)) { - $string.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); - } else { - $string.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); - } - } - - print $string; - print ''.$rib->iban; - if (! empty($rib->iban)) { - if (! checkIbanForAccount($rib)) { - print ' '.img_picto($langs->trans("IbanNotValid"),'warning'); - } else { - print ' '.img_picto($langs->trans("IbanValid"),'info'); - } - } - print ''.$rib->bic; - if (! empty($rib->bic)) { - if (! checkSwiftForAccount($rib)) { - print ' '.img_picto($langs->trans("SwiftNotValid"),'warning'); - } else { - print ' '.img_picto($langs->trans("SwiftValid"),'info'); - } - } - print ''.$prelevement->buildRumNumber($object->code_client, $rib->datec, $rib->id).''.$rib->rum.''.$rib->frstrecur.''; - if (!$rib->default_rib) { - print ''; - print img_picto($langs->trans("Disabled"),'off'); - print ''; - } else { - print img_picto($langs->trans("Enabled"),'on'); - } - print ''; - - $buttonlabel = $langs->trans("BuildDoc"); - $forname='builddocrib'.$rib->id; - - include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php'; - $modellist=ModeleBankAccountDoc::liste_modeles($db); - - $out = ''; - if (is_array($modellist) && count($modellist)) - { - $out.= ''; - $out.= ''; - $out.= ''; - $out.= ''; - $out.= ''; - - if (is_array($modellist) && count($modellist) == 1) // If there is only one element - { - $arraykeys=array_keys($modellist); - $modelselected=$arraykeys[0]; - } - if (! empty($conf->global->BANKADDON_PDF)) $modelselected = $conf->global->BANKADDON_PDF; - - $out.= $form->selectarray('modelrib'.$rib->id, $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100'); - $out.= ajax_combobox('modelrib'.$rib->id); - - // Language code (if multilang) - if ($conf->global->MAIN_MULTILANGS) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; - $formadmin=new FormAdmin($db); - $defaultlang=$codelang?$codelang:$langs->getDefaultLang(); - $morecss='maxwidth150'; - if (! empty($conf->browser->phone)) $morecss='maxwidth100'; - $out.= $formadmin->select_language($defaultlang, 'lang_idrib'.$rib->id, 0, 0, 0, 0, 0, $morecss); - } - // Button - $genbutton = 'dol_no_mouse_hover) && $modulepart != 'unpaid') - { - $langs->load("errors"); - $genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated")); - } - if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton=''; - if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton=''; - $out.= $genbutton; - $out.= ''; - } - print $out; - print ''; - if ($user->rights->societe->creer) - { - print ''; - print img_picto($langs->trans("Modify"),'edit'); - print ''; - - print ' '; - - print ''; - print img_picto($langs->trans("Delete"),'delete'); - print ''; - } - print '
    '.$langs->trans("NoBANRecord").'
    '; - print '
    '; - } else { - dol_print_error($db); - } - - dol_fiche_end(); -/* - if ($socid && $action != 'edit' && $action != 'create') - { - // Barre d'actions - print '
    '; - - if ($user->rights->societe->creer) - { - print ''.$langs->trans("Add").''; - } - - print '
    '; - } -*/ - if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC)) - { - print '
    '; - print ''; // ancre - - /* - * Documents generes - */ - $filedir=$conf->societe->multidir_output[$object->entity].'/'.$object->id; - $urlsource=$_SERVER["PHP_SELF"]."?socid=".$object->id; - $genallowed=$user->rights->societe->lire; - $delallowed=$user->rights->societe->creer; - - $var=true; - - print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang); - - print '
    '; - - - print '
    '; - - print '
    '; - } - /* - include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php'; - $modellist=ModeleBankAccountDoc::liste_modeles($db); - //print '
    '; - if (is_array($modellist) && count($modellist) == 1) // If there is only one element - { - $arraykeys=array_keys($modellist); - $modelselected=$arraykeys[0]; - } - $out.= $form->selectarray('model', $modellist, $modelselected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100'); - $out.= ajax_combobox('model'); - //print $out; - $buttonlabel=$langs->trans("Generate"); - $genbutton = ''; // TODO Add link to generate doc - */ -} - -// Edit -if ($socid && $action == 'edit' && $user->rights->societe->creer) -{ - dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); - - $linkback = ''.$langs->trans("BackToList").''; - - dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); - - print '
    '; - - print '
    '; - print ''; - - print ''; - print ''; - - print ''; - print ''; - - // Show fields of bank account - foreach ($account->getFieldsToShow(1) as $val) { - - $require=false; - if ($val == 'BankCode') { - $name = 'code_banque'; - $size = 8; - $content = $account->code_banque; - } elseif ($val == 'DeskCode') { - $name = 'code_guichet'; - $size = 8; - $content = $account->code_guichet; - } elseif ($val == 'BankAccountNumber') { - $name = 'number'; - $size = 18; - $content = $account->number; - } elseif ($val == 'BankAccountNumberKey') { - $name = 'cle_rib'; - $size = 3; - $content = $account->cle_rib; - } elseif ($val == 'IBAN') { - $name = 'iban'; - $size = 30; - $content = $account->iban; - if ($account->needIBAN()) $require=true; - } elseif ($val == 'BIC') { - $name = 'bic'; - $size = 12; - $content = $account->bic; - if ($account->needIBAN()) $require=true; - } - - print ''.$langs->trans($val).''; - print ''; - print ''; - } - - print '"; - - print ''; - print ''; - print "\n"; - - print '"; - - print '
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("BankName").'
    '.$langs->trans("BankAccountDomiciliation").''; - print '
    '.$langs->trans("BankAccountOwner").'
    '.$langs->trans("BankAccountOwnerAddress").''; - print '
    '; - - if ($conf->prelevement->enabled) - { - print '
    '; - - print ''; - - if (empty($account->rum)) $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - - // RUM - print ''; - print ''; - - print ''; - - print '
    '.$langs->trans("RUM").'
    '.$langs->trans("WithdrawMode").''; - $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); - print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur')?GETPOST('frstrecur'):$account->frstrecur), 0); - print '
    '; - } - - print '
    '; - - dol_fiche_end(); - - print '
    '; - print ''; - print '     '; - print ''; - print '
    '; -} - - -// Create -if ($socid && $action == 'create' && $user->rights->societe->creer) -{ - dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); - - $linkback = ''.$langs->trans("BackToList").''; - - dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); - - print '
    '; - - print '
    '; - print ''; - - print ''; - print ''; - - print ''; - print ''; - - // Show fields of bank account - foreach ($account->getFieldsToShow(1) as $val) { - - $require=false; - if ($val == 'BankCode') { - $name = 'code_banque'; - $size = 8; - } elseif ($val == 'DeskCode') { - $name = 'code_guichet'; - $size = 8; - } elseif ($val == 'BankAccountNumber') { - $name = 'number'; - $size = 18; - } elseif ($val == 'BankAccountNumberKey') { - $name = 'cle_rib'; - $size = 3; - } elseif ($val == 'IBAN') { - $name = 'iban'; - $size = 30; - if ($account->needIBAN()) $require=true; - } elseif ($val == 'BIC') { - $name = 'bic'; - $size = 12; - if ($account->needIBAN()) $require=true; - } - - print ''.$langs->trans($val).''; - print ''; - print ''; - } - - print '"; - - print ''; - print ''; - print "\n"; - - print '"; - - print '
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("Bank").'
    '.$langs->trans("BankAccountDomiciliation").''; - print '
    '.$langs->trans("BankAccountOwner").'
    '.$langs->trans("BankAccountOwnerAddress").''; - print '
    '; - - if ($conf->prelevement->enabled) - { - print '
    '; - - print ''; - - // RUM - print ''; - print ''; - - print ''; - - print '
    '.$langs->trans("RUM").'
    '.$langs->trans("RUMWillBeGenerated").'
    '.$langs->trans("WithdrawMode").''; - $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); - print $form->selectarray("frstrecur", $tblArraychoice, (isset($_POST['frstrecur'])?GETPOST('frstrecur'):'FRST'), 0); - print '
    '; - } - - print '
    '; - - dol_fiche_end(); - - print '
    '; - print ''; - print '     '; - print ''; - print '
    '; -} - -if ($socid && $action == 'edit' && $user->rights->societe->creer) -{ - print ''; -} -if ($socid && $action == 'create' && $user->rights->societe->creer) -{ - print ''; -} - - -llxFooter(); - -$db->close(); From 5c04c2886ca681cd08d3089569e45e51b9d1412d Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Thu, 8 Mar 2018 02:09:27 +0100 Subject: [PATCH 068/413] Delete because replace by paymentmodes.php --- htdocs/societe/rib.php | 932 ----------------------------------------- 1 file changed, 932 deletions(-) delete mode 100644 htdocs/societe/rib.php diff --git a/htdocs/societe/rib.php b/htdocs/societe/rib.php deleted file mode 100644 index d4263cc0b21..00000000000 --- a/htdocs/societe/rib.php +++ /dev/null @@ -1,932 +0,0 @@ - - * Copyright (C) 2003 Jean-Louis Bergamo - * Copyright (C) 2004-2016 Laurent Destailleur - * Copyright (C) 2005-2009 Regis Houssin - * Copyright (C) 2013 Peter Fontaine - * Copyright (C) 2015-2016 Marcos García - * Copyright (C) 2017 Ferran Marcet - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/societe/rib.php - * \ingroup societe - * \brief BAN tab for companies - */ - -require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; - -$langs->load("companies"); -$langs->load("commercial"); -$langs->load("banks"); -$langs->load("bills"); - -// Security check -$socid = GETPOST("socid","int"); -if ($user->societe_id) $socid=$user->societe_id; -$result = restrictedArea($user, 'societe','',''); - -$id=GETPOST("id","int"); -$ribid=GETPOST("ribid","int"); -$action=GETPOST("action", 'alpha', 3); - -$object = new Societe($db); -$object->fetch($socid); - -$account = new CompanyBankAccount($db); -$prelevement = new BonPrelevement($db); - -$extrafields = new ExtraFields($db); - -// fetch optionals attributes and labels -$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); - -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('thirdpartybancard','globalcard')); - - -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('thirdpartybancard')); - - - -/* - * Actions - */ - -$parameters=array('id'=>$socid, 'objcanvas'=>$objcanvas); -$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - -if (empty($reshook)) -{ - if ($cancel) - { - $action=''; - if (! empty($backtopage)) - { - header("Location: ".$backtopage); - exit; - } - } - - - if ($action == 'update' && ! $_POST["cancel"]) - { - // Modification - if (! GETPOST('label')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $action='edit'; - $error++; - } - if (! GETPOST('bank')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); - $action='edit'; - $error++; - } - if ($account->needIBAN() == 1) - { - if (! GETPOST('iban')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); - $action='edit'; - $error++; - } - if (! GETPOST('bic')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); - $action='edit'; - $error++; - } - } - - $account->fetch($id); - if (! $error) - { - $account->socid = $object->id; - - $account->bank = GETPOST('bank','alpha'); - $account->label = GETPOST('label','alpha'); - $account->courant = GETPOST('courant','alpha'); - $account->clos = GETPOST('clos','alpha'); - $account->code_banque = GETPOST('code_banque','alpha'); - $account->code_guichet = GETPOST('code_guichet','alpha'); - $account->number = GETPOST('number','alpha'); - $account->cle_rib = GETPOST('cle_rib','alpha'); - $account->bic = GETPOST('bic','alpha'); - $account->iban = GETPOST('iban','alpha'); - $account->domiciliation = GETPOST('domiciliation','alpha'); - $account->proprio = GETPOST('proprio','alpha'); - $account->owner_address = GETPOST('owner_address','alpha'); - $account->frstrecur = GETPOST('frstrecur','alpha'); - $account->rum = GETPOST('rum','alpha'); - if (empty($account->rum)) - { - $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - $account->date_rum = dol_now(); - } - - $result = $account->update($user); - if (! $result) - { - setEventMessages($account->error, $account->errors, 'errors'); - } - else - { - // If this account is the default bank account, we disable others - if ($account->default_rib) - { - $account->setAsDefault($id); // This will make sure there is only one default rib - } - - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - } - } - - if ($action == 'add' && ! $_POST["cancel"]) - { - $error=0; - - if (! GETPOST('label')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $action='create'; - $error++; - } - if (! GETPOST('bank')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); - $action='create'; - $error++; - } - - if (! $error) - { - // Ajout - $account = new CompanyBankAccount($db); - - $account->socid = $object->id; - - $account->bank = GETPOST('bank','alpha'); - $account->label = GETPOST('label','alpha'); - $account->courant = GETPOST('courant','alpha'); - $account->clos = GETPOST('clos','alpha'); - $account->code_banque = GETPOST('code_banque','alpha'); - $account->code_guichet = GETPOST('code_guichet','alpha'); - $account->number = GETPOST('number','alpha'); - $account->cle_rib = GETPOST('cle_rib','alpha'); - $account->bic = GETPOST('bic','alpha'); - $account->iban = GETPOST('iban','alpha'); - $account->domiciliation = GETPOST('domiciliation','alpha'); - $account->proprio = GETPOST('proprio','alpha'); - $account->owner_address = GETPOST('owner_address','alpha'); - $account->frstrecur = GETPOST('frstrecur'); - $account->rum = GETPOST('rum','alpha'); - $account->datec = dol_now(); - - $db->begin(); - - // This test can be done only once properties were set - if ($account->needIBAN() == 1) - { - if (! GETPOST('iban')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); - $action='create'; - $error++; - } - if (! GETPOST('bic')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); - $action='create'; - $error++; - } - } - - if (! $error) - { - $result = $account->create($user); - if ($result < 0) - { - $error++; - setEventMessages($account->error, $account->errors, 'errors'); - $action='create'; // Force chargement page création - } - - if (empty($account->rum)) - { - $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - $account->date_rum = dol_now(); - } - } - - if (! $error) - { - $result = $account->update($user); // This will set the UMR number. - if ($result < 0) - { - $error++; - setEventMessages($account->error, $account->errors, 'errors'); - $action='create'; - } - } - - if (! $error) - { - $db->commit(); - - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - else - { - $db->rollback(); - } - } - } - - if ($action == 'setasdefault') - { - $account = new CompanyBankAccount($db); - $res = $account->setAsDefault(GETPOST('ribid','int')); - if ($res) - { - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - else - { - setEventMessages($db->lasterror, null, 'errors'); - } - } - - if ($action == 'confirm_delete' && $_GET['confirm'] == 'yes') - { - $account = new CompanyBankAccount($db); - if ($account->fetch($ribid?$ribid:$id)) - { - $result = $account->delete($user); - if ($result > 0) - { - $url = $_SERVER['PHP_SELF']."?socid=".$object->id; - header('Location: '.$url); - exit; - } - else - { - setEventMessages($account->error, $account->errors, 'errors'); - } - } - else - { - setEventMessages($account->error, $account->errors, 'errors'); - } - } - - $savid=$id; - - // Actions to build doc - if ($action == 'builddocrib') - { - $action = 'builddoc'; - $moreparams = array( - 'use_companybankid'=>GETPOST('companybankid'), - 'force_dir_output'=>$conf->societe->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->id) - ); - $_POST['lang_id'] = GETPOST('lang_idrib'.GETPOST('companybankid')); - $_POST['model'] = GETPOST('modelrib'.GETPOST('companybankid')); - } - $id = $socid; - $upload_dir = $conf->societe->multidir_output[$object->entity]; - $permissioncreate=$user->rights->societe->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - - $id = $savid; -} - - - -/* - * View - */ - -$form = new Form($db); -$formfile = new FormFile($db); - -llxHeader(); - -$head=societe_prepare_head($object); -if (! $id) -{ - $account->fetch(0,$object->id); -} -else -{ - $account->fetch($id); -} -if (empty($account->socid)) $account->socid=$object->id; - -if ($socid && $action == 'edit' && $user->rights->societe->creer) -{ - print '
    '; - print ''; - print ''; - print ''; -} -if ($socid && $action == 'create' && $user->rights->societe->creer) -{ - print ''; - print ''; - print ''; -} - - -// View -if ($socid && $action != 'edit' && $action != "create") -{ - dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"), -1, 'company'); - - // Confirm delete third party - if ($action == 'delete') - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $account->getRibLabel()), "confirm_delete", '', 0, 1); - } - - $linkback = ''.$langs->trans("BackToList").''; - - dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); - - - print load_fiche_titre($langs->trans("DefaultRIB"), '', ''); - - print '
    '; - print '
    '; - - print ''; - - print ''; - print ''; - - print ''; - print ''; - - // Show fields of bank account - foreach($account->getFieldsToShow(1) as $val) - { - if ($val == 'BankCode') { - $content = $account->code_banque; - } elseif ($val == 'DeskCode') { - $content = $account->code_guichet; - } elseif ($val == 'BankAccountNumber') { - $content = $account->number; - if (! empty($account->label) && $account->number) { - if (! checkBanForAccount($account)) { - $content.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); - } else { - $content.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); - } - } - } elseif ($val == 'BankAccountNumberKey') { - $content = $account->cle_rib; - } elseif ($val == 'IBAN') { - $content = $account->iban; - if (! empty($account->iban)) { - if (! checkIbanForAccount($account)) { - $content.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); - } else { - $content.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); - } - } - } elseif ($val == 'BIC') { - $content = $account->bic; - if (! empty($account->bic)) { - if (! checkSwiftForAccount($account)) { - $content.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); - } else { - $content.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); - } - } - } - - print ''; - print ''; - print ''; - } - - print '\n"; - - print '\n"; - - print '\n"; - - print '
    '.$langs->trans("LabelRIB").''.$account->label.'
    '.$langs->trans("BankName").''.$account->bank.'
    '.$langs->trans($val).''.$content.'
    '.$langs->trans("BankAccountDomiciliation").''; - print $account->domiciliation; - print "
    '.$langs->trans("BankAccountOwner").''; - print $account->proprio; - print "
    '.$langs->trans("BankAccountOwnerAddress").''; - print $account->owner_address; - print "
    '; - print '
    '; - - print '
    '; - - // List of bank accounts - - $morehtmlright=''.$langs->trans("Add").''; - - print load_fiche_titre($langs->trans("AllRIB"), $morehtmlright, ''); - - $rib_list = $object->get_all_rib(); - $var = false; - if (is_array($rib_list)) - { - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print ''; - - print ''; - print_liste_field_titre("LabelRIB"); - print_liste_field_titre("Bank"); - print_liste_field_titre("RIB"); - print_liste_field_titre("IBAN"); - print_liste_field_titre("BIC"); - if (! empty($conf->prelevement->enabled)) - { - print print_liste_field_titre("RUM"); - print print_liste_field_titre("WithdrawMode"); - } - print_liste_field_titre("DefaultRIB", '', '', '', '', 'align="center"'); - print_liste_field_titre('', '', '', '', '', 'align="center"'); - print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; - - foreach ($rib_list as $rib) - { - print ''; - // Label - print ''; - // Bank name - print ''; - // Account number - print ''; - // IBAN - print ''; - // BIC - print ''; - - if (! empty($conf->prelevement->enabled)) - { - // RUM - //print ''; - print ''; - - // FRSTRECUR - print ''; - } - - // Default - print ''; - - // Generate doc - print ''; - - // Edit/Delete - print ''; - - print ''; - } - - if (count($rib_list) == 0) - { - $colspan=8; - if (! empty($conf->prelevement->enabled)) $colspan+=2; - print ''; - } - - print '
    '.$rib->label.''.$rib->bank.''; - $string=''; - foreach ($rib->getFieldsToShow() as $val) { - - if ($val == 'BankCode') { - $string .= $rib->code_banque.' '; - } elseif ($val == 'BankAccountNumber') { - $string .= $rib->number.' '; - } elseif ($val == 'DeskCode') { - $string .= $rib->code_guichet.' '; - } elseif ($val == 'BankAccountNumberKey') { - $string .= $rib->cle_rib.' '; - /* Already output after - }elseif ($val == 'BIC') { - $string .= $rib->bic.' '; - }elseif ($val == 'IBAN') { - $string .= $rib->iban.' ';*/ - } - } - if (! empty($rib->label) && $rib->number) { - if (! checkBanForAccount($rib)) { - $string.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); - } else { - $string.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); - } - } - - print $string; - print ''.$rib->iban; - if (! empty($rib->iban)) { - if (! checkIbanForAccount($rib)) { - print ' '.img_picto($langs->trans("IbanNotValid"),'warning'); - } else { - print ' '.img_picto($langs->trans("IbanValid"),'info'); - } - } - print ''.$rib->bic; - if (! empty($rib->bic)) { - if (! checkSwiftForAccount($rib)) { - print ' '.img_picto($langs->trans("SwiftNotValid"),'warning'); - } else { - print ' '.img_picto($langs->trans("SwiftValid"),'info'); - } - } - print ''.$prelevement->buildRumNumber($object->code_client, $rib->datec, $rib->id).''.$rib->rum.''.$rib->frstrecur.''; - if (!$rib->default_rib) { - print ''; - print img_picto($langs->trans("Disabled"),'off'); - print ''; - } else { - print img_picto($langs->trans("Enabled"),'on'); - } - print ''; - - $buttonlabel = $langs->trans("BuildDoc"); - $forname='builddocrib'.$rib->id; - - include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php'; - $modellist=ModeleBankAccountDoc::liste_modeles($db); - - $out = ''; - if (is_array($modellist) && count($modellist)) - { - $out.= ''; - $out.= ''; - $out.= ''; - $out.= ''; - $out.= ''; - - if (is_array($modellist) && count($modellist) == 1) // If there is only one element - { - $arraykeys=array_keys($modellist); - $modelselected=$arraykeys[0]; - } - if (! empty($conf->global->BANKADDON_PDF)) $modelselected = $conf->global->BANKADDON_PDF; - - $out.= $form->selectarray('modelrib'.$rib->id, $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100'); - $out.= ajax_combobox('modelrib'.$rib->id); - - // Language code (if multilang) - if ($conf->global->MAIN_MULTILANGS) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; - $formadmin=new FormAdmin($db); - $defaultlang=$codelang?$codelang:$langs->getDefaultLang(); - $morecss='maxwidth150'; - if (! empty($conf->browser->phone)) $morecss='maxwidth100'; - $out.= $formadmin->select_language($defaultlang, 'lang_idrib'.$rib->id, 0, 0, 0, 0, 0, $morecss); - } - // Button - $genbutton = 'dol_no_mouse_hover) && $modulepart != 'unpaid') - { - $langs->load("errors"); - $genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated")); - } - if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton=''; - if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton=''; - $out.= $genbutton; - $out.= ''; - } - print $out; - print ''; - if ($user->rights->societe->creer) - { - print ''; - print img_picto($langs->trans("Modify"),'edit'); - print ''; - - print ' '; - - print ''; - print img_picto($langs->trans("Delete"),'delete'); - print ''; - } - print '
    '.$langs->trans("NoBANRecord").'
    '; - print '
    '; - } else { - dol_print_error($db); - } - - dol_fiche_end(); - - - /* - if ($socid && $action != 'edit' && $action != 'create') - { - // Barre d'actions - print '
    '; - - if ($user->rights->societe->creer) - { - print ''.$langs->trans("Add").''; - } - - print '
    '; - } - */ - - - - if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC)) - { - print '
    '; - print ''; // ancre - - /* - * Documents generes - */ - $filedir=$conf->societe->multidir_output[$object->entity].'/'.$object->id; - $urlsource=$_SERVER["PHP_SELF"]."?socid=".$object->id; - $genallowed=$user->rights->societe->lire; - $delallowed=$user->rights->societe->creer; - - $var=true; - - print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang); - - print '
    '; - - - print '
    '; - - print '
    '; - } - /* - include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php'; - $modellist=ModeleBankAccountDoc::liste_modeles($db); - //print '
    '; - if (is_array($modellist) && count($modellist) == 1) // If there is only one element - { - $arraykeys=array_keys($modellist); - $modelselected=$arraykeys[0]; - } - $out.= $form->selectarray('model', $modellist, $modelselected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100'); - $out.= ajax_combobox('model'); - //print $out; - $buttonlabel=$langs->trans("Generate"); - $genbutton = ''; // TODO Add link to generate doc - */ -} - -// Edit -if ($socid && $action == 'edit' && $user->rights->societe->creer) -{ - dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); - - $linkback = ''.$langs->trans("BackToList").''; - - dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); - - print '
    '; - - print '
    '; - print ''; - - print ''; - print ''; - - print ''; - print ''; - - // Show fields of bank account - foreach ($account->getFieldsToShow(1) as $val) { - - $require=false; - if ($val == 'BankCode') { - $name = 'code_banque'; - $size = 8; - $content = $account->code_banque; - } elseif ($val == 'DeskCode') { - $name = 'code_guichet'; - $size = 8; - $content = $account->code_guichet; - } elseif ($val == 'BankAccountNumber') { - $name = 'number'; - $size = 18; - $content = $account->number; - } elseif ($val == 'BankAccountNumberKey') { - $name = 'cle_rib'; - $size = 3; - $content = $account->cle_rib; - } elseif ($val == 'IBAN') { - $name = 'iban'; - $size = 30; - $content = $account->iban; - if ($account->needIBAN()) $require=true; - } elseif ($val == 'BIC') { - $name = 'bic'; - $size = 12; - $content = $account->bic; - if ($account->needIBAN()) $require=true; - } - - print ''.$langs->trans($val).''; - print ''; - print ''; - } - - print '"; - - print ''; - print ''; - print "\n"; - - print '"; - - print '
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("BankName").'
    '.$langs->trans("BankAccountDomiciliation").''; - print '
    '.$langs->trans("BankAccountOwner").'
    '.$langs->trans("BankAccountOwnerAddress").''; - print '
    '; - - if ($conf->prelevement->enabled) - { - print '
    '; - - print ''; - - if (empty($account->rum)) $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - - // RUM - print ''; - print ''; - - print ''; - - print '
    '.$langs->trans("RUM").'
    '.$langs->trans("WithdrawMode").''; - $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); - print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur')?GETPOST('frstrecur'):$account->frstrecur), 0); - print '
    '; - } - - print '
    '; - - dol_fiche_end(); - - print '
    '; - print ''; - print '     '; - print ''; - print '
    '; -} - - -// Create -if ($socid && $action == 'create' && $user->rights->societe->creer) -{ - dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); - - $linkback = ''.$langs->trans("BackToList").''; - - dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); - - print '
    '; - - print '
    '; - print ''; - - print ''; - print ''; - - print ''; - print ''; - - // Show fields of bank account - foreach ($account->getFieldsToShow(1) as $val) { - - $require=false; - if ($val == 'BankCode') { - $name = 'code_banque'; - $size = 8; - } elseif ($val == 'DeskCode') { - $name = 'code_guichet'; - $size = 8; - } elseif ($val == 'BankAccountNumber') { - $name = 'number'; - $size = 18; - } elseif ($val == 'BankAccountNumberKey') { - $name = 'cle_rib'; - $size = 3; - } elseif ($val == 'IBAN') { - $name = 'iban'; - $size = 30; - if ($account->needIBAN()) $require=true; - } elseif ($val == 'BIC') { - $name = 'bic'; - $size = 12; - if ($account->needIBAN()) $require=true; - } - - print ''.$langs->trans($val).''; - print ''; - print ''; - } - - print '"; - - print ''; - print ''; - print "\n"; - - print '"; - - print '
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("Bank").'
    '.$langs->trans("BankAccountDomiciliation").''; - print '
    '.$langs->trans("BankAccountOwner").'
    '.$langs->trans("BankAccountOwnerAddress").''; - print '
    '; - - if ($conf->prelevement->enabled) - { - print '
    '; - - print ''; - - // RUM - print ''; - print ''; - - print ''; - - print '
    '.$langs->trans("RUM").'
    '.$langs->trans("RUMWillBeGenerated").'
    '.$langs->trans("WithdrawMode").''; - $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); - print $form->selectarray("frstrecur", $tblArraychoice, (isset($_POST['frstrecur'])?GETPOST('frstrecur'):'FRST'), 0); - print '
    '; - } - - print '
    '; - - dol_fiche_end(); - - print '
    '; - print ''; - print '     '; - print ''; - print '
    '; -} - -if ($socid && $action == 'edit' && $user->rights->societe->creer) -{ - print ''; -} -if ($socid && $action == 'create' && $user->rights->societe->creer) -{ - print ''; -} - - -llxFooter(); - -$db->close(); From e2bd0198d1bcfec9f0b1cceae41e6e36246b7cc8 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Thu, 8 Mar 2018 02:26:57 +0100 Subject: [PATCH 069/413] Fix class call --- htdocs/stripe/class/stripe.class.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index c3fded06264..a1eefd6ecb7 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2018 PtibogXIV * * 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 @@ -213,7 +213,7 @@ $metadata = array( "idsource" => "".$item."", "idcustomer" => "".$societe->id."" ); -$return = new StripeConnexion($this->db); +$return = new Stripe($this->db); try { if ($stripeamount>=100) { if ($entite=='1' or empty($conf->stripeconnect->enabled)){ @@ -264,8 +264,8 @@ $return->id = $charge->id; if ($charge->source->type=='card'){ $return->message = $charge->source->card->brand." ****".$charge->source->card->last4; }elseif ($charge->source->type=='three_d_secure'){ -$stripeconnect=new StripeConnexion($this->db); -$src = \Stripe\Source::retrieve("".$charge->source->three_d_secure->card."",array("stripe_account" => $stripeconnect->GetStripeAccount($conf->entity))); +$stripe=new Stripe($this->db); +$src = \Stripe\Source::retrieve("".$charge->source->three_d_secure->card."",array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); $return->message = $src->card->brand." ****".$src->card->last4; }else { $return->message = $charge->id; From 93a9430e49ff45bfb9559f8de4d3d8250b38bbfb Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Wed, 7 Mar 2018 17:32:57 +0100 Subject: [PATCH 070/413] Fix: regression, restore primary key --- htdocs/admin/dict.php | 4 +- htdocs/comm/propal/class/propal.class.php | 4 +- htdocs/commande/class/commande.class.php | 4 +- htdocs/compta/bank/class/account.class.php | 4 +- htdocs/compta/bank/various_payment/index.php | 2 +- htdocs/compta/charges/index.php | 6 +- htdocs/compta/facture/card.php | 2 +- .../facture/class/facture-rec.class.php | 4 +- htdocs/compta/facture/class/facture.class.php | 4 +- .../facture/class/paymentterm.class.php | 57 +++++++++---------- htdocs/compta/paiement.php | 2 +- htdocs/compta/paiement/list.php | 2 +- htdocs/compta/resultat/clientfourn.php | 4 +- htdocs/compta/resultat/index.php | 4 +- htdocs/compta/salaries/index.php | 2 +- htdocs/compta/sociales/card.php | 2 +- .../sociales/class/chargesociales.class.php | 2 +- .../class/paymentsocialcontribution.class.php | 2 +- htdocs/compta/sociales/payments.php | 2 +- htdocs/compta/tva/reglement.php | 2 +- htdocs/core/class/commoninvoice.class.php | 10 +++- htdocs/core/class/html.form.class.php | 8 +-- .../modules/facture/doc/pdf_crabe.modules.php | 4 +- htdocs/core/modules/modFacture.class.php | 2 +- htdocs/core/modules/modSalaries.class.php | 2 +- htdocs/core/modules/modSociete.class.php | 4 +- .../modules/rapport/pdf_paiement.class.php | 4 +- .../pdf/pdf_canelle.modules.php | 2 +- htdocs/don/card.php | 7 ++- htdocs/don/class/don.class.php | 2 +- htdocs/don/class/paymentdonation.class.php | 2 +- htdocs/expensereport/card.php | 2 +- .../class/expensereport.class.php | 2 +- .../class/paymentexpensereport.class.php | 2 +- .../class/fournisseur.commande.class.php | 4 +- .../fourn/class/fournisseur.facture.class.php | 4 +- htdocs/fourn/class/paiementfourn.class.php | 2 +- htdocs/fourn/facture/card.php | 2 +- htdocs/fourn/facture/paiement.php | 2 +- .../install/mysql/migration/7.0.0-8.0.0.sql | 5 +- .../mysql/tables/llx_c_paiement.key.sql | 2 - .../mysql/tables/llx_c_payment_term.key.sql | 2 +- .../mysql/tables/llx_c_payment_term.sql | 2 +- htdocs/loan/card.php | 2 +- htdocs/loan/class/loanschedule.class.php | 2 +- htdocs/loan/class/paymentloan.class.php | 2 +- .../class/supplier_proposal.class.php | 4 +- 47 files changed, 104 insertions(+), 99 deletions(-) diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index fbb0b5f38c5..e0d2c861cb2 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -383,8 +383,8 @@ $tabrowid[8] = "id"; $tabrowid[9] = "code_iso"; $tabrowid[10]= ""; $tabrowid[11]= "rowid"; -$tabrowid[12]= "rowid"; -$tabrowid[13]= "id"; +$tabrowid[12]= ""; +$tabrowid[13]= ""; $tabrowid[14]= ""; $tabrowid[15]= ""; $tabrowid[16]= "code"; diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index 3adc58ecbae..67090f386dc 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -1343,8 +1343,8 @@ class Propal extends CommonObject $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid'; diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 5cf5b6c7b40..f69ccb502fd 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -1584,8 +1584,8 @@ class Commande extends CommonOrder $sql.= ', ca.code as availability_code, ca.label as availability_label'; $sql.= ', dr.code as demand_reason_code'; $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid'; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 719a48c3e3c..2cba05f0bac 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -399,6 +399,8 @@ class Account extends CommonObject */ function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='') { + global $conf; + // Deprecatîon warning if (is_numeric($oper)) { dol_syslog(__METHOD__ . ": using numeric operations is deprecated", LOG_WARNING); @@ -414,7 +416,7 @@ class Account extends CommonObject { $sql = "SELECT code FROM ".MAIN_DB_PREFIX."c_paiement"; $sql.= " WHERE id=".$oper; - $sql.= " AND entity IN (".getEntity('c_paiement').")"; + $sql.= " AND entity = ".$conf->entity; $resql=$this->db->query($sql); if ($resql) { diff --git a/htdocs/compta/bank/various_payment/index.php b/htdocs/compta/bank/various_payment/index.php index 41c0baa61d5..5e24463566c 100644 --- a/htdocs/compta/bank/various_payment/index.php +++ b/htdocs/compta/bank/various_payment/index.php @@ -102,7 +102,7 @@ $sql = "SELECT v.rowid, v.sens, v.amount, v.label, v.datep as datep, v.datev as $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number as bank_account_number, ba.fk_accountancy_journal as accountancy_journal, ba.label as blabel,"; $sql.= " pst.code as payment_code"; $sql.= " FROM ".MAIN_DB_PREFIX."payment_various as v"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON v.fk_typepayment = pst.id AND pst.entity IN (" . getEntity('c_paiement').")"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON v.fk_typepayment = pst.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON v.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE v.entity IN (".getEntity('payment_various').")"; diff --git a/htdocs/compta/charges/index.php b/htdocs/compta/charges/index.php index 6e765cdacb0..321fad5baf6 100644 --- a/htdocs/compta/charges/index.php +++ b/htdocs/compta/charges/index.php @@ -139,7 +139,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; $sql.= " ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id AND pct.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pc.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE cs.fk_type = c.id"; @@ -260,7 +260,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."tva as pv"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pv.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id AND pct.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id"; $sql.= " WHERE pv.entity IN (".getEntity("tax").")"; if ($year > 0) { @@ -474,7 +474,7 @@ if (! empty($conf->salaries->enabled) && $user->rights->salaries->read) $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id AND pct.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id"; $sql.= " , ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE s.entity IN (".getEntity('user').")"; $sql.= " AND u.rowid = s.fk_user"; diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index a08b6663c38..028a9ed42c3 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -716,7 +716,7 @@ if (empty($reshook)) $sql = 'SELECT SUM(pf.amount) as total_paiements'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement') . ')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql.= ' WHERE pf.fk_facture = '.$object->id; $sql.= ' AND pf.fk_paiement = p.rowid'; $sql.= ' AND p.entity IN (' . getEntity('facture').')'; diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index f45a0a46ede..c36e6cb09d1 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -304,8 +304,8 @@ class FactureRec extends CommonInvoice $sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc'; //$sql.= ', el.fk_source'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN ('.getEntity('c_payment_term').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'"; $sql.= ' WHERE f.entity IN ('.getEntity('facture').')'; if ($rowid) $sql.= ' AND f.rowid='.$rowid; diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 7c49ff909d6..e4438d4771a 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -1256,8 +1256,8 @@ class Facture extends CommonInvoice $sql.= ', f.fk_incoterms, f.location_incoterms'; $sql.= ", i.libelle as libelle_incoterms"; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN (' . getEntity('c_payment_term').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid'; $sql.= ' WHERE f.entity IN ('.getEntity('facture').')'; if ($rowid) $sql.= " AND f.rowid=".$rowid; diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index bc13b0d5876..b0ee10aa19b 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -102,7 +102,7 @@ class PaymentTerm // extends CommonObject $sql.= "decalage"; $sql.= ") VALUES ("; $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").","; - $sql.= " ".(! isset($this->entity)?getEntity('c_payment_term'):"'".$this->db->escape($this->entity)."'").","; + $sql.= " ".(! isset($this->entity)?$conf->entity:"'".$this->db->escape($this->entity)."'").","; $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; $sql.= " ".(! isset($this->sortorder)?'NULL':"'".$this->db->escape($this->sortorder)."'").","; $sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->escape($this->active)."'").","; @@ -181,7 +181,6 @@ class PaymentTerm // extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; $sql.= " WHERE t.rowid = ".$id; - $sql.= " AND t.entity = " . getEntity('c_payment_term'); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); @@ -221,36 +220,36 @@ class PaymentTerm // extends CommonObject * * @return int <0 if KO, >0 if OK */ - function getDefaultId() - { - global $langs; + function getDefaultId() + { + global $conf, $langs; - $ret=0; + $ret=0; - $sql = "SELECT"; + $sql = "SELECT"; $sql.= " t.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; - $sql.= " WHERE t.code = 'RECEP'"; - $sql.= " AND t.entity = " . getEntity('c_payment_term'); + $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; + $sql.= " WHERE t.code = 'RECEP'"; + $sql.= " AND t.entity = " . $conf->entity; - dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - if ($obj) $ret=$obj->rowid; - } - $this->db->free($resql); - return $ret; - } - else - { - $this->error="Error ".$this->db->lasterror(); - return -1; - } - } + dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + if ($obj) $ret=$obj->rowid; + } + $this->db->free($resql); + return $ret; + } + else + { + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } /** @@ -293,7 +292,6 @@ class PaymentTerm // extends CommonObject $sql.= " nbjour=".(isset($this->nbjour)?$this->nbjour:"null").","; $sql.= " decalage=".(isset($this->decalage)?$this->decalage:"null").""; $sql.= " WHERE rowid = " . $this->id; - $sql.= " AND entity = " . getEntity('c_payment_term'); $this->db->begin(); @@ -350,7 +348,6 @@ class PaymentTerm // extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_payment_term"; $sql.= " WHERE rowid = " . $this->id; - $sql.= " AND t.entity = " . getEntity('c_payment_term'); $this->db->begin(); diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index 4f17a4444f5..29528aacfa3 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -827,7 +827,7 @@ if (! GETPOST('action','aZ09')) $sql = 'SELECT p.datep as dp, p.amount, f.amount as fa_amount, f.facnumber'; $sql.=', f.rowid as facid, c.libelle as paiement_type, p.num_paiement'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement').')'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql.= ', '.MAIN_DB_PREFIX.'facture as f'; $sql.= ' WHERE p.fk_facture = f.rowid'; $sql.= ' AND f.entity IN (' . getEntity('facture').')'; diff --git a/htdocs/compta/paiement/list.php b/htdocs/compta/paiement/list.php index 595c9e868dc..6ca9f29c16e 100644 --- a/htdocs/compta/paiement/list.php +++ b/htdocs/compta/paiement/list.php @@ -138,7 +138,7 @@ else $reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; $sql.= " FROM ".MAIN_DB_PREFIX."paiement as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (" . getEntity('c_paiement') . ")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON p.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index 1bbeb9f2f29..8fde6fcb78c 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -822,7 +822,7 @@ else $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; $sql.= " WHERE p.entity IN (".getEntity('expensereport').")"; $sql.= " AND p.fk_statut>=5"; @@ -906,7 +906,7 @@ else $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; $sql.= " WHERE p.entity IN (".getEntity('donation').")"; $sql.= " AND fk_statut >= 2"; } diff --git a/htdocs/compta/resultat/index.php b/htdocs/compta/resultat/index.php index 26f12e3f7c5..26647d5f0f0 100644 --- a/htdocs/compta/resultat/index.php +++ b/htdocs/compta/resultat/index.php @@ -698,7 +698,7 @@ if (! empty($conf->expensereport->enabled) && ($modecompta == 'CREANCES-DETTES' $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; $sql.= " WHERE p.entity IN (".getEntity('expensereport').")"; $sql.= " AND p.fk_statut>=5"; @@ -761,7 +761,7 @@ if (! empty($conf->don->enabled) && ($modecompta == 'CREANCES-DETTES' || $modeco $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(pe.datep,'%Y-%m') as dm, sum(p.amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; $sql.= " WHERE p.entity IN (".getEntity('donation').")"; $sql.= " AND fk_statut >= 2"; if (! empty($date_start) && ! empty($date_end)) diff --git a/htdocs/compta/salaries/index.php b/htdocs/compta/salaries/index.php index f911636a7ef..4cad9117040 100644 --- a/htdocs/compta/salaries/index.php +++ b/htdocs/compta/salaries/index.php @@ -105,7 +105,7 @@ $sql.= " s.rowid, s.fk_user, s.amount, s.salary, s.label, s.datep as datep, s.da $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel,"; $sql.= " pst.code as payment_code"; $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id AND pst.entity IN (".getEntity('c_paiement').")"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid,"; $sql.= " ".MAIN_DB_PREFIX."user as u"; diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index 23e3494a25d..cdcabc5617b 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -586,7 +586,7 @@ if ($id > 0) $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as p"; $sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid'; $sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid'; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepaiement = c.id AND c.entity IN (" . getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepaiement = c.id"; $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " WHERE p.fk_charge = ".$id; $sql.= " AND p.fk_charge = cs.rowid"; diff --git a/htdocs/compta/sociales/class/chargesociales.class.php b/htdocs/compta/sociales/class/chargesociales.class.php index 2d75584cbda..fa4127c3af6 100644 --- a/htdocs/compta/sociales/class/chargesociales.class.php +++ b/htdocs/compta/sociales/class/chargesociales.class.php @@ -83,7 +83,7 @@ class ChargeSociales extends CommonObject $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql.= " FROM ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as c ON cs.fk_type = c.id"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id'; $sql.= ' WHERE cs.entity IN ('.getEntity('tax').')'; if ($ref) $sql.= " AND cs.rowid = ".$ref; else $sql.= " AND cs.rowid = ".$id; diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index 60a1a647661..4cd0dfd2b59 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -203,7 +203,7 @@ class PaymentSocialContribution extends CommonObject $sql.= " t.fk_user_modif,"; $sql.= " pt.code as type_code, pt.libelle as type_libelle,"; $sql.= ' b.fk_account'; - $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as t LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepaiement = pt.id AND pt.entity IN (" . getEntity('c_paiement') . ")"; + $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as t LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepaiement = pt.id"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id; // TODO link on entity of tax; diff --git a/htdocs/compta/sociales/payments.php b/htdocs/compta/sociales/payments.php index a7c388a26e6..879e9b69ee7 100644 --- a/htdocs/compta/sociales/payments.php +++ b/htdocs/compta/sociales/payments.php @@ -133,7 +133,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; $sql.= " ".MAIN_DB_PREFIX."chargesociales as cs,"; $sql.= " ".MAIN_DB_PREFIX."paiementcharge as pc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id AND pct.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; $sql.= " WHERE cs.fk_type = c.id AND pc.fk_charge = cs.rowid"; $sql.= " AND cs.entity = ".$conf->entity; if ($year > 0) diff --git a/htdocs/compta/tva/reglement.php b/htdocs/compta/tva/reglement.php index 27e314762f8..5041450dd8b 100644 --- a/htdocs/compta/tva/reglement.php +++ b/htdocs/compta/tva/reglement.php @@ -100,7 +100,7 @@ $bankstatic = new Account($db); $sql = "SELECT t.rowid, t.amount, t.label, t.datev, t.datep, t.fk_typepayment as type, t.num_payment, t.fk_bank, pst.code as payment_code,"; $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON t.fk_typepayment = pst.id AND pst.entity IN (".getEntity('c_paiement').")"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON t.fk_typepayment = pst.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON t.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE t.entity IN (".getEntity('tax').")"; diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index ac5d3869a3d..97762482685 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -595,6 +595,8 @@ abstract class CommonInvoice extends CommonObject */ function calculate_date_lim_reglement($cond_reglement=0) { + global $conf; + if (! $cond_reglement) $cond_reglement=$this->cond_reglement_code; if (! $cond_reglement) $cond_reglement=$this->cond_reglement_id; @@ -602,9 +604,11 @@ abstract class CommonInvoice extends CommonObject $sqltemp = 'SELECT c.type_cdr,c.nbjour,c.decalage'; $sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c'; - $sqltemp.= " WHERE c.entity IN (" . getEntity('c_payment_term').")"; - if (is_numeric($cond_reglement)) $sqltemp.= " AND c.rowid=".$cond_reglement; - else $sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'"; + if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement; + else { + $sqltemp.= " WHERE c.entity = ".$conf->entity; + $sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'"; + } dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG); $resqltemp=$this->db->query($sqltemp); diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 61d21cec7e8..3c4df109818 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -2784,7 +2784,7 @@ class Form */ function load_cache_conditions_paiements() { - global $langs; + global $conf, $langs; $num = count($this->cache_conditions_paiements); if ($num > 0) return 0; // Cache already loaded @@ -2793,7 +2793,7 @@ class Form $sql = "SELECT rowid, code, libelle as label"; $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term'; - $sql.= " WHERE entity = " . getEntity('c_payment_term'); + $sql.= " WHERE entity = " . $conf->entity; $sql.= " AND active > 0"; $sql.= " ORDER BY sortorder"; @@ -2997,7 +2997,7 @@ class Form */ function load_cache_types_paiements() { - global $langs; + global $conf, $langs; $num=count($this->cache_types_paiements); if ($num > 0) return $num; // Cache already loaded @@ -3008,7 +3008,7 @@ class Form $sql = "SELECT id, code, libelle as label, type, active"; $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement"; - $sql.= " WHERE entity IN (".getEntity('c_paiement').")"; + $sql.= " WHERE entity = ".$conf->entity; //if ($active >= 0) $sql.= " AND active = ".$active; $resql = $this->db->query($sql); diff --git a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php index 8050abf811b..21adfe4edb4 100644 --- a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php +++ b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php @@ -828,7 +828,7 @@ class pdf_crabe extends ModelePDFFactures $sql = "SELECT p.datep as date, p.fk_paiement, p.num_paiement as num, pf.amount as amount, pf.multicurrency_amount,"; $sql.= " cp.code"; $sql.= " FROM ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."paiement as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON p.fk_paiement = cp.id AND cp.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON p.fk_paiement = cp.id"; $sql.= " WHERE pf.fk_paiement = p.rowid AND pf.fk_facture = ".$object->id; //$sql.= " WHERE pf.fk_paiement = p.rowid AND pf.fk_facture = 1"; $sql.= " ORDER BY p.datep"; @@ -1688,7 +1688,7 @@ class pdf_crabe extends ModelePDFFactures { $top_shift = $pdf->getY() - $current_y; } - + if ($showaddress) { // Sender properties diff --git a/htdocs/core/modules/modFacture.class.php b/htdocs/core/modules/modFacture.class.php index 9a23c0e5e9d..0a7154a9ce2 100644 --- a/htdocs/core/modules/modFacture.class.php +++ b/htdocs/core/modules/modFacture.class.php @@ -259,7 +259,7 @@ class modFacture extends DolibarrModules $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'facture_extrafields as extra ON f.rowid = extra.fk_object'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'paiement as p ON pf.fk_paiement = p.rowid'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as pt ON pt.id = p.fk_paiement AND pt.entity IN ('.getEntity('c_paiement').')'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as pt ON pt.id = p.fk_paiement'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON b.rowid = p.fk_bank'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON ba.rowid = b.fk_account'; $this->export_sql_end[$r] .=' WHERE f.fk_soc = s.rowid'; diff --git a/htdocs/core/modules/modSalaries.class.php b/htdocs/core/modules/modSalaries.class.php index 1e648c1386a..1edfd419378 100644 --- a/htdocs/core/modules/modSalaries.class.php +++ b/htdocs/core/modules/modSalaries.class.php @@ -165,7 +165,7 @@ class modSalaries extends DolibarrModules $this->export_sql_start[$r]='SELECT DISTINCT '; $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'user as u'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'payment_salary as p ON p.fk_user = u.rowid'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_typepayment = cp.id AND cp.entity IN ('.getEntity('c_paiement').')'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_typepayment = cp.id'; $this->export_sql_end[$r] .=' AND u.entity IN ('.getEntity('user').')'; } diff --git a/htdocs/core/modules/modSociete.class.php b/htdocs/core/modules/modSociete.class.php index 52e865cbdbc..711e2ead71c 100644 --- a/htdocs/core/modules/modSociete.class.php +++ b/htdocs/core/modules/modSociete.class.php @@ -283,8 +283,8 @@ class modSociete extends DolibarrModules $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'societe_commerciaux as sc ON sc.fk_soc = s.rowid LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON sc.fk_user = u.rowid'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as payterm ON s.cond_reglement = payterm.rowid AND payterm.entity IN ('.getEntity('c_payment_term').')'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as paymode ON s.mode_reglement = paymode.id AND paymode.entity IN ('.getEntity('c_paiement').')'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as payterm ON s.cond_reglement = payterm.rowid'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as paymode ON s.mode_reglement = paymode.id'; $this->export_sql_end[$r] .=' WHERE s.entity IN ('.getEntity('societe').')'; if (is_object($user) && empty($user->rights->societe->client->voir)) { $this->export_sql_end[$r] .=' AND (sc.fk_user = '.$user->id.' '; diff --git a/htdocs/core/modules/rapport/pdf_paiement.class.php b/htdocs/core/modules/rapport/pdf_paiement.class.php index 2bb784aa578..2594a4a0b6a 100644 --- a/htdocs/core/modules/rapport/pdf_paiement.class.php +++ b/htdocs/core/modules/rapport/pdf_paiement.class.php @@ -187,7 +187,7 @@ class pdf_paiement if (! empty($conf->banque->enabled)) $sql.= ", ba.ref as bankaccount"; $sql.= ", p.rowid as prowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."paiement as p LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (" . getEntity('c_paiement').")"; + $sql.= " FROM ".MAIN_DB_PREFIX."paiement as p LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id"; $sql.= ", ".MAIN_DB_PREFIX."facture as f,"; $sql.= " ".MAIN_DB_PREFIX."paiement_facture as pf,"; if (! empty($conf->banque->enabled)) @@ -218,7 +218,7 @@ class pdf_paiement if (! empty($conf->banque->enabled)) $sql.= ", ba.ref as bankaccount"; $sql.= ", p.rowid as prowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn as p LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn as p LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id"; $sql.= ", ".MAIN_DB_PREFIX."facture_fourn as f,"; $sql.= " ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf,"; if (! empty($conf->banque->enabled)) diff --git a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php index 0a57ab1e449..9cdb9ebc6a0 100644 --- a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php +++ b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php @@ -933,7 +933,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices $sql = "SELECT p.datep as date, p.fk_paiement as type, p.num_paiement as num, pf.amount as amount, pf.multicurrency_amount,"; $sql.= " cp.code"; $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf, ".MAIN_DB_PREFIX."paiementfourn as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON p.fk_paiement = cp.id AND cp.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON p.fk_paiement = cp.id"; $sql.= " WHERE pf.fk_paiementfourn = p.rowid and pf.fk_facturefourn = ".$object->id; $sql.= " ORDER BY p.datep"; $resql=$this->db->query($sql); diff --git a/htdocs/don/card.php b/htdocs/don/card.php index ced8111a93f..38d7d6e6240 100644 --- a/htdocs/don/card.php +++ b/htdocs/don/card.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2017 Laurent Destailleur +s * Copyright (C) 2004-2017 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2013 Florian Henry * Copyright (C) 2015-2016 Alexandre Spangaro @@ -643,8 +643,9 @@ if (! empty($id) && $action != 'edit') * Payments */ $sql = "SELECT p.rowid, p.num_payment, p.datep as dp, p.amount,"; - $sql.= " c.code as type_code,c.libelle as paiement_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."payment_donation as p LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON c.entity IN (".getEntity('c_paiement').")"; + $sql.= "c.code as type_code,c.libelle as paiement_type"; + $sql.= " FROM ".MAIN_DB_PREFIX."payment_donation as p"; + $sql.= ", ".MAIN_DB_PREFIX."c_paiement as c "; $sql.= ", ".MAIN_DB_PREFIX."don as d"; $sql.= " WHERE d.rowid = '".$id."'"; $sql.= " AND p.fk_donation = d.rowid"; diff --git a/htdocs/don/class/don.class.php b/htdocs/don/class/don.class.php index 56a685eef12..86bfe2e6823 100644 --- a/htdocs/don/class/don.class.php +++ b/htdocs/don/class/don.class.php @@ -611,7 +611,7 @@ class Don extends CommonObject $sql.= " c.code as country_code, c.label as country"; $sql.= " FROM ".MAIN_DB_PREFIX."don as d"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = d.fk_projet"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON cp.id = d.fk_payment AND cp.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON cp.id = d.fk_payment"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.fk_country = c.rowid"; $sql.= " WHERE d.entity IN (".getEntity('donation').")"; if (! empty($id)) diff --git a/htdocs/don/class/paymentdonation.class.php b/htdocs/don/class/paymentdonation.class.php index 1023bf68b7a..8d31c292155 100644 --- a/htdocs/don/class/paymentdonation.class.php +++ b/htdocs/don/class/paymentdonation.class.php @@ -182,7 +182,7 @@ class PaymentDonation extends CommonObject $sql.= " pt.code as type_code, pt.libelle as type_libelle,"; $sql.= ' b.fk_account'; $sql.= " FROM ".MAIN_DB_PREFIX."payment_donation as t"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id AND pt.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id; diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index dd5db880bc9..d4bc45e925a 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -1880,7 +1880,7 @@ else $sql.= "c.code as p_code, c.libelle as payment_type,"; $sql.= "ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal"; $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."payment_expensereport as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = c.id"; $sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid'; $sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid'; $sql.= " WHERE e.rowid = '".$id."'"; diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index 5674192906c..28870cc78de 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -450,7 +450,7 @@ class ExpenseReport extends CommonObject $sql.= " d.fk_statut as status, d.fk_c_paiement,"; $sql.= " dp.libelle as libelle_paiement, dp.code as code_paiement"; // INNER JOIN paiement $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as dp ON d.fk_c_paiement = dp.id AND dp.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as dp ON d.fk_c_paiement = dp.id"; if ($ref) $sql.= " WHERE d.ref = '".$this->db->escape($ref)."'"; else $sql.= " WHERE d.rowid = ".$id; //$sql.= $restrict; diff --git a/htdocs/expensereport/class/paymentexpensereport.class.php b/htdocs/expensereport/class/paymentexpensereport.class.php index 023a9709d08..43fcacc8483 100644 --- a/htdocs/expensereport/class/paymentexpensereport.class.php +++ b/htdocs/expensereport/class/paymentexpensereport.class.php @@ -166,7 +166,7 @@ class PaymentExpenseReport extends CommonObject $sql.= " pt.code as type_code, pt.libelle as type_libelle,"; $sql.= ' b.fk_account'; $sql.= " FROM ".MAIN_DB_PREFIX."payment_expensereport as t"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id AND pt.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id; diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index 1fd6bb84de1..b06b6188183 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -232,8 +232,8 @@ class CommandeFournisseur extends CommonOrder $sql.= ', c.fk_incoterms, c.location_incoterms'; $sql.= ', i.libelle as libelle_incoterms'; $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid AND cr.entity IN (".getEntity('c_payment_term').")"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON c.fk_mode_reglement = p.id AND p.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON c.fk_mode_reglement = p.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid'; $sql.= " WHERE c.entity = ".$conf->entity; diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index ccbd93b46e4..51f0263a664 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -561,8 +561,8 @@ class FactureFournisseur extends CommonInvoice $sql.= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t'; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON t.fk_cond_reglement = cr.rowid AND cr.entity IN (".getEntity('c_payment_term').")"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON t.fk_mode_reglement = p.id AND p.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON t.fk_cond_reglement = cr.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON t.fk_mode_reglement = p.id"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid'; if ($id) $sql.= " WHERE t.rowid=".$id; if ($ref) $sql.= " WHERE t.ref='".$this->db->escape($ref)."'"; diff --git a/htdocs/fourn/class/paiementfourn.class.php b/htdocs/fourn/class/paiementfourn.class.php index fc917e112f7..1a22356695a 100644 --- a/htdocs/fourn/class/paiementfourn.class.php +++ b/htdocs/fourn/class/paiementfourn.class.php @@ -80,7 +80,7 @@ class PaiementFourn extends Paiement $sql.= ' c.code as paiement_code, c.libelle as paiement_type,'; $sql.= ' p.num_paiement, p.note, b.fk_account'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid '; $sql.= ' WHERE p.entity IN ('.getEntity('facture_fourn').')'; if ($id > 0) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 1f9227ce9b6..0e2337228f6 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2433,7 +2433,7 @@ else $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid'; $sql.= ' WHERE pf.fk_facturefourn = '.$object->id; $sql.= ' ORDER BY p.datep, p.tms'; diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index 64223d4b4e9..cc636718bb7 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -745,7 +745,7 @@ if (empty($action)) $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn AS p'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn AS pf ON p.rowid=pf.fk_paiementfourn'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn AS f ON f.rowid=pf.fk_facturefourn'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement AS c ON p.fk_paiement = c.id AND c.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement AS c ON p.fk_paiement = c.id'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON s.rowid = f.fk_soc'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 2b2bb6949d5..2a86a414dca 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -76,4 +76,7 @@ ALTER TABLE llx_c_paiement DROP INDEX uk_c_paiement; ALTER TABLE llx_c_paiement ADD UNIQUE INDEX uk_c_paiement_code(entity, code); ALTER TABLE llx_c_paiement CHANGE COLUMN id id INTEGER AUTO_INCREMENT PRIMARY KEY; - +-- Add missing keys and primary key +ALTER TABLE llx_c_payment_term DROP INDEX uk_c_payment_term; +ALTER TABLE llx_c_payment_term CHANGE COLUMN rowid rowid INTEGER AUTO_INCREMENT PRIMARY KEY; +ALTER TABLE llx_c_payment_term ADD UNIQUE INDEX uk_c_payment_term_code(entity, code); diff --git a/htdocs/install/mysql/tables/llx_c_paiement.key.sql b/htdocs/install/mysql/tables/llx_c_paiement.key.sql index 1e22789d7bf..fc8147805ef 100644 --- a/htdocs/install/mysql/tables/llx_c_paiement.key.sql +++ b/htdocs/install/mysql/tables/llx_c_paiement.key.sql @@ -17,6 +17,4 @@ -- -- ======================================================================== -ALTER TABLE llx_c_paiement ADD UNIQUE INDEX uk_c_paiement(id, entity, code); - ALTER TABLE llx_c_paiement ADD UNIQUE INDEX uk_c_paiement_code(entity, code); diff --git a/htdocs/install/mysql/tables/llx_c_payment_term.key.sql b/htdocs/install/mysql/tables/llx_c_payment_term.key.sql index 1bd86401945..fc2f49de529 100644 --- a/htdocs/install/mysql/tables/llx_c_payment_term.key.sql +++ b/htdocs/install/mysql/tables/llx_c_payment_term.key.sql @@ -17,4 +17,4 @@ -- -- ======================================================================== -ALTER TABLE llx_c_payment_term ADD UNIQUE INDEX uk_c_payment_term(rowid, entity, code); +ALTER TABLE llx_c_payment_term ADD UNIQUE INDEX uk_c_payment_term_code(entity, code); diff --git a/htdocs/install/mysql/tables/llx_c_payment_term.sql b/htdocs/install/mysql/tables/llx_c_payment_term.sql index cc7c7a22dea..39ccaa70916 100644 --- a/htdocs/install/mysql/tables/llx_c_payment_term.sql +++ b/htdocs/install/mysql/tables/llx_c_payment_term.sql @@ -20,7 +20,7 @@ create table llx_c_payment_term ( - rowid integer, + rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id code varchar(16), sortorder smallint, diff --git a/htdocs/loan/card.php b/htdocs/loan/card.php index b920c8d1a6a..17900d1772a 100644 --- a/htdocs/loan/card.php +++ b/htdocs/loan/card.php @@ -676,7 +676,7 @@ if ($id > 0) $sql.= " p.amount_capital, p.amount_insurance, p.amount_interest,"; $sql.= " c.libelle as paiement_type"; $sql.= " FROM ".MAIN_DB_PREFIX."payment_loan as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = c.id"; $sql.= ", ".MAIN_DB_PREFIX."loan as l"; $sql.= " WHERE p.fk_loan = ".$id; $sql.= " AND p.fk_loan = l.rowid"; diff --git a/htdocs/loan/class/loanschedule.class.php b/htdocs/loan/class/loanschedule.class.php index a72487e706a..ebb1820bca0 100644 --- a/htdocs/loan/class/loanschedule.class.php +++ b/htdocs/loan/class/loanschedule.class.php @@ -177,7 +177,7 @@ class LoanSchedule extends CommonObject $sql.= " pt.code as type_code, pt.libelle as type_libelle,"; $sql.= ' b.fk_account'; $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id AND pt.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id; diff --git a/htdocs/loan/class/paymentloan.class.php b/htdocs/loan/class/paymentloan.class.php index 557262de945..022cf050f11 100644 --- a/htdocs/loan/class/paymentloan.class.php +++ b/htdocs/loan/class/paymentloan.class.php @@ -176,7 +176,7 @@ class PaymentLoan extends CommonObject $sql.= " pt.code as type_code, pt.libelle as type_libelle,"; $sql.= ' b.fk_account'; $sql.= " FROM ".MAIN_DB_PREFIX."payment_loan as t"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id AND pt.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id; diff --git a/htdocs/supplier_proposal/class/supplier_proposal.class.php b/htdocs/supplier_proposal/class/supplier_proposal.class.php index 8a713bccb95..ce70fe996d3 100644 --- a/htdocs/supplier_proposal/class/supplier_proposal.class.php +++ b/htdocs/supplier_proposal/class/supplier_proposal.class.php @@ -1153,8 +1153,8 @@ class SupplierProposal extends CommonObject $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."supplier_proposal as p"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; $sql.= " WHERE p.fk_statut = c.id"; $sql.= " AND p.entity IN (".getEntity('supplier_proposal').")"; if ($ref) $sql.= " AND p.ref='".$ref."'"; From fd9c79fa7f245d87495572a6c426dad6d56ae6da Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Wed, 7 Mar 2018 17:53:15 +0100 Subject: [PATCH 071/413] Fix: use getEntity if no rowid to compare --- htdocs/compta/bank/class/account.class.php | 4 +--- htdocs/compta/facture/class/paymentterm.class.php | 6 +++--- htdocs/core/class/commoninvoice.class.php | 4 +--- htdocs/core/class/html.form.class.php | 8 ++++---- 4 files changed, 9 insertions(+), 13 deletions(-) diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 2cba05f0bac..719a48c3e3c 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -399,8 +399,6 @@ class Account extends CommonObject */ function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='') { - global $conf; - // Deprecatîon warning if (is_numeric($oper)) { dol_syslog(__METHOD__ . ": using numeric operations is deprecated", LOG_WARNING); @@ -416,7 +414,7 @@ class Account extends CommonObject { $sql = "SELECT code FROM ".MAIN_DB_PREFIX."c_paiement"; $sql.= " WHERE id=".$oper; - $sql.= " AND entity = ".$conf->entity; + $sql.= " AND entity IN (".getEntity('c_paiement').")"; $resql=$this->db->query($sql); if ($resql) { diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index b0ee10aa19b..ffe50e86ee4 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -102,7 +102,7 @@ class PaymentTerm // extends CommonObject $sql.= "decalage"; $sql.= ") VALUES ("; $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").","; - $sql.= " ".(! isset($this->entity)?$conf->entity:"'".$this->db->escape($this->entity)."'").","; + $sql.= " ".(! isset($this->entity)?getEntity('c_payment_term'):"'".$this->db->escape($this->entity)."'").","; $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; $sql.= " ".(! isset($this->sortorder)?'NULL':"'".$this->db->escape($this->sortorder)."'").","; $sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->escape($this->active)."'").","; @@ -222,7 +222,7 @@ class PaymentTerm // extends CommonObject */ function getDefaultId() { - global $conf, $langs; + global $langs; $ret=0; @@ -230,7 +230,7 @@ class PaymentTerm // extends CommonObject $sql.= " t.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; $sql.= " WHERE t.code = 'RECEP'"; - $sql.= " AND t.entity = " . $conf->entity; + $sql.= " AND t.entity IN (".getEntity('c_payment_term').")"; dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG); $resql=$this->db->query($sql); diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 97762482685..595105c5695 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -595,8 +595,6 @@ abstract class CommonInvoice extends CommonObject */ function calculate_date_lim_reglement($cond_reglement=0) { - global $conf; - if (! $cond_reglement) $cond_reglement=$this->cond_reglement_code; if (! $cond_reglement) $cond_reglement=$this->cond_reglement_id; @@ -606,7 +604,7 @@ abstract class CommonInvoice extends CommonObject $sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c'; if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement; else { - $sqltemp.= " WHERE c.entity = ".$conf->entity; + $sqltemp.= " WHERE c.entity IN (".getEntity('c_payment_term').")"; $sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'"; } diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 3c4df109818..785685e9011 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -2784,7 +2784,7 @@ class Form */ function load_cache_conditions_paiements() { - global $conf, $langs; + global $langs; $num = count($this->cache_conditions_paiements); if ($num > 0) return 0; // Cache already loaded @@ -2793,7 +2793,7 @@ class Form $sql = "SELECT rowid, code, libelle as label"; $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term'; - $sql.= " WHERE entity = " . $conf->entity; + $sql.= " WHERE entity IN (".getEntity('c_payment_term').")"; $sql.= " AND active > 0"; $sql.= " ORDER BY sortorder"; @@ -2997,7 +2997,7 @@ class Form */ function load_cache_types_paiements() { - global $conf, $langs; + global $langs; $num=count($this->cache_types_paiements); if ($num > 0) return $num; // Cache already loaded @@ -3008,7 +3008,7 @@ class Form $sql = "SELECT id, code, libelle as label, type, active"; $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement"; - $sql.= " WHERE entity = ".$conf->entity; + $sql.= " WHERE entity IN (".getEntity('c_paiement').")"; //if ($active >= 0) $sql.= " AND active = ".$active; $resql = $this->db->query($sql); From 7774b49beb6afe22087fd4c41db2addb339e7609 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Thu, 8 Mar 2018 10:03:36 +0100 Subject: [PATCH 072/413] Fix paymentmodes.php --- htdocs/societe/paymentmodes.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index cbafeb68a09..4bd19295e7a 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -345,8 +345,8 @@ if (class_exists('Stripe')) $cu->default_source = "$source"; // obtained with Stripe.js $cu->save(); - //header('Location: '.$url); - //exit; + header('Location: '.$url); + exit; } elseif ($action == 'delete') { From 861a831e249bd8d00e10a362546e6533e8e33785 Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Thu, 8 Mar 2018 11:53:46 +0100 Subject: [PATCH 073/413] Fix: debug --- htdocs/api/class/api_setup.class.php | 6 ++++-- htdocs/compta/facture/class/paymentterm.class.php | 2 -- htdocs/compta/paiement/class/cpaiement.class.php | 7 ++++--- htdocs/compta/salaries/card.php | 2 +- htdocs/core/lib/functions.lib.php | 5 ----- 5 files changed, 9 insertions(+), 13 deletions(-) diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index 65ba8f4ff37..22c763100d4 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -66,7 +66,8 @@ class Setup extends DolibarrApi $sql = "SELECT id, code, type, libelle as label, module"; $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; - $sql.= " WHERE t.active = ".$active; + $sql.= " WHERE t.entity IN (".getEntity('c_paiement').")"; + $sql.= " AND t.active = ".$active; // Add sql filters if ($sqlfilters) { @@ -538,7 +539,8 @@ class Setup extends DolibarrApi $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module"; $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; - $sql.= " WHERE t.active = ".$active; + $sql.= " WHERE t.entity IN (".getEntity('c_payment_term').")"; + $sql.= " AND t.active = ".$active; // Add sql filters if ($sqlfilters) { diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index ffe50e86ee4..9c1f0020d36 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -90,7 +90,6 @@ class PaymentTerm // extends CommonObject // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_payment_term("; - $sql.= "rowid,"; $sql.= "entity,"; $sql.= "code,"; $sql.= "sortorder,"; @@ -101,7 +100,6 @@ class PaymentTerm // extends CommonObject $sql.= "nbjour,"; $sql.= "decalage"; $sql.= ") VALUES ("; - $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").","; $sql.= " ".(! isset($this->entity)?getEntity('c_payment_term'):"'".$this->db->escape($this->entity)."'").","; $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; $sql.= " ".(! isset($this->sortorder)?'NULL':"'".$this->db->escape($this->sortorder)."'").","; diff --git a/htdocs/compta/paiement/class/cpaiement.class.php b/htdocs/compta/paiement/class/cpaiement.class.php index b089cac6aab..59f13023b24 100644 --- a/htdocs/compta/paiement/class/cpaiement.class.php +++ b/htdocs/compta/paiement/class/cpaiement.class.php @@ -107,7 +107,7 @@ class Cpaiement // Insert request $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '('; - $sql.= 'id,'; + $sql.= 'entity,'; $sql.= 'code,'; $sql.= 'libelle,'; $sql.= 'type,'; @@ -118,7 +118,7 @@ class Cpaiement $sql .= ') VALUES ('; - $sql .= ' '.(! isset($this->id)?'NULL':$this->id).','; + $sql .= ' '.(! isset($this->entity)?getEntity('c_paiement'):$this->entity).','; $sql .= ' '.(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").','; $sql .= ' '.(! isset($this->libelle)?'NULL':"'".$this->db->escape($this->libelle)."'").','; $sql .= ' '.(! isset($this->type)?'NULL':$this->type).','; @@ -186,7 +186,8 @@ class Cpaiement $sql .= " t.module"; $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; if (null !== $ref) { - $sql .= ' WHERE t.code = ' . '\'' . $ref . '\''; + $sql .= ' WHERE t.entity IN ('.getEntity('c_paiement').')'; + $sql .= ' AND t.code = ' . '\'' . $ref . '\''; } else { $sql .= ' WHERE t.id = ' . $id; } diff --git a/htdocs/compta/salaries/card.php b/htdocs/compta/salaries/card.php index 608b5a737b0..4f28e2c76c9 100644 --- a/htdocs/compta/salaries/card.php +++ b/htdocs/compta/salaries/card.php @@ -73,7 +73,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) $dateep=dol_mktime(12,0,0, $_POST["dateepmonth"], $_POST["dateepday"], $_POST["dateepyear"]); if (empty($datev)) $datev=$datep; - $type_payment = dol_getIdFromCode($db, GETPOST("paymenttype", 'alpha'), 'c_paiement'); + $type_payment = dol_getIdFromCode($db, GETPOST("paymenttype", 'alpha'), 'c_paiement', 'code', 'id', 1); $object->accountid=GETPOST("accountid") > 0 ? GETPOST("accountid","int") : 0; $object->fk_user=GETPOST("fk_user") > 0 ? GETPOST("fk_user","int") : 0; diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index bc06c31b10e..b38024b3ec0 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -121,11 +121,6 @@ function getEntity($element, $shared=1, $forceentity=null) { global $conf, $mc; - // For backward compatibilty - if ($element == 'actioncomm') $element='agenda'; - if ($element == 'fichinter') $element='intervention'; - if ($element == 'categorie') $element='category'; - if (is_object($mc)) { return $mc->getEntity($element, $shared, $forceentity); From 73a63c1abc49b78ca57849712a9209c5f5baa8c8 Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Thu, 8 Mar 2018 11:57:38 +0100 Subject: [PATCH 074/413] Fix: syntax error --- htdocs/don/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/don/card.php b/htdocs/don/card.php index 38d7d6e6240..78b8d01e51d 100644 --- a/htdocs/don/card.php +++ b/htdocs/don/card.php @@ -1,6 +1,6 @@ -s * Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2004-2017 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2013 Florian Henry * Copyright (C) 2015-2016 Alexandre Spangaro From 7a7c4b8f14e8ca1c3ef5a1e1820171562c3f5d2c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 14:41:13 +0100 Subject: [PATCH 075/413] Fix invalid url --- htdocs/public/paybox/paymentok.php | 2 +- htdocs/public/payment/paymentok.php | 2 +- htdocs/public/paypal/paymentok.php | 2 +- htdocs/public/stripe/paymentok.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/public/paybox/paymentok.php b/htdocs/public/paybox/paymentok.php index 63c15b035f2..9e711ade51b 100644 --- a/htdocs/public/paybox/paymentok.php +++ b/htdocs/public/paybox/paymentok.php @@ -157,7 +157,7 @@ if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) if (! empty($tmptag['MEM'])) { $langs->load("members"); - $url=$urlwithroot."/adherents/card_subscriptions.php?rowid=".$tmptag['MEM']; + $url=$urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content.=$langs->trans("PaymentSubscription")."
    \n"; $content.=$langs->trans("MemberId").': '.$tmptag['MEM']."
    \n"; $content.=$langs->trans("Link").': '.$url.''."
    \n"; diff --git a/htdocs/public/payment/paymentok.php b/htdocs/public/payment/paymentok.php index d74305890df..6f01ed9f991 100644 --- a/htdocs/public/payment/paymentok.php +++ b/htdocs/public/payment/paymentok.php @@ -322,7 +322,7 @@ if ($ispaymentok) if (! empty($tmptag['MEM'])) { $langs->load("members"); - $url=$urlwithroot."/adherents/card_subscriptions.php?rowid=".$tmptag['MEM']; + $url=$urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content.=$langs->trans("PaymentSubscription")."
    \n"; $content.=$langs->trans("MemberId").': '.$tmptag['MEM']."
    \n"; $content.=$langs->trans("Link").': '.$url.''."
    \n"; diff --git a/htdocs/public/paypal/paymentok.php b/htdocs/public/paypal/paymentok.php index 80ec1d8ec2b..1e6adb7ca51 100644 --- a/htdocs/public/paypal/paymentok.php +++ b/htdocs/public/paypal/paymentok.php @@ -212,7 +212,7 @@ if ($PAYPALTOKEN) if (! empty($tmptag['MEM'])) { $langs->load("members"); - $url=$urlwithroot."/adherents/card_subscriptions.php?rowid=".$tmptag['MEM']; + $url=$urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content.=$langs->trans("PaymentSubscription")."
    \n"; $content.=$langs->trans("MemberId").': '.$tmptag['MEM']."
    \n"; $content.=$langs->trans("Link").': '.$url.''."
    \n"; diff --git a/htdocs/public/stripe/paymentok.php b/htdocs/public/stripe/paymentok.php index d0ce82d1ca8..52b3dac8a7f 100644 --- a/htdocs/public/stripe/paymentok.php +++ b/htdocs/public/stripe/paymentok.php @@ -158,7 +158,7 @@ if ($ispaymentok) if (! empty($tmptag['MEM'])) { $langs->load("members"); - $url=$urlwithroot."/adherents/card_subscriptions.php?rowid=".$tmptag['MEM']; + $url=$urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content.=$langs->trans("PaymentSubscription")."
    \n"; $content.=$langs->trans("MemberId").': '.$tmptag['MEM']."
    \n"; $content.=$langs->trans("Link").': '.$url.''."
    \n"; From 0b316c39807585d604e271ee520ec850f4fc1ae4 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 15:01:34 +0100 Subject: [PATCH 076/413] Attach invoice on email subscription confirmation --- htdocs/adherents/class/adherent.class.php | 69 +++++++++++++---------- htdocs/adherents/subscription.php | 41 ++++++++++++-- htdocs/core/class/html.formmail.class.php | 9 ++- htdocs/langs/en_US/members.lang | 5 +- htdocs/public/payment/paymentok.php | 27 ++++++++- htdocs/public/paypal/paymentok.php | 2 +- 6 files changed, 113 insertions(+), 40 deletions(-) diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 78fc662f6b4..20041333ee6 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -1330,19 +1330,19 @@ class Adherent extends CommonObject /** * Do complementary actions after subscription recording. * - * @param int $subscriptionid Id of created subscription - * @param string $option Which action ('bankdirect', 'invoiceonly', ...) - * @param int $accountid Id bank account - * @param int $datesubscription Date of subscription - * @param int $paymentdate Date of payment - * @param string $operation Code of type of operation (if Id bank account provided). Example 'CB', ... - * @param string $label Label operation (if Id bank account provided) - * @param double $amount Amount of subscription (0 accepted for some members) - * @param string $num_chq Numero cheque (if Id bank account provided) - * @param string $emetteur_nom Name of cheque writer - * @param string $emetteur_banque Name of bank of cheque + * @param int $subscriptionid Id of created subscription + * @param string $option Which action ('bankdirect', 'invoiceonly', ...) + * @param int $accountid Id bank account + * @param int $datesubscription Date of subscription + * @param int $paymentdate Date of payment + * @param string $operation Code of type of operation (if Id bank account provided). Example 'CB', ... + * @param string $label Label operation (if Id bank account provided) + * @param double $amount Amount of subscription (0 accepted for some members) + * @param string $num_chq Numero cheque (if Id bank account provided) + * @param string $emetteur_nom Name of cheque writer + * @param string $emetteur_banque Name of bank of cheque * @param string $autocreatethirdparty Auto create new thirdparty if member not linked to a thirdparty. - * @return int <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK */ function subscriptionComplementaryActions($subscriptionid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom='', $emetteur_banque='', $autocreatethirdparty=0) { @@ -1350,6 +1350,8 @@ class Adherent extends CommonObject $error = 0; + $this->invoice = null; // This will contains invoice if an invoice is created + // Insert into bank account directlty (if option choosed for) + link to llx_subscription if option is 'bankdirect' if ($option == 'bankdirect' && $accountid) { @@ -1489,6 +1491,10 @@ class Adherent extends CommonObject $this->errors=$invoice->errors; $error++; } + else + { + $this->invoice = $invoice; + } } if (! $error) @@ -1524,6 +1530,11 @@ class Adherent extends CommonObject } } + if (! $error) + { + // TODO Link invoice with subscription ? + } + // Add payment onto invoice if (! $error && $option == 'bankviainvoice' && $accountid) { @@ -1584,25 +1595,25 @@ class Adherent extends CommonObject // Set invoice as paid $invoice->set_paid($user); } + } - if (! $error) - { - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $customer->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - // Generate PDF (whatever is option MAIN_DISABLE_PDF_AUTOUPDATE) so we can include it into email - //if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - - $invoice->generateDocument($invoice->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if (! $error) + { + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) + $newlang = $_REQUEST['lang_id']; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + $newlang = $customer->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); } + // Generate PDF (whatever is option MAIN_DISABLE_PDF_AUTOUPDATE) so we can include it into email + //if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + + $invoice->generateDocument($invoice->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } } diff --git a/htdocs/adherents/subscription.php b/htdocs/adherents/subscription.php index 3b200ed526c..9d164307e91 100644 --- a/htdocs/adherents/subscription.php +++ b/htdocs/adherents/subscription.php @@ -322,11 +322,15 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && ! $error++; setEventMessages($object->error, $object->errors, 'errors'); } + else + { + // If an invoice was created, it is into $object->invoice + } } if (! $error) { - $db->commit(); +// $db->commit(); } else { @@ -334,6 +338,11 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && ! $action = 'addsubscription'; } + if (! $error) + { + setEventMessages("SubscriptionRecorded", null, 'mesgs'); + } + // Send email if (! $error) { @@ -343,12 +352,36 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && ! $subjecttosend=$object->makeSubstitution($conf->global->ADHERENT_MAIL_COTIS_SUBJECT); $texttosend=$object->makeSubstitution($adht->getMailOnSubscription()); - $result=$object->send_an_email($texttosend,$subjecttosend,array(),array(),array(),"","",0,-1); + // Attach a file ? + $file=''; + $listofpaths=array(); + $listofnames=array(); + $listofmimes=array(); + if (is_object($object->invoice)) + { + $invoicediroutput = $conf->facture->dir_output; + $fileparams = dol_most_recent_file($invoicediroutput . '/' . $object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+'); + $file = $fileparams['fullname']; + + $listofpaths=array($file); + $listofnames=array(basename($file)); + $listofmimes=array(dol_mimetype($file)); + } + + $result=$object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofnames, $listofmimes, "", "", 0, -1); if ($result < 0) { $errmsg=$object->error; - setEventMessages($errmsg, null, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } + else + { + setEventMessages($langs->trans("EmailSentToMember", $object->email), null, 'mesgs'); + } + } + else + { + setEventMessages($langs->trans("NoEmailSentToMember"), null, 'mesgs'); } } @@ -998,7 +1031,7 @@ if ($rowid > 0) $helpcontent.=''.$langs->trans("MailText").':
    '; $helpcontent.=dol_htmlentitiesbr($texttosend)."\n"; - print $form->textwithpicto($tmp,$helpcontent,1,'help'); + print $form->textwithpicto($tmp, $helpcontent, 1, 'help', '', 0, 2, 'helpemailtosend'); } print '
    '; $i=0; +// $list is defined into oauth.lib.php foreach ($list as $key) { $supported=0; diff --git a/htdocs/admin/oauthlogintokens.php b/htdocs/admin/oauthlogintokens.php index 15e70897fb6..97b774edf80 100644 --- a/htdocs/admin/oauthlogintokens.php +++ b/htdocs/admin/oauthlogintokens.php @@ -141,13 +141,27 @@ if ($mode == 'setup' && $user->admin) $urltodelete=$urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); $urltocheckperms='https://github.com/settings/applications/'; } - if ($key[0] == 'OAUTH_GOOGLE_NAME') + elseif ($key[0] == 'OAUTH_GOOGLE_NAME') { $OAUTH_SERVICENAME='Google'; $urltorenew=$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state=userinfo_email,userinfo_profile,cloud_print&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); $urltodelete=$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); $urltocheckperms='https://security.google.com/settings/security/permissions'; } + elseif ($key[0] == 'OAUTH_STRIPE_TEST_NAME') + { + $OAUTH_SERVICENAME='StripeTest'; + $urltorenew=$urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete=''; + $urltocheckperms=''; + } + else + { + $urltorenew=''; + $urltodelete=''; + $urltocheckperms=''; + } + // Show value of token $tokenobj=null; @@ -204,7 +218,6 @@ if ($mode == 'setup' && $user->admin) print '
    '."\n"; - $var=false; print ''; print ''; print ''; @@ -222,7 +235,6 @@ if ($mode == 'setup' && $user->admin) print ''; print ''."\n"; - $var = ! $var; print ''; print ''; //var_dump($key); @@ -237,19 +249,21 @@ if ($mode == 'setup' && $user->admin) if (is_object($tokenobj)) { //test on $storage->hasAccessToken($OAUTH_SERVICENAME) ? - print ''.$langs->trans('DeleteAccess').'

    '; + print ''.$langs->trans('DeleteAccess').'
    '; } // Request remote token - print ''.$langs->trans('RequestAccess').'

    '; + if ($urltorenew) + { + print ''.$langs->trans('RequestAccess').'
    '; + } // Check remote access if ($urltocheckperms) { - print $langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': '.$urltocheckperms.''; + print '
    '.$langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': '.$urltocheckperms.''; } print ''; print '
    '; - $var = ! $var; print ''; print ''; //var_dump($key); @@ -272,7 +286,6 @@ if ($mode == 'setup' && $user->admin) if (is_object($tokenobj)) { // Token refresh - $var = ! $var; print ''; print ''; //var_dump($key); @@ -283,7 +296,6 @@ if ($mode == 'setup' && $user->admin) print ''; // Token expired - $var = ! $var; print ''; print ''; //var_dump($key); @@ -294,7 +306,6 @@ if ($mode == 'setup' && $user->admin) print ''; // Token expired at - $var = ! $var; print ''; print ''; //var_dump($key); @@ -354,7 +365,6 @@ if ($mode == 'userconf' && $user->admin) print $langs->trans('PrintUserConfDesc'.$driver)."

    \n"; print '
    '.$langs->trans($key[0]).'
    '; - $var=true; print ''; print ''; print ''; diff --git a/htdocs/core/lib/oauth.lib.php b/htdocs/core/lib/oauth.lib.php index 0149b581fa2..a1582cceca5 100644 --- a/htdocs/core/lib/oauth.lib.php +++ b/htdocs/core/lib/oauth.lib.php @@ -27,12 +27,15 @@ $supportedoauth2array=array( 'OAUTH_GOOGLE_NAME'=>'google', ); - if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { - $supportedoauth2array['OAUTH_GITHUB_NAME']='github'; + $supportedoauth2array['OAUTH_STRIPE_TEST_NAME']='stripetest'; + $supportedoauth2array['OAUTH_STRIPE_LIVE_NAME']='stripelive'; } $supportedoauth2array['OAUTH_GITHUB_NAME']='github'; + + + // API access parameters OAUTH $list = array ( array( @@ -217,7 +220,17 @@ $list = array ( 'OAUTH_STRAVA_ID', 'OAUTH_STRAVA_SECRET', ), - array( + array( + 'OAUTH_STRIPE_TEST_NAME', + 'OAUTH_STRIPE_TEST_ID', + 'STRIPE_TEST_SECRET_KEY', + ), + array( + 'OAUTH_STRIPE_LIVE_NAME', + 'OAUTH_STRIPE_LIVE_ID', + 'STRIPE_LIVE_SECRET_KEY', + ), + array( 'OAUTH_TUMBLR_NAME', 'OAUTH_TUMBLR_ID', 'OAUTH_TUMBLR_SECRET', @@ -266,12 +279,12 @@ function oauthadmin_prepare_head() $head[$h][1] = $langs->trans("OAuthServices"); $head[$h][2] = 'services'; $h++; - + $head[$h][0] = dol_buildpath('/admin/oauthlogintokens.php', 1); $head[$h][1] = $langs->trans("TokenManager"); $head[$h][2] = 'tokengeneration'; $h++; - + complete_head_from_modules($conf, $langs, null, $head, $h, 'oauthadmin'); complete_head_from_modules($conf, $langs, null, $head, $h, 'oauthadmin', 'remove'); diff --git a/htdocs/core/modules/oauth/github_oauthcallback.php b/htdocs/core/modules/oauth/github_oauthcallback.php index a2f6eb08953..052964eca66 100644 --- a/htdocs/core/modules/oauth/github_oauthcallback.php +++ b/htdocs/core/modules/oauth/github_oauthcallback.php @@ -109,7 +109,7 @@ if (! empty($_GET['code'])) // We are coming from oauth provider page // We should have //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16)) - dol_syslog("We are coming fr mthe oauth provider page"); + dol_syslog("We are coming from the oauth provider page"); //llxHeader('',$langs->trans("OAuthSetup")); //$linkback=''.$langs->trans("BackToModuleList").''; @@ -125,14 +125,14 @@ if (! empty($_GET['code'])) // We are coming from oauth provider page //var_dump($_GET['code']); //var_dump($state); //var_dump($apiService); // OAuth\OAuth2\Service\GitHub - + //$token = $apiService->requestAccessToken($_GET['code'], $state); $token = $apiService->requestAccessToken($_GET['code']); // Github is a service that does not need state to be stored. // Into constructor of GitHub, the call // parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri) // has not the ending parameter to true like the Google class constructor. - + setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"]; diff --git a/htdocs/core/modules/oauth/google_oauthcallback.php b/htdocs/core/modules/oauth/google_oauthcallback.php index 8584648ba4c..b63aca5bdf6 100644 --- a/htdocs/core/modules/oauth/google_oauthcallback.php +++ b/htdocs/core/modules/oauth/google_oauthcallback.php @@ -109,7 +109,7 @@ if ($action == 'delete') if (! empty($_GET['code'])) // We are coming from oauth provider page { - dol_syslog("We are coming fr mthe oauth provider page"); + dol_syslog("We are coming from the oauth provider page"); //llxHeader('',$langs->trans("OAuthSetup")); //$linkback=''.$langs->trans("BackToModuleList").''; diff --git a/htdocs/core/modules/oauth/stripetest_oauthcallback.php b/htdocs/core/modules/oauth/stripetest_oauthcallback.php new file mode 100644 index 00000000000..3a663cd7162 --- /dev/null +++ b/htdocs/core/modules/oauth/stripetest_oauthcallback.php @@ -0,0 +1,180 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/modules/oauth/stripe_oauthcallback.php + * \ingroup oauth + * \brief Page to get oauth callback + */ + +require '../../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; +use OAuth\Common\Storage\DoliStorage; +use OAuth\Common\Consumer\Credentials; +use OAuth\OAuth2\Service\GitHub; + +// Define $urlwithroot +$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); +$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file +//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + + + +$action = GETPOST('action', 'alpha'); +$backtourl = GETPOST('backtourl', 'alpha'); + + +/** + * Create a new instance of the URI class with the current URI, stripping the query string + */ +$uriFactory = new \OAuth\Common\Http\Uri\UriFactory(); +//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER); +//$currentUri->setQuery(''); +$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/stripe_oauthcallback.php'); + + +/** + * Load the credential for the service + */ + +/** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */ +$serviceFactory = new \OAuth\ServiceFactory(); +$httpClient = new \OAuth\Common\Http\Client\CurlClient(); +// TODO Set options for proxy and timeout +// $params=array('CURLXXX'=>value, ...) +//$httpClient->setCurlParameters($params); +$serviceFactory->setHttpClient($httpClient); + +// Dolibarr storage +$storage = new DoliStorage($db, $conf); + +// Setup the credentials for the requests +$credentials = new Credentials( + $conf->global->OAUTH_STRIPE_TEST_ID, + $conf->global->STRIPE_TEST_SECRET_KEY, + $currentUri->getAbsoluteUri() +); + +$requestedpermissionsarray=array(); +if (GETPOST('state')) $requestedpermissionsarray=explode(',', GETPOST('state')); // Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to retrieve some parameters back +/*if ($action != 'delete' && empty($requestedpermissionsarray)) +{ + print 'Error, parameter state is not defined'; + exit; +}*/ +//var_dump($requestedpermissionsarray);exit; + +// Instantiate the Api service using the credentials, http client and storage mechanism for the token +/** @var $apiService Service */ +//$apiService = $serviceFactory->createService('StripeTest', $credentials, $storage, $requestedpermissionsarray); + +$sql="INSERT INTO ".MAIN_DB_PREFIX."oauth_token set service='StripeTest', entity=".$conf->entity; +$db->query($sql); + +// access type needed to have oauth provider refreshing token +//$apiService->setAccessType('offline'); + +$langs->load("oauth"); + + +/* + * Actions + */ + + +if ($action == 'delete') +{ + $storage->clearToken('StripeTest'); + + setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs'); + + header('Location: ' . $backtourl); + exit(); +} + +if (! empty($_GET['code'])) // We are coming from oauth provider page +{ + // We should have + //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16)) + + dol_syslog("We are coming from the oauth provider page"); + //llxHeader('',$langs->trans("OAuthSetup")); + + //$linkback=''.$langs->trans("BackToModuleList").''; + //print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup'); + + //dol_fiche_head(); + // retrieve the CSRF state parameter + $state = isset($_GET['state']) ? $_GET['state'] : null; + //print '
    '.$langs->trans("User").''.$langs->trans("PrintModule").'
    '; + + // This was a callback request from service, get the token + try { + //var_dump($_GET['code']); + //var_dump($state); + //var_dump($apiService); // OAuth\OAuth2\Service\GitHub + + //$token = $apiService->requestAccessToken($_GET['code'], $state); + $token = $apiService->requestAccessToken($_GET['code']); + // Github is a service that does not need state to be stored. + // Into constructor of GitHub, the call + // parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri) + // has not the ending parameter to true like the Google class constructor. + + setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token + + $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"]; + unset($_SESSION["backtourlsavedbeforeoauthjump"]); + + header('Location: ' . $backtourl); + exit(); + } catch (Exception $e) { + print $e->getMessage(); + } +} +else // If entry on page with no parameter, we arrive here +{ + $_SESSION["backtourlsavedbeforeoauthjump"]=$backtourl; + + // This may create record into oauth_state before the header redirect. + // Creation of record with state in this tables depend on the Provider used (see its constructor). + if (GETPOST('state')) + { + $url = $apiService->getAuthorizationUri(array('state'=>GETPOST('state'))); + } + else + { + //$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated + //https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_AX27ut70tJ1j6eyFCV3ObEXhNOo2jY6V&scope=read_write + $url = 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id='.$conf->global->OAUTH_STRIPE_TEST_ID.'&scope=read_write'; + } + + // we go on oauth provider authorization page + header('Location: ' . $url); + exit(); +} + + +/* + * View + */ + +// No view at all, just actions + +$db->close(); + diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 2a86a414dca..dc7b7d083ab 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -80,3 +80,5 @@ ALTER TABLE llx_c_paiement CHANGE COLUMN id id INTEGER AUTO_INCREMENT PRIMARY KE ALTER TABLE llx_c_payment_term DROP INDEX uk_c_payment_term; ALTER TABLE llx_c_payment_term CHANGE COLUMN rowid rowid INTEGER AUTO_INCREMENT PRIMARY KEY; ALTER TABLE llx_c_payment_term ADD UNIQUE INDEX uk_c_payment_term_code(entity, code); + +ALTER TABLE llx_oauth_token ADD COLUMN tokenstring text; diff --git a/htdocs/install/mysql/tables/llx_oauth_token.sql b/htdocs/install/mysql/tables/llx_oauth_token.sql index 0ae4fed1ea8..5c7d6d62177 100644 --- a/htdocs/install/mysql/tables/llx_oauth_token.sql +++ b/htdocs/install/mysql/tables/llx_oauth_token.sql @@ -18,8 +18,9 @@ CREATE TABLE llx_oauth_token ( rowid integer AUTO_INCREMENT PRIMARY KEY, service varchar(36), - token text, + token text, -- token in serialize() format, of an object StdOAuth2Token of library phpoauth2 + tokenstring text, -- token in json format '{ "access_token": "sk_test_cccc", "refresh_token": "rt_aaa", "token_type": "bearer", ..., "scope": "read_write" } fk_user integer, fk_adherent integer, entity integer DEFAULT 1 -)ENGINE=InnoDB; \ No newline at end of file +)ENGINE=InnoDB; diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 9bc202685dd..12b23955bc8 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -43,4 +43,6 @@ ONLINE_PAYMENT_WAREHOUSE=Stock to use for stock decrease when payment online pay StripeLiveEnabled=Stripe live enabled (otherwise test/sandbox mode) StripeImportPayment=Import Stripe payments ExampleOfTestCreditCard=Example of credit card for test: %s (valid), %s (error CVC), %s (expired), %s (charge fails) -StripeGateways=Stripe gateways \ No newline at end of file +StripeGateways=Stripe gateways +OAUTH_STRIPE_TEST_ID=Stripe Connect Client ID (ca_...) +OAUTH_STRIPE_LIVE_ID=Stripe Connect Client ID (ca_...) \ No newline at end of file diff --git a/htdocs/stripe/admin/stripe.php b/htdocs/stripe/admin/stripe.php index 91d056aa094..80165b00273 100644 --- a/htdocs/stripe/admin/stripe.php +++ b/htdocs/stripe/admin/stripe.php @@ -116,6 +116,7 @@ if ($action=="setlive") } //TODO: import script for stripe account saving in alone or connect mode for stripe.class.php + /* * View */ @@ -169,62 +170,51 @@ else print ''; } print ''; -if (empty($conf->stripeconnect->enabled)) { -print ''; -print ''; - -print ''; - -print ''; - -print ''; - -print ''; -} else { -print ''; -print ''; -} - -if (! empty($conf->banque->enabled)) //deplace here for separate stripe setting of general and common online payment settings +if (empty($conf->stripeconnect->enabled)) { print ''; - if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // target bank account for stripe transfer: automatic banktransfert with stripe webhook from stripe account (receiving funds, payment, debit fee/application fee, payment dispute) to real bank account - { - print ''; - } + print ''; + + print ''; + + print ''; + + print ''; + + print ''; } +else +{ + print ''; + print ''; +} + print '
    '; -print ''.$langs->trans("STRIPE_TEST_PUBLISHABLE_KEY").''; -print ''; -print '   '.$langs->trans("Example").': pk_test_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
    '; -print ''.$langs->trans("STRIPE_TEST_SECRET_KEY").''; -print ''; -print '   '.$langs->trans("Example").': sk_test_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
    '; -print ''.$langs->trans("STRIPE_TEST_WEBHOOK_KEY").''; -print ''; -print '   '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
    '; -print ''.$langs->trans("STRIPE_LIVE_PUBLISHABLE_KEY").''; -print ''; -print '   '.$langs->trans("Example").': pk_live_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
    '; -print ''.$langs->trans("STRIPE_LIVE_SECRET_KEY").''; -print ''; -print '   '.$langs->trans("Example").': sk_live_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
    '; -print ''.$langs->trans("STRIPE_LIVE_WEBHOOK_KEY").''; -print ''; -print '   '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
    '.$langs->trans("StripeConnect").''.$langs->trans("StripeConnect_Mode").'
    '; - print $langs->trans("BankAccount").''; - print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS, 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1); + print ''.$langs->trans("STRIPE_TEST_PUBLISHABLE_KEY").''; + print ''; + print '   '.$langs->trans("Example").': pk_test_xxxxxxxxxxxxxxxxxxxxxxxx'; print '
    '; - print $langs->trans("BankAccountForBankTransfer").''; - print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1); - print '
    '; + print ''.$langs->trans("STRIPE_TEST_SECRET_KEY").''; + print ''; + print '   '.$langs->trans("Example").': sk_test_xxxxxxxxxxxxxxxxxxxxxxxx'; + print '
    '; + print ''.$langs->trans("STRIPE_TEST_WEBHOOK_KEY").''; + print ''; + print '   '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; + print '
    '; + print ''.$langs->trans("STRIPE_LIVE_PUBLISHABLE_KEY").''; + print ''; + print '   '.$langs->trans("Example").': pk_live_xxxxxxxxxxxxxxxxxxxxxxxx'; + print '
    '; + print ''.$langs->trans("STRIPE_LIVE_SECRET_KEY").''; + print ''; + print '   '.$langs->trans("Example").': sk_live_xxxxxxxxxxxxxxxxxxxxxxxx'; + print '
    '; + print ''.$langs->trans("STRIPE_LIVE_WEBHOOK_KEY").''; + print ''; + print '   '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; + print '
    '.$langs->trans("StripeConnect").''.$langs->trans("StripeConnect_Mode").'
    '; @@ -243,21 +233,17 @@ print 'name; print '
    '; - print $langs->trans("ONLINE_PAYMENT_WAREHOUSE").''; - print $formproduct->selectWarehouses($conf->global->ONLINE_PAYMENT_WAREHOUSE,'ONLINE_PAYMENT_WAREHOUSE','',1,$disabled); - print '
    '; +print $langs->trans("BankAccount").''; +print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS, 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1); +print '
    '; - print $langs->trans("BankAccountForBankTransfer").''; - print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1); - print '
    '; + print $langs->trans("BankAccountForBankTransfer").''; + print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1); + print '
    '; print $langs->trans("ONLINE_PAYMENT_SENDEMAIL").''; print ''; print '   '.$langs->trans("Example").': myemail@myserver.com'; -print '
    '; diff --git a/htdocs/stripe/charge.php b/htdocs/stripe/charge.php index aaa0b0475f8..d13235c4f01 100644 --- a/htdocs/stripe/charge.php +++ b/htdocs/stripe/charge.php @@ -46,20 +46,36 @@ $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; + + /* -* View -*/ + * View + */ + llxHeader('', $langs->trans("StripeChargeList")); + $form = new Form($db); $societestatic = new societe($db); $acc = new Account($db); $stripe=new Stripe($db); if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) { + $service = 'StripeTest'; dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); } -if (!$rowid){ +else +{ + $service = 'StripeLive'; +} +$stripeaccount = $stripe->GetStripeAccount($service); +if (empty($stripeaccount)) +{ + print $langs->trans('ErrorStripeAccountNotDefined'); +} + +if (!$rowid && $stripeaccount) +{ print '
    '; if ($optioncss != '') print ''; print ''; @@ -85,68 +101,71 @@ if (!$rowid){ print "
    ".$charge->id."".$societestatic->getNomUrl(1).""; -if ($charge->metadata->source=="order"){ -$object = new Commande($db); -$object->fetch($charge->metadata->idsource); - print "".img_picto('', 'object_order')." ".$object->ref.""; -} elseif ($charge->metadata->source=="invoice"){ -$object = new Facture($db); -$object->fetch($charge->metadata->idsource); - print "".img_picto('', 'object_invoice')." ".$object->ref.""; -} - print "'.dol_print_date($charge->created,'%d/%m/%Y %H:%M').""; -if ($charge->refunded=='1'){ - print $langs->trans("refunded"); -} elseif ($charge->paid=='1'){ - print $langs->trans("".$charge->status.""); -} else { -$label="Message: ".$charge->failure_message."
    "; -$label.="Réseau: ".$charge->outcome->network_status."
    "; -$label.="Statut: ".$langs->trans("".$charge->outcome->seller_message.""); - print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1); -} - print "
    '; -if ($charge->source->object=='card'){ - print $langs->trans("card"); -} -elseif ($charge->source->type=='card'){ - print $langs->trans("card"); -} elseif ($charge->source->type=='three_d_secure'){ - print $langs->trans("card3DS"); -} - print '".price(($charge->amount-$charge->amount_refunded)/100)."
    '.dol_print_date($charge->created,'%d/%m/%Y %H:%M').""; + if ($charge->refunded=='1'){ + print $langs->trans("refunded"); + } elseif ($charge->paid=='1'){ + print $langs->trans("".$charge->status.""); + } else { + $label="Message: ".$charge->failure_message."
    "; + $label.="Réseau: ".$charge->outcome->network_status."
    "; + $label.="Statut: ".$langs->trans("".$charge->outcome->seller_message.""); + print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1); + } + print "
    '; + if ($charge->source->object=='card') + { + print $langs->trans("card"); + } + elseif ($charge->source->type=='card'){ + print $langs->trans("card"); + } elseif ($charge->source->type=='three_d_secure'){ + print $langs->trans("card3DS"); + } + print '".price(($charge->amount-$charge->amount_refunded)/100)."
    '."\n"; + print '
    '; + print '
    ' . "\n"; - print ''; - print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); - print_liste_field_titre("Customer",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); - print_liste_field_titre("Origin",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); - print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"","","",'align="center"',$sortfield,$sortorder); - print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"","","",'align="left"'); - print_liste_field_titre("Type",$_SERVER["PHP_SELF"],"","","",'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Paid",$_SERVER["PHP_SELF"],"","","",'align="right"',$sortfield,$sortorder); - print_liste_field_titre("Fee",$_SERVER["PHP_SELF"],"","","",'align="right"',$sortfield,$sortorder); - print "\n"; + print ''; + print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder); + print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder); + print_liste_field_titre("Origin", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder); + print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "", "", "", 'align="center"', $sortfield, $sortorder); + print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "", "", "", 'align="left"'); + print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "", "", "", 'align="left"', $sortfield, $sortorder); + print_liste_field_titre("Paid", $_SERVER["PHP_SELF"], "", "", "", 'align="right"', $sortfield, $sortorder); + print_liste_field_titre("Fee", $_SERVER["PHP_SELF"], "", "", "", 'align="right"', $sortfield, $sortorder); + print "\n"; - print "\n"; - -$txn=\Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); -foreach ($txn->data as $txn) { - print ''; - $societestatic->fetch($charge->metadata->idcustomer); - $societestatic->id=$charge->metadata->idcustomer; - $societestatic->lastname=$obj->lastname; - $societestatic->firstname=$obj->firstname; - $societestatic->admin=$obj->admin; - $societestatic->login=$obj->login; - $societestatic->email=$obj->email; - $societestatic->societe_id=$obj->fk_soc; + print "\n"; - // Ref - print "\n"; + $stripeaccount = $stripe->GetStripeAccount($conf->entity); + + $txn = \Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripeaccount)); + + foreach ($txn->data as $txn) { + print ''; + $societestatic->fetch($charge->metadata->idcustomer); + $societestatic->id = $charge->metadata->idcustomer; + $societestatic->lastname = $obj->lastname; + $societestatic->firstname = $obj->firstname; + $societestatic->admin = $obj->admin; + $societestatic->login = $obj->login; + $societestatic->email = $obj->email; + $societestatic->societe_id = $obj->fk_soc; + + // Ref + print "\n"; // Employee - print "\n"; - // Origine + print "\n"; + // Origine print "\n"; + if ($charge->metadata->source == "order") { + $object = new Commande($db); + $object->fetch($charge->metadata->idsource); + print "" . img_picto('', 'object_order') . " " . $object->ref . ""; + } elseif ($txn->metadata->source == "invoice") { + $object = new Facture($db); + $object->fetch($txn->metadata->idsource); + print "" . img_picto('', 'object_invoice') . " " . $object->ref . ""; + } + print "\n"; // Date payment - print '\n"; - // Label payment - print "\n"; + // Label payment + print "\n"; - // Type - print ''; - // Amount - print ""; - print ""; - print "\n"; - } - print "
    ".$txn->source."
    " . $txn->source . "".$societestatic->getNomUrl(1)."" . $societestatic->getNomUrl(1) . ""; -if ($charge->metadata->source=="order"){ -$object = new Commande($db); -$object->fetch($charge->metadata->idsource); - print "".img_picto('', 'object_order')." ".$object->ref.""; -} elseif ($txn->metadata->source=="invoice"){ -$object = new Facture($db); -$object->fetch($txn->metadata->idsource); - print "".img_picto('', 'object_invoice')." ".$object->ref.""; -} - print "'.dol_print_date($txn->created,'%d/%m/%Y %H:%M').""; + print '' . dol_print_date($txn->created, '%d/%m/%Y %H:%M') . ""; - print "'.$txn->type.'".price(($txn->amount)/100)."".price(($txn->fee)/100)."
    "; - print ''; - print ''; -}else{ - -} + print "
    ' . $txn->type . '" . price(($txn->amount) / 100) . "" . price(($txn->fee) / 100) . "
    "; + print ''; + print ''; +} else {} llxFooter(); $db->close(); From b07fdafa656238056b914a918c95eda18bc0c70e Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 19:57:22 +0100 Subject: [PATCH 079/413] Trans --- htdocs/langs/en_US/stripe.lang | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 12b23955bc8..4782294ef78 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -45,4 +45,5 @@ StripeImportPayment=Import Stripe payments ExampleOfTestCreditCard=Example of credit card for test: %s (valid), %s (error CVC), %s (expired), %s (charge fails) StripeGateways=Stripe gateways OAUTH_STRIPE_TEST_ID=Stripe Connect Client ID (ca_...) -OAUTH_STRIPE_LIVE_ID=Stripe Connect Client ID (ca_...) \ No newline at end of file +OAUTH_STRIPE_LIVE_ID=Stripe Connect Client ID (ca_...) +BankAccountForBankTransfer=Bank account for fund payouts \ No newline at end of file From e0af4f8489720ae7e5524b4b58fe34308beb826c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 19:58:11 +0100 Subject: [PATCH 080/413] Trans --- htdocs/langs/en_US/stripe.lang | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 4782294ef78..5c7b782f593 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -39,7 +39,7 @@ STRIPE_TEST_WEBHOOK_KEY=Webhook test key STRIPE_LIVE_SECRET_KEY=Secret live key STRIPE_LIVE_PUBLISHABLE_KEY=Publishable live key STRIPE_LIVE_WEBHOOK_KEY=Webhook live key -ONLINE_PAYMENT_WAREHOUSE=Stock to use for stock decrease when payment online payment is done (TODO When option to decrease stock is done on an action on invoice and the online payment generate itself the invoice ?) +ONLINE_PAYMENT_WAREHOUSE=Stock to use for stock decrease when payment online payment is done
    (TODO When option to decrease stock is done on an action on invoice and the online payment generate itself the invoice ?) StripeLiveEnabled=Stripe live enabled (otherwise test/sandbox mode) StripeImportPayment=Import Stripe payments ExampleOfTestCreditCard=Example of credit card for test: %s (valid), %s (error CVC), %s (expired), %s (charge fails) From 415332c22a9c47fcc9686e604bc4880f4d4d682a Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Thu, 8 Mar 2018 20:05:40 +0100 Subject: [PATCH 081/413] ADD IPN/Webhook for stripe TODO: optimise code and uncustomize of ptibogxiv.net but good and fonctionnal for test --- htdocs/public/stripe/ipn.php | 335 +++++++++++++++++++++++++++++++++++ 1 file changed, 335 insertions(+) create mode 100644 htdocs/public/stripe/ipn.php diff --git a/htdocs/public/stripe/ipn.php b/htdocs/public/stripe/ipn.php new file mode 100644 index 00000000000..d60d7d618bd --- /dev/null +++ b/htdocs/public/stripe/ipn.php @@ -0,0 +1,335 @@ +stripeconnect->enabled)) accessforbidden('',0,0,1); +require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; +require_once DOL_DOCUMENT_ROOT.'/includes/stripe/init.php'; +require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; +//dol_include_once('/stripeconnect/class/paymentfee.class.php'); +require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; +require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; + +// You can find your endpoint's secret in your webhook settings +if (isset($_GET['connect'])){ +if (isset($_GET['test'])) +{ +$endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_CONNECT_KEY; +} +else +{ +$endpoint_secret = $conf->global->STRIPE_LIVE_WEBHOOK_CONNECT_KEY; +} +}else { +if (isset($_GET['test'])) +{ +$endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_KEY; +} +else +{ +$endpoint_secret = $conf->global->STRIPE_LIVE_WEBHOOK_KEY; +} +} +$payload = @file_get_contents("php://input"); +$sig_header = $_SERVER["HTTP_STRIPE_SIGNATURE"]; +$event = null; + +$error = 0; + +try { +$event = \Stripe\Webhook::constructEvent($payload, $sig_header, $endpoint_secret); +} +catch(\UnexpectedValueException $e) { + // Invalid payload + http_response_code(400); // PHP 5.4 or greater + exit(); +} catch(\Stripe\Error\SignatureVerification $e) { + // Invalid signature + http_response_code(400); // PHP 5.4 or greater + exit(); +} + +// Do something with $event + +http_response_code(200); // PHP 5.4 or greater +$langs->load("main"); +$user = new User($db); +$user->fetch(5); +$user->getrights(); + +if (! empty($conf->stripeconnect->enabled) && ! empty($conf->multicompany>enabled)) { + $sql = "SELECT entity"; + $sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity"; + $sql.= " WHERE key_account = '".$event->account."'"; + + dol_syslog(get_class($db) . "::fetch", LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + if ($db->num_rows($result)) + { + $obj = $db->fetch_object($result); + $key=$obj->entity; + } + else {$key=1;} + } + else {$key=1;} +$ret=$mc->switchEntity($key); +if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); // to work if your module directory is into a subdir of root htdocs directory +if (! $res) die("Include of main fails"); +} + +// list of action +$stripeconnect=new StripeConnexion($db); +if ($event->type == 'payout.created') { + $error=0; + $db->begin(); + $sql = "UPDATE ".MAIN_DB_PREFIX."stripeconnect_entity SET next_payout = '".date('Y-m-d H:i:s',$event->data->object->arrival_date)."'"; + $sql.= " WHERE entity = ".$key; + + $result = $db->query($sql); + if ($result) + { +$body = "Un virement de ".price2num($event->data->object->amount/100)." ".$event->data->object->currency." est attendu sur votre compte le ".date('d-m-Y H:i:s',$event->data->object->arrival_date); +$subject = '[NOTIFICATION] Virement programmée'; +$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; +mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); + $db->commit(); + return 1; + } + else + { + $db->error(); + $db->rollback(); + return -1; + } +} +elseif ($event->type == 'payout.paid') { +global $conf; + $error=0; + $db->begin(); + $sql = "UPDATE ".MAIN_DB_PREFIX."stripeconnect_entity SET next_payout = null"; + $sql.= " WHERE entity = ".$key; + + $result = $db->query($sql); + if ($result) + { + // Call trigger + //$result=$this->call_trigger('MEMBER_RESILIATE',$user); + //if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers + $langs->load("errors"); + + $dateo = dol_now(); + $label = $event->data->object->description; + $amount= $event->data->object->amount/100; + $amount_to= $event->data->object->amount/100; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + + $accountfrom=new Account($db); + $accountfrom->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS); + + $accountto=new Account($db); + $accountto->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANFERS); + + if ($accountto->currency_code != $accountfrom->currency_code) { + $error++; + setEventMessages($langs->trans("ErrorTransferBetweenDifferentCurrencyNotPossible"), null, 'errors'); + } + + if ($accountto->id != $accountfrom->id) + { + + $bank_line_id_from=0; + $bank_line_id_to=0; + $result=0; + + // By default, electronic transfert from bank to bank + $typefrom='PRE'; + $typeto='VIR'; + + if (! $error) $bank_line_id_from = $accountfrom->addline($dateo, $typefrom, $label, -1*price2num($amount), '', '', $user); + if (! ($bank_line_id_from > 0)) $error++; + if ((! $error) && ($accountto->currency_code == $accountfrom->currency_code)) $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount), '', '', $user); + if ((! $error) && ($accountto->currency_code != $accountfrom->currency_code)) $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount_to), '', '', $user); + if (! ($bank_line_id_to > 0)) $error++; + + if (! $error) $result=$accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT.'/compta/bank/ligne.php?rowid=', '(banktransfert)', 'banktransfert'); + if (! ($result > 0)) $error++; + if (! $error) $result=$accountto->add_url_line($bank_line_id_to, $bank_line_id_from, DOL_URL_ROOT.'/compta/bank/ligne.php?rowid=', '(banktransfert)', 'banktransfert'); + if (! ($result > 0)) $error++; + } + +$body = "Un virement de ".price2num($event->data->object->amount/100)." ".$event->data->object->currency." a ete effectue sur votre compte le ".date('d-m-Y H:i:s',$event->data->object->arrival_date); +$subject = '[NOTIFICATION] Virement effectué'; +$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; +mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); + $db->commit(); + return 1; + } + else + { + $db->error(); + $db->rollback(); + return -1; + } +} +elseif ($event->type == 'charge.succeeded') { +//if (isset($_GET['connect'])){ +//$txn=\Stripe\BalanceTransaction::retrieve("".$event->data->object->balance_transaction."",array("stripe_account" => $event->account)); +//} +//else { +//$txn=\Stripe\BalanceTransaction::retrieve("".$event->data->object->balance_transaction.""); +//} + +//$input=$txn->fee_details; +//$fee = new PaymentStripeFee($db); +//$fee->accountid=10; +//$fee->fk_soc=473; +///foreach ($input as $src) { +//if ($src->type=='stripe_fee') { +//$fee->stripe_fee=price2num($src->amount/100); +//} +//elseif ($src->type=='application_fee') { +//$fee->application_fee=price2num($src->amount/100); +//} + +//}// +//$fee->currency=$txn->currency; +//$fee->datev=dol_now(); +//$fee->datep=dol_now(); +//$fee->datesp=dol_now(); +//$fee->dateep=dol_now(); +//$fee->type_payment=3; +//$fee->num_payment=$txn->source; +//$fee->fk_user_author=$user->id; +//$fee->create($user); + +} +elseif ($event->type == 'charge.failed') { + +$subject = 'Your payment has been received: '.$event->data->object->id.''; +$headers = 'From: "test webhook" '; +//mail('ptibogxiv@msn.com', $subject, 'test', $headers); + +} +elseif (($event->type == 'source.chargeable') && ($event->data->object->type == 'three_d_secure') && ($event->data->object->three_d_secure->authenticated==true)) { + +$stripeconnect=new StripeConnexion($db); +$charge=$stripeconnect->CreatePaymentStripe($event->data->object->amount/100,$event->data->object->currency,$event->data->object->metadata->source,$event->data->object->metadata->idsource,$event->data->object->id,$event->data->object->metadata->customer,$stripeconnect->GetStripeAccount($entity)); + +if (isset($charge->id) && $charge->statut=='error'){ +$msg=$charge->message; +$code=$charge->code; +$error++; +} +elseif (isset($charge->id) && $charge->statut=='success' && $event->data->object->metadata->source=='order') { +$order=new Commande($db); +$order->fetch($event->data->object->metadata->idsource); +$invoice = new Facture($db); +$idinv=$invoice->createFromOrder($order); + +if ($idinv > 0) +{ +$result=$invoice->validate($user); +if ($result > 0) { +$invoice->fetch($idinv); +$paiement = $invoice->getSommePaiement(); +$creditnotes=$invoice->getSumCreditNotesUsed(); +$deposits=$invoice->getSumDepositsUsed(); +$ref=$invoice->ref; +$ifverif=$invoice->socid; +$currency=$invoice->multicurrency_code; +$total=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); +}else{ +$msg=$invoice->error; +$error++; +} +}else{ +$msg=$invoice->error; +$error++; +} +} + +if (!$error){ +$datepaye = dol_now(); +$paiementcode ="CB"; +$amounts=array(); +$amounts[$invoice->id] = $total; +$multicurrency_amounts=array(); +//$multicurrency_amounts[$item] = $total; + $paiement = new Paiement($db); + $paiement->datepaye = $datepaye; + $paiement->amounts = $amounts; // Array with all payments dispatching + $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching + $paiement->paiementid = dol_getIdFromCode($db,$paiementcode,'c_paiement'); + $paiement->num_paiement = $charge->message; + $paiement->note = ''; +} + +if (! $error){ +$paiement_id=$paiement->create($user, 0); + +if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && count($invoice->lines)){ + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $invoice->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$invoice->modelpdf; + $ret = $invoice->fetch($invoice->id); // Reload to get new records + +$invoice->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);} +if ($paiement_id < 0){ + $msg=$paiement->errors; + $error++; +}else{ + if ($event->data->object->metadata->source=='order') { + $order->classifyBilled($user); + } + } + } + +if (! $error){ + $label='(CustomerInvoicePayment)'; + if (GETPOST('type') == 2) $label='(CustomerInvoicePaymentBack)'; + $paiement->addPaymentToBank($user,'payment',$label,$conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS,'',''); + if ($result < 0) + { + $msg=$paiement->errors; + $error++; + } +$invoice->set_paid($user); +} + +$body = ""; +$subject = 'Facture '.$invoice->ref; +$headers = 'From: "test webhook" '; +//mail('ptibogxiv@msn.com', $subject, $body, $headers); +} +elseif ($event->type == 'customer.deleted') { + $db->begin(); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_stripe WHERE fk_key = '".$event->data->object->id."' "; + dol_syslog(get_class($this) . "::delete sql=" . $sql, LOG_DEBUG); + $db->query($sql); + $db->commit(); +} + + + +?> \ No newline at end of file From 432aa5081262ab0a7fb2ff461816e2de4e064535 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Thu, 8 Mar 2018 20:08:43 +0100 Subject: [PATCH 082/413] Update ipn.php --- htdocs/public/stripe/ipn.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/public/stripe/ipn.php b/htdocs/public/stripe/ipn.php index d60d7d618bd..1f4b4cbb3d6 100644 --- a/htdocs/public/stripe/ipn.php +++ b/htdocs/public/stripe/ipn.php @@ -69,7 +69,7 @@ $user = new User($db); $user->fetch(5); $user->getrights(); -if (! empty($conf->stripeconnect->enabled) && ! empty($conf->multicompany>enabled)) { +if (! empty($conf->stripeconnect->enabled) && ! empty($conf->multicompany->enabled)) { $sql = "SELECT entity"; $sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity"; $sql.= " WHERE key_account = '".$event->account."'"; @@ -332,4 +332,4 @@ elseif ($event->type == 'customer.deleted') { -?> \ No newline at end of file +?> From bf1bada4351481f457c4a68a8b990c46d11de35b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 20:35:50 +0100 Subject: [PATCH 083/413] Contact tab after main tab --- htdocs/core/lib/fourn.lib.php | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/htdocs/core/lib/fourn.lib.php b/htdocs/core/lib/fourn.lib.php index 44e7774cae6..ac956abf524 100644 --- a/htdocs/core/lib/fourn.lib.php +++ b/htdocs/core/lib/fourn.lib.php @@ -34,7 +34,7 @@ function facturefourn_prepare_head($object) { global $db, $langs, $conf; - + $h = 0; $head = array(); @@ -102,7 +102,7 @@ function facturefourn_prepare_head($object) function ordersupplier_prepare_head($object) { global $db, $langs, $conf, $user; - + $h = 0; $head = array(); @@ -111,15 +111,6 @@ function ordersupplier_prepare_head($object) $head[$h][2] = 'card'; $h++; - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) - { - $langs->load("stocks"); - $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/dispatch.php?id='.$object->id; - $head[$h][1] = $langs->trans("OrderDispatch"); - $head[$h][2] = 'dispatch'; - $h++; - } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external')); @@ -130,7 +121,16 @@ function ordersupplier_prepare_head($object) $h++; } - // Show more tabs from modules + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) + { + $langs->load("stocks"); + $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/dispatch.php?id='.$object->id; + $head[$h][1] = $langs->trans("OrderDispatch"); + $head[$h][2] = 'dispatch'; + $h++; + } + + // Show more tabs from modules // Entries must be declared in modules descriptor with line // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab @@ -193,7 +193,7 @@ function supplierorder_admin_prepare_head() $head[$h][1] = $langs->trans("SuppliersInvoice"); $head[$h][2] = 'invoice'; $h++; - + $head[$h][0] = DOL_URL_ROOT."/admin/supplier_payment.php"; $head[$h][1] = $langs->trans("SuppliersPayment"); $head[$h][2] = 'supplierpayment'; From e983e0709f41acefda6e20790e9f67680a2d067d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 20:49:37 +0100 Subject: [PATCH 084/413] Fix not visible template selector for supplier order/invoice emails --- htdocs/fourn/commande/card.php | 2 +- htdocs/fourn/facture/card.php | 40 +++++++++++++++++----------------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index faf0cba82a8..13027312f44 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -2740,7 +2740,7 @@ elseif (! empty($object->id)) } // Presend form - $modelmail='supplier_order_send'; + $modelmail='order_supplier_send'; $defaulttopic='SendOrderRef'; $diroutput = $conf->fournisseur->commande->dir_output; $trackid = 'sor'.$object->id; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index c90336f8a4b..0ae8b0669c8 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -266,7 +266,7 @@ if (empty($reshook)) $action=''; } } - + // Delete link of credit note to invoice else if ($action == 'unlinkdiscount' && $user->rights->fournisseur->facture->creer) { @@ -388,7 +388,7 @@ if (empty($reshook)) elseif ($action == "setabsolutediscount" && $user->rights->fournisseur->facture->creer) { // POST[remise_id] or POST[remise_id_for_payment] - + // We use the credit to reduce amount of invoice if (! empty($_POST["remise_id"])) { $ret = $object->fetch($id); @@ -407,7 +407,7 @@ if (empty($reshook)) require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php'; $discount = new DiscountAbsolute($db); $discount->fetch($_POST["remise_id_for_payment"]); - + //var_dump($object->getRemainToPay(0)); //var_dump($discount->amount_ttc);exit; if ($discount->amount_ttc > $object->getRemainToPay(0)) @@ -425,7 +425,7 @@ if (empty($reshook)) } } } - + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; @@ -437,7 +437,7 @@ if (empty($reshook)) $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($id); // Reload to get new records - + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -448,7 +448,7 @@ if (empty($reshook)) $object->fetch($id); $object->fetch_thirdparty(); //$object->fetch_lines(); // Already done into fetch - + // Check if there is already a discount (protection to avoid duplicate creation when resubmit post) $discountcheck=new DiscountAbsolute($db); $result=$discountcheck->fetch(0,0,$object->id); @@ -459,9 +459,9 @@ if (empty($reshook)) if ($canconvert) { $db->begin(); - + $amount_ht = $amount_tva = $amount_ttc = array(); - + // Loop on each vat rate $i = 0; foreach ($object->lines as $line) @@ -474,7 +474,7 @@ if (empty($reshook)) $i ++; } } - + // Insert one discount by VAT rate category $discount = new DiscountAbsolute($db); if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) @@ -489,13 +489,13 @@ if (empty($reshook)) $discount->discount_type = 1; // Supplier discount $discount->fk_soc = $object->socid; $discount->fk_invoice_supplier_source = $object->id; - + $error = 0; - + if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) { // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT - + $sql = 'SELECT SUM(pf.amount) as total_paiements'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement') . ')'; @@ -509,7 +509,7 @@ if (empty($reshook)) $res = $db->fetch_object($resql); $total_paiements = $res->total_paiements; - + $discount->amount_ht = $discount->amount_ttc = $total_paiements - $object->total_ttc; $discount->amount_tva = 0; $discount->tva_tx = 0; @@ -519,7 +519,7 @@ if (empty($reshook)) { $error++; } - + } if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { @@ -529,7 +529,7 @@ if (empty($reshook)) $discount->amount_tva = abs($amount_tva[$tva_tx]); $discount->amount_ttc = abs($amount_ttc[$tva_tx]); $discount->tva_tx = abs($tva_tx); - + $result = $discount->create($user); if ($result < 0) { @@ -537,9 +537,9 @@ if (empty($reshook)) break; } } - + } - + if (empty($error)) { if($object->type != FactureFournisseur::TYPE_DEPOSIT) { @@ -565,7 +565,7 @@ if (empty($reshook)) } } } - + // Delete payment elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) @@ -2141,7 +2141,7 @@ else $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } - + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); @@ -3166,7 +3166,7 @@ else } // Presend form - $modelmail='order_supplier_send'; + $modelmail='invoice_supplier_send'; $defaulttopic='SendBillRef'; $diroutput = $conf->fournisseur->facture->dir_output; $trackid = 'sin'.$object->id; From ad96229ec420a8f91a0f5f222b05d82616146434 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 20:49:37 +0100 Subject: [PATCH 085/413] Fix not visible template selector for supplier order/invoice emails Conflicts: htdocs/fourn/facture/card.php --- htdocs/fourn/commande/card.php | 2 +- htdocs/fourn/facture/card.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index bd2d0591400..f083d71740e 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -2695,7 +2695,7 @@ elseif (! empty($object->id)) } // Presend form - $modelmail='supplier_order_send'; + $modelmail='order_supplier_send'; $defaulttopic='SendOrderRef'; $diroutput = $conf->fournisseur->commande->dir_output; $trackid = 'sor'.$object->id; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 99a50e08af8..0fc05bd7627 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -265,7 +265,7 @@ if (empty($reshook)) $action=''; } } - + elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { $object->fetch($id); @@ -2928,7 +2928,7 @@ else } // Presend form - $modelmail='order_supplier_send'; + $modelmail='invoice_supplier_send'; $defaulttopic='SendBillRef'; $diroutput = $conf->fournisseur->facture->dir_output; $trackid = 'sin'.$object->id; From 2cd0122d3448f3da93332d65b86df9a8de44c105 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 20:59:23 +0100 Subject: [PATCH 086/413] Fix phpcs --- htdocs/stripe/charge.php | 2 +- htdocs/stripe/class/stripe.class.php | 18 +++++++++--------- htdocs/stripe/transaction.php | 6 +++--- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/htdocs/stripe/charge.php b/htdocs/stripe/charge.php index d13235c4f01..9ba246cf9a8 100644 --- a/htdocs/stripe/charge.php +++ b/htdocs/stripe/charge.php @@ -68,7 +68,7 @@ else $service = 'StripeLive'; } -$stripeaccount = $stripe->GetStripeAccount($service); +$stripeaccount = $stripe->getStripeAccount($service); if (empty($stripeaccount)) { print $langs->trans('ErrorStripeAccountNotDefined'); diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 4ea45b7a4b3..a9df01d6acb 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -52,12 +52,12 @@ class Stripe extends CommonObject /** - * GetStripeAccount + * Return stripe account * * @param string $mode 'StripeTest' or 'StripeLive' * @return int ??? */ - public function GetStripeAccount($mode='StripeTest') + public function getStripeAccount($mode='StripeTest') { global $conf; @@ -90,12 +90,12 @@ class Stripe extends CommonObject } /** - * GetStripeCustomerAccount + * getStripeCustomerAccount * * @param int $id ??? * @return int ??? */ - public function GetStripeCustomerAccount($id) + public function getStripeCustomerAccount($id) { global $conf; @@ -122,13 +122,13 @@ class Stripe extends CommonObject /** - * CustomerStripe + * customerStripe * * @param int $id ??? * @param string $key ??? * @return \Stripe\StripeObject|\Stripe\ApiResource */ - public function CustomerStripe($id,$key) + public function customerStripe($id,$key) { global $conf; if (empty($conf->global->STRIPECONNECT_LIVE)) { @@ -186,7 +186,7 @@ class Stripe extends CommonObject } /** - * CreatePaymentStripe + * createPaymentStripe * * @param unknown $amount ??? * @param unknown $currency ??? @@ -197,7 +197,7 @@ class Stripe extends CommonObject * @param unknown $account ??? * @return Stripe */ - public function CreatePaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) + public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) { global $conf; if (empty($conf->global->STRIPECONNECT_LIVE)) { @@ -299,7 +299,7 @@ class Stripe extends CommonObject } elseif ($charge->source->type == 'three_d_secure') { $stripe = new Stripe($this->db); $src = \Stripe\Source::retrieve("" . $charge->source->three_d_secure->card . "", array( - "stripe_account" => $stripe->GetStripeAccount($conf->entity) + "stripe_account" => $stripe->getStripeAccount($conf->entity) )); $return->message = $src->card->brand . " ****" . $src->card->last4; } else { diff --git a/htdocs/stripe/transaction.php b/htdocs/stripe/transaction.php index 143c34f7530..56d94c36dee 100644 --- a/htdocs/stripe/transaction.php +++ b/htdocs/stripe/transaction.php @@ -62,10 +62,10 @@ if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || emp } else { - $servie = 'StripeLive'; + $service = 'StripeLive'; } -$stripeaccount = $stripe->GetStripeAccount($service); +$stripeaccount = $stripe->getStripeAccount($service); if (empty($stripeaccount)) { print $langs->trans('ErrorStripeAccountNotDefined'); @@ -101,7 +101,7 @@ if (! $rowid && $stripeaccount) { print "
    ".$charge->id."".$charge->customer."".$societestatic->getNomUrl(1).""; + if ($societestatic->id > 0) + { + print $societestatic->getNomUrl(1); + } + if ($memberstatic->id > 0) + { + print $memberstatic->getNomUrl(1); + } + print ""; + print $FULLTAG; if ($charge->metadata->source=="order"){ $object = new Commande($db); $object->fetch($charge->metadata->idsource); @@ -132,21 +163,8 @@ if (!$rowid && $stripeaccount) print "".img_picto('', 'object_invoice')." ".$object->ref.""; } print "'.dol_print_date($charge->created,'%d/%m/%Y %H:%M').""; - if ($charge->refunded=='1'){ - print $langs->trans("refunded"); - } elseif ($charge->paid=='1'){ - print $langs->trans("".$charge->status.""); - } else { - $label="Message: ".$charge->failure_message."
    "; - $label.="Réseau: ".$charge->outcome->network_status."
    "; - $label.="Statut: ".$langs->trans("".$charge->outcome->seller_message.""); - print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1); - } - print "
    '; if ($charge->source->object=='card') @@ -161,6 +179,20 @@ if (!$rowid && $stripeaccount) print '".price(($charge->amount-$charge->amount_refunded)/100).""; + if ($charge->refunded=='1'){ + print $langs->trans("refunded"); + } elseif ($charge->paid=='1'){ + print $langs->trans("".$charge->status.""); + } else { + $label="Message: ".$charge->failure_message."
    "; + $label.="Réseau: ".$charge->outcome->network_status."
    "; + $label.="Statut: ".$langs->trans("".$charge->outcome->seller_message.""); + print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1); + } + print "
    trans('RIB'); ?> rights->societe->creer) { ?> - control->tpl['image_edit']; ?> + control->tpl['image_edit']; ?>   diff --git a/htdocs/societe/canvas/individual/tpl/card_view.tpl.php b/htdocs/societe/canvas/individual/tpl/card_view.tpl.php index 359f4ec7b44..fd9b3487f50 100644 --- a/htdocs/societe/canvas/individual/tpl/card_view.tpl.php +++ b/htdocs/societe/canvas/individual/tpl/card_view.tpl.php @@ -144,7 +144,7 @@ dol_fiche_head($head, 'card', $langs->trans("ThirdParty"),0,'company'); trans('RIB'); ?> rights->societe->creer) { ?> - control->tpl['image_edit']; ?> + control->tpl['image_edit']; ?>   diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index b936a431080..f7098d88478 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1662,7 +1662,7 @@ class Societe extends CommonObject return 1; } } - + /** * Definit la societe comme un client * @@ -1674,7 +1674,7 @@ class Societe extends CommonObject function set_remise_supplier($remise, $note, User $user) { global $conf, $langs; - + // Nettoyage parametres $note=trim($note); if (! $note) @@ -1682,15 +1682,15 @@ class Societe extends CommonObject $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason")); return -2; } - + dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id); - + if ($this->id) { $this->db->begin(); - + $now=dol_now(); - + // Positionne remise courante $sql = "UPDATE ".MAIN_DB_PREFIX."societe "; $sql.= " SET remise_supplier = '".$this->db->escape($remise)."'"; @@ -1702,7 +1702,7 @@ class Societe extends CommonObject $this->error=$this->db->error(); return -1; } - + // Ecrit trace dans historique des remises $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier"; $sql.= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)"; @@ -1710,7 +1710,7 @@ class Societe extends CommonObject $sql.= " '".$this->db->escape($note)."',"; $sql.= " ".$user->id; $sql.= ")"; - + $resql=$this->db->query($sql); if (! $resql) { @@ -1718,7 +1718,7 @@ class Societe extends CommonObject $this->error=$this->db->lasterror(); return -1; } - + $this->db->commit(); return 1; } @@ -2037,7 +2037,7 @@ class Societe extends CommonObject else if ($option == 'ban') { $label.= '' . $langs->trans("ShowBan") . ''; - $linkstart = 'setAsDefault($id); // This will make sure there is only one default rib } - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + $url=$_SERVER["PHP_SELF"].'?socid='.$object->id; header('Location: '.$url); exit; } @@ -261,7 +261,7 @@ if (empty($reshook)) { $db->commit(); - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + $url=$_SERVER["PHP_SELF"].'?socid='.$object->id; header('Location: '.$url); exit; } @@ -332,19 +332,23 @@ if (empty($reshook)) $id = $savid; } -if (class_exists('Stripe')) +if (! empty($conf->stripe->enabled) && class_exists('Stripe')) { $stripe=new Stripe($db); - $customerstripe=$stripe->CustomerStripe($socid,$stripe->GetStripeAccount($conf->entity)); + + if (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; + else $service = 'StripeLive'; + + $customerstripe=$stripe->customerStripe($socid, $stripe->getStripeAccount($service)); if ($customerstripe->id) { - $cu = \Stripe\Customer::retrieve("".$customerstripe->id."");} + $cu = \Stripe\Customer::retrieve("".$customerstripe->id."");} $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; if ($action == 'setassourcedefault') { $cu->default_source = "$source"; // obtained with Stripe.js $cu->save(); - + header('Location: '.$url); exit; } @@ -366,7 +370,7 @@ $form = new Form($db); $formfile = new FormFile($db); llxHeader(); - + $head=societe_prepare_head($object); if (! $id) @@ -381,14 +385,14 @@ if (empty($account->socid)) $account->socid=$object->id; if ($socid && $action == 'edit' && $user->rights->societe->creer) { - print '
    '; + print ''; print ''; print ''; print ''; } if ($socid && $action == 'create' && $user->rights->societe->creer) { - print ''; + print ''; print ''; print ''; } @@ -414,9 +418,12 @@ if ($socid && $action != 'edit' && $action != "create") { print load_fiche_titre($langs->trans('StripeGateways'), '', ''); - if (is_object($stripe) && $stripe->GetStripeAccount($conf->entity)) + if (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; + else $service = 'StripeLive'; + + if (is_object($stripe) && $stripe->getStripeAccount($service)) { - $customerstripe=$stripe->CustomerStripe($object->id,$stripe->GetStripeAccount($conf->entity)); + $customerstripe=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service)); } if ($customerstripe->id) { @@ -538,7 +545,7 @@ if ($socid && $action != 'edit' && $action != "create") // List of bank accounts - $morehtmlright=''.$langs->trans("Add").''; + $morehtmlright=''.$langs->trans("Add").''; print load_fiche_titre($langs->trans("AllRIB"), $morehtmlright, ''); @@ -636,7 +643,7 @@ if ($socid && $action != 'edit' && $action != "create") // Default print '
    '; if (!$rib->default_rib) { - print ''; + print ''; print img_picto($langs->trans("Disabled"),'off'); print ''; } else { @@ -704,13 +711,13 @@ if ($socid && $action != 'edit' && $action != "create") print ''; if ($user->rights->societe->creer) { - print ''; + print ''; print img_picto($langs->trans("Modify"),'edit'); print ''; print ' '; - print ''; + print ''; print img_picto($langs->trans("Delete"),'delete'); print ''; } @@ -741,7 +748,7 @@ if ($socid && $action != 'edit' && $action != "create") if ($user->rights->societe->creer) { - print ''.$langs->trans("Add").''; + print ''.$langs->trans("Add").''; } print ''; @@ -879,7 +886,7 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) print '
    '.$langs->trans("WithdrawMode").''; $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); - print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur')?GETPOST('frstrecur'):$account->frstrecur), 0); + print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur','alpha')?GETPOST('frstrecur','alpha'):$account->frstrecur), 0); print '
    '; diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index a9df01d6acb..4167c6a0d81 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -200,6 +200,7 @@ class Stripe extends CommonObject public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) { global $conf; + if (empty($conf->global->STRIPECONNECT_LIVE)) { $mode = 0; } else { @@ -292,6 +293,9 @@ class Stripe extends CommonObject if (isset($charge->id)) {} } + if (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; + else $service = 'StripeLive'; + $return->statut = 'success'; $return->id = $charge->id; if ($charge->source->type == 'card') { @@ -299,7 +303,7 @@ class Stripe extends CommonObject } elseif ($charge->source->type == 'three_d_secure') { $stripe = new Stripe($this->db); $src = \Stripe\Source::retrieve("" . $charge->source->three_d_secure->card . "", array( - "stripe_account" => $stripe->getStripeAccount($conf->entity) + "stripe_account" => $stripe->getStripeAccount($service) )); $return->message = $src->card->brand . " ****" . $src->card->last4; } else { From 9f42e1b17238dff317d5c379fcd74171cabb10ce Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 22:33:40 +0100 Subject: [PATCH 089/413] Prepare code to introduce different payment modes than BAN --- .../class/bonprelevement.class.php | 8 ++------ .../class/companybankaccount.class.php | 19 ++++++++++--------- htdocs/societe/class/societe.class.php | 2 +- 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index d0aa788fe48..e2517bdfada 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -726,16 +726,12 @@ class BonPrelevement extends CommonObject $sql = "SELECT count(f.rowid) as nb"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //if ($banque || $agence) $sql.=", ".MAIN_DB_PREFIX."societe_rib as sr"; $sql.= " WHERE f.fk_statut = 1"; $sql.= " AND f.entity = ".$conf->entity; $sql.= " AND f.rowid = pfd.fk_facture"; $sql.= " AND f.paye = 0"; $sql.= " AND pfd.traite = 0"; $sql.= " AND f.total_ttc > 0"; - //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid"; - //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; - //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; dol_syslog(get_class($this)."::SommeAPrelever"); $resql = $this->db->query($sql); @@ -805,9 +801,8 @@ class BonPrelevement extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr"; $sql.= " WHERE f.rowid = pfd.fk_facture"; - $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND f.entity IN (".getEntity('facture').')'; $sql.= " AND s.rowid = f.fk_soc"; //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc"; $sql.= " AND f.fk_statut = 1"; @@ -1340,6 +1335,7 @@ class BonPrelevement extends CommonObject $sql.= " AND soc.rowid = f.fk_soc"; $sql.= " AND rib.fk_soc = f.fk_soc"; $sql.= " AND rib.default_rib = 1"; + $sql.= " AND rib.type = 'ban'"; //print $sql; // Define $fileDebiteurSection. One section DrctDbtTxInf per invoice. diff --git a/htdocs/societe/class/companybankaccount.class.php b/htdocs/societe/class/companybankaccount.class.php index 428f5b96f42..97c8871202e 100644 --- a/htdocs/societe/class/companybankaccount.class.php +++ b/htdocs/societe/class/companybankaccount.class.php @@ -72,7 +72,7 @@ class CompanyBankAccount extends Account $now = dol_now(); $error = 0; // Correct default_rib to be sure to have always one default - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib where fk_soc = ".$this->socid." AND default_rib = 1"; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib where fk_soc = ".$this->socid." AND default_rib = 1 AND type = 'ban'"; $result = $this->db->query($sql); if ($result) { @@ -81,8 +81,8 @@ class CompanyBankAccount extends Account if (empty($this->default_rib) && $numrows == 0) $this->default_rib = 1; } - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_rib (fk_soc, datec)"; - $sql.= " VALUES (".$this->socid.", '".$this->db->idate($now)."')"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_rib (fk_soc, type, datec)"; + $sql.= " VALUES (".$this->socid.", 'ban', '".$this->db->idate($now)."')"; $resql=$this->db->query($sql); if ($resql) { @@ -204,7 +204,7 @@ class CompanyBankAccount extends Account { if (empty($id) && empty($socid)) return -1; - $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; + $sql = "SELECT rowid, type, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; $sql.= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib"; if ($id) $sql.= " WHERE rowid = ".$id; @@ -220,6 +220,7 @@ class CompanyBankAccount extends Account $this->ref = $obj->fk_soc.'-'.$obj->label; // Generate an artificial ref $this->id = $obj->rowid; + $this->type = $obj->type; $this->socid = $obj->fk_soc; $this->bank = $obj->bank; $this->code_banque = $obj->code_banque; @@ -321,7 +322,7 @@ class CompanyBankAccount extends Account } /** - * Set RIB as Default + * Set a BAN as Default * * @param int $rib RIB id * @return int 0 if KO, 1 if OK @@ -345,13 +346,13 @@ class CompanyBankAccount extends Account $this->db->begin(); - $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0 "; - $sql2.= "WHERE fk_soc = ".$obj->fk_soc; + $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0"; + $sql2.= " WHERE type = 'ban' AND fk_soc = ".$obj->fk_soc; dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result2 = $this->db->query($sql2); - $sql3 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 1 "; - $sql3.= "WHERE rowid = ".$obj->id; + $sql3 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 1"; + $sql3.= " WHERE rowid = ".$obj->id; dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result3 = $this->db->query($sql3); diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index f7098d88478..dbf3015ba1e 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -2433,7 +2433,7 @@ class Societe extends CommonObject function get_all_rib() { require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc = ".$this->id; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".$this->id; $result = $this->db->query($sql); if (!$result) { $this->error++; From 3ad95e46c0a8a506ea46590161b17cb55834c6fa Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 22:40:42 +0100 Subject: [PATCH 090/413] Fix phpunit --- htdocs/install/mysql/tables/llx_oauth_token.sql | 2 +- test/phpunit/CodingSqlTest.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/install/mysql/tables/llx_oauth_token.sql b/htdocs/install/mysql/tables/llx_oauth_token.sql index 5c7d6d62177..81ae99c6ce6 100644 --- a/htdocs/install/mysql/tables/llx_oauth_token.sql +++ b/htdocs/install/mysql/tables/llx_oauth_token.sql @@ -19,7 +19,7 @@ CREATE TABLE llx_oauth_token ( rowid integer AUTO_INCREMENT PRIMARY KEY, service varchar(36), token text, -- token in serialize() format, of an object StdOAuth2Token of library phpoauth2 - tokenstring text, -- token in json format '{ "access_token": "sk_test_cccc", "refresh_token": "rt_aaa", "token_type": "bearer", ..., "scope": "read_write" } + tokenstring text, -- token in json format '{"access_token": "sk_test_cccc", "refresh_token": "rt_aaa", "token_type": "bearer", ..., "scope": "read_write"} fk_user integer, fk_adherent integer, entity integer DEFAULT 1 diff --git a/test/phpunit/CodingSqlTest.php b/test/phpunit/CodingSqlTest.php index 0b29b29240d..57be8fc62a9 100644 --- a/test/phpunit/CodingSqlTest.php +++ b/test/phpunit/CodingSqlTest.php @@ -163,10 +163,10 @@ class CodingSqlTest extends PHPUnit_Framework_TestCase $result=strpos($filecontent,'"'); if ($result) { - $result=! strpos($filecontent,'["'); + $result=(! strpos($filecontent,'["') && ! strpos($filecontent,'{"')); } print __METHOD__." Result for checking we don't have double quote = ".$result."\n"; - $this->assertTrue($result===false, 'Found double quote that is not [" (used for json content) into '.$file.'. Bad.'); + $this->assertTrue($result===false, 'Found double quote that is not [" neither {" (used for json content) into '.$file.'. Bad.'); $result=strpos($filecontent,'int('); print __METHOD__." Result for checking we don't have 'int(' instead of 'integer' = ".$result."\n"; From 264112ab59534b3cb145f84c6e3d804ebbd813bf Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Thu, 8 Mar 2018 23:07:58 +0100 Subject: [PATCH 091/413] NEW actions on card.php for company and member --- htdocs/stripe/class/actions_stripe.class.php | 217 +++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 htdocs/stripe/class/actions_stripe.class.php diff --git a/htdocs/stripe/class/actions_stripe.class.php b/htdocs/stripe/class/actions_stripe.class.php new file mode 100644 index 00000000000..6101ce31f70 --- /dev/null +++ b/htdocs/stripe/class/actions_stripe.class.php @@ -0,0 +1,217 @@ + + * Copyright (C) 2011 Herve Prot + * Copyright (C) 2014 Philippe Grand + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/** + * \file htdocs/multicompany/actions_multicompany.class.php + * \ingroup multicompany + * \brief File Class multicompany + */ +require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';; +$langs->load("stripeconnect@stripeconnect"); + +/** + * \class ActionsMulticompany + * \brief Class Actions of the module multicompany + */ +class ActionsStripeconnect +{ + /** @var DoliDB */ + var $db; + + private $config=array(); + + // For Hookmanager return + var $resprints; + var $results=array(); + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db = $db; + } + + + /** + * + */ + function formObjectOptions($parameters=false, &$object, &$action='') + { + global $db,$conf,$user,$langs,$form; + + if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) +{ + $service = 'StripeTest'; + dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); +} +else +{ + $service = 'StripeLive'; +} + + if (is_array($parameters) && ! empty($parameters)) + { + foreach($parameters as $key=>$value) + { + $key=$value; + } + } + + + if (is_object($object) && $object->element == 'societe') + { + $this->resprints.= ''; + $this->resprints.= '
    '; + $this->resprints.= $langs->trans('StripeCustomer'); + $this->resprints.= ''; +// $this->resprints.= ''.img_edit().''; + $this->resprints.= '
    '; + $this->resprints.= ''; + $this->resprints.= ''; + $stripe=new Stripe($db); +if ($stripe->getStripeAccount($service)&&$object->client!=0) { +$customer=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service)); +$this->resprints.= $customer->id; +} +else { +$this->resprints.= $langs->trans("NoStripe"); +} + $this->resprints.= ''; + + } + elseif (is_object($object) && $object->element == 'member'){ + $this->resprints.= ''; + $this->resprints.= '
    '; + $this->resprints.= $langs->trans('StripeCustomer'); + $this->resprints.= ''; + $this->resprints.= '
    '; + $this->resprints.= ''; + $this->resprints.= ''; + $stripe=new Stripe($db); +if ($stripe->getStripeAccount($service)&&$object->fk_soc>'0') { +$customer=$stripe->customerStripe($object->fk_soc,$stripe->getStripeAccount($service)); +$this->resprints.= $customer->id; +} +else { +$this->resprints.= $langs->trans("NoStripe"); +} + $this->resprints.= ''; + + $this->resprints.= ''; + $this->resprints.= '
    '; + $this->resprints.= $langs->trans('SubscriptionStripe'); + $this->resprints.= ''; + $this->resprints.= '
    '; + $this->resprints.= ''; + $this->resprints.= ''; + $stripe=new Stripe($db); +if (7==4) { +$customer=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service)); +$this->resprints.= $customer->id; +} +else { +$this->resprints.= $langs->trans("NoStripe"); +} + $this->resprints.= ''; + } + elseif (is_object($object) && $object->element == 'adherent_type'){ + $this->resprints.= ''; + $this->resprints.= '
    '; + $this->resprints.= $langs->trans('PlanStripe'); + $this->resprints.= ''; +// $this->resprints.= ''.img_edit().''; + $this->resprints.= '
    '; + $this->resprints.= ''; + $this->resprints.= ''; + $stripe=new Stripe($db); +if (7==4) { +$customer=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service)); +$this->resprints.= $customer->id; +} +else { +$this->resprints.= $langs->trans("NoStripe"); +} + $this->resprints.= ''; + } + return 0; + } + + function addMoreActionsButtons($parameters=false, &$object, &$action='') + { + global $db,$conf,$user,$langs,$form; + if (is_object($object) && $object->element == 'facture'){ + // On verifie si la facture a des paiements + $sql = 'SELECT pf.amount'; + $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf'; + $sql .= ' WHERE pf.fk_facture = ' . $object->id; + + $result = $db->query($sql); + if ($result) { + $i = 0; + $num = $db->num_rows($result); + + while ($i < $num) { + $objp = $db->fetch_object($result); + $totalpaye += $objp->amount; + $i ++; + } + } else { + dol_print_error($db, ''); + } + + $resteapayer = $object->total_ttc - $totalpaye; + // Request a direct debit order + if ($object->statut > Facture::STATUS_DRAFT && $object->statut < Facture::STATUS_ABANDONED && $object->paye == 0) + { $stripe=new Stripe($db); + if ($resteapayer > 0) + { + if ($stripe->getStripeAccount($conf->entity)) // a modifier avec droit stripe + { + $langs->load("withdrawals"); + print ''.$langs->trans("StripeConnectPay").''; + } + else + { + print ''.$langs->trans("StripeConnectPay").''; + } + } + elseif ($resteapayer == 0) + { + print ''.$langs->trans("StripeConnectPay").''; + } + } + else { + print ''.$langs->trans("StripeConnectPay").''; + } + } + elseif (is_object($object) && $object->element == 'invoice_supplier'){ +print ''.$langs->trans("StripeConnectPay").''; + } + elseif (is_object($object) && $object->element == 'member'){ +print ''.$langs->trans("StripeAutoSubscription").''; + } + return 0; + } + +} From 3d411f09fc8f9e94bed1c3645ce5686fe8e60f61 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Thu, 8 Mar 2018 23:13:37 +0100 Subject: [PATCH 092/413] Update actions_stripe.class.php --- htdocs/stripe/class/actions_stripe.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/stripe/class/actions_stripe.class.php b/htdocs/stripe/class/actions_stripe.class.php index 6101ce31f70..513999854e8 100644 --- a/htdocs/stripe/class/actions_stripe.class.php +++ b/htdocs/stripe/class/actions_stripe.class.php @@ -24,7 +24,7 @@ * \brief File Class multicompany */ require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';; -$langs->load("stripeconnect@stripeconnect"); +$langs->load("stripe@stripe"); /** * \class ActionsMulticompany From b68b66edcb0c08e4799a28b339d4b43cda4938bd Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 23:16:55 +0100 Subject: [PATCH 093/413] Fix phpcs --- htdocs/stripe/class/stripe.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 4167c6a0d81..a87d80c265e 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -319,9 +319,9 @@ class Stripe extends CommonObject $return->type = $err['type']; $return->code = $err['code']; $return->message = $err['message']; - $body = "Une erreur de paiement est survenue. Voici le code d'erreur:
    " . $return->id . " " . $return->message . " "; + $body = "Error:
    " . $return->id . " " . $return->message . " "; $subject = '[NOTIFICATION] Erreur de paiement'; - $headers = 'From: "ptibogxiv.net" <' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '>'; + $headers = 'From: "noreply" <' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '>'; mail('' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '', $subject, $body, $headers); $error ++; dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); From 51398ad060f955710bfc715d070c8b00973bee54 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Thu, 8 Mar 2018 23:27:20 +0100 Subject: [PATCH 094/413] FIX dolibarr version --- htdocs/stripe/config.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/stripe/config.php b/htdocs/stripe/config.php index a692e541050..0e207474a51 100644 --- a/htdocs/stripe/config.php +++ b/htdocs/stripe/config.php @@ -65,4 +65,4 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; -\Stripe\Stripe::setAppInfo("Stripe", "dolibarr version", "https://www.dolibarr.org"); // add dolibarr version +\Stripe\Stripe::setAppInfo("Stripe", DOL_VERSION, "https://www.dolibarr.org"); // add dolibarr version From a2fd2bc3f36c6a9a4cfdbdd5d517f253b5b139c1 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Fri, 9 Mar 2018 00:03:44 +0100 Subject: [PATCH 095/413] FIX entity TO DO: save stripe account in multicompany mode and without stripe connect in theadmin of stripe module because stripe doesn't send custom field for all request RISK: confusion and error in payment and transfert bank without this --- htdocs/public/stripe/ipn.php | 607 +++++++++++++++++------------------ 1 file changed, 297 insertions(+), 310 deletions(-) diff --git a/htdocs/public/stripe/ipn.php b/htdocs/public/stripe/ipn.php index 1f4b4cbb3d6..d56fa61422a 100644 --- a/htdocs/public/stripe/ipn.php +++ b/htdocs/public/stripe/ipn.php @@ -1,335 +1,322 @@ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ -define("NOLOGIN",1); // This means this output page does not require to be logged. -define("NOCSRFCHECK",1); // We accept to go on this page from external web site. - -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); - -$res=0; -if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); // to work if your module directory is into a subdir of root htdocs directory -if (! $res) die("Include of main fails"); - -if (empty($conf->stripeconnect->enabled)) accessforbidden('',0,0,1); -require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; -require_once DOL_DOCUMENT_ROOT.'/includes/stripe/init.php'; -require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; -//dol_include_once('/stripeconnect/class/paymentfee.class.php'); -require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; -require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; -// You can find your endpoint's secret in your webhook settings -if (isset($_GET['connect'])){ -if (isset($_GET['test'])) + +/** + * Stripe class + */ +class Stripe extends CommonObject { -$endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_CONNECT_KEY; -} -else -{ -$endpoint_secret = $conf->global->STRIPE_LIVE_WEBHOOK_CONNECT_KEY; -} -}else { -if (isset($_GET['test'])) -{ -$endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_KEY; -} -else -{ -$endpoint_secret = $conf->global->STRIPE_LIVE_WEBHOOK_KEY; -} -} -$payload = @file_get_contents("php://input"); -$sig_header = $_SERVER["HTTP_STRIPE_SIGNATURE"]; -$event = null; + public $rowid; + public $fk_soc; + public $fk_key; + public $id; + public $mode; + public $entity; + public $statut; + public $type; + public $code; + public $message; -$error = 0; - -try { -$event = \Stripe\Webhook::constructEvent($payload, $sig_header, $endpoint_secret); -} -catch(\UnexpectedValueException $e) { - // Invalid payload - http_response_code(400); // PHP 5.4 or greater - exit(); -} catch(\Stripe\Error\SignatureVerification $e) { - // Invalid signature - http_response_code(400); // PHP 5.4 or greater - exit(); -} + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; -// Do something with $event + } -http_response_code(200); // PHP 5.4 or greater -$langs->load("main"); -$user = new User($db); -$user->fetch(5); -$user->getrights(); -if (! empty($conf->stripeconnect->enabled) && ! empty($conf->multicompany->enabled)) { - $sql = "SELECT entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity"; - $sql.= " WHERE key_account = '".$event->account."'"; + /** + * Return stripe account + * + * @param string $mode 'StripeTest' or 'StripeLive' + * @return int ??? + */ + public function getStripeAccount($mode='StripeTest') + { + global $conf; - dol_syslog(get_class($db) . "::fetch", LOG_DEBUG); - $result = $db->query($sql); - if ($result) + $sql = "SELECT tokenstring"; + $sql.= " FROM ".MAIN_DB_PREFIX."oauth_token"; + $sql.= " WHERE entity = ".$conf->entity; + $sql.= " AND service = '".$mode."'"; + + dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { - if ($db->num_rows($result)) + if ($this->db->num_rows($result)) { - $obj = $db->fetch_object($result); - $key=$obj->entity; - } - else {$key=1;} - } - else {$key=1;} -$ret=$mc->switchEntity($key); -if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); // to work if your module directory is into a subdir of root htdocs directory -if (! $res) die("Include of main fails"); -} + $obj = $this->db->fetch_object($result); + $tokenstring=$obj->tokenstring; -// list of action -$stripeconnect=new StripeConnexion($db); -if ($event->type == 'payout.created') { - $error=0; - $db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."stripeconnect_entity SET next_payout = '".date('Y-m-d H:i:s',$event->data->object->arrival_date)."'"; - $sql.= " WHERE entity = ".$key; + $tmparray = dol_json_decode($tokenstring); + $key = $tmparray->stripe_user_id; + } + else { + $tokenstring=''; + } + } + else { + dol_print_error($this->db); + } - $result = $db->query($sql); - if ($result) - { -$body = "Un virement de ".price2num($event->data->object->amount/100)." ".$event->data->object->currency." est attendu sur votre compte le ".date('d-m-Y H:i:s',$event->data->object->arrival_date); -$subject = '[NOTIFICATION] Virement programmée'; -$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; -mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); - $db->commit(); - return 1; - } - else - { - $db->error(); - $db->rollback(); - return -1; - } -} -elseif ($event->type == 'payout.paid') { -global $conf; - $error=0; - $db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."stripeconnect_entity SET next_payout = null"; - $sql.= " WHERE entity = ".$key; + return $key; + } - $result = $db->query($sql); - if ($result) - { - // Call trigger - //$result=$this->call_trigger('MEMBER_RESILIATE',$user); - //if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers - $langs->load("errors"); + /** + * customerStripe + * + * @param int $id ??? + * @param string $key ??? + * @return \Stripe\StripeObject|\Stripe\ApiResource + */ + public function customerStripe($id,$key) + { + global $conf; + if (empty($conf->global->STRIPECONNECT_LIVE)) { + $mode = 0; + } else { + if (empty($conf->global->STRIPE_LIVE)) { + $mode = 0; + } else { + $mode = $conf->global->STRIPE_LIVE; + } + } + $sql = "SELECT rowid,fk_soc,fk_key,mode,entity"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe"; + $sql .= " WHERE fk_soc = " . $id . " "; + $sql .= " AND mode=" . $mode . " AND entity IN (" . getEntity('stripe') . ")"; - $dateo = dol_now(); - $label = $event->data->object->description; - $amount= $event->data->object->amount/100; - $amount_to= $event->data->object->amount/100; -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $soc = new Societe($this->db); + $soc->fetch($id); + $num = $this->db->num_rows($resql); + if ($num) { + $obj = $this->db->fetch_object($resql); + $tiers = $obj->fk_key; + if ($conf->entity == 1) { + $customer = \Stripe\Customer::retrieve("$tiers"); + } else { + $customer = \Stripe\Customer::retrieve("$tiers", array( + "stripe_account" => $key + )); + } + } else { + if ($conf->entity == 1) { + $customer = \Stripe\Customer::create(array( + "email" => $soc->email, + "description" => $soc->name + )); + } else { + $customer = \Stripe\Customer::create(array( + "email" => $soc->email, + "description" => $soc->name + ), array( + "stripe_account" => $key + )); + } + $customer_id = "" . $customer->id . ""; + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_stripe (fk_soc,fk_key,mode,entity)"; + $sql .= " VALUES ($id,'$customer_id'," . $mode . "," . $conf->entity . ")"; + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + } + } + return $customer; + } - $accountfrom=new Account($db); - $accountfrom->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS); + /** + * createPaymentStripe + * + * @param unknown $amount ??? + * @param unknown $currency ??? + * @param unknown $origin ??? + * @param unknown $item ??? + * @param unknown $source ??? + * @param unknown $customer ??? + * @param unknown $account ??? + * @return Stripe + */ + public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) + { + global $conf; + if (empty($conf->global->STRIPECONNECT_LIVE)) { + $mode = 0; + } else { + if (empty($conf->global->STRIPE_LIVE)) { + $mode = 0; + } else { + $mode = $conf->global->STRIPE_LIVE; + } + } + $sql = "SELECT fk_soc,fk_key,mode,entity"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe"; + $sql .= " WHERE fk_key = '$customer' "; + $sql .= " AND mode=" . $mode . " "; - $accountto=new Account($db); - $accountto->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANFERS); + dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $entite = $obj->entity; + $fksoc = $obj->fk_soc; + } + } + $stripeamount = round($amount * 100); + $societe = new Societe($this->db); + $societe->fetch($fksoc); - if ($accountto->currency_code != $accountfrom->currency_code) { - $error++; - setEventMessages($langs->trans("ErrorTransferBetweenDifferentCurrencyNotPossible"), null, 'errors'); + if ($origin == order) { + $order = new Commande($this->db); + $order->fetch($item); + $ref = $order->ref; + $description = "ORD=" . $ref . ".CUS=" . $societe->code_client; + } elseif ($origin == invoice) { + $invoice = new Facture($this->db); + $invoice->fetch($item); + $ref = $invoice->ref; + $description = "INV=" . $ref . ".CUS=" . $societe->code_client; } - if ($accountto->id != $accountfrom->id) - { - - $bank_line_id_from=0; - $bank_line_id_to=0; - $result=0; - - // By default, electronic transfert from bank to bank - $typefrom='PRE'; - $typeto='VIR'; - - if (! $error) $bank_line_id_from = $accountfrom->addline($dateo, $typefrom, $label, -1*price2num($amount), '', '', $user); - if (! ($bank_line_id_from > 0)) $error++; - if ((! $error) && ($accountto->currency_code == $accountfrom->currency_code)) $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount), '', '', $user); - if ((! $error) && ($accountto->currency_code != $accountfrom->currency_code)) $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount_to), '', '', $user); - if (! ($bank_line_id_to > 0)) $error++; - - if (! $error) $result=$accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT.'/compta/bank/ligne.php?rowid=', '(banktransfert)', 'banktransfert'); - if (! ($result > 0)) $error++; - if (! $error) $result=$accountto->add_url_line($bank_line_id_to, $bank_line_id_from, DOL_URL_ROOT.'/compta/bank/ligne.php?rowid=', '(banktransfert)', 'banktransfert'); - if (! ($result > 0)) $error++; - } - -$body = "Un virement de ".price2num($event->data->object->amount/100)." ".$event->data->object->currency." a ete effectue sur votre compte le ".date('d-m-Y H:i:s',$event->data->object->arrival_date); -$subject = '[NOTIFICATION] Virement effectué'; -$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; -mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); - $db->commit(); - return 1; - } - else - { - $db->error(); - $db->rollback(); - return -1; - } -} -elseif ($event->type == 'charge.succeeded') { -//if (isset($_GET['connect'])){ -//$txn=\Stripe\BalanceTransaction::retrieve("".$event->data->object->balance_transaction."",array("stripe_account" => $event->account)); -//} -//else { -//$txn=\Stripe\BalanceTransaction::retrieve("".$event->data->object->balance_transaction.""); -//} - -//$input=$txn->fee_details; -//$fee = new PaymentStripeFee($db); -//$fee->accountid=10; -//$fee->fk_soc=473; -///foreach ($input as $src) { -//if ($src->type=='stripe_fee') { -//$fee->stripe_fee=price2num($src->amount/100); -//} -//elseif ($src->type=='application_fee') { -//$fee->application_fee=price2num($src->amount/100); -//} - -//}// -//$fee->currency=$txn->currency; -//$fee->datev=dol_now(); -//$fee->datep=dol_now(); -//$fee->datesp=dol_now(); -//$fee->dateep=dol_now(); -//$fee->type_payment=3; -//$fee->num_payment=$txn->source; -//$fee->fk_user_author=$user->id; -//$fee->create($user); - -} -elseif ($event->type == 'charge.failed') { - -$subject = 'Your payment has been received: '.$event->data->object->id.''; -$headers = 'From: "test webhook" '; -//mail('ptibogxiv@msn.com', $subject, 'test', $headers); - -} -elseif (($event->type == 'source.chargeable') && ($event->data->object->type == 'three_d_secure') && ($event->data->object->three_d_secure->authenticated==true)) { - -$stripeconnect=new StripeConnexion($db); -$charge=$stripeconnect->CreatePaymentStripe($event->data->object->amount/100,$event->data->object->currency,$event->data->object->metadata->source,$event->data->object->metadata->idsource,$event->data->object->id,$event->data->object->metadata->customer,$stripeconnect->GetStripeAccount($entity)); - -if (isset($charge->id) && $charge->statut=='error'){ -$msg=$charge->message; -$code=$charge->code; -$error++; -} -elseif (isset($charge->id) && $charge->statut=='success' && $event->data->object->metadata->source=='order') { -$order=new Commande($db); -$order->fetch($event->data->object->metadata->idsource); -$invoice = new Facture($db); -$idinv=$invoice->createFromOrder($order); - -if ($idinv > 0) -{ -$result=$invoice->validate($user); -if ($result > 0) { -$invoice->fetch($idinv); -$paiement = $invoice->getSommePaiement(); -$creditnotes=$invoice->getSumCreditNotesUsed(); -$deposits=$invoice->getSumDepositsUsed(); -$ref=$invoice->ref; -$ifverif=$invoice->socid; -$currency=$invoice->multicurrency_code; -$total=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); -}else{ -$msg=$invoice->error; -$error++; -} -}else{ -$msg=$invoice->error; -$error++; -} -} - -if (!$error){ -$datepaye = dol_now(); -$paiementcode ="CB"; -$amounts=array(); -$amounts[$invoice->id] = $total; -$multicurrency_amounts=array(); -//$multicurrency_amounts[$item] = $total; - $paiement = new Paiement($db); - $paiement->datepaye = $datepaye; - $paiement->amounts = $amounts; // Array with all payments dispatching - $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching - $paiement->paiementid = dol_getIdFromCode($db,$paiementcode,'c_paiement'); - $paiement->num_paiement = $charge->message; - $paiement->note = ''; -} - -if (! $error){ -$paiement_id=$paiement->create($user, 0); - -if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && count($invoice->lines)){ - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $invoice->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); + $metadata = array( + "source" => "" . $origin . "", + "idsource" => "" . $item . "", + "idcustomer" => "" . $societe->id . "" + ); + $return = new Stripe($this->db); + try { + if ($stripeamount >= 100) { + if ($entite == '1' or empty($conf->stripeconnect->enabled)) { + if (preg_match('/acct_/i', $source)) { + $charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", + // "statement_descriptor" => " ", + "metadata" => $metadata, + "source" => "$source" + )); + } else { + $charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", + // "statement_descriptor" => " ", + "description" => "$description", + "metadata" => $metadata, + "receipt_email" => $societe->email, + "source" => "$source", + "customer" => "$customer" + ), array( + "idempotency_key" => "$ref" + )); + } + } else { + $fee = round(($amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE) * 100); + if ($fee < ($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100)) { + $fee = round($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100); + } + $charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", + // "statement_descriptor" => " ", + "description" => "$description", + "metadata" => $metadata, + "source" => "$source", + "customer" => "$customer", + "application_fee" => "$fee" + ), array( + "idempotency_key" => "$ref", + "stripe_account" => "$account" + )); } - $model=$invoice->modelpdf; - $ret = $invoice->fetch($invoice->id); // Reload to get new records + if (isset($charge->id)) {} + } -$invoice->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);} -if ($paiement_id < 0){ - $msg=$paiement->errors; - $error++; -}else{ - if ($event->data->object->metadata->source=='order') { - $order->classifyBilled($user); - } - } - } - -if (! $error){ - $label='(CustomerInvoicePayment)'; - if (GETPOST('type') == 2) $label='(CustomerInvoicePaymentBack)'; - $paiement->addPaymentToBank($user,'payment',$label,$conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS,'',''); - if ($result < 0) - { - $msg=$paiement->errors; - $error++; - } -$invoice->set_paid($user); -} + $return->statut = 'success'; + $return->id = $charge->id; + if ($charge->source->type == 'card') { + $return->message = $charge->source->card->brand . " ****" . $charge->source->card->last4; + } elseif ($charge->source->type == 'three_d_secure') { + $stripe = new Stripe($this->db); + $src = \Stripe\Source::retrieve("" . $charge->source->three_d_secure->card . "", array( + "stripe_account" => $stripe->getStripeAccount($conf->entity) + )); + $return->message = $src->card->brand . " ****" . $src->card->last4; + } else { + $return->message = $charge->id; + } + } catch (\Stripe\Error\Card $e) { + // Since it's a decline, \Stripe\Error\Card will be caught + $body = $e->getJsonBody(); + $err = $body['error']; + + $return->statut = 'error'; + $return->id = $err['charge']; + $return->type = $err['type']; + $return->code = $err['code']; + $return->message = $err['message']; + $body = "Une erreur de paiement est survenue. Voici le code d'erreur:
    " . $return->id . " " . $return->message . " "; + $subject = '[NOTIFICATION] Erreur de paiement'; + $headers = 'From: "ptibogxiv.net" <' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '>'; + mail('' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '', $subject, $body, $headers); + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\RateLimit $e) { + // Too many requests made to the API too quickly + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\InvalidRequest $e) { + // Invalid parameters were supplied to Stripe's API + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\Authentication $e) { + // Authentication with Stripe's API failed + // (maybe you changed API keys recently) + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\ApiConnection $e) { + // Network communication with Stripe failed + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\Base $e) { + // Display a very generic error to the user, and maybe send + // yourself an email + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (Exception $e) { + // Something else happened, completely unrelated to Stripe + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } + return $return; + } -$body = ""; -$subject = 'Facture '.$invoice->ref; -$headers = 'From: "test webhook" '; -//mail('ptibogxiv@msn.com', $subject, $body, $headers); } -elseif ($event->type == 'customer.deleted') { - $db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_stripe WHERE fk_key = '".$event->data->object->id."' "; - dol_syslog(get_class($this) . "::delete sql=" . $sql, LOG_DEBUG); - $db->query($sql); - $db->commit(); -} - - - -?> From 82057b35233fa22d72c2f6978647c49531d4f3d2 Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Fri, 9 Mar 2018 08:11:02 +0100 Subject: [PATCH 096/413] Fix: use code instead id --- htdocs/compta/facture/list.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 8319f42bd97..987ed926986 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -276,7 +276,7 @@ if ($massaction == 'withdrawrequest') $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors'); } - if(!($objecttmp->statut > Facture::STATUS_DRAFT)){ + if (!($objecttmp->statut > Facture::STATUS_DRAFT)){ $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors'); } @@ -298,11 +298,11 @@ if ($massaction == 'withdrawrequest') $numprlv = $db->num_rows($result_sql); } - if($numprlv>0){ + if ($numprlv>0){ $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'errors'); } - if(!empty($objecttmp->mode_reglement_id ) && $objecttmp->mode_reglement_id != 3){ + if (!empty($objecttmp->mode_reglement_code ) && $objecttmp->mode_reglement_code != 'PRE'){ $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); } From ea175cd6c176c3722c627d7be26cf398dfd267a8 Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Fri, 9 Mar 2018 09:37:23 +0100 Subject: [PATCH 097/413] Fix: compatibility with multicompany dictionnary sharing --- htdocs/comm/propal/card.php | 2 +- htdocs/commande/card.php | 2 +- htdocs/fourn/facture/card.php | 2 +- htdocs/supplier_proposal/card.php | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 2e9c184dd11..0b5fcd547e7 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -1371,7 +1371,7 @@ if ($action == 'create') $soc = $objectsrc->thirdparty; - $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); + $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index cf70d422130..f11c4778b0b 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -1450,7 +1450,7 @@ if ($action == 'create' && $user->rights->commande->creer) $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : ''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 0ae8b0669c8..5b1be2239f1 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1626,7 +1626,7 @@ if ($action == 'create') //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:1)); + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:0)); $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 5585d3ba87b..e12e1e34505 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -998,7 +998,7 @@ if ($action == 'create') $projectid = (! empty($objectsrc->fk_project) ? $objectsrc->fk_project : ''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); + $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); @@ -1056,7 +1056,7 @@ if ($action == 'create') if ($soc->id > 0) { // Discounts for third party - print '' . $langs->trans('Discounts') . ''; + print '' . $langs->trans('Discounts') . ''; $absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1); From f4f81482e776010fa42492da348a10d5524da75d Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Fri, 9 Mar 2018 09:39:57 +0100 Subject: [PATCH 098/413] Fix: add todo if you use the good id by entities --- htdocs/fourn/facture/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 5b1be2239f1..d69e1be6c3a 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1626,7 +1626,7 @@ if ($action == 'create') //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:0)); + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:0)); // TODO maybe add default value option $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); From f37d48233183d8fc1c7cf24a167d83cfd013c696 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 11:37:23 +0100 Subject: [PATCH 099/413] fix warning and sql error --- htdocs/blockedlog/class/blockedlog.class.php | 1 + htdocs/core/modules/modFournisseur.class.php | 6 +++++- htdocs/holiday/define_holiday.php | 5 +++-- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 8c35ec11834..77bf90e2717 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -103,6 +103,7 @@ class BlockedLog public $ref_object = ''; public $object_data = null; + public $user_fullname=''; /** * Array of tracked event codes diff --git a/htdocs/core/modules/modFournisseur.class.php b/htdocs/core/modules/modFournisseur.class.php index 9e8bdc8ea03..d8ed86907fd 100644 --- a/htdocs/core/modules/modFournisseur.class.php +++ b/htdocs/core/modules/modFournisseur.class.php @@ -531,7 +531,11 @@ class modFournisseur extends DolibarrModules case 'sellist': $tmp=''; $tmpparam=unserialize($obj->param); // $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null - if ($tmpparam['options'] && is_array($tmpparam['options'])) $tmp=array_shift(array_keys($tmpparam['options'])); + + if ($tmpparam['options'] && is_array($tmpparam['options'])) { + $tmpparam_param_key=array_keys($tmpparam['options']); + $tmp=array_shift($tmpparam_param_key); + } if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp; break; } diff --git a/htdocs/holiday/define_holiday.php b/htdocs/holiday/define_holiday.php index a7d4789468e..e5bd8c0e8c0 100644 --- a/htdocs/holiday/define_holiday.php +++ b/htdocs/holiday/define_holiday.php @@ -216,8 +216,9 @@ if (empty($user->rights->holiday->read_all)) $userchilds=$user->getAllChildIds(1); $filters.=' AND u.rowid IN ('.join(', ',$userchilds).')'; } - -$filters.=natural_search(array('u.firstname','u.lastname'), $search_name); +if (!empty($search_name)) { + $filters.=natural_search(array('u.firstname','u.lastname'), $search_name); +} if ($search_supervisor > 0) $filters.=natural_search(array('u.fk_user'), $search_supervisor, 2); $listUsers = $holiday->fetchUsers(false, true, $filters); From ee557768865200c759948872bd4aa6919f0b811a Mon Sep 17 00:00:00 2001 From: Romain DELVAL Date: Fri, 9 Mar 2018 12:38:28 +0100 Subject: [PATCH 100/413] FIX Duplicate product_type asignement on order addline On addline order method, ther is a duplicate assignation on line->product_type before call to "insert" method. The second assignement always make product_type to "0" while it was fetched from product himsel like it was made on first asignement few lines above --- htdocs/commande/class/commande.class.php | 1 - 1 file changed, 1 deletion(-) diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index c107dff6960..b7b92eb997d 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -1405,7 +1405,6 @@ class Commande extends CommonOrder $this->line->total_localtax1=$total_localtax1; $this->line->total_localtax2=$total_localtax2; $this->line->total_ttc=$total_ttc; - $this->line->product_type=$type; $this->line->special_code=$special_code; $this->line->origin=$origin; $this->line->origin_id=$origin_id; From 3eeeaf2d2dd59ed4b7527ff360fd9f7c12ff8f2f Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Fri, 9 Mar 2018 12:54:34 +0100 Subject: [PATCH 101/413] Fix: REST API must be enabled for all entities --- htdocs/api/admin/index.php | 8 ++++---- htdocs/core/modules/modApi.class.php | 29 ++++++++++++++++++++++++---- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/htdocs/api/admin/index.php b/htdocs/api/admin/index.php index 57efe8d7cb9..7ebff2c5da6 100644 --- a/htdocs/api/admin/index.php +++ b/htdocs/api/admin/index.php @@ -1,9 +1,9 @@ +/* Copyright (C) 2004 Rodolphe Quiedeville * Copyright (C) 2005-2016 Laurent Destailleur * Copyright (C) 2011 Juanjo Menent - * Copyright (C) 2012 Regis Houssin - * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2012-2018 Regis Houssin + * Copyright (C) 2015 Jean-François Ferry * * 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 @@ -41,7 +41,7 @@ if ($action == 'setproductionmode') { $status = GETPOST('status','alpha'); - if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', $conf->entity) > 0) + if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', 0) > 0) { $error=0; diff --git a/htdocs/core/modules/modApi.class.php b/htdocs/core/modules/modApi.class.php index 3e27031fd6f..24d784585d3 100644 --- a/htdocs/core/modules/modApi.class.php +++ b/htdocs/core/modules/modApi.class.php @@ -1,7 +1,8 @@ - * Copyright (C) 2004-2012 Laurent Destailleur - * Copyright (C) 2015 Jean-François Ferry +/* Copyright (C) 2003 Rodolphe Quiedeville + * Copyright (C) 2004-2012 Laurent Destailleur + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2018 Regis Houssin * * 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 @@ -60,12 +61,13 @@ class modApi extends DolibarrModules $this->version = 'dolibarr'; // Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase) $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); + // Can be enabled / disabled only in the main company with superadmin account + $this->core_enabled = 1; // Name of image file used for this module. // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' $this->picto='technic'; - $this->module_parts = array(); // Data directories to create when module is enabled. @@ -230,5 +232,24 @@ class modApi extends DolibarrModules return $this->_init($sql, $options); } + + /** + * Function called when module is disabled. + * Remove from database constants, boxes and permissions from Dolibarr database. + * Data directories are not deleted. + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + function remove($options = '') + { + // Remove old constants with entity fields different of 0 + $sql = array( + "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = ".$this->db->encrypt('MAIN_MODULE_API', 1), + "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = ".$this->db->encrypt('API_PRODUCTION_MODE', 1) + ); + + return $this->_remove($sql, $options); + } } From 1c966d4769b5257ee68dfd6f6a8ed5ed70f2ddb3 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 12:57:58 +0100 Subject: [PATCH 102/413] on going --- htdocs/core/menus/standard/eldy.lib.php | 6 +++--- htdocs/product/inventory/card.php | 10 ++++++---- htdocs/product/inventory/list.php | 1 + 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index 077b6c8ba64..3abff3f714e 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -1257,9 +1257,9 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu if (! empty($conf->stock->enabled)) { $langs->load("stocks"); - $newmenu->add("/product/inventory/list.php?leftmenu=stock", $langs->trans("Inventory"), 0, $user->rights->stock->lire, '', $mainmenu, 'stock'); - $newmenu->add("/product/inventory/card.php?action=create", $langs->trans("NewInventory"), 1, $user->rights->stock->creer); - $newmenu->add("/product/inventory/list.php", $langs->trans("List"), 1, $user->rights->stock->lire); + $newmenu->add("/product/inventory/list.php?leftmenu=stock", $langs->trans("Inventory"), 0, $user->rights->stock->advance_inventory->read, '', $mainmenu, 'stock'); + $newmenu->add("/product/inventory/card.php?action=create", $langs->trans("NewInventory"), 1, $user->rights->stock->advance_inventory->create); + $newmenu->add("/product/inventory/list.php", $langs->trans("List"), 1, $user->rights->stock->advance_inventory->read); } } diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index e393721c47d..5fc63653ffc 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -36,6 +36,8 @@ $action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); +$result = restrictedArea($user, 'stock', $id, '', 'advance_inventory'); + // Initialize technical objects $object=new Inventory($db); $extrafields = new ExtraFields($db); @@ -80,8 +82,8 @@ if (empty($reshook)) { $error=0; - $permissiontoadd = $user->rights->stock->creer; - $permissiontodelete = $user->rights->stock->supprimer; + $permissiontoadd = $user->rights->stock->advance_inventory->create; + $permissiontodelete = $user->rights->stock->advance_inventory->write; $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php'; // Actions cancel, add, update or delete @@ -327,7 +329,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Send print '' . $langs->trans('SendMail') . ''."\n"; - if ($user->rights->inventory->write) + if ($user->rights->stock->advance_inventory->write) { print ''.$langs->trans("Modify").''."\n"; } @@ -336,7 +338,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''.$langs->trans('Modify').''."\n"; } - if ($user->rights->inventory->delete) + if ($user->rights->stock->advance_inventory->write) { print ''.$langs->trans('Delete').''."\n"; } diff --git a/htdocs/product/inventory/list.php b/htdocs/product/inventory/list.php index cb67168b214..c53ffafa8a3 100644 --- a/htdocs/product/inventory/list.php +++ b/htdocs/product/inventory/list.php @@ -72,6 +72,7 @@ if ($user->societe_id > 0) //$socid = $user->societe_id; accessforbidden(); } +$result = restrictedArea($user, 'stock', $objectid, '', 'advance_inventory'); // Initialize array of search criterias $search_all=trim(GETPOST("search_all",'alpha')); From f0164f268996f893083f53570fb4854b1b05919c Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 14:25:37 +0100 Subject: [PATCH 103/413] fix type date --- htdocs/core/actions_addupdatedelete.inc.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php index 6318e4d5c54..b8ede4d7d14 100644 --- a/htdocs/core/actions_addupdatedelete.inc.php +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -93,8 +93,16 @@ if ($action == 'update' && ! empty($permissiontoadd)) if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat', 'fk_user_modif', 'import_key'))) continue; // Ignore special fields // Set value to update - if (in_array($object->fields[$key]['type'], array('text', 'html'))) $value = GETPOST($key,'none'); - else $value = GETPOST($key,'alpha'); + if (in_array($object->fields[$key]['type'], array('text', 'html'))) { + $value = GETPOST($key,'none'); + } + elseif ($object->fields[$key]['type']=='date') { + $value = dol_mktime(12, 0, 0, GETPOST($key.'month'), GETPOST($key.'day'), GETPOST($key.'year')); + } elseif ($object->fields[$key]['type']=='datetime') { + $value = dol_mktime(GETPOST($key.'hour'), GETPOST($key.'min'), 0, GETPOST($key.'month'), GETPOST($key.'day'), GETPOST($key.'year')); + } else { + $value = GETPOST($key,'alpha'); + } if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') $value=''; // This is an implicit foreign key field if (! empty($object->fields[$key]['foreignkey']) && $value == '-1') $value=''; // This is an explicit foreign key field From bfa74785682a7a38c975b5490648b70fb2314742 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Fri, 9 Mar 2018 14:40:20 +0100 Subject: [PATCH 104/413] FIX compatibility for multicompany (stripeconnect or not) TODO: more test and create fee with stripe callback --- htdocs/public/stripe/ipn.php | 568 +++++++++++++++++------------------ 1 file changed, 272 insertions(+), 296 deletions(-) diff --git a/htdocs/public/stripe/ipn.php b/htdocs/public/stripe/ipn.php index d56fa61422a..32d874eafbe 100644 --- a/htdocs/public/stripe/ipn.php +++ b/htdocs/public/stripe/ipn.php @@ -1,322 +1,298 @@ - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -// Put here all includes required by your class file -require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; -require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +define("NOLOGIN",1); // This means this output page does not require to be logged. +define("NOCSRFCHECK",1); // We accept to go on this page from external web site. + +$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); +if (is_numeric($entity)) define("DOLENTITY", $entity); + +$res=0; +if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); // to work if your module directory is into a subdir of root htdocs directory +if (! $res) die("Include of main fails"); + +if (empty($conf->stripe->enabled)) accessforbidden('',0,0,1); +require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; +require_once DOL_DOCUMENT_ROOT.'/includes/stripe/init.php'; +require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - -/** - * Stripe class - */ -class Stripe extends CommonObject +// You can find your endpoint's secret in your webhook settings +if (isset($_GET['connect'])){ +if (isset($_GET['test'])) { - public $rowid; - public $fk_soc; - public $fk_key; - public $id; - public $mode; - public $entity; - public $statut; - public $type; - public $code; - public $message; +$endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_CONNECT_KEY; +$service = 'StripeTest'; +} +else +{ +$endpoint_secret = $conf->global->STRIPE_LIVE_WEBHOOK_CONNECT_KEY; +$service = 'StripeLive'; +} +}else { +if (isset($_GET['test'])) +{ +$endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_KEY; +$service = 'StripeTest'; +} +else +{ +$endpoint_secret = $conf->global->STRIPE_LIVE_WEBHOOK_KEY; +$service = 'StripeLive'; +} +} +$payload = @file_get_contents("php://input"); +$sig_header = $_SERVER["HTTP_STRIPE_SIGNATURE"]; +$event = null; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; +$error = 0; + +try { +$event = \Stripe\Webhook::constructEvent($payload, $sig_header, $endpoint_secret); +} +catch(\UnexpectedValueException $e) { + // Invalid payload + http_response_code(400); // PHP 5.4 or greater + exit(); +} catch(\Stripe\Error\SignatureVerification $e) { + // Invalid signature + http_response_code(400); // PHP 5.4 or greater + exit(); +} - } +// Do something with $event +http_response_code(200); // PHP 5.4 or greater +$langs->load("main"); +$user = new User($db); +$user->fetch(5); +$user->getrights(); - /** - * Return stripe account - * - * @param string $mode 'StripeTest' or 'StripeLive' - * @return int ??? - */ - public function getStripeAccount($mode='StripeTest') - { - global $conf; - - $sql = "SELECT tokenstring"; +if (! empty($conf->multicompany->enabled) && ! empty($conf->stripeconnect->enabled)) { + $sql = "SELECT entity"; $sql.= " FROM ".MAIN_DB_PREFIX."oauth_token"; - $sql.= " WHERE entity = ".$conf->entity; - $sql.= " AND service = '".$mode."'"; + $sql.= " WHERE service = '$service' and tokenstring = '%".$event->account."%'"; - dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) + dol_syslog(get_class($db) . "::fetch", LOG_DEBUG); + $result = $db->query($sql); + if ($result) { - if ($this->db->num_rows($result)) + if ($db->num_rows($result)) { - $obj = $this->db->fetch_object($result); - $tokenstring=$obj->tokenstring; + $obj = $db->fetch_object($result); + $key=$obj->entity; + } + else {$key=1;} + } + else {$key=1;} +$ret=$mc->switchEntity($key); +if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); // to work if your module directory is into a subdir of root htdocs directory +if (! $res) die("Include of main fails"); +} - $tmparray = dol_json_decode($tokenstring); - $key = $tmparray->stripe_user_id; - } - else { - $tokenstring=''; - } - } - else { - dol_print_error($this->db); - } +// list of action +$stripe=new Stripe($db); +if ($event->type == 'payout.created') { + $error=0; - return $key; - } + $result=dolibarr_set_const($db, $service."_NEXTPAYOUT",date('Y-m-d H:i:s',$event->data->object->arrival_date),'chaine',0,'',$conf->entity); + + if ($result > 0) + { +$body = "Un virement de ".price2num($event->data->object->amount/100)." ".$event->data->object->currency." est attendu sur votre compte le ".date('d-m-Y H:i:s',$event->data->object->arrival_date); +$subject = '[NOTIFICATION] Virement programmée'; +$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; +mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); + return 1; + } + else + { + $error++; + return -1; + } +} +elseif ($event->type == 'payout.paid') { +global $conf; + $error=0; + $result=dolibarr_set_const($db, $service."_NEXTPAYOUT",null,'chaine',0,'',$conf->entity); + if ($result) + { + $langs->load("errors"); - /** - * customerStripe - * - * @param int $id ??? - * @param string $key ??? - * @return \Stripe\StripeObject|\Stripe\ApiResource - */ - public function customerStripe($id,$key) - { - global $conf; - if (empty($conf->global->STRIPECONNECT_LIVE)) { - $mode = 0; - } else { - if (empty($conf->global->STRIPE_LIVE)) { - $mode = 0; - } else { - $mode = $conf->global->STRIPE_LIVE; - } - } - $sql = "SELECT rowid,fk_soc,fk_key,mode,entity"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe"; - $sql .= " WHERE fk_soc = " . $id . " "; - $sql .= " AND mode=" . $mode . " AND entity IN (" . getEntity('stripe') . ")"; + $dateo = dol_now(); + $label = $event->data->object->description; + $amount= $event->data->object->amount/100; + $amount_to= $event->data->object->amount/100; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $soc = new Societe($this->db); - $soc->fetch($id); - $num = $this->db->num_rows($resql); - if ($num) { - $obj = $this->db->fetch_object($resql); - $tiers = $obj->fk_key; - if ($conf->entity == 1) { - $customer = \Stripe\Customer::retrieve("$tiers"); - } else { - $customer = \Stripe\Customer::retrieve("$tiers", array( - "stripe_account" => $key - )); - } - } else { - if ($conf->entity == 1) { - $customer = \Stripe\Customer::create(array( - "email" => $soc->email, - "description" => $soc->name - )); - } else { - $customer = \Stripe\Customer::create(array( - "email" => $soc->email, - "description" => $soc->name - ), array( - "stripe_account" => $key - )); - } - $customer_id = "" . $customer->id . ""; - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_stripe (fk_soc,fk_key,mode,entity)"; - $sql .= " VALUES ($id,'$customer_id'," . $mode . "," . $conf->entity . ")"; - dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); - $resql = $this->db->query($sql); - } - } - return $customer; - } + $accountfrom=new Account($db); + $accountfrom->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS); - /** - * createPaymentStripe - * - * @param unknown $amount ??? - * @param unknown $currency ??? - * @param unknown $origin ??? - * @param unknown $item ??? - * @param unknown $source ??? - * @param unknown $customer ??? - * @param unknown $account ??? - * @return Stripe - */ - public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) - { - global $conf; - if (empty($conf->global->STRIPECONNECT_LIVE)) { - $mode = 0; - } else { - if (empty($conf->global->STRIPE_LIVE)) { - $mode = 0; - } else { - $mode = $conf->global->STRIPE_LIVE; - } - } - $sql = "SELECT fk_soc,fk_key,mode,entity"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe"; - $sql .= " WHERE fk_key = '$customer' "; - $sql .= " AND mode=" . $mode . " "; + $accountto=new Account($db); + $accountto->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANFERS); - dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) { - if ($this->db->num_rows($result)) { - $obj = $this->db->fetch_object($result); - $entite = $obj->entity; - $fksoc = $obj->fk_soc; - } - } - $stripeamount = round($amount * 100); - $societe = new Societe($this->db); - $societe->fetch($fksoc); - - if ($origin == order) { - $order = new Commande($this->db); - $order->fetch($item); - $ref = $order->ref; - $description = "ORD=" . $ref . ".CUS=" . $societe->code_client; - } elseif ($origin == invoice) { - $invoice = new Facture($this->db); - $invoice->fetch($item); - $ref = $invoice->ref; - $description = "INV=" . $ref . ".CUS=" . $societe->code_client; + if ($accountto->currency_code != $accountfrom->currency_code) { + $error++; + setEventMessages($langs->trans("ErrorTransferBetweenDifferentCurrencyNotPossible"), null, 'errors'); } - $metadata = array( - "source" => "" . $origin . "", - "idsource" => "" . $item . "", - "idcustomer" => "" . $societe->id . "" - ); - $return = new Stripe($this->db); - try { - if ($stripeamount >= 100) { - if ($entite == '1' or empty($conf->stripeconnect->enabled)) { - if (preg_match('/acct_/i', $source)) { - $charge = \Stripe\Charge::create(array( - "amount" => "$stripeamount", - "currency" => "$currency", - // "statement_descriptor" => " ", - "metadata" => $metadata, - "source" => "$source" - )); - } else { - $charge = \Stripe\Charge::create(array( - "amount" => "$stripeamount", - "currency" => "$currency", - // "statement_descriptor" => " ", - "description" => "$description", - "metadata" => $metadata, - "receipt_email" => $societe->email, - "source" => "$source", - "customer" => "$customer" - ), array( - "idempotency_key" => "$ref" - )); - } - } else { - $fee = round(($amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE) * 100); - if ($fee < ($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100)) { - $fee = round($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100); - } - $charge = \Stripe\Charge::create(array( - "amount" => "$stripeamount", - "currency" => "$currency", - // "statement_descriptor" => " ", - "description" => "$description", - "metadata" => $metadata, - "source" => "$source", - "customer" => "$customer", - "application_fee" => "$fee" - ), array( - "idempotency_key" => "$ref", - "stripe_account" => "$account" - )); - } - if (isset($charge->id)) {} - } + if ($accountto->id != $accountfrom->id) + { - $return->statut = 'success'; - $return->id = $charge->id; - if ($charge->source->type == 'card') { - $return->message = $charge->source->card->brand . " ****" . $charge->source->card->last4; - } elseif ($charge->source->type == 'three_d_secure') { - $stripe = new Stripe($this->db); - $src = \Stripe\Source::retrieve("" . $charge->source->three_d_secure->card . "", array( - "stripe_account" => $stripe->getStripeAccount($conf->entity) - )); - $return->message = $src->card->brand . " ****" . $src->card->last4; - } else { - $return->message = $charge->id; - } - } catch (\Stripe\Error\Card $e) { - // Since it's a decline, \Stripe\Error\Card will be caught - $body = $e->getJsonBody(); - $err = $body['error']; + $bank_line_id_from=0; + $bank_line_id_to=0; + $result=0; - $return->statut = 'error'; - $return->id = $err['charge']; - $return->type = $err['type']; - $return->code = $err['code']; - $return->message = $err['message']; - $body = "Une erreur de paiement est survenue. Voici le code d'erreur:
    " . $return->id . " " . $return->message . " "; - $subject = '[NOTIFICATION] Erreur de paiement'; - $headers = 'From: "ptibogxiv.net" <' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '>'; - mail('' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '', $subject, $body, $headers); - $error ++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\RateLimit $e) { - // Too many requests made to the API too quickly - $error ++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\InvalidRequest $e) { - // Invalid parameters were supplied to Stripe's API - $error ++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\Authentication $e) { - // Authentication with Stripe's API failed - // (maybe you changed API keys recently) - $error ++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\ApiConnection $e) { - // Network communication with Stripe failed - $error ++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\Base $e) { - // Display a very generic error to the user, and maybe send - // yourself an email - $error ++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (Exception $e) { - // Something else happened, completely unrelated to Stripe - $error ++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } - return $return; - } + // By default, electronic transfert from bank to bank + $typefrom='PRE'; + $typeto='VIR'; + + if (! $error) $bank_line_id_from = $accountfrom->addline($dateo, $typefrom, $label, -1*price2num($amount), '', '', $user); + if (! ($bank_line_id_from > 0)) $error++; + if ((! $error) && ($accountto->currency_code == $accountfrom->currency_code)) $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount), '', '', $user); + if ((! $error) && ($accountto->currency_code != $accountfrom->currency_code)) $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount_to), '', '', $user); + if (! ($bank_line_id_to > 0)) $error++; + + if (! $error) $result=$accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT.'/compta/bank/ligne.php?rowid=', '(banktransfert)', 'banktransfert'); + if (! ($result > 0)) $error++; + if (! $error) $result=$accountto->add_url_line($bank_line_id_to, $bank_line_id_from, DOL_URL_ROOT.'/compta/bank/ligne.php?rowid=', '(banktransfert)', 'banktransfert'); + if (! ($result > 0)) $error++; + } + +$body = "Un virement de ".price2num($event->data->object->amount/100)." ".$event->data->object->currency." a ete effectue sur votre compte le ".date('d-m-Y H:i:s',$event->data->object->arrival_date); +$subject = '[NOTIFICATION] Virement effectué'; +$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; +mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); + + return 1; + } + else + { + $error++; + return -1; + } +} +elseif ($event->type == 'charge.succeeded') { + +//TODO: create fees } +elseif ($event->type == 'charge.failed') { + +$subject = 'Your payment has been received: '.$event->data->object->id.''; +$headers = 'From: "test webhook" '; +//mail('ptibogxiv@msn.com', $subject, 'test', $headers); + +} +elseif (($event->type == 'source.chargeable') && ($event->data->object->type == 'three_d_secure') && ($event->data->object->three_d_secure->authenticated==true)) { + +$stripe=new Stripe($db); +$charge=$stripe->CreatePaymentStripe($event->data->object->amount/100,$event->data->object->currency,$event->data->object->metadata->source,$event->data->object->metadata->idsource,$event->data->object->id,$event->data->object->metadata->customer,$stripe->getStripeAccount($service)); + +if (isset($charge->id) && $charge->statut=='error'){ +$msg=$charge->message; +$code=$charge->code; +$error++; +} +elseif (isset($charge->id) && $charge->statut=='success' && $event->data->object->metadata->source=='order') { +$order=new Commande($db); +$order->fetch($event->data->object->metadata->idsource); +$invoice = new Facture($db); +$idinv=$invoice->createFromOrder($order); + +if ($idinv > 0) +{ +$result=$invoice->validate($user); +if ($result > 0) { +$invoice->fetch($idinv); +$paiement = $invoice->getSommePaiement(); +$creditnotes=$invoice->getSumCreditNotesUsed(); +$deposits=$invoice->getSumDepositsUsed(); +$ref=$invoice->ref; +$ifverif=$invoice->socid; +$currency=$invoice->multicurrency_code; +$total=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); +}else{ +$msg=$invoice->error; +$error++; +} +}else{ +$msg=$invoice->error; +$error++; +} +} + +if (!$error){ +$datepaye = dol_now(); +$paiementcode ="CB"; +$amounts=array(); +$amounts[$invoice->id] = $total; +$multicurrency_amounts=array(); +//$multicurrency_amounts[$item] = $total; + $paiement = new Paiement($db); + $paiement->datepaye = $datepaye; + $paiement->amounts = $amounts; // Array with all payments dispatching + $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching + $paiement->paiementid = dol_getIdFromCode($db,$paiementcode,'c_paiement'); + $paiement->num_paiement = $charge->message; + $paiement->note = ''; +} + +if (! $error){ +$paiement_id=$paiement->create($user, 0); + +if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && count($invoice->lines)){ + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $invoice->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$invoice->modelpdf; + $ret = $invoice->fetch($invoice->id); // Reload to get new records + +$invoice->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);} +if ($paiement_id < 0){ + $msg=$paiement->errors; + $error++; +}else{ + if ($event->data->object->metadata->source=='order') { + $order->classifyBilled($user); + } + } + } + +if (! $error){ + $label='(CustomerInvoicePayment)'; + if (GETPOST('type') == 2) $label='(CustomerInvoicePaymentBack)'; + $paiement->addPaymentToBank($user,'payment',$label,$conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS,'',''); + if ($result < 0) + { + $msg=$paiement->errors; + $error++; + } +$invoice->set_paid($user); +} + +$body = ""; +$subject = 'Facture '.$invoice->ref; +$headers = 'From: "test webhook" '; +//mail('ptibogxiv@msn.com', $subject, $body, $headers); +} +elseif ($event->type == 'customer.deleted') { + $db->begin(); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_stripe WHERE fk_key = '".$event->data->object->id."' "; + dol_syslog(get_class($this) . "::delete sql=" . $sql, LOG_DEBUG); + $db->query($sql); + $db->commit(); +} + + + +?> From d6b4bc14e4f7e42c784ffb903980d8732dc0cf71 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 9 Mar 2018 16:52:06 +0100 Subject: [PATCH 105/413] NEW: syslog file autoclean --- htdocs/admin/syslog.php | 17 ++++ htdocs/core/class/utils.class.php | 112 +++++++++++++++++++++++- htdocs/core/modules/modSyslog.class.php | 5 ++ htdocs/langs/en_US/admin.lang | 3 + 4 files changed, 135 insertions(+), 2 deletions(-) diff --git a/htdocs/admin/syslog.php b/htdocs/admin/syslog.php index d850e7eeb11..e434f669f45 100644 --- a/htdocs/admin/syslog.php +++ b/htdocs/admin/syslog.php @@ -146,6 +146,16 @@ if ($action == 'setlevel') dol_syslog("admin/syslog: level ".$level); if (! $res > 0) $error++; + + if (! $error) + { + $file_saves = GETPOST("file_saves"); + $res = dolibarr_set_const($db,"SYSLOG_FILE_SAVES",$file_saves,'chaine',0,'',0); + dol_syslog("admin/syslog: file saves ".$file_saves); + + if (! $res > 0) $error++; + } + if (! $error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); @@ -284,6 +294,13 @@ print ''; print ''; print ''; + +if(! empty($conf->loghandlers['mod_syslog_file']) && ! empty($conf->cron->enabled)) { + print ''.$langs->trans("SyslogFileNumberOfSaves").''; + print ''; + print ' ('.$langs->trans('ConfigureCleaningCronjobToSetFrequencyOfSaves').')'; +} + print ''; print "\n"; diff --git a/htdocs/core/class/utils.class.php b/htdocs/core/class/utils.class.php index 37ccea748f1..e60070f1179 100644 --- a/htdocs/core/class/utils.class.php +++ b/htdocs/core/class/utils.class.php @@ -93,7 +93,7 @@ class Utils // Define files log if ($dolibarr_main_data_root) { - $filesarray=dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1); + $filesarray=dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*(\.gz)?$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1); } $filelog=''; @@ -668,4 +668,112 @@ class Utils return -1; } -} + + /** + * This saves syslog files and compresses older ones + * Used from cronjob + * + * @return int 0 if OK, < 0 if KO + */ + function compressSyslogs() { + global $conf; + + if(empty($conf->loghandlers['mod_syslog_file'])) { // File Syslog disabled + return 0; + } + + if(! function_exists('gzopen')) { + return -1; + } + + dol_include_once('/core/lib/files.lib.php'); + + $nbSaves = ! empty($conf->global->SYSLOG_FILE_SAVES) ? intval($conf->global->SYSLOG_FILE_SAVES) : 14; + + if(empty($conf->global->SYSLOG_FILE)) { + $mainlogdir = DOL_DATA_ROOT; + $mainlog = 'dolibarr.log'; + } else { + $mainlogfull = str_replace('DOL_DATA_ROOT', DOL_DATA_ROOT, $conf->global->SYSLOG_FILE); + $mainlogdir = dirname($mainlogfull); + $mainlog = basename($mainlogfull); + } + + $tabfiles = dol_dir_list(DOL_DATA_ROOT, 'files', 0, '^(dolibarr_.+|odt2pdf)\.log$'); // Also handle other log files like dolibarr_install.log + $tabfiles[] = array('name' => $mainlog, 'path' => $mainlogdir); + + foreach($tabfiles as $file) { + + $logname = $file['name']; + $logpath = $file['path']; + + // Handle already compressed files + + $filter = '^'.preg_quote($logname, '/').'\.([0-9]+)\.gz$'; + + $gzfilestmp = dol_dir_list($logpath, 'files', 0, $filter); + $gzfiles = array(); + + foreach($gzfilestmp as $gzfile) { + $tabmatches = array(); + preg_match('/'.$filter.'/i', $gzfile['name'], $tabmatches); + + $numsave = intval($tabmatches[1]); + + $gzfiles[$numsave] = $gzfile; + } + + krsort($gzfiles, SORT_NUMERIC); + + foreach($gzfiles as $numsave => $dummy) { + if(dol_is_file($logpath.'/'.$logname.'.'.($numsave+1).'.gz')) { + return -2; + } + + if($numsave >= $nbSaves) { + dol_delete_file($logpath.'/'.$logname.'.'.$numsave.'.gz'); + } else { + dol_move($logpath.'/'.$logname.'.'.$numsave.'.gz', $logpath.'/'.$logname.'.'.($numsave+1).'.gz', 0, 1, 0, 0); + } + } + + // Compress last save + + if(dol_is_file($logpath.'/'.$logname.'.1')) { + if($nbSaves > 1) { + $gzfilehandle = gzopen($logpath.'/'.$logname.'.2.gz', 'wb9'); + + if(empty($gzfilehandle)) { + return -3; + } + + $sourcehandle = fopen($logpath.'/'.$logname.'.1', 'r'); + + if(empty($sourcehandle)) { + return -4; + } + + while(! feof($sourcehandle)) { + gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024)); // Read 512 kB at a time + } + + fclose($sourcehandle); + gzclose($gzfilehandle); + } else { + dol_delete_file($logpath.'/'.$logname.'.1'); + } + } + + // Compress current file et recreate it + + if(dol_is_file($logpath.'/'.$logname)) { + if(dol_move($logpath.'/'.$logname, $logpath.'/'.$logname.'.1', 0, 1, 0, 0)) { + $newlog = fopen($logpath.'/'.$logname, 'a+'); + fclose($newlog); + } + } + } + + return 0; + } +} \ No newline at end of file diff --git a/htdocs/core/modules/modSyslog.class.php b/htdocs/core/modules/modSyslog.class.php index 97c7b71ae21..8c84214ca47 100644 --- a/htdocs/core/modules/modSyslog.class.php +++ b/htdocs/core/modules/modSyslog.class.php @@ -79,5 +79,10 @@ class modSyslog extends DolibarrModules // Permissions $this->rights = array(); $this->rights_class = 'syslog'; + + // Cronjobs + $this->cronjobs = array( + 0=>array('label'=>'CompressSyslogs', 'jobtype'=>'method', 'class'=>'core/class/utils.class.php', 'objectname'=>'Utils', 'method'=>'compressSyslogs', 'parameters'=>'', 'comment'=>'PurgeDeleteTemporaryFiles', 'frequency'=>1, 'unitfrequency'=> 3600 * 24, 'priority'=>50, 'status'=>1, 'test'=>true), + ); } } diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index d6514db4d2c..6648e43501e 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -1444,6 +1444,9 @@ SyslogFilename=File name and path YouCanUseDOL_DATA_ROOT=You can use DOL_DATA_ROOT/dolibarr.log for a log file in Dolibarr "documents" directory. You can set a different path to store this file. ErrorUnknownSyslogConstant=Constant %s is not a known Syslog constant OnlyWindowsLOG_USER=Windows only supports LOG_USER +CompressSyslogs=Syslog files compression and backup +SyslogFileNumberOfSaves=Log backups +ConfigureCleaningCronjobToSetFrequencyOfSaves=Configure cleaning scheduled job to set log backup frequency ##### Donations ##### DonationsSetup=Donation module setup DonationsReceiptModel=Template of donation receipt From 164ca682d52282e0f77297c6c1ab7474aeb3a18e Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 17:23:43 +0100 Subject: [PATCH 106/413] fix add "late" invoice into "save last search/backtolist" feature --- htdocs/compta/facture/list.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 880a18d501a..0ed7f28ad54 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -96,7 +96,7 @@ $day_lim = GETPOST('day_lim','int'); $month_lim = GETPOST('month_lim','int'); $year_lim = GETPOST('year_lim','int'); -$option = GETPOST('option'); +$option = GETPOST('search_option'); if ($option == 'late') { $search_status = '1'; } @@ -560,7 +560,7 @@ if ($resql) if ($search_status != '') $param.='&search_status='.urlencode($search_status); if ($search_paymentmode > 0) $param.='search_paymentmode='.urlencode($search_paymentmode); if ($show_files) $param.='&show_files=' .$show_files; - if ($option) $param.="&option=".$option; + if ($option) $param.="&search_option=".$option; if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -714,7 +714,7 @@ if ($resql) if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; print ''; $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5, 0, 0, '', 'width75'); - print '
    '.$langs->trans("Late"); + print '
    '.$langs->trans("Late"); print ''; } // Project From d763bfcbf159d406ca2613537ee419660d921ecd Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Fri, 9 Mar 2018 17:56:49 +0100 Subject: [PATCH 107/413] Fix set time limit to 0 If the dolibarr was installed on a pc and not on server or in the doliwamp. --- htdocs/admin/system/filecheck.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/admin/system/filecheck.php b/htdocs/admin/system/filecheck.php index 38cf0b3f0df..7a0a4745996 100644 --- a/htdocs/admin/system/filecheck.php +++ b/htdocs/admin/system/filecheck.php @@ -3,6 +3,7 @@ * Copyright (C) 2007 Rodolphe Quiedeville * Copyright (C) 2007-2012 Regis Houssin * Copyright (C) 2015 Frederic France + * Copyright (C) 2017 Nicolas ZABOURI * * 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 @@ -22,7 +23,7 @@ * \file htdocs/admin/system/filecheck.php * \brief Page to check Dolibarr files integrity */ - +set_time_limit(0); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; From 5a56e802d9bcdc39409394539a98153b16d18033 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 19:10:52 +0100 Subject: [PATCH 108/413] FIX #8232 --- htdocs/core/class/commonobject.class.php | 4 +++- htdocs/core/tpl/extrafields_view.tpl.php | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 54eeffdc4b6..a632a29b0f3 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -5835,9 +5835,11 @@ abstract class CommonObject jQuery(document).ready(function() { function showOptions(child_list, parent_list) { - var val = $("select[name=\"options_"+parent_list+"\"]").val(); + var val = $("select[name="+parent_list+"]").val(); + var parentVal = parent_list + ":" + val; if(val > 0) { + $("select[name=\""+child_list+"\"] option[parent]").hide(); $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show(); } else { diff --git a/htdocs/core/tpl/extrafields_view.tpl.php b/htdocs/core/tpl/extrafields_view.tpl.php index 3559df44c9c..e7abadac599 100644 --- a/htdocs/core/tpl/extrafields_view.tpl.php +++ b/htdocs/core/tpl/extrafields_view.tpl.php @@ -151,7 +151,7 @@ if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element][ jQuery(document).ready(function() { function showOptions(child_list, parent_list) { - var val = $("select[name=\"options_"+parent_list+"\"]").val(); + var val = $("select[name="+parent_list+"]").val(); var parentVal = parent_list + ":" + val; if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); From 02beed265eac5f9e6acd27c7fccafe6e96301973 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 19:14:43 +0100 Subject: [PATCH 109/413] better space --- htdocs/core/class/commonobject.class.php | 3 +-- htdocs/core/tpl/extrafields_view.tpl.php | 1 + 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index a632a29b0f3..d9e08070f8b 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -5836,10 +5836,9 @@ abstract class CommonObject function showOptions(child_list, parent_list) { var val = $("select[name="+parent_list+"]").val(); - var parentVal = parent_list + ":" + val; - if(val > 0) { + if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show(); } else { diff --git a/htdocs/core/tpl/extrafields_view.tpl.php b/htdocs/core/tpl/extrafields_view.tpl.php index e7abadac599..dffd0e739f6 100644 --- a/htdocs/core/tpl/extrafields_view.tpl.php +++ b/htdocs/core/tpl/extrafields_view.tpl.php @@ -153,6 +153,7 @@ if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element][ { var val = $("select[name="+parent_list+"]").val(); var parentVal = parent_list + ":" + val; + if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show(); From 42fed5981d2f5617188d55ce0c6be73263255856 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 19:16:06 +0100 Subject: [PATCH 110/413] bettre syntax --- htdocs/core/class/commonobject.class.php | 1 - htdocs/core/tpl/extrafields_view.tpl.php | 1 - 2 files changed, 2 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index d9e08070f8b..d55e564d774 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -5837,7 +5837,6 @@ abstract class CommonObject { var val = $("select[name="+parent_list+"]").val(); var parentVal = parent_list + ":" + val; - if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show(); diff --git a/htdocs/core/tpl/extrafields_view.tpl.php b/htdocs/core/tpl/extrafields_view.tpl.php index dffd0e739f6..e7abadac599 100644 --- a/htdocs/core/tpl/extrafields_view.tpl.php +++ b/htdocs/core/tpl/extrafields_view.tpl.php @@ -153,7 +153,6 @@ if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element][ { var val = $("select[name="+parent_list+"]").val(); var parentVal = parent_list + ":" + val; - if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show(); From bb8525614c1dcdbccce8f036bfb874a7231480c9 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 19:37:39 +0100 Subject: [PATCH 111/413] better fix --- htdocs/admin/expensereport.php | 2 +- htdocs/admin/expensereport_extrafields.php | 2 +- htdocs/admin/expensereport_ik.php | 32 ++++++------ htdocs/admin/expensereport_rules.php | 60 +++++++++++----------- 4 files changed, 48 insertions(+), 48 deletions(-) diff --git a/htdocs/admin/expensereport.php b/htdocs/admin/expensereport.php index 3806a17c99f..28ced963f87 100644 --- a/htdocs/admin/expensereport.php +++ b/htdocs/admin/expensereport.php @@ -195,7 +195,7 @@ else if ($action == 'setoptions') $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); -llxHeader(); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $form=new Form($db); diff --git a/htdocs/admin/expensereport_extrafields.php b/htdocs/admin/expensereport_extrafields.php index db06f06d84a..a83c9b04194 100644 --- a/htdocs/admin/expensereport_extrafields.php +++ b/htdocs/admin/expensereport_extrafields.php @@ -67,7 +67,7 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; $textobject=$langs->transnoentitiesnoconv("expensereports"); -llxHeader('',$langs->trans("expensereportsSetup")); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $linkback=''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("ExpenseReportsSetup"),$linkback,'title_setup'); diff --git a/htdocs/admin/expensereport_ik.php b/htdocs/admin/expensereport_ik.php index a3bb7c4fc91..adf18433caa 100644 --- a/htdocs/admin/expensereport_ik.php +++ b/htdocs/admin/expensereport_ik.php @@ -58,12 +58,12 @@ if ($action == 'updateik') $result = $expIk->fetch($id); if ($result < 0) dol_print_error('', $expIk->error, $expIk->errors); } - + $expIk->setValues($_POST); $result = $expIk->create($user); - + if ($result > 0) setEventMessages('SetupSaved', null, 'mesgs'); - + header('Location: '.$_SERVER['PHP_SELF']); exit; } @@ -74,11 +74,11 @@ elseif ($action == 'delete') // TODO add confirm { $result = $expIk->fetch($id); if ($result < 0) dol_print_error('', $expIk->error, $expIk->errors); - + $expIk->delete($user); } - - + + header('Location: '.$_SERVER['PHP_SELF']); exit; } @@ -89,7 +89,7 @@ $rangesbycateg = ExpenseReportIk::getAllRanges(); * View */ -llxHeader(); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $form=new Form($db); @@ -125,23 +125,23 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) echo ''.$langs->trans('expenseReportTotalForFive').''; echo ' '; echo ''; - + if ($Tab['active'] == 0) continue; - + $tranche=1; $var = true; foreach ($Tab['ranges'] as $k => $range) { if (isset($Tab['ranges'][$k+1])) $label = $langs->trans('expenseReportRangeFromTo', $range->range_ik, ($Tab['ranges'][$k+1]->range_ik-1)); else $label = $langs->trans('expenseReportRangeMoreThan', $range->range_ik); - + if ($range->range_active == 0) $label = $form->textwithpicto($label, $langs->trans('expenseReportRangeDisabled'), 1, 'help', '', 0, 3); - + echo ''; - + // Label echo '['.$langs->trans('RangeNum', $tranche++).'] - '.$label.''; - + // Offset echo ''; if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; @@ -152,10 +152,10 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; else echo ($range->ik->id > 0 ? $range->ik->coef : $langs->trans('expenseReportCoefUndefined')); echo ''; - + // Total for one echo ''.$langs->trans('expenseReportPrintExample', price($range->ik->offset + 5 * $range->ik->coef)).''; - + // Action echo ''; if ($range->range_active == 1) @@ -173,7 +173,7 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) } } echo ''; - + echo ''; $var=!$var; } diff --git a/htdocs/admin/expensereport_rules.php b/htdocs/admin/expensereport_rules.php index 26312f708d9..bf615676f81 100644 --- a/htdocs/admin/expensereport_rules.php +++ b/htdocs/admin/expensereport_rules.php @@ -57,17 +57,17 @@ $amount = GETPOST('amount'); $restrictive = GETPOST('restrictive'); $object = new ExpenseReportRule($db); -if (!empty($id)) +if (!empty($id)) { $result = $object->fetch($id); if ($result < 0) dol_print_error('', $object->error, $object->errors); } - + // TODO do action if ($action == 'save') { $error = 0; - + // check parameters if (empty($apply_to)) { $error++; @@ -93,11 +93,11 @@ if ($action == 'save') $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpenseReportLimitAmount")), null, 'errors'); } - + if (empty($error)) { $object->setValues($_POST); - + if($apply_to=='U'){ $object->fk_user=$fk_user; $object->fk_usergroup=0; @@ -114,13 +114,13 @@ if ($action == 'save') $object->dates = $dates; $object->datee = $datee; - + $object->entity = $conf->entity; $res = $object->create($user); if ($res > 0) setEventMessages($langs->trans('ExpenseReportRuleSave'), null); else dol_print_error($object->db); - + header('Location: '.$_SERVER['PHP_SELF']); exit; } @@ -129,7 +129,7 @@ elseif ($action == 'delete') { // TODO add confirm $res = $object->delete($user); - + if ($res < 0) dol_print_error($object->db); header('Location: '.$_SERVER['PHP_SELF']); @@ -145,7 +145,7 @@ $tab_rules_type = array('EX_DAY' => $langs->trans('Day'), 'EX_MON' => $langs->tr * View */ -llxHeader(); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $form=new Form($db); @@ -194,7 +194,7 @@ if ($action != 'edit') echo ''; echo ''; - echo ''; + echo ''; } @@ -224,7 +224,7 @@ $var=true; foreach ($rules as $rule) { echo ''; - + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -240,8 +240,8 @@ foreach ($rules as $rule) elseif ($rule->fk_user > 0) echo $tab_apply['U'].' ('.$rule->getUserName().')'; } echo ''; - - + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -250,7 +250,7 @@ foreach ($rules as $rule) else { if ($rule->fk_c_type_fees == -1) echo $langs->trans('AllExpenseReport'); - else + else { $key = getDictvalue(MAIN_DB_PREFIX.'c_type_fees', 'code', $rule->fk_c_type_fees, false, 'id'); if ($key != $langs->trans($key)) echo $langs->trans($key); @@ -258,9 +258,9 @@ foreach ($rules as $rule) } } echo ''; - - - + + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -271,8 +271,8 @@ foreach ($rules as $rule) echo $tab_rules_type[$rule->code_expense_rules_type]; } echo ''; - - + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -283,8 +283,8 @@ foreach ($rules as $rule) echo dol_print_date($rule->dates, 'day'); } echo ''; - - + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -295,8 +295,8 @@ foreach ($rules as $rule) echo dol_print_date($rule->datee, 'day'); } echo ''; - - + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -307,8 +307,8 @@ foreach ($rules as $rule) echo price($rule->amount, 0, $langs, 1, -1, -1, $conf->currency); } echo ''; - - + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -319,8 +319,8 @@ foreach ($rules as $rule) echo yn($rule->restrictive, 1, 1); } echo ''; - - + + echo ''; if ($object->id != $rule->id) { @@ -333,7 +333,7 @@ foreach ($rules as $rule) echo ''.$langs->trans('Cancel').''; } echo ''; - + echo ''; $var=!$var; } @@ -355,9 +355,9 @@ echo ''; dol_fiche_end(); From 9eeb80151eefc59acc76f0eb0ce84d38df01104c Mon Sep 17 00:00:00 2001 From: TuxGasy Date: Fri, 9 Mar 2018 21:13:54 +0100 Subject: [PATCH 112/413] Fix bug when updating multi currency rate on invoice supplier --- htdocs/core/class/commonobject.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index ab7afea77a4..4d44a4b6fec 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -1560,7 +1560,7 @@ abstract class CommonObject $this->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); break; case 'invoice_supplier': - $this->updateline($line->id, $line->desc, $line->subprice, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); + $this->updateline($line->id, $line->desc, $line->subprice, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->qty, $line->fk_product, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); break; default: dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG); From d82c62b638191f5ec960af456c8a841e306f8210 Mon Sep 17 00:00:00 2001 From: Maxime Kohlhaas Date: Fri, 9 Mar 2018 21:51:59 +0100 Subject: [PATCH 113/413] Fix supplier order clone was keeping objectlinked --- htdocs/fourn/class/fournisseur.commande.class.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index a42546fdb84..a58f33502aa 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -321,8 +321,6 @@ class CommandeFournisseur extends CommonOrder if ($this->statut == 0) $this->brouillon = 1; - $this->fetchObjectLinked(); - //$result=$this->fetch_lines(); $this->lines=array(); From d858426b7b5735775181359cc82d38b6f365d065 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 9 Mar 2018 22:33:39 +0100 Subject: [PATCH 114/413] Update modSyslog.class.php --- htdocs/core/modules/modSyslog.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/modules/modSyslog.class.php b/htdocs/core/modules/modSyslog.class.php index 8c84214ca47..b3e83f90ca2 100644 --- a/htdocs/core/modules/modSyslog.class.php +++ b/htdocs/core/modules/modSyslog.class.php @@ -82,7 +82,7 @@ class modSyslog extends DolibarrModules // Cronjobs $this->cronjobs = array( - 0=>array('label'=>'CompressSyslogs', 'jobtype'=>'method', 'class'=>'core/class/utils.class.php', 'objectname'=>'Utils', 'method'=>'compressSyslogs', 'parameters'=>'', 'comment'=>'PurgeDeleteTemporaryFiles', 'frequency'=>1, 'unitfrequency'=> 3600 * 24, 'priority'=>50, 'status'=>1, 'test'=>true), + 0=>array('label'=>'CompressSyslogs', 'jobtype'=>'method', 'class'=>'core/class/utils.class.php', 'objectname'=>'Utils', 'method'=>'compressSyslogs', 'parameters'=>'', 'comment'=>'PurgeDeleteTemporaryFiles', 'frequency'=>1, 'unitfrequency'=> 3600 * 24, 'priority'=>50, 'status'=>0, 'test'=>true), ); } } From a34709c112a4fb2a9425eaf1699d9d7d03b0ce33 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 22:36:00 +0100 Subject: [PATCH 115/413] fix better thirdparty link --- htdocs/comm/index.php | 2 +- htdocs/comm/propal/card.php | 2 +- htdocs/comm/propal/contact.php | 2 +- htdocs/comm/propal/document.php | 2 +- htdocs/compta/facture/card.php | 2 +- htdocs/compta/facture/contact.php | 2 +- htdocs/compta/facture/document.php | 2 +- htdocs/compta/facture/info.php | 2 +- htdocs/compta/facture/note.php | 2 +- htdocs/compta/index.php | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/htdocs/comm/index.php b/htdocs/comm/index.php index 91004c86f67..5ec77389f63 100644 --- a/htdocs/comm/index.php +++ b/htdocs/comm/index.php @@ -266,7 +266,7 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; $companystatic->canvas=$obj->canvas; - print $companystatic->getNomUrl(1,'customer',16); + print $companystatic->getNomUrl(1,'supplier',16); print ''; print ''.price($obj->total_ht).''; $i++; diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 60db23814b3..51a1caa9502 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -1824,7 +1824,7 @@ if ($action == 'create') $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherProposals").')'; // Project if (! empty($conf->projet->enabled)) diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php index 01e851769a7..eff22ba4358 100644 --- a/htdocs/comm/propal/contact.php +++ b/htdocs/comm/propal/contact.php @@ -164,7 +164,7 @@ if ($object->id > 0) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/comm/propal/document.php b/htdocs/comm/propal/document.php index ba373c78f44..e292a61686e 100644 --- a/htdocs/comm/propal/document.php +++ b/htdocs/comm/propal/document.php @@ -114,7 +114,7 @@ if ($object->id > 0) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 37f38b732fe..4807ac3dddd 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -3270,7 +3270,7 @@ else if ($id > 0 || ! empty($ref)) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherBills").')'; // Project if (! empty($conf->projet->enabled)) diff --git a/htdocs/compta/facture/contact.php b/htdocs/compta/facture/contact.php index 2c95366f9a9..61f37d221f8 100644 --- a/htdocs/compta/facture/contact.php +++ b/htdocs/compta/facture/contact.php @@ -155,7 +155,7 @@ if ($id > 0 || ! empty($ref)) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/document.php b/htdocs/compta/facture/document.php index 8b76f9b167f..a9396e445c9 100644 --- a/htdocs/compta/facture/document.php +++ b/htdocs/compta/facture/document.php @@ -125,7 +125,7 @@ if ($id > 0 || ! empty($ref)) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/info.php b/htdocs/compta/facture/info.php index 00272fee9b3..2347178b05d 100644 --- a/htdocs/compta/facture/info.php +++ b/htdocs/compta/facture/info.php @@ -69,7 +69,7 @@ $morehtmlref='
    '; $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty -$morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); +$morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/note.php b/htdocs/compta/facture/note.php index 755ac413743..356ba3916a0 100644 --- a/htdocs/compta/facture/note.php +++ b/htdocs/compta/facture/note.php @@ -92,7 +92,7 @@ if ($id > 0 || ! empty($ref)) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index c36037940b9..12a4ecee052 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -199,7 +199,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) print $facturestatic->getNomUrl(1,''); print ''; print ''; - print $companystatic->getNomUrl(1,'',16); + print $companystatic->getNomUrl(1,'customer',16); print ''; print ''.price($obj->total_ttc).''; print ''; From 40d04482b030e4b697e23fcb51e37b00f7b2d47b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 9 Mar 2018 22:45:16 +0100 Subject: [PATCH 116/413] Fix set time --- htdocs/admin/system/filecheck.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/htdocs/admin/system/filecheck.php b/htdocs/admin/system/filecheck.php index 7a0a4745996..6fd623bf1bb 100644 --- a/htdocs/admin/system/filecheck.php +++ b/htdocs/admin/system/filecheck.php @@ -23,7 +23,7 @@ * \file htdocs/admin/system/filecheck.php * \brief Page to check Dolibarr files integrity */ -set_time_limit(0); + require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; @@ -40,6 +40,8 @@ $error=0; * View */ +@set_time_limit(300); + llxHeader(); print load_fiche_titre($langs->trans("FileCheckDolibarr"),'','title_setup'); From 42aa7a25f904c3ff63a1b9cf073d8e73a314d70c Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Fri, 9 Mar 2018 22:54:45 +0100 Subject: [PATCH 117/413] FIX include cache issue --- htdocs/modulebuilder/index.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/modulebuilder/index.php b/htdocs/modulebuilder/index.php index 3b2e36e21d8..1058f38ffd2 100644 --- a/htdocs/modulebuilder/index.php +++ b/htdocs/modulebuilder/index.php @@ -490,8 +490,7 @@ if ($dirins && $action == 'addproperty' && !empty($module) && ! empty($tabobj)) setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null); clearstatcache(true); - sleep(4); // With sleep 2, after the header("Location...", the new page output does not see the change. TODO Why do we need this sleep ? - + // Make a redirect to reload all data header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=objects&module='.$module.'&tabobj='.$objectname.'&nocache='.time()); @@ -526,8 +525,7 @@ if ($dirins && $action == 'confirm_deleteproperty' && $propertykey) setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null); clearstatcache(true); - sleep(4); // With sleep 2, after the header("Location...", the new page output does not see the change. TODO Why do we need this sleep ? - + // Make a redirect to reload all data header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=objects&module='.$module.'&tabobj='.$objectname); @@ -1550,6 +1548,8 @@ elseif (! empty($module)) print '


    '; + opcache_invalidate($dirread.'/'.$pathtoclass,true); // remove the include cache hell ! + if (empty($forceddirread)) { $result = dol_include_once($pathtoclass); From 9efea6e30ec4848eddd1a1d82d7996ed516a78fa Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 9 Mar 2018 22:59:44 +0100 Subject: [PATCH 118/413] Fix var not defined --- htdocs/adherents/class/adherent.class.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 20041333ee6..c55e1bb3fc1 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -33,7 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; +require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; /** @@ -1429,8 +1429,8 @@ class Adherent extends CommonObject $result=$customer->create_from_member($this, $companyname, $companyalias); if ($result < 0) { - $this->error = $company->error; - $this->errors = $company->errors; + $this->error = $customer->error; + $this->errors = $customer->errors; $error++; } else From 1d69d8e51ebe6b9e65c0e3f3c7c1325f181ba9b8 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Fri, 9 Mar 2018 23:03:23 +0100 Subject: [PATCH 119/413] add function_exist --- htdocs/modulebuilder/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/modulebuilder/index.php b/htdocs/modulebuilder/index.php index 1058f38ffd2..dbc69c943dd 100644 --- a/htdocs/modulebuilder/index.php +++ b/htdocs/modulebuilder/index.php @@ -1548,7 +1548,7 @@ elseif (! empty($module)) print '


    '; - opcache_invalidate($dirread.'/'.$pathtoclass,true); // remove the include cache hell ! + if(function_exists('opcache_invalidate')) opcache_invalidate($dirread.'/'.$pathtoclass,true); // remove the include cache hell ! if (empty($forceddirread)) { From c1d148458bb05c5633f34fbd9f46ede563d7a86c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 9 Mar 2018 23:44:00 +0100 Subject: [PATCH 120/413] Fix migration --- htdocs/install/mysql/migration/7.0.0-8.0.0.sql | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 227562ea9bc..7c82c54fb94 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -32,6 +32,10 @@ -- VMYSQL4.1 ALTER TABLE llx_product_association ADD COLUMN rowid integer AUTO_INCREMENT PRIMARY KEY; +ALTER TABLE llx_website_page ADD COLUMN fk_user_create integer; +ALTER TABLE llx_website_page ADD COLUMN fk_user_modif integer; +ALTER TABLE llx_website_page ADD COLUMN type_container varchar(16) NOT NULL DEFAULT 'page'; + -- For 8.0 From 5e468133237e2148550c3b205c0a4d09829a9ebc Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Fri, 9 Mar 2018 23:45:28 +0100 Subject: [PATCH 121/413] Add phone research --- htdocs/societe/list.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/htdocs/societe/list.php b/htdocs/societe/list.php index 9861f4b8d66..d046c325eca 100644 --- a/htdocs/societe/list.php +++ b/htdocs/societe/list.php @@ -9,6 +9,7 @@ * Copyright (C) 2016 Ferran Marcet * Copyright (C) 2017 Rui Strecht * Copyright (C) 2017 Juanjo Menent + * Copyright (C) 2018 Nicolas ZABOURI * * 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 @@ -137,6 +138,7 @@ $fieldstosearchall = array( 's.siren'=>"ProfId1", 's.siret'=>"ProfId2", 's.ape'=>"ProfId3", + 's.phone'=>"Phone", ); if (($tmp = $langs->transnoentities("ProfId4".$mysoc->country_code)) && $tmp != "ProfId4".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof4']='ProfId4'; if (($tmp = $langs->transnoentities("ProfId5".$mysoc->country_code)) && $tmp != "ProfId5".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof5']='ProfId5'; From 5d1e54c6fd2d90f95e66cd271853cc0ac7bdd8ae Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Fri, 9 Mar 2018 23:48:50 +0100 Subject: [PATCH 122/413] Add phone search --- htdocs/contact/list.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 6e62cef1eb0..e2ad6031937 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -7,6 +7,7 @@ * Copyright (C) 2013 Cédric Salvador * Copyright (C) 2013 Alexandre Spangaro * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2018 Nicolas ZABOURI * * 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 @@ -133,6 +134,7 @@ $fieldstosearchall = array( 'p.firstname'=>'Firstname', 'p.email'=>'EMail', 's.nom'=>"ThirdParty", + 'p.phone'=>"Phone", ); // Definition of fields for list From d92fa3a69c1ab614e99ee519fbb770002942688b Mon Sep 17 00:00:00 2001 From: Maxime Kohlhaas Date: Fri, 9 Mar 2018 23:49:40 +0100 Subject: [PATCH 123/413] Fix required field + space in dispatch --- htdocs/fourn/commande/card.php | 2 +- htdocs/fourn/commande/dispatch.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index f083d71740e..ad27a496672 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -2453,7 +2453,7 @@ elseif (! empty($object->id)) print $form->select_date('','',1,1,'',"commande",1,1,1); print "\n"; - print "".$langs->trans("Delivery")."\n"; + print "".$langs->trans("Delivery")."\n"; $liv = array(); $liv[''] = ' '; $liv['tot'] = $langs->trans("CompleteOrNoMoreReceptionExpected"); diff --git a/htdocs/fourn/commande/dispatch.php b/htdocs/fourn/commande/dispatch.php index 049f158a0be..04c039cfbb1 100644 --- a/htdocs/fourn/commande/dispatch.php +++ b/htdocs/fourn/commande/dispatch.php @@ -457,7 +457,7 @@ if ($id > 0 || ! empty($ref)) { print ''; print ''; - print '
    '; + print '
    '; print ''; // Set $products_dispatched with qty dispatched for each product id From aaf68b904e3261bceaa4b6c8f0250b82c881139d Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Sat, 10 Mar 2018 00:00:23 +0100 Subject: [PATCH 124/413] Add mass action proposal closed --- htdocs/core/actions_massactions.inc.php | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 5a713168c48..9a9298528eb 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -1,5 +1,6 @@ + * Copyright (C) 2018 Nicolas ZABOURI * * 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 @@ -973,7 +974,41 @@ if (! $error && $massaction == 'validate' && $permtocreate) //var_dump($listofobjectthirdparties);exit; } } +// Closed records +if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permtoclose) { + $db->begin(); + $objecttmp = new $objectclass($db); + $nbok = 0; + foreach ($toselect as $toselectid) { + $result = $objecttmp->fetch($toselectid); + if ($result > 0) { + $result = $objecttmp->cloture($user, 3); + if ($result <= 0) { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } else + $nbok++; + } + else { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + } + + if (!$error) { + if ($nbok > 1) + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + else + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + $db->commit(); + } + else { + $db->rollback(); + } +} // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before) if (! $error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permtodelete) { From 9075ed4107c12a3aa59aac9cc70fe3c239fe5408 Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Sat, 10 Mar 2018 00:04:58 +0100 Subject: [PATCH 125/413] Add mass action proposal closed --- htdocs/comm/propal/list.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index cdcd5bf014b..de7715bdcf4 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -12,6 +12,7 @@ * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2016 Ferran Marcet * Copyright (C) 2017 Charlene Benke + * Copyright (C) 2018 Nicolas ZABOURI * * 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 @@ -214,6 +215,7 @@ if (empty($reshook)) $objectlabel='Proposals'; $permtoread = $user->rights->propal->lire; $permtodelete = $user->rights->propal->supprimer; + $permtoclose = $user->rights->propal->cloturer; $uploaddir = $conf->propal->multidir_output[$conf->entity]; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -389,7 +391,8 @@ if ($resql) 'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->propal->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); + if ($user->rights->propal->cloturer) $arrayofmassactions['closed']=$langs->trans("Closed"); + if (in_array($massaction, array('presend','predelete','closed'))) $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); // Lignes des champs de filtre From 8e84b733dc4a489901379410ad505efe63b68526 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sat, 10 Mar 2018 00:13:41 +0100 Subject: [PATCH 126/413] fix scrutinizer --- htdocs/adherents/class/adherent.class.php | 5 +++-- htdocs/compta/bank/class/account.class.php | 20 +++++++++++++++----- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index c55e1bb3fc1..3247fdf31e4 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -1602,8 +1602,9 @@ class Adherent extends CommonObject // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; + $lang_id=GETPOST('lang_id'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($lang_id)) + $newlang = $lang_id; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $customer->default_lang; if (! empty($newlang)) { diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 719a48c3e3c..b019dd7068c 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -509,6 +509,8 @@ class Account extends CommonObject { global $langs,$conf, $hookmanager; + $error=0; + // Clean parameters if (! $this->min_allowed) $this->min_allowed=0; if (! $this->min_desired) $this->min_desired=0; @@ -668,7 +670,7 @@ class Account extends CommonObject * @param int $notrigger 1=Disable triggers * @return int <0 if KO, >0 if OK */ - function update(User $user = null, $notrigger = 0) + function update(User $user, $notrigger = 0) { global $langs,$conf, $hookmanager; @@ -1135,6 +1137,8 @@ class Account extends CommonObject */ function solde($option=0) { + $solde=0; + $sql = "SELECT sum(amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."bank"; $sql.= " WHERE fk_account = ".$this->id; @@ -1149,8 +1153,13 @@ class Account extends CommonObject $solde = $obj->amount; } $this->db->free($resql); - return $solde; + } else { + $this->errors[]=$this->db->lasterror; + return -1; } + + return $solde; + } /** @@ -1593,7 +1602,7 @@ class Account extends CommonObject $this->code_banque = '123'; $this->code_guichet = '456'; $this->number = 'ABC12345'; - $this->cle_rib = 50; + $this->cle_rib = '50'; $this->bic = 'AA12'; $this->iban = 'FR999999999'; $this->domiciliation = 'My bank address'; @@ -1904,7 +1913,7 @@ class AccountLine extends CommonObject */ function update_conciliation(User $user, $cat) { - global $conf; + global $conf,$langs; $this->db->begin(); @@ -2132,9 +2141,10 @@ class AccountLine extends CommonObject * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto * @param int $maxlen Longueur max libelle * @param string $option Option ('showall') + * @param int $notooltip 1=Disable tooltip * @return string Chaine avec URL */ - function getNomUrl($withpicto=0,$maxlen=0,$option='') + function getNomUrl($withpicto=0,$maxlen=0,$option='',$notooltip=0) { global $langs; From 63fb53159c06c057ffb6d35930bc4e5614c07fa2 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sat, 10 Mar 2018 01:12:47 +0100 Subject: [PATCH 127/413] fix scrunitizer --- htdocs/compta/facture/class/facture.class.php | 53 ++++++++----------- htdocs/core/class/commoninvoice.class.php | 2 +- 2 files changed, 22 insertions(+), 33 deletions(-) diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index e4438d4771a..382002fddc7 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -86,11 +86,11 @@ class Facture extends CommonInvoice //var $amount; public $remise_absolue; public $remise_percent; - public $total_ht=0; - public $total_tva=0; - public $total_localtax1=0; - public $total_localtax2=0; - public $total_ttc=0; + public $total_ht=0.0; + public $total_tva=0.0; + public $total_localtax1=0.0; + public $total_localtax2=0.0; + public $total_ttc=0.0; public $revenuestamp; //! Fermeture apres paiement partiel: discount_vat, badcustomer, abandon @@ -140,7 +140,7 @@ class Facture extends CommonInvoice public $situation_counter; /** - * @var bool Final situation flag + * @var int Final situation flag */ public $situation_final; @@ -303,13 +303,13 @@ class Facture extends CommonInvoice $this->entity = $_facrec->entity; // Invoice created in same entity than template // Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI - $this->fk_project = GETPOST('projectid','int') > 0 ? GETPOST('projectid','int') : $_facrec->fk_project; + $this->fk_project = (int)GETPOST('projectid','int') > 0 ? (int)GETPOST('projectid','int') : $_facrec->fk_project; $this->note_public = GETPOST('note_public','none') ? GETPOST('note_public','none') : $_facrec->note_public; $this->note_private = GETPOST('note_private','none') ? GETPOST('note_private','none') : $_facrec->note_private; $this->modelpdf = GETPOST('model') ? GETPOST('model') : $_facrec->modelpdf; - $this->cond_reglement_id = GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $_facrec->cond_reglement_id; - $this->mode_reglement_id = GETPOST('mode_reglement_id') > 0 ? GETPOST('mode_reglement_id') : $_facrec->mode_reglement_id; - $this->fk_account = GETPOST('fk_account') > 0 ? GETPOST('fk_account') : $_facrec->fk_account; + $this->cond_reglement_id = (int)GETPOST('cond_reglement_id') > 0 ? (int)GETPOST('cond_reglement_id') : $_facrec->cond_reglement_id; + $this->mode_reglement_id = (int)GETPOST('mode_reglement_id') > 0 ? (int)GETPOST('mode_reglement_id') : $_facrec->mode_reglement_id; + $this->fk_account = (int)GETPOST('fk_account') > 0 ? (int)GETPOST('fk_account') : $_facrec->fk_account; // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result $this->total_ht = $_facrec->total_ht; @@ -860,7 +860,7 @@ class Facture extends CommonInvoice } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) { - $this->fetchObjectLinked('', '', $object->id, 'facture'); + $this->fetchObjectLinked('', '', $facture->id, 'facture'); foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) { @@ -1519,7 +1519,7 @@ class Facture extends CommonInvoice * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=null, $notrigger=0) + function update(User $user, $notrigger=0) { $error=0; @@ -1535,17 +1535,6 @@ class Facture extends CommonInvoice if (isset($this->note_public)) $this->note_public=trim($this->note_public); if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf); if (isset($this->import_key)) $this->import_key=trim($this->import_key); - if (empty($this->situation_cycle_ref)) { - $this->situation_cycle_ref = 'null'; - } - - if (empty($this->situation_counter)) { - $this->situation_counter = 'null'; - } - - if (empty($this->situation_final)) { - $this->situation_final = '0'; - } // Check parameters // Put here code to add control on parameters values @@ -1585,9 +1574,9 @@ class Facture extends CommonInvoice $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").","; $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").","; $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null"); - $sql.= ", situation_cycle_ref=".$this->situation_cycle_ref; - $sql.= ", situation_counter=".$this->situation_counter; - $sql.= ", situation_final=".$this->situation_final; + $sql.= ", situation_cycle_ref=".(empty($this->situation_cycle_ref)?"null":$this->situation_cycle_ref); + $sql.= ", situation_counter=".(empty($this->situation_counter)?"null":$this->situation_counter); + $sql.= ", situation_final=".(empty($this->situation_counter)?"0":$this->situation_counter); $sql.= " WHERE rowid=".$this->id; @@ -1810,9 +1799,9 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".$this->thirdparty->name, LOG_DEBUG); // Test to avoid invoice deletion (allowed if draft) - $test = $this->is_erasable(); + $result = $this->is_erasable(); - if ($test <= 0) return 0; + if ($result <= 0) return 0; $error=0; @@ -2556,7 +2545,7 @@ class Facture extends CommonInvoice * @param double $pu_ht_devise Unit price in currency * @return int <0 if KO, Id of line if OK */ - function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id='', $fk_unit = null, $pu_ht_devise = 0) + function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id=0, $fk_unit = null, $pu_ht_devise = 0) { // Deprecation warning if ($label) { @@ -3061,7 +3050,7 @@ class Facture extends CommonInvoice // For triggers $result = $line->fetch($rowid); - if (! ($result > 0)) dol_print_error($db, $line->error, $line->errors); + if (! ($result > 0)) dol_print_error($this->db, $line->error, $line->errors); if ($line->delete($user) > 0) { @@ -4379,7 +4368,7 @@ class FactureLigne extends CommonInvoiceLine if (empty($this->subprice)) $this->subprice=0; if (empty($this->special_code)) $this->special_code=0; if (empty($this->fk_parent_line)) $this->fk_parent_line=0; - if (empty($this->fk_prev_id)) $this->fk_prev_id = 'null'; + if (empty($this->fk_prev_id)) $this->fk_prev_id = 0; if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100; if (empty($this->pa_ht)) $this->pa_ht=0; @@ -4462,7 +4451,7 @@ class FactureLigne extends CommonInvoiceLine $sql.= " ".price2num($this->total_localtax1).","; $sql.= " ".price2num($this->total_localtax2); $sql.= ", " . $this->situation_percent; - $sql.= ", " . $this->fk_prev_id; + $sql.= ", " . (!empty($this->fk_prev_id)?$this->fk_prev_id:"null"); $sql.= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit); $sql.= ", ".$user->id; $sql.= ", ".$user->id; diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 7d1f8feda8d..9ce569edb35 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -676,7 +676,7 @@ abstract class CommonInvoiceLine extends CommonObjectLine { /** * Quantity - * @var int + * @var double */ public $qty; From 40fb803ffd3c43c4971a63f0252454f1e362ea88 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sat, 10 Mar 2018 09:34:33 +0100 Subject: [PATCH 128/413] scrunitizer --- htdocs/compta/facture/class/paymentterm.class.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index 9c1f0020d36..3697a61672b 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -57,7 +57,6 @@ class PaymentTerm // extends CommonObject function __construct($db) { $this->db = $db; - return 1; } @@ -332,11 +331,11 @@ class PaymentTerm // extends CommonObject } - /** + /** * Delete object in database * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ function delete($user, $notrigger=0) From 594497d085f51adf0963d05faec3c1f5aad7a906 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sat, 10 Mar 2018 10:34:11 +0100 Subject: [PATCH 129/413] fix scrunitizer --- htdocs/contrat/class/contrat.class.php | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index f1b0c5cdfb9..a9dec780ba8 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -899,17 +899,20 @@ class Contrat extends CommonObject if ($result > 0) { $modCodeContract = new $module(); - } - if (!empty($modCodeContract->code_auto)) { - // Mise a jour ref - $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id; - if ($this->db->query($sql)) - { - if ($this->id) + if (!empty($modCodeContract->code_auto)) { + // Mise a jour ref + $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id; + if ($this->db->query($sql)) { - $this->ref="(PROV".$this->id.")"; + if ($this->id) + { + $this->ref="(PROV".$this->id.")"; + } } + } else { + $error++; + $this->error='Failed to get PROV number'; } } @@ -1336,6 +1339,7 @@ class Contrat extends CommonObject function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null, $rang=0) { global $user, $langs, $conf, $mysoc; + $error=0; dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang"); @@ -1544,6 +1548,8 @@ class Contrat extends CommonObject { global $user, $conf, $langs, $mysoc; + $error=0; + // Clean parameters $qty=trim($qty); $desc=trim($desc); From 26686a05c29d1b3d3a3876bded3d014abbe4cbeb Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sat, 10 Mar 2018 10:38:56 +0100 Subject: [PATCH 130/413] fix scrunituzer --- htdocs/core/class/commondocgenerator.class.php | 1 - 1 file changed, 1 deletion(-) diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index a4ea3a70447..4d45f5aabbb 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -44,7 +44,6 @@ abstract class CommonDocGenerator */ public function __construct($db) { $this->db = $db; - return 1; } From 5d692482a3ea7dd2638453b8ea771e9063afe717 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Sat, 10 Mar 2018 11:18:05 +0100 Subject: [PATCH 131/413] fix good write to add --- htdocs/modulebuilder/template/myobject_card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/modulebuilder/template/myobject_card.php b/htdocs/modulebuilder/template/myobject_card.php index a82ec237006..4e43063cc94 100644 --- a/htdocs/modulebuilder/template/myobject_card.php +++ b/htdocs/modulebuilder/template/myobject_card.php @@ -113,7 +113,7 @@ if (empty($reshook)) { $error=0; - $permissiontoadd = $user->rights->mymodule->create; + $permissiontoadd = $user->rights->mymodule->write; $permissiontodelete = $user->rights->mymodule->delete; $backurlforlist = dol_buildpath('/mymodule/myobject_list.php',1); From fd36ade61a1a6e9a68079638a260e00b2cfff204 Mon Sep 17 00:00:00 2001 From: Maxime Kohlhaas Date: Sat, 10 Mar 2018 11:20:32 +0100 Subject: [PATCH 132/413] Fix unit in replenish #7225 --- htdocs/product/stock/replenish.php | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/htdocs/product/stock/replenish.php b/htdocs/product/stock/replenish.php index 26c6ab1dfd1..23cb58ed7e3 100644 --- a/htdocs/product/stock/replenish.php +++ b/htdocs/product/stock/replenish.php @@ -154,6 +154,8 @@ if ($action == 'order' && isset($_POST['valid'])) $line->total_ttc = $line->total_ht + $line->total_tva; $line->remise_percent = $obj->remise_percent; $line->ref_fourn = $obj->ref_fourn; + $line->type = $product->type; + $line->fk_unit = $product->fk_unit; $suppliers[$obj->fk_soc]['lines'][] = $line; } } @@ -198,7 +200,13 @@ if ($action == 'order' && isset($_POST['valid'])) $line->remise_percent, 'HT', 0, - $line->info_bits + $line->type, + 0, + false, + null, + null, + 0, + $line->fk_unit ); } if ($result < 0) { From 975300b90bb8e40eb52895d29f0c244c20dafe07 Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Sat, 10 Mar 2018 11:23:35 +0100 Subject: [PATCH 133/413] Add execution date on prelevement --- .../class/bonprelevement.class.php | 14 ++++++--- htdocs/compta/prelevement/create.php | 31 ++++++++++--------- htdocs/langs/en_US/withdrawals.lang | 4 +++ 3 files changed, 31 insertions(+), 18 deletions(-) diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index e2517bdfada..f720d088b6d 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -4,6 +4,7 @@ * Copyright (C) 2010-2015 Juanjo Menent * Copyright (C) 2010-2014 Laurent Destailleur * Copyright (C) 2014-2016 Ferran Marcet + * Copyright (C) 2018 Nicolas ZABOURI * * 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 @@ -760,9 +761,10 @@ class BonPrelevement extends CommonObject * @param int $agence dolibarr mysoc bank office (guichet) * @param string $mode real=do action, simu=test only * @param string $format FRST, RCUR or ALL + * @param string $executiondate * @return int <0 if KO, nbre of invoice withdrawed if OK */ - function Create($banque=0, $agence=0, $mode='real', $format='ALL') + function Create($banque=0, $agence=0, $mode='real', $format='ALL',$executiondate='') { global $conf,$langs; @@ -776,6 +778,8 @@ class BonPrelevement extends CommonObject $error = 0; $datetimeprev = time(); + //Choice the date of the execution direct debit + if(!empty($executiondate)) $datetimeprev = $executiondate; $month = strftime("%m", $datetimeprev); $year = strftime("%Y", $datetimeprev); @@ -1077,7 +1081,7 @@ class BonPrelevement extends CommonObject $this->factures = $factures_prev_id; // Generation of SEPA file $this->filename - $this->generate($format); + $this->generate($format,$executiondate); } dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG); } @@ -1276,7 +1280,7 @@ class BonPrelevement extends CommonObject * @param string $format FRST, RCUR or ALL * @return int 0 if OK, <0 if KO */ - function generate($format='ALL') + function generate($format='ALL',$executiondate='') { global $conf,$langs,$mysoc; @@ -1306,9 +1310,11 @@ class BonPrelevement extends CommonObject // SEPA Initialisation $CrLf = "\n"; $date_actu = dol_now(); + $dateTime_ECMA = dol_print_date($date_actu, '%Y-%m-%dT%H:%M:%S'); + + if(!empty($executiondate)) $date_actu=$executiondate; $dateTime_YMD = dol_print_date($date_actu, '%Y%m%d'); $dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S'); - $dateTime_ECMA = dol_print_date($date_actu, '%Y-%m-%dT%H:%M:%S'); $fileDebiteurSection = ''; $fileEmetteurSection = ''; $i = 0; diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index cd3aebf62f4..c94a786917f 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -3,6 +3,7 @@ * Copyright (C) 2010-2015 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2010-2012 Juanjo Menent + * Copyright (C) 2018 Nicolas ZABOURI * * 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 @@ -65,7 +66,9 @@ if ($action == 'create') { // $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty $bprev = new BonPrelevement($db); - $result=$bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format); + $executiondate = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + + $result = $bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format,$executiondate); if ($result < 0) { setEventMessages($bprev->error, $bprev->errors, 'errors'); @@ -90,6 +93,7 @@ if ($action == 'create') /* * View */ +$form = new Form($db); $thirdpartystatic=new Societe($db); $invoicestatic=new Facture($db); @@ -144,23 +148,22 @@ print ''; if ($mesg) print $mesg; print "
    \n"; +print '
    '; +print ''; +if ($nb) { + if ($pricetowithdraw) { + print $langs->trans('ExecutionDate').' '; + print $form->select_date(); + if ($mysoc->isInEEC()) { + print ''; + print ''; + } else { + print '' . $langs->trans("CreateAll") . "\n"; + } -if ($nb) -{ - if ($pricetowithdraw) - { - if ($mysoc->isInEEC()) - { - print ''.$langs->trans("CreateForSepaFRST")."\n"; - print ''.$langs->trans("CreateForSepaRCUR")."\n"; } else { - print ''.$langs->trans("CreateAll")."\n"; - } - } - else - { if ($mysoc->isInEEC()) { print ''.$langs->trans("CreateForSepaFRST")."\n"; diff --git a/htdocs/langs/en_US/withdrawals.lang b/htdocs/langs/en_US/withdrawals.lang index 7b33ad15947..8dd4e573e37 100644 --- a/htdocs/langs/en_US/withdrawals.lang +++ b/htdocs/langs/en_US/withdrawals.lang @@ -98,6 +98,10 @@ ModeFRST=One-off payment PleaseCheckOne=Please check one only DirectDebitOrderCreated=Direct debit order %s created AmountRequested=Amount requested +SEPARCUR=SEPA CUR +SEPAFRST=SEPA FRST +ExecutionDate=Execution date +CreateForSepa=Create direct debit file ### Notifications InfoCreditSubject=Payment of direct debit payment order %s by the bank From d2dff92f26c4b75ab33cd9e906a186f0fd750c77 Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Sat, 10 Mar 2018 11:28:12 +0100 Subject: [PATCH 134/413] Add execution date on prelevement --- htdocs/compta/prelevement/class/bonprelevement.class.php | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index f720d088b6d..be946d31a19 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -1278,6 +1278,7 @@ class BonPrelevement extends CommonObject * File is generated with name this->filename * * @param string $format FRST, RCUR or ALL + * @param string $executiondate * @return int 0 if OK, <0 if KO */ function generate($format='ALL',$executiondate='') From a833c271e11cfdee5d122e556380eef37ed17eb0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:37:44 +0100 Subject: [PATCH 135/413] Missing user --- htdocs/variants/class/ProductAttributeValue.class.php | 7 ++++--- htdocs/variants/create_val.php | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/htdocs/variants/class/ProductAttributeValue.class.php b/htdocs/variants/class/ProductAttributeValue.class.php index 9c9d9929f46..9b455851507 100644 --- a/htdocs/variants/class/ProductAttributeValue.class.php +++ b/htdocs/variants/class/ProductAttributeValue.class.php @@ -140,15 +140,16 @@ class ProductAttributeValue /** * Creates a value for a product attribute * - * @return int <0 KO >0 OK + * @param User $user Object user + * @return int <0 KO >0 OK */ - public function create() + public function create(User $user) { if (!$this->fk_product_attribute) { return -1; } - //Ref must be uppercase + // Ref must be uppercase $this->ref = strtoupper($this->ref); $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_attribute_value (fk_product_attribute, ref, value, entity) diff --git a/htdocs/variants/create_val.php b/htdocs/variants/create_val.php index 7c624765e32..b290182a042 100644 --- a/htdocs/variants/create_val.php +++ b/htdocs/variants/create_val.php @@ -65,7 +65,7 @@ if ($action == 'add') $objectval->ref = $ref; $objectval->value = $value; - if ($objectval->create() > 0) { + if ($objectval->create($user) > 0) { setEventMessage($langs->trans('RecordSaved')); header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$object->id); exit(); From 04bcc4dd46666d73518c22db3e2bfa6184a10586 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:39:39 +0100 Subject: [PATCH 136/413] Update eldy.lib.php --- htdocs/core/menus/standard/eldy.lib.php | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index 3abff3f714e..e976408c285 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -1257,9 +1257,18 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu if (! empty($conf->stock->enabled)) { $langs->load("stocks"); - $newmenu->add("/product/inventory/list.php?leftmenu=stock", $langs->trans("Inventory"), 0, $user->rights->stock->advance_inventory->read, '', $mainmenu, 'stock'); - $newmenu->add("/product/inventory/card.php?action=create", $langs->trans("NewInventory"), 1, $user->rights->stock->advance_inventory->create); - $newmenu->add("/product/inventory/list.php", $langs->trans("List"), 1, $user->rights->stock->advance_inventory->read); + if (empty(MAIN_USE_ADVANCED_PERMS)) + { + $newmenu->add("/product/inventory/list.php?leftmenu=stock", $langs->trans("Inventory"), 0, $user->rights->stock->read, '', $mainmenu, 'stock'); + $newmenu->add("/product/inventory/card.php?action=create", $langs->trans("NewInventory"), 1, $user->rights->stock->create); + $newmenu->add("/product/inventory/list.php", $langs->trans("List"), 1, $user->rights->stock->read); + } + else + { + $newmenu->add("/product/inventory/list.php?leftmenu=stock", $langs->trans("Inventory"), 0, $user->rights->stock->advance_inventory->read, '', $mainmenu, 'stock'); + $newmenu->add("/product/inventory/card.php?action=create", $langs->trans("NewInventory"), 1, $user->rights->stock->advance_inventory->create); + $newmenu->add("/product/inventory/list.php", $langs->trans("List"), 1, $user->rights->stock->advance_inventory->read); + } } } From 75b470b5801c653c2d525f4aceac937c1fb7b198 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:43:01 +0100 Subject: [PATCH 137/413] Update eldy.lib.php --- htdocs/core/menus/standard/eldy.lib.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index e976408c285..15a262654f4 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -1257,16 +1257,16 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu if (! empty($conf->stock->enabled)) { $langs->load("stocks"); - if (empty(MAIN_USE_ADVANCED_PERMS)) + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { - $newmenu->add("/product/inventory/list.php?leftmenu=stock", $langs->trans("Inventory"), 0, $user->rights->stock->read, '', $mainmenu, 'stock'); - $newmenu->add("/product/inventory/card.php?action=create", $langs->trans("NewInventory"), 1, $user->rights->stock->create); - $newmenu->add("/product/inventory/list.php", $langs->trans("List"), 1, $user->rights->stock->read); + $newmenu->add("/product/inventory/list.php?leftmenu=stock", $langs->trans("Inventory"), 0, $user->rights->stock->lire, '', $mainmenu, 'stock'); + $newmenu->add("/product/inventory/card.php?action=create", $langs->trans("NewInventory"), 1, $user->rights->stock->creer); + $newmenu->add("/product/inventory/list.php", $langs->trans("List"), 1, $user->rights->stock->lire); } else { $newmenu->add("/product/inventory/list.php?leftmenu=stock", $langs->trans("Inventory"), 0, $user->rights->stock->advance_inventory->read, '', $mainmenu, 'stock'); - $newmenu->add("/product/inventory/card.php?action=create", $langs->trans("NewInventory"), 1, $user->rights->stock->advance_inventory->create); + $newmenu->add("/product/inventory/card.php?action=create", $langs->trans("NewInventory"), 1, $user->rights->stock->advance_inventory->write); $newmenu->add("/product/inventory/list.php", $langs->trans("List"), 1, $user->rights->stock->advance_inventory->read); } } From d00b549f91dc9f00b8e39e5761e00c5a3c630fcd Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:46:45 +0100 Subject: [PATCH 138/413] Remove duplicate perm --- htdocs/core/modules/modStock.class.php | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/htdocs/core/modules/modStock.class.php b/htdocs/core/modules/modStock.class.php index ccbf6f83f57..ca518ed8851 100644 --- a/htdocs/core/modules/modStock.class.php +++ b/htdocs/core/modules/modStock.class.php @@ -128,13 +128,7 @@ class modStock extends DolibarrModules $this->rights[6][1] = 'inventoryCreatePermission'; // Permission label $this->rights[6][3] = 0; // Permission by default for new user (0/1) $this->rights[6][4] = 'advance_inventory'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - $this->rights[6][5] = 'create'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - - $this->rights[7][0] = 1013; - $this->rights[7][1] = 'inventoryWritePermission'; // Permission label - $this->rights[7][3] = 0; // Permission by default for new user (0/1) - $this->rights[7][4] = 'advance_inventory'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - $this->rights[7][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) + $this->rights[6][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) $this->rights[8][0] = 1014; $this->rights[8][1] = 'inventoryValidatePermission'; // Permission label From a7f82af352555379fcd7d2d8e85b3252365f8cd1 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:49:25 +0100 Subject: [PATCH 139/413] Update card.php --- htdocs/product/inventory/card.php | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index 5fc63653ffc..69658f2b42a 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -36,7 +36,14 @@ $action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); -$result = restrictedArea($user, 'stock', $id, '', 'advance_inventory'); +if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) +{ + $result = restrictedArea($user, 'stock', $id); +} +else +{ + $result = restrictedArea($user, 'stock', $id, '', 'advance_inventory'); +} // Initialize technical objects $object=new Inventory($db); @@ -82,8 +89,16 @@ if (empty($reshook)) { $error=0; - $permissiontoadd = $user->rights->stock->advance_inventory->create; - $permissiontodelete = $user->rights->stock->advance_inventory->write; + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) + { + $permissiontoadd = $user->rights->stock->write; + $permissiontodelete = $user->rights->stock->write; + } + else + { + $permissiontoadd = $user->rights->stock->advance_inventory->create; + $permissiontodelete = $user->rights->stock->advance_inventory->write; + } $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php'; // Actions cancel, add, update or delete From 64f2f324de8d40e4438e5ec1f354e39f25f92492 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:52:09 +0100 Subject: [PATCH 140/413] Update card.php --- htdocs/product/inventory/card.php | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index 69658f2b42a..30bb3312576 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -75,6 +75,16 @@ $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) +{ + $permissiontoadd = $user->rights->stock->write; + $permissiontodelete = $user->rights->stock->write; +} +else +{ + $permissiontoadd = $user->rights->stock->advance_inventory->create; + $permissiontodelete = $user->rights->stock->advance_inventory->write; +} /* @@ -89,16 +99,6 @@ if (empty($reshook)) { $error=0; - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) - { - $permissiontoadd = $user->rights->stock->write; - $permissiontodelete = $user->rights->stock->write; - } - else - { - $permissiontoadd = $user->rights->stock->advance_inventory->create; - $permissiontodelete = $user->rights->stock->advance_inventory->write; - } $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php'; // Actions cancel, add, update or delete @@ -344,7 +344,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Send print '' . $langs->trans('SendMail') . ''."\n"; - if ($user->rights->stock->advance_inventory->write) + if ($permissiontoadd) { print ''.$langs->trans("Modify").''."\n"; } @@ -353,7 +353,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''.$langs->trans('Modify').''."\n"; } - if ($user->rights->stock->advance_inventory->write) + if ($permissiontodelete) { print ''.$langs->trans('Delete').''."\n"; } From 212536a3fdf9e1b89aaa17bdf7e5a09b5011564c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:54:20 +0100 Subject: [PATCH 141/413] Update list.php --- htdocs/product/inventory/list.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/htdocs/product/inventory/list.php b/htdocs/product/inventory/list.php index c53ffafa8a3..f3089099efe 100644 --- a/htdocs/product/inventory/list.php +++ b/htdocs/product/inventory/list.php @@ -72,7 +72,14 @@ if ($user->societe_id > 0) //$socid = $user->societe_id; accessforbidden(); } -$result = restrictedArea($user, 'stock', $objectid, '', 'advance_inventory'); +if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) +{ + $result = restrictedArea($user, 'stock', $objectid); +} +else +{ + $result = restrictedArea($user, 'stock', $objectid, '', 'advance_inventory'); +} // Initialize array of search criterias $search_all=trim(GETPOST("search_all",'alpha')); From b0bd8cf9105a6fc17af2624c910600203773f652 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:56:19 +0100 Subject: [PATCH 142/413] Update facture.class.php --- htdocs/compta/facture/class/facture.class.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 382002fddc7..349be5ed9cd 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -86,11 +86,11 @@ class Facture extends CommonInvoice //var $amount; public $remise_absolue; public $remise_percent; - public $total_ht=0.0; - public $total_tva=0.0; - public $total_localtax1=0.0; - public $total_localtax2=0.0; - public $total_ttc=0.0; + public $total_ht=0; + public $total_tva=0; + public $total_localtax1=0; + public $total_localtax2=0; + public $total_ttc=0; public $revenuestamp; //! Fermeture apres paiement partiel: discount_vat, badcustomer, abandon From b370a3096c10a89de2a94e8323e0a025ac74d5c9 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Sat, 10 Mar 2018 14:14:31 +0100 Subject: [PATCH 143/413] fix commonobject isInt for module builder capabilities --- htdocs/core/class/commonobject.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index f4a60385a37..6616745888b 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -5527,7 +5527,7 @@ abstract class CommonObject $label = $val['label']; $type = $val['type']; $size = $val['css']; - + // Convert var to be able to share same code than showOutputField of extrafields if (preg_match('/varchar\((\d+)\)/', $type, $reg)) { @@ -6203,7 +6203,7 @@ abstract class CommonObject { if(is_array($info)) { - if(isset($info['type']) && ($info['type']=='int' || $info['type']=='integer' )) return true; + if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true; else return false; } else return false; From 6793bfae3a1f0740cf5449c89f3ea5740a0e5161 Mon Sep 17 00:00:00 2001 From: jean Date: Sat, 10 Mar 2018 14:17:52 +0100 Subject: [PATCH 144/413] FIX #8289 add a cofoiguration for correct stopck calculation --- htdocs/product/class/product.class.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index e6439031146..8d6042907ca 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -2271,6 +2271,29 @@ class Product extends CommonObject } } } + + if (! empty($conf->global->STOCK_CALCULATE_ON_BILL) && ! empty($conf->global->DECREASE_ONLY_UNINVOICEDPRODUCTS)) + { + $adeduire = 0; + $sql = "SELECT sum(fd.qty) as count FROM ".MAIN_DB_PREFIX."facturedet fd "; + $sql .= " JOIN ".MAIN_DB_PREFIX."facture f ON fd.fk_facture = f.rowid "; + $sql .= " JOIN ".MAIN_DB_PREFIX."element_element el ON el.fk_target = f.rowid and el.targettype = 'facture' and sourcetype = 'commande'"; + $sql .= " JOIN ".MAIN_DB_PREFIX."commande c ON el.fk_source = c.rowid "; + $sql .= " WHERE c.fk_statut IN (".$filtrestatut.") AND c.facture = 0 AND fd.fk_product = ".$this->id; + dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE); + + $resql = $this->db->query($sql); + if ( $resql ) + { + if ($this->db->num_rows($resql) > 0) + { + $obj = $this->db->fetch_object($resql); + $adeduire += $obj->count; + } + } + + $this->stats_commande['qty'] -= $adeduire ; + } return 1; } From dd15dc56dd692cda903de4fd76a1143674e408b9 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Sat, 10 Mar 2018 14:34:10 +0100 Subject: [PATCH 145/413] Update and fix prepare integration for more callback support --- htdocs/public/stripe/ipn.php | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/htdocs/public/stripe/ipn.php b/htdocs/public/stripe/ipn.php index 32d874eafbe..15cd2d5cc69 100644 --- a/htdocs/public/stripe/ipn.php +++ b/htdocs/public/stripe/ipn.php @@ -90,7 +90,7 @@ if (! empty($conf->multicompany->enabled) && ! empty($conf->stripeconnect->enabl } else {$key=1;} $ret=$mc->switchEntity($key); -if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); // to work if your module directory is into a subdir of root htdocs directory +if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); if (! $res) die("Include of main fails"); } @@ -105,7 +105,7 @@ if ($event->type == 'payout.created') { { $body = "Un virement de ".price2num($event->data->object->amount/100)." ".$event->data->object->currency." est attendu sur votre compte le ".date('d-m-Y H:i:s',$event->data->object->arrival_date); $subject = '[NOTIFICATION] Virement programmée'; -$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; +$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; TODO convert in dolibarr standard mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); return 1; } @@ -165,7 +165,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $body = "Un virement de ".price2num($event->data->object->amount/100)." ".$event->data->object->currency." a ete effectue sur votre compte le ".date('d-m-Y H:i:s',$event->data->object->arrival_date); $subject = '[NOTIFICATION] Virement effectué'; -$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; +$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; TODO convert in dolibarr standard mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); return 1; @@ -180,11 +180,26 @@ elseif ($event->type == 'charge.succeeded') { //TODO: create fees +} +elseif ($event->type == 'customer.source.created') { + +//TODO: save customer's source + +} +elseif ($event->type == 'customer.source.updated') { + +//TODO: update customer's source + +} +elseif ($event->type == 'customer.source.delete') { + +//TODO: delete customer's source + } elseif ($event->type == 'charge.failed') { $subject = 'Your payment has been received: '.$event->data->object->id.''; -$headers = 'From: "test webhook" '; +$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; //mail('ptibogxiv@msn.com', $subject, 'test', $headers); } @@ -282,8 +297,8 @@ $invoice->set_paid($user); $body = ""; $subject = 'Facture '.$invoice->ref; -$headers = 'From: "test webhook" '; -//mail('ptibogxiv@msn.com', $subject, $body, $headers); +$headers = 'From: "'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; +//mail('ptibogxiv@msn.com', $subject, $body, $headers); TODO convert in dolibarr standard } elseif ($event->type == 'customer.deleted') { $db->begin(); From bbff580fb3d152cb9b7583af6907aaa38e6f3461 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Sat, 10 Mar 2018 14:45:07 +0100 Subject: [PATCH 146/413] integration of fee's platform --- htdocs/stripe/admin/stripe.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/htdocs/stripe/admin/stripe.php b/htdocs/stripe/admin/stripe.php index 91d056aa094..d25831ee264 100644 --- a/htdocs/stripe/admin/stripe.php +++ b/htdocs/stripe/admin/stripe.php @@ -206,8 +206,14 @@ print 'trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; print ''; } else { -print '
    '; -print ''; + print ''; + print ''; + print ''; } if (! empty($conf->banque->enabled)) //deplace here for separate stripe setting of general and common online payment settings From 5403e7a34719d212911f1410d06f5b7ac749cc0a Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Sat, 10 Mar 2018 14:46:37 +0100 Subject: [PATCH 147/413] Update stripe.php --- htdocs/stripe/admin/stripe.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/stripe/admin/stripe.php b/htdocs/stripe/admin/stripe.php index d25831ee264..42306b5b866 100644 --- a/htdocs/stripe/admin/stripe.php +++ b/htdocs/stripe/admin/stripe.php @@ -208,7 +208,7 @@ print ''; } else { print ''; print ''; print price($conf->global->STRIPE_APPLICATION_FEE_PERCENT); print '% + '; print price($conf->global->STRIPE_APPLICATION_FEE); - print $langs->getCurrencySymbol($conf->currency).' avec un minimum de '.price($conf->global->STRIPE_APPLICATION_FEE_MINIMAL).' '.$langs->getCurrencySymbol($conf->currency).' '; + print ' '.$langs->getCurrencySymbol($conf->currency).' avec un minimum de '.price($conf->global->STRIPE_APPLICATION_FEE_MINIMAL).' '.$langs->getCurrencySymbol($conf->currency).' '; print ''; } From 836054a8b3eb67b776a79daafd475c470b1ff0aa Mon Sep 17 00:00:00 2001 From: BadPixxel Date: Sat, 10 Mar 2018 14:51:24 +0100 Subject: [PATCH 149/413] BugFix Issue #8261: Variants module. Combinations cannot be edited --- htdocs/variants/combinations.php | 36 +++++++++++++++++--------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/htdocs/variants/combinations.php b/htdocs/variants/combinations.php index 3101d44ecf5..84f3b7fa91c 100644 --- a/htdocs/variants/combinations.php +++ b/htdocs/variants/combinations.php @@ -346,12 +346,12 @@ if (! empty($id) || ! empty($ref)) foreach ($prodattr_all as $each) { $prodattr_alljson[$each->id] = $each; } - + ?> '; + } + + // Contact and type + print ''; + } else { + print ''; + print ''; + print ''; + } + } + + // TITLE + if ($this->withemail) { + print ''; + } + + // Si origin du ticket + if (isset($this->param['origin']) && $this->param['originid'] > 0) { + // Parse element/subelement (ex: project_task) + $element = $subelement = $this->param['origin']; + if (preg_match('/^([^_]+)_([^_]+)/i', $this->param['origin'], $regs)) { + $element = $regs[1]; + $subelement = $regs[2]; + } + + dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + $classname = ucfirst($subelement); + $objectsrc = new $classname($this->db); + $objectsrc->fetch(GETPOST('originid')); + + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { + $objectsrc->fetch_lines(); + } + + $objectsrc->fetch_thirdparty(); + $newclassname = $classname; + print ''; + } + + // Type + print ''; + + // Category + print ''; + + // Severity + print ''; + + // Not notify tiers at create + print ''; + + // TITLE + if ($this->withtitletopic) { + print ''; + } else { + if ($this->withthreadid > 0) { + $subject = $langs->trans('SubjectAnswerToTicket') . ' ' . $this->withthreadid . ' : ' . $this->topic_title . ''; + } + print ''; + print ''; + } + } + + // MESSAGE + $msg = GETPOST('message', 'alpha') ? GETPOST('message', 'alpha') : ''; + print ''; + + // Attached files + if (!empty($this->withfile)) { + // Define list of attached files + $listofpaths = array(); + $listofnames = array(); + $listofmimes = array(); + if (!empty($_SESSION["listofpaths"])) { + $listofpaths = explode(';', $_SESSION["listofpaths"]); + } + + if (!empty($_SESSION["listofnames"])) { + $listofnames = explode(';', $_SESSION["listofnames"]); + } + + if (!empty($_SESSION["listofmimes"])) { + $listofmimes = explode(';', $_SESSION["listofmimes"]); + } + + $out .= ''; + $out .= ''; + $out .= '\n"; + + print $out; + } + + // Other attributes + if ($this->withextrafields == 1) { + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $ticketstat, $action); // Note that $action and $object may have been modified by hook + if (empty($reshook) && !empty($extrafields->attribute_label)) { + print $ticketstat->showOptionals($extrafields, 'edit'); + } + } + + print '
    '.$langs->trans("StripeConnect").''.$langs->trans("StripeConnect_Mode").'
    '.$langs->trans("StripeConnect").''.$langs->trans("StripeConnect_Mode").'
    '; + print $langs->trans("STRIPE_APPLICATION_FEE_PLATFORM"); + print price($conf->global->STRIPE_APPLICATION_FEE_PERCENT); + print '% + '; + print price($conf->global->STRIPE_APPLICATION_FEE); + print $langs->getCurrencySymbol($conf->currency).' avec un minimum de '.price($conf->global->STRIPE_APPLICATION_FEE_MINIMAL).' '.$langs->getCurrencySymbol($conf->currency).'
    '.$langs->trans("StripeConnect").''.$langs->trans("StripeConnect_Mode").'
    '; - print $langs->trans("STRIPE_APPLICATION_FEE_PLATFORM"); + print $langs->trans("STRIPE_APPLICATION_FEE_PLATFORM").' '; print price($conf->global->STRIPE_APPLICATION_FEE_PERCENT); print '% + '; print price($conf->global->STRIPE_APPLICATION_FEE); From 6b43477c3960979bb45931b2a4d1117615ca77b0 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Sat, 10 Mar 2018 14:48:07 +0100 Subject: [PATCH 148/413] Update stripe.php --- htdocs/stripe/admin/stripe.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/stripe/admin/stripe.php b/htdocs/stripe/admin/stripe.php index 42306b5b866..5253002691f 100644 --- a/htdocs/stripe/admin/stripe.php +++ b/htdocs/stripe/admin/stripe.php @@ -212,7 +212,7 @@ print '
    ' . $langs->trans("Contact") . ''; + // If no socid, set to first one (id=1) to avoid full contacts list + $selectedCompany = $this->withfromsocid > 0 ? $this->withfromsocid : 1; + $nbofcontacts = $form->select_contacts($selectedCompany, $this->withfromcontactid, 'contactid', 0, '', '', 0, 'minwidth200'); + $formcompany->selectTypeContact($ticketstatic, '', 'type', 'external'); + print '
    '; + print ''; + print '
    ' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1) . '
    '; + print $this->selectTypesTickets((GETPOST('type_code') ? GETPOST('type_code') : $this->type_code), 'type_code', '', '2'); + print '
    '; + print $this->selectCategoriesTickets((GETPOST('category_code') ? GETPOST('category_code') : $this->category_code), 'category_code', '', '2'); + print '
    '; + print $this->selectSeveritiesTickets((GETPOST('severity_code') ? GETPOST('severity_code') : $this->severity_code), 'severity_code', '', '2'); + print '
    '; + print 'withnotnotifytiersatcreate?' checked="checked"':'').'>'; + print '
    '; + + // Réponse à un ticket : affichage du titre du thread en readonly + if ($this->withtopicreadonly) { + print $langs->trans('SubjectAnswerToTicket') . ' ' . $this->topic_title; + print '
    '; + + // If public form, display more information + if ($this->ispublic) { + print '
    ' . ($conf->global->TICKETS_PUBLIC_TEXT_HELP_MESSAGE ? $conf->global->TICKETS_PUBLIC_TEXT_HELP_MESSAGE : $langs->trans('TicketPublicPleaseBeAccuratelyDescribe')) . '
    '; + } + include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + $uselocalbrowser = true; + $doleditor = new DolEditor('message', GETPOST('message', 'alpha'), '100%', 250, 'dolibarr_details', 'In', true, $uselocalbrowser); + $doleditor->Create(); + print '
    ' . $langs->trans("MailFile") . ''; + // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript + $out .= '' . "\n"; + $out .= '' . "\n"; + if (count($listofpaths)) { + foreach ($listofpaths as $key => $val) { + $out .= '
    '; + $out .= img_mime($listofnames[$key]) . ' ' . $listofnames[$key]; + if (!$this->withfilereadonly) { + $out .= ' '; + } + $out .= '
    '; + } + } else { + $out .= $langs->trans("NoAttachedFiles") . '
    '; + } + if ($this->withfile == 2) { // Can add other files + $out .= ''; + $out .= ' '; + $out .= ''; + } + $out .= "
    '; + + print '
    '; + print ''; + + if ($this->withcancel) { + print "     "; + print "trans("Cancel") . "\">"; + } + print "
    \n"; + + print "\n"; + print "\n"; + } + + /** + * Return html list of tickets type + * + * @param string $selected Id du type pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $filtertype To filter on field type in llx_c_ticketsup_type (array('code'=>xx,'label'=>zz)) + * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code + * @param int $empty 1=peut etre vide, 0 sinon + * @param int $noadmininfo 0=Add admin info, 1=Disable admin info + * @param int $maxlength Max length of label + * @return void + */ + public function selectTypesTickets($selected = '', $htmlname = 'tickettype', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0) + { + global $langs, $user; + + $ticketstat = new Ticketsup($this->db); + + dol_syslog(get_class($this) . "::select_types_tickets " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG); + + $filterarray = array(); + + if ($filtertype != '' && $filtertype != '-1') { + $filterarray = explode(',', $filtertype); + } + + $ticketstat->load_cache_types_tickets(); + + print ''; + if ($user->admin && !$noadmininfo) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); + } + } + + /** + * Return html list of ticket categories + * + * @param string $selected Id categorie pre-selectionnée + * @param string $htmlname Nom de la zone select + * @param string $filtertype To filter on field type in llx_c_ticketsup_category (array('code'=>xx,'label'=>zz)) + * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code + * @param int $empty 1=peut etre vide, 0 sinon + * @param int $noadmininfo 0=Add admin info, 1=Disable admin info + * @param int $maxlength Max length of label + * @return void + */ + public function selectCategoriesTickets($selected = '', $htmlname = 'ticketcategory', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0) + { + global $langs, $user; + + $ticketstat = new Ticketsup($this->db); + + dol_syslog(get_class($this) . "::selectCategoryTickets " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG); + + $filterarray = array(); + + if ($filtertype != '' && $filtertype != '-1') { + $filterarray = explode(',', $filtertype); + } + + $ticketstat->load_cache_categories_tickets(); + + print ''; + if ($user->admin && !$noadmininfo) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); + } + } + + /** + * Return html list of ticket severitys + * + * @param string $selected Id severity pre-selectionnée + * @param string $htmlname Nom de la zone select + * @param string $filtertype To filter on field type in llx_c_ticketsup_severity (array('code'=>xx,'label'=>zz)) + * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code + * @param int $empty 1=peut etre vide, 0 sinon + * @param int $noadmininfo 0=Add admin info, 1=Disable admin info + * @param int $maxlength Max length of label + * @return void + */ + public function selectSeveritiesTickets($selected = '', $htmlname = 'ticketseverity', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0) + { + global $langs, $user; + + $ticketstat = new Ticketsup($this->db); + + dol_syslog(get_class($this) . "::selectSeveritiesTickets " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG); + + $filterarray = array(); + + if ($filtertype != '' && $filtertype != '-1') { + $filterarray = explode(',', $filtertype); + } + + $ticketstat->load_cache_severities_tickets(); + + print ''; + if ($user->admin && !$noadmininfo) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); + } + } + + /** + * Show the form to add message on ticket + * + * @param string $width Width of form + * @return void + */ + public function showMessageForm($width = '40%') + { + global $conf, $langs, $user, $mysoc; + + $langs->load("other"); + $langs->load("mails"); + + $addfileaction = 'addfile'; + + $form = new Form($this->db); + $formmail = new FormMail($this->db); + + + // Define list of attached files + $listofpaths = array(); + $listofnames = array(); + $listofmimes = array(); + if (!empty($_SESSION["listofpaths"])) { + $listofpaths = explode(';', $_SESSION["listofpaths"]); + } + + if (!empty($_SESSION["listofnames"])) { + $listofnames = explode(';', $_SESSION["listofnames"]); + } + + if (!empty($_SESSION["listofmimes"])) { + $listofmimes = explode(';', $_SESSION["listofmimes"]); + } + + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $this->param['langsmodels']; + } + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + $outputlangs->load('other'); + } + + print "\n\n"; + + $send_email = GETPOST('send_email', 'int') ? GETPOST('send_email', 'int') : 0; + + // Example 1 : Adding jquery code + print ''; + + print '
    '; + print ''; + print ''; + foreach ($this->param as $key => $value) { + print ''; + } + + // Get message template + $model_id=0; + if (array_key_exists('models_id', $this->param)) { + $model_id=$this->param["models_id"]; + $arraydefaultmessage=$this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id); + } + + $result = $formmail->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs); + if ($result<0) { + setEventMessages($this->error, $this->errors, 'errors'); + } + $modelmail_array=array(); + foreach ($formmail->lines_model as $line) { + $modelmail_array[$line->id]=$line->label; + } + + + + print ''; + + + // External users can't send message email + if ($user->rights->ticketsup->write && !$user->societe_id) { + print ''; + + // Zone to select its email template + if (count($modelmail_array)>0) { + print ''; + } + + // Substitution array + if ($this->withsubstit) { + print '"; + } + + if (!$user->societe_id) { + print ''; + } + + + print ''; + $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE; + print ''; + + // Destinataires + print ''; + } + + // Intro + // External users can't send message email + if ($user->rights->ticketsup->write && !$user->societe_id) { + $mail_intro = GETPOST('mail_intro') ? GETPOST('mail_intro') : $conf->global->TICKETS_MESSAGE_MAIL_INTRO; + print ''; + } + + // MESSAGE + $defaultmessage=""; + if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['content']) { + $defaultmessage=$arraydefaultmessage['content']; + } + $defaultmessage=str_replace('\n', "\n", $defaultmessage); + + // Deal with format differences between message and signature (text / HTML) + if (dol_textishtml($defaultmessage) && !dol_textishtml($this->substit['__SIGNATURE__'])) { + $this->substit['__SIGNATURE__'] = dol_nl2br($this->substit['__SIGNATURE__']); + } elseif (!dol_textishtml($defaultmessage) && dol_textishtml($this->substit['__SIGNATURE__'])) { + $defaultmessage = dol_nl2br($defaultmessage); + } + if (isset($_POST["message"]) && ! $_POST['modelselected']) { + $defaultmessage=GETPOST('message'); + } else { + $defaultmessage=make_substitutions($defaultmessage, $this->substit); + // Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty) + $defaultmessage=preg_replace("/^(
    )+/", "", $defaultmessage); + $defaultmessage=preg_replace("/^\n+/", "", $defaultmessage); + } + + print ''; + + // Signature + // External users can't send message email + if ($user->rights->ticketsup->write && !$user->societe_id) { + $mail_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE; + print ''; + } + + // Attached files + if (!empty($this->withfile)) { + $out .= ''; + $out .= ''; + $out .= '\n"; + + print $out; + } + + print ''; + print '
    '; + $checkbox_selected = ( GETPOST('send_email') == "1" ? ' checked' : ''); + print ' '; + print ''; + print '
    '; + $checkbox_selected = ( GETPOST('private_message') == "1" ? ' checked' : ''); + print ' '; + print ''; + print ''; + print $form->textwithpicto('', $langs->trans("TicketMessagePrivateHelp"), 1, 'help'); + print '
    '; + include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + $doleditor = new DolEditor('message', $defaultmessage, '100%', 350, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70); + $doleditor->Create(); + print ''; + if ($user->rights->ticketsup->write && !$user->societe_id) { + print $form->textwithpicto('', $langs->trans("TicketMessageHelp"), 1, 'help'); + } + + print '
    ' . $langs->trans("MailFile") . ''; + // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript + $out .= '' . "\n"; + $out .= '' . "\n"; + if (count($listofpaths)) { + foreach ($listofpaths as $key => $val) { + $out .= '
    '; + $out .= img_mime($listofnames[$key]) . ' ' . $listofnames[$key]; + if (!$this->withfilereadonly) { + $out .= ' '; + } + $out .= '
    '; + } + } else { + $out .= $langs->trans("NoAttachedFiles") . '
    '; + } + if ($this->withfile == 2) { // Can add other files + $out .= ''; + $out .= ' '; + $out .= ''; + } + $out .= "
    '; + print '
    '; + print ''; + + if ($this->withcancel) { + print "     "; + print "trans("Cancel") . "\">"; + } + print "
    \n"; + print '
    '; + + print "
    \n"; + print "\n"; + } + + /** + * Return template of email + * Search into table c_email_templates + * + * @param DoliDB $db Database handler + * @param string $type_template Get message for key module + * @param string $user Use template public or limited to this user + * @param Translate $outputlangs Output lang object + * @param int $id Id template to find + * @param int $active 1=Only active template, 0=Only disabled, -1=All + * @return array array('topic'=>,'content'=>,..) + */ + private function getEMailTemplate($db, $type_template, $user, $outputlangs, $id = 0, $active = 1) + { + $ret=array(); + + $sql = "SELECT label, topic, content, lang"; + $sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates'; + $sql.= " WHERE type_template='".$db->escape($type_template)."'"; + $sql.= " AND entity IN (".getEntity("c_email_templates").")"; + $sql.= " AND (fk_user is NULL or fk_user = 0 or fk_user = ".$user->id.")"; + if ($active >= 0) { + $sql.=" AND active = ".$active; + } + if (is_object($outputlangs)) { + $sql.= " AND (lang = '".$outputlangs->defaultlang."' OR lang IS NULL OR lang = '')"; + } + if (!empty($id)) { + $sql.= " AND rowid=".$id; + } + $sql.= $db->order("lang,label", "ASC"); + //print $sql; + + $resql = $db->query($sql); + if ($resql) { + $obj = $db->fetch_object($resql); // Get first found + if ($obj) { + $ret['label']=$obj->label; + $ret['topic']=$obj->topic; + $ret['content']=$obj->content; + $ret['lang']=$obj->lang; + } else { + $defaultmessage=''; + if ($type_template=='facture_send') { + $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoice"); + } elseif ($type_template=='facture_relance') { + $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder"); + } elseif ($type_template=='propal_send') { + $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendProposal"); + } elseif ($type_template=='supplier_proposal_send') { + $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal"); + } elseif ($type_template=='order_send') { + $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendOrder"); + } elseif ($type_template=='order_supplier_send') { + $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder"); + } elseif ($type_template=='invoice_supplier_send') { + $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice"); + } elseif ($type_template=='shipping_send') { + $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendShipping"); + } elseif ($type_template=='fichinter_send') { + $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendFichInter"); + } elseif ($type_template=='thirdparty') { + $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentThirdparty"); + } + + $ret['label']='default'; + $ret['topic']=''; + $ret['content']=$defaultmessage; + $ret['lang']=$outputlangs->defaultlang; + } + + $db->free($resql); + return $ret; + } else { + dol_print_error($db); + return -1; + } + } +} diff --git a/htdocs/core/lib/ticketsup.lib.php b/htdocs/core/lib/ticketsup.lib.php new file mode 100644 index 00000000000..0e6b433f183 --- /dev/null +++ b/htdocs/core/lib/ticketsup.lib.php @@ -0,0 +1,200 @@ + + * Copyright (C) 2013-2016 Jean-François FERRY + * 2016 Christophe Battarel + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file lib/ticketsup.lib.php + * \ingroup ticketsup + * \brief This file is an example module library + * Put some comments here + */ + +function ticketsupAdminPrepareHead() +{ + global $langs, $conf; + + $langs->load("ticketsup@ticketsup"); + + $h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath("/ticketsup/admin/admin_ticketsup.php", 1); + $head[$h][1] = $langs->trans("TicketSupSettings"); + $head[$h][2] = 'settings'; + $h++; + $head[$h][0] = dol_buildpath("/ticketsup/admin/ticketsup_extrafields.php", 1); + $head[$h][1] = $langs->trans("ExtraFieldsTicketSup"); + $head[$h][2] = 'attributes'; + $h++; + $head[$h][0] = dol_buildpath("/ticketsup/admin/about.php", 1); + $head[$h][1] = $langs->trans("About"); + $head[$h][2] = 'about'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@ticketsup:/ticketsup/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@ticketsup:/ticketsup/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticketsupadmin'); + + return $head; +} + +/** + * \file htdocs/hosting/lib/hosting.lib.php + * \brief Ensemble de fonctions de base pour le module hosting + * \ingroup business + * \version $Id$ + */ + +function ticketsup_prepare_head($object) +{ + + global $db, $langs, $conf, $user; + $h = 0; + $head = array(); + $head[$h][0] = dol_buildpath('/ticketsup/card.php', 1) . '?action=view&track_id=' . $object->track_id; + $head[$h][1] = $langs->trans("Card"); + $head[$h][2] = 'tabTicketsup'; + $h++; + + if (empty($user->socid)) { + $head[$h][0] = dol_buildpath('/ticketsup/contacts.php', 1) . '?track_id=' . $object->track_id; + $head[$h][1] = $langs->trans('Contacts'); + $head[$h][2] = 'tabTicketContacts'; + $h++; + } + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticketsup'); + + + // Attached files + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + $upload_dir = $conf->ticketsup->dir_output . "/" . $object->track_id; + $nbFiles = count(dol_dir_list($upload_dir, 'files')); + $head[$h][0] = dol_buildpath('/ticketsup/document.php', 1) . '?track_id=' . $object->track_id; + $head[$h][1] = $langs->trans("Documents"); + if ($nbFiles > 0) { + $head[$h][1] .= ' ' . $nbFiles . ''; + } + + $head[$h][2] = 'tabTicketDocument'; + $h++; + + + // History + $head[$h][0] = dol_buildpath('/ticketsup/history.php', 1) . '?track_id=' . $object->track_id; + $head[$h][1] = $langs->trans('TicketHistory'); + $head[$h][2] = 'tabTicketLogs'; + $h++; + + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticketsup','remove'); + + + return $head; +} + +/** + * Generate a random id + * + * @param string $car Char to generate key + * @return void + */ +function generate_random_id($car=16) +{ + $string = ""; + $chaine = "abcdefghijklmnopqrstuvwxyz123456789"; + srand((double) microtime() * 1000000); + for ($i = 0; $i < $car; $i++) { + $string .= $chaine[rand() % strlen($chaine)]; + } + return $string; +} + +/** + * Show header for public pages + * + * @param string $title Title + * @param string $head Head array + * @param int $disablejs More content into html header + * @param int $disablehead More content into html header + * @param array $arrayofjs Array of complementary js files + * @param array $arrayofcss Array of complementary css files + * @return void + */ +function llxHeaderTicket($title, $head = "", $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '') +{ + global $user, $conf, $langs, $mysoc; + + top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); // Show html headers + print ''; + + if (! empty($conf->global->TICKETS_SHOW_COMPANY_LOGO)) { + showlogo(); + } + + print '
    '; +} + +/** + * Show footer for new member + * + * @return void + */ +function llxFooterTicket() +{ + print '
    '; + + printCommonFooter('public'); + + dol_htmloutput_events(); + + print "\n"; + print "\n"; +} + +/** + * Show logo + * + * @return void + */ +function showlogo() +{ + global $conf, $langs, $mysoc; + + // Print logo + $urllogo = DOL_URL_ROOT . '/theme/login_logo.png'; + + if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output . '/logos/thumbs/' . $mysoc->logo_small)) { + $urllogo = DOL_URL_ROOT . '/viewimage.php?cache=1&modulepart=companylogo&file=' . urlencode('thumbs/' . $mysoc->logo_small); + } elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output . '/logos/' . $mysoc->logo)) { + $urllogo = DOL_URL_ROOT . '/viewimage.php?cache=1&modulepart=companylogo&file=' . urlencode($mysoc->logo); + $width = 128; + } elseif (is_readable(DOL_DOCUMENT_ROOT . '/theme/dolibarr_logo.png')) { + $urllogo = DOL_URL_ROOT . '/theme/dolibarr_logo.png'; + } + print '
    '; + print 'Logo
    '; + print '' . ($conf->global->TICKETS_PUBLIC_INTERFACE_TOPIC ? $conf->global->TICKETS_PUBLIC_INTERFACE_TOPIC : $langs->trans("TicketSystem")) . ''; + print '

    '; +} diff --git a/htdocs/core/modules/modTicketsup.class.php b/htdocs/core/modules/modTicketsup.class.php new file mode 100644 index 00000000000..52830ef4924 --- /dev/null +++ b/htdocs/core/modules/modTicketsup.class.php @@ -0,0 +1,367 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \defgroup ticketsup Ticketsup module + * \brief Ticketsup module descriptor. + * \file core/modules/modTicketsup.class.php + * \ingroup ticketsup + * \brief Description and activation file for module Ticketsup + */ +require_once DOL_DOCUMENT_ROOT . "/core/modules/DolibarrModules.class.php"; + +/** + * Description and activation class for module Ticketsup + */ +class modTicketsup extends DolibarrModules +{ + + /** + * Constructor. Define names, constants, directories, boxes, permissions + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $langs, $conf; + + $this->db = $db; + + // Id for module (must be unique). + // Use a free id here + // (See in Home -> System information -> Dolibarr for list of used modules id). + $this->numero = 110120; + // Key text used to identify module (for permissions, menus, etc...) + $this->rights_class = 'ticketsup'; + + $this->editor_name = "Dolibarr"; + $this->editor_web = "https://dolibrr.org"; + + // Family can be 'crm','financial','hr','projects','products','ecm','technic','other' + // It is used to group modules in module setup page + $this->family = "crm"; + // Module position in the family + $this->module_position = 500; + // Module label (no space allowed) + // used if translation string 'ModuleXXXName' not found + // (where XXX is value of numeric property 'numero' of module) + $this->name = preg_replace('/^mod/i', '', get_class($this)); + // Module description + // used if translation string 'ModuleXXXDesc' not found + // (where XXX is value of numeric property 'numero' of module) + $this->description = "Incident/support ticket management"; + // Possible values for version are: 'development', 'experimental' or version + $this->version = 'experimental'; + // Key used in llx_const table to save module status enabled/disabled + // (where MYMODULE is value of property name of module in uppercase) + $this->const_name = 'MAIN_MODULE_' . strtoupper($this->name); + // Where to store the module in setup page + // (0=common,1=interface,2=others,3=very specific) + $this->special = 2; + // Name of image file used for this module. + // If file is in theme/yourtheme/img directory under name object_pictovalue.png + // use this->picto='pictovalue' + // If file is in module/img directory under name object_pictovalue.png + // use this->picto='pictovalue@module' + $this->picto = 'ticketsup@ticketsup'; // mypicto@ticketsup + // Defined all module parts (triggers, login, substitutions, menus, css, etc...) + // for default path (eg: /ticketsup/core/xxxxx) (0=disable, 1=enable) + // for specific path of parts (eg: /ticketsup/core/modules/barcode) + // for specific css file (eg: /ticketsup/css/ticketsup.css.php) + $this->module_parts = array( + // Set this to 1 if module has its own trigger directory + 'triggers' => 1, + // Set this to 1 if module has its own login method directory + //'login' => 0, + // Set this to 1 if module has its own substitution function file + //'substitutions' => 0, + // Set this to 1 if module has its own menus handler directory + //'menus' => 0, + // Set this to 1 if module has its own barcode directory + //'barcode' => 0, + // Set this to 1 if module has its own models directory + 'models' => 1, + // Set this to relative path of css if module has its own css file + 'css' => '/ticketsup/css/ticketsup.css', + // Set here all hooks context managed by module + 'hooks' => array('admin') + // Set here all workflow context managed by module + //'workflow' => array('order' => array('WORKFLOW_ORDER_AUTOCREATE_INVOICE')) + ); + + // Data directories to create when module is enabled. + // Example: this->dirs = array("/ticketsup/temp"); + $this->dirs = array(); + + // Config pages. Put here list of php pages + // stored into ticketsup/admin directory, used to setup module. + $this->config_page_url = array("ticketsup.php"); + + // Dependencies + // List of modules id that must be enabled if this module is enabled + $this->depends = array(); + // List of modules id to disable if this one is disabled + $this->requiredby = array(); + // Minimum version of PHP required by module + $this->phpmin = array(5, 3); + $this->langfiles = array("ticketsup"); + // Constants + // List of particular constants to add when module is enabled + // (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive) + // Example: + $this->const = array(); + $this->const[1] = array('TICKETS_ENABLE_PUBLIC_INTERFACE', 'chaine', '1', 'Enable ticket public interface'); + $this->const[2] = array('TICKETSUP_ADDON', 'chaine', 'mod_ticketsup_simple', 'Ticketsup ref module'); + + $this->tabs = array( + 'thirdparty:+ticketsup:Tickets:@ticketsup:$user->rights->ticketsup->read:/ticketsup/list.php?socid=__ID__', + 'project:+ticketsup:Tickets:@ticketsup:$user->rights->ticketsup->read:/ticketsup/list.php?projectid=__ID__', + ); + + // Dictionnaries + if (! isset($conf->ticketsup->enabled)) { + $conf->ticketsup=new stdClass(); + $conf->ticketsup->enabled=0; + } + $this->dictionaries = array( + 'langs' => 'ticketsup@ticketsup', + 'tabname' => array(MAIN_DB_PREFIX . "c_ticketsup_type", MAIN_DB_PREFIX . "c_ticketsup_category", MAIN_DB_PREFIX . "c_ticketsup_severity"), + 'tablib' => array("TicketsupDictType", "TicketsupDictCategory", "TicketsupDictSeverity"), + 'tabsql' => array('SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticketsup_type as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticketsup_category as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticketsup_severity as f'), + 'tabsqlsort' => array("pos ASC", "pos ASC", "pos ASC"), + 'tabfield' => array("pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default"), + 'tabfieldvalue' => array("pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default"), + 'tabfieldinsert' => array("pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default"), + 'tabrowid' => array("rowid", "rowid", "rowid"), + 'tabcond' => array($conf->ticketsup->enabled, $conf->ticketsup->enabled, $conf->ticketsup->enabled), + ); + + // Boxes + // Add here list of php file(s) stored in core/boxes that contains class to show a box. + $this->boxes = array(); // Boxes list + $r = 0; + // Example: + + $this->boxes[$r][1] = "box_last_ticketsup@ticketsup"; + $r++; + + $this->boxes[$r][1] = "box_last_modified_ticketsup@ticketsup"; + $r++; + + // Permissions + $this->rights = array(); // Permission array used by this module + $r = 0; + + $r++; + $this->rights[$r][0] = 110120; // id de la permission + $this->rights[$r][1] = "Créer un ticket"; // libelle de la permission + $this->rights[$r][2] = 'c'; // type de la permission (deprecie a ce jour) + $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut + $this->rights[$r][4] = 'create'; + + $r++; + $this->rights[$r][0] = 110121; // id de la permission + $this->rights[$r][1] = "Lire les tickets"; // libelle de la permission + $this->rights[$r][2] = 'r'; // type de la permission (deprecie a ce jour) + $this->rights[$r][3] = 1; // La permission est-elle une permission par defaut + $this->rights[$r][4] = 'read'; + + $r++; + $this->rights[$r][0] = 110122; // id de la permission + $this->rights[$r][1] = "Modifier les tickets"; // libelle de la permission + $this->rights[$r][2] = 'w'; // type de la permission (deprecie a ce jour) + $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut + $this->rights[$r][4] = 'write'; + + $r++; + $this->rights[$r][0] = 110123; // id de la permission + $this->rights[$r][1] = "Supprimer les tickets"; // libelle de la permission + $this->rights[$r][2] = 'd'; // type de la permission (deprecie a ce jour) + $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut + $this->rights[$r][4] = 'delete'; + + $r++; + $this->rights[$r][0] = 110124; // id de la permission + $this->rights[$r][1] = "Gérer les tickets"; // libelle de la permission + //$this->rights[$r][2] = 'd'; // type de la permission (deprecie a ce jour) + $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut + $this->rights[$r][4] = 'manage'; + + $r++; + $this->rights[$r][0] = 110125; // id de la permission + $this->rights[$r][1] = 'Voir tous les tickets (non effectif pour les utilisateurs externes, toujours limités au tiers dont ils dépendent)'; // libelle de la permission + $this->rights[$r][2] = 'r'; // type de la permission (deprecie a ce jour) + $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut + $this->rights[$r][4] = 'view'; + $this->rights[$r][5] = 'all'; + + // Main menu entries + $this->menus = array(); // List of menus to add + $r = 0; + + $this->menu[$r] = array('fk_menu' => 0, // Put 0 if this is a top menu + 'type' => 'top', // This is a Top menu entry + 'titre' => 'Ticket', + 'mainmenu' => 'ticketsup', + 'leftmenu' => '1', // Use 1 if you also want to add left menu entries using this descriptor. + 'url' => '/ticketsup/index.php', + 'langs' => 'ticketsup@ticketsup', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position' => 100, + 'enabled' => '1', // Define condition to show or hide menu entry. Use '$conf->ticketsup->enabled' if entry must be visible if module is enabled. + 'perms' => '$user->rights->ticketsup->read', // Use 'perms'=>'$user->rights->ticketsup->level1->level2' if you want your menu with a permission rules + 'target' => '', + 'user' => 2); // 0=Menu for internal users, 1=external users, 2=both + $r++; + + $this->menu[$r] = array('fk_menu' => 'fk_mainmenu=ticketsup', + 'type' => 'left', + 'titre' => 'Ticket', + 'mainmenu' => 'ticketsup', + 'leftmenu' => 'ticketsup', + 'url' => '/ticketsup/index.php', + 'langs' => 'ticketsup@ticketsup', + 'position' => 101, + 'enabled' => 1, + 'perms' => '$user->rights->ticketsup->read', + 'target' => '', + 'user' => 2); + $r++; + + $this->menu[$r] = array('fk_menu' => 'fk_mainmenu=ticketsup,fk_leftmenu=ticketsup', + 'type' => 'left', + 'titre' => 'NewTicket', + 'mainmenu' => 'ticketsup', + 'url' => '/ticketsup/new.php?action=create_ticket', + 'langs' => 'ticketsup@ticketsup', + 'position' => 102, + 'enabled' => 1, + 'perms' => '$user->rights->ticketsup->create', + 'target' => '', + 'user' => 2); + $r++; + + $this->menu[$r] = array('fk_menu' => 'fk_mainmenu=ticketsup,fk_leftmenu=ticketsup', + 'type' => 'left', + 'titre' => 'List', + 'mainmenu' => 'ticketsup', + 'leftmenu' => 'ticketsuplist', + 'url' => '/ticketsup/list.php', + 'langs' => 'ticketsup@ticketsup', + 'position' => 103, + 'enabled' => 1, + 'perms' => '$user->rights->ticketsup->read', + 'target' => '', + 'user' => 2); + $r++; + + $this->menu[$r] = array('fk_menu' => 'fk_mainmenu=ticketsup,fk_leftmenu=ticketsuplist', + 'type' => 'left', + 'titre' => 'MenuListNonClosed', + 'mainmenu' => 'ticketsup', + 'leftmenu' => 'ticketsuplist', + 'url' => '/ticketsup/list.php?search_fk_status=non_closed', + 'langs' => 'ticketsup@ticketsup', + 'position' => 104, + 'enabled' => 1, + 'perms' => '$user->rights->ticketsup->read', + 'target' => '', + 'user' => 2); + $r++; + + $this->menu[$r] = array('fk_menu' => 'fk_mainmenu=ticketsup,fk_leftmenu=ticketsup', + 'type' => 'left', + 'titre' => 'MenuTicketsupMyAssign', + 'mainmenu' => 'ticketsup', + 'leftmenu' => 'ticketsupmy', + 'url' => '/ticketsup/list.php?mode=my_assign', + 'langs' => 'ticketsup@ticketsup', + 'position' => 105, + 'enabled' => 1, + 'perms' => '$user->rights->ticketsup->read', + 'target' => '', + 'user' => 0); + $r++; + + $this->menu[$r] = array('fk_menu' => 'fk_mainmenu=ticketsup,fk_leftmenu=ticketsupmy', + 'type' => 'left', + 'titre' => 'MenuTicketsupMyAssignNonClosed', + 'mainmenu' => 'ticketsup', + 'url' => '/ticketsup/list.php?mode=my_assign&search_fk_status=non_closed', + 'langs' => 'ticketsup@ticketsup', + 'position' => 106, + 'enabled' => 1, + 'perms' => '$user->rights->ticketsup->read', + 'target' => '', + 'user' => 0); + $r++; + } + + /** + * Function called when module is enabled. + * The init function add constants, boxes, permissions and menus + * (defined in constructor) into Dolibarr database. + * It also creates data directories + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + public function init($options = '') + { + + $sql = array( + array("sql" => "insert into llx_c_type_contact(rowid, element, source, code, libelle, active ) values (110120, 'ticketsup', 'internal', 'SUPPORTTEC', 'Utilisateur assigné au ticket', 1);", "ignoreerror" => 1), + array("sql" => "insert into llx_c_type_contact(rowid, element, source, code, libelle, active ) values (110121, 'ticketsup', 'internal', 'CONTRIBUTOR', 'Intervenant', 1);", "ignoreerror" => 1), + array("sql" => "insert into llx_c_type_contact(rowid, element, source, code, libelle, active ) values (110122, 'ticketsup', 'external', 'SUPPORTCLI', 'Contact client suivi incident', 1);", "ignoreerror" => 1), + array("sql" => "insert into llx_c_type_contact(rowid, element, source, code, libelle, active ) values (110123, 'ticketsup', 'external', 'CONTRIBUTOR', 'Intervenant', 1);", "ignoreerror" => 1), + array("sql" => "insert into llx_c_action_trigger (rowid,code,label,description,elementtype,rang) values ('','TICKETMESSAGE_SENTBYMAIL','Envoi message de réponse par mail','Executed when a response is made on a ticket','ticketsup','');", "ignoreerror" => 1), + + ); + + $result = $this->loadTables(); + + return $this->_init($sql, $options); + } + + /** + * Function called when module is disabled. + * Remove from database constants, boxes and permissions from Dolibarr database. + * Data directories are not deleted + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + public function remove($options = '') + { + $sql = array(); + + return $this->_remove($sql, $options); + } + + /** + * Create tables, keys and data required by module + * Files llx_table1.sql, llx_table1.key.sql llx_data.sql with create table, create keys + * and create data commands must be stored in directory /ticketsup/sql/ + * This function is called by this->init + * + * @return int <=0 if KO, >0 if OK + */ + private function loadTables() + { + return $this->_load_tables('/ticketsup/sql/'); + } +} diff --git a/htdocs/core/modules/modules_ticketsup.php b/htdocs/core/modules/modules_ticketsup.php new file mode 100644 index 00000000000..9eb652c31f4 --- /dev/null +++ b/htdocs/core/modules/modules_ticketsup.php @@ -0,0 +1,120 @@ + + * Copyright (C) 2014 Marcos García + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see http://www.gnu.org/ + */ + +/** + * \file htdocs/core/modules/project/modules_project.php + * \ingroup project + * \brief File that contain parent class for projects models + * and parent class for projects numbering models + */ + +/** + * Classe mere des modeles de numerotation des references de projets + */ +abstract class ModeleNumRefTicketsup +{ + public $error = ''; + + /** + * Return if a module can be used or not + * + * @return boolean true if module can be used + */ + public function isEnabled() + { + return true; + } + + /** + * Renvoi la description par defaut du modele de numerotation + * + * @return string Texte descripif + */ + public function info() + { + global $langs; + $langs->load("ticketsup@ticketsup"); + return $langs->trans("NoDescription"); + } + + /** + * Renvoi un exemple de numerotation + * + * @return string Example + */ + public function getExample() + { + global $langs; + $langs->load("ticketsup@ticketsup"); + return $langs->trans("NoExample"); + } + + /** + * Test si les numeros deja en vigueur dans la base ne provoquent pas de + * de conflits qui empechera cette numerotation de fonctionner. + * + * @return boolean false si conflit, true si ok + */ + public function canBeActivated() + { + return true; + } + + /** + * Renvoi prochaine valeur attribuee + * + * @param Societe $objsoc Object third party + * @param Project $project Object project + * @return string Valeur + */ + public function getNextValue($objsoc, $project) + { + global $langs; + return $langs->trans("NotAvailable"); + } + + /** + * Renvoi version du module numerotation + * + * @return string Valeur + */ + public function getVersion() + { + global $langs; + $langs->load("admin"); + + if ($this->version == 'development') { + return $langs->trans("VersionDevelopment"); + } + + if ($this->version == 'experimental') { + return $langs->trans("VersionExperimental"); + } + + if ($this->version == 'dolibarr') { + return DOL_VERSION; + } + + if ($this->version) { + return $this->version; + } + + return $langs->trans("NotAvailable"); + } +} diff --git a/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php b/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php new file mode 100644 index 00000000000..a8220c0ec9f --- /dev/null +++ b/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php @@ -0,0 +1,153 @@ + + * Copyright (C) 2010 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see http://www.gnu.org/ + */ + +/** + * \file htdocs/core/modules/ticketsup/mod_ticketsup_simple.php + * \ingroup ticketsup + * \brief File with class to manage the numbering module Simple for ticketsup references + */ + +dol_include_once('/ticketsup/core/modules/modules_ticketsup.php'); + +/** + * Class to manage the numbering module Simple for ticketsup references + */ +class mod_ticketsup_simple extends ModeleNumRefTicketsup +{ + public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' + public $prefix = 'TS'; + public $error = ''; + public $nom = "Simple"; + public $name = "Simple"; + + /** + * Return description of numbering module + * + * @return string Text with description + */ + public function info() + { + global $langs; + return $langs->trans("SimpleNumRefModelDesc", $this->prefix); + } + + /** + * Return an example of numbering module values + * + * @return string Example + */ + public function getExample() + { + return $this->prefix . "0501-0001"; + } + + /** + * Test si les numeros deja en vigueur dans la base ne provoquent pas de + * de conflits qui empechera cette numerotation de fonctionner. + * + * @return boolean false si conflit, true si ok + */ + public function canBeActivated() + { + global $conf, $langs, $db; + + $coyymm = ''; + $max = ''; + + $posindice = 8; + $sql = "SELECT MAX(CAST(SUBSTRING(ref FROM " . $posindice . ") AS SIGNED)) as max"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup"; + $sql .= " WHERE ref LIKE '" . $this->prefix . "____-%'"; + $sql .= " AND entity = " . $conf->entity; + $resql = $db->query($sql); + if ($resql) { + $row = $db->fetch_row($resql); + if ($row) { + $coyymm = substr($row[0], 0, 6); + $max = $row[0]; + } + } + if (!$coyymm || preg_match('/' . $this->prefix . '[0-9][0-9][0-9][0-9]/i', $coyymm)) { + return true; + } else { + $langs->load("errors"); + $this->error = $langs->trans('ErrorNumRefModel', $max); + return false; + } + } + + /** + * Return next value + * + * @param Societe $objsoc Object third party + * @param Project $ticketsup Object ticketsup + * @return string Value if OK, 0 if KO + */ + public function getNextValue($objsoc, $ticketsup) + { + global $db, $conf; + + // D'abord on recupere la valeur max + $posindice = 8; + $sql = "SELECT MAX(CAST(SUBSTRING(ref FROM " . $posindice . ") AS SIGNED)) as max"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup"; + $sql .= " WHERE ref like '" . $this->prefix . "____-%'"; + $sql .= " AND entity = " . $conf->entity; + + $resql = $db->query($sql); + if ($resql) { + $obj = $db->fetch_object($resql); + if ($obj) { + $max = intval($obj->max); + } else { + $max = 0; + } + } else { + dol_syslog("mod_ticketsup_simple::getNextValue", LOG_DEBUG); + return -1; + } + + $date = empty($ticketsup->datec) ? dol_now() : $ticketsup->datec; + + //$yymm = strftime("%y%m",time()); + $yymm = strftime("%y%m", $date); + + if ($max >= (pow(10, 4) - 1)) { + $num = $max + 1; + } // If counter > 9999, we do not format on 4 chars, we take number as it is + else { + $num = sprintf("%04s", $max + 1); + } + + dol_syslog("mod_ticketsup_simple::getNextValue return " . $this->prefix . $yymm . "-" . $num); + return $this->prefix . $yymm . "-" . $num; + } + + /** + * Return next reference not yet used as a reference + * + * @param Societe $objsoc Object third party + * @param Project $ticketsup Object ticketsup + * @return string Next not used reference + */ + public function ticketsup_get_num($objsoc = 0, $ticketsup = '') + { + return $this->getNextValue($objsoc, $ticketsup); + } +} diff --git a/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php b/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php new file mode 100644 index 00000000000..5fe78df4e48 --- /dev/null +++ b/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php @@ -0,0 +1,136 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see http://www.gnu.org/ + */ + +/** + * \file ticketsup/core/modules/ticketsup/mod_ticketsup_universal.php + * \ingroup ticketsup + * \brief Fichier contenant la classe du modele de numerotation de reference de projet Universal + */ + +dol_include_once('/ticketsup/core/modules/modules_ticketsup.php'); + +/** + * Classe du modele de numerotation de reference de projet Universal + */ +class mod_ticketsup_universal extends ModeleNumRefTicketsup +{ + public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' + public $error = ''; + public $nom = 'Universal'; + public $name = 'Universal'; + + /** + * Renvoi la description du modele de numerotation + * + * @return string Texte descripif + */ + public function info() + { + global $conf, $langs; + + $langs->load("ticketsup@ticketsup"); + $langs->load("admin"); + + $form = new Form($this->db); + + $texte = $langs->trans('GenericNumRefModelDesc') . "
    \n"; + $texte .= '
    '; + $texte .= ''; + $texte .= ''; + $texte .= ''; + $texte .= ''; + + $tooltip = $langs->trans("GenericMaskCodes", $langs->transnoentities("Ticketsup"), $langs->transnoentities("Ticketsup")); + $tooltip .= $langs->trans("GenericMaskCodes2"); + $tooltip .= $langs->trans("GenericMaskCodes3"); + $tooltip .= $langs->trans("GenericMaskCodes4a", $langs->transnoentities("Ticketsup"), $langs->transnoentities("Ticketsup")); + $tooltip .= $langs->trans("GenericMaskCodes5"); + + // Parametrage du prefix + $texte .= ''; + $texte .= ''; + + $texte .= ''; + + $texte .= ''; + + $texte .= '
    ' . $langs->trans("Mask") . ':' . $form->textwithpicto('', $tooltip, 1, 1) . ' 
    '; + $texte .= '
    '; + + return $texte; + } + + /** + * Renvoi un exemple de numerotation + * + * @return string Example + */ + public function getExample() + { + global $conf, $langs, $mysoc; + + $old_code_client = $mysoc->code_client; + $mysoc->code_client = 'CCCCCCCCCC'; + $numExample = $this->getNextValue($mysoc, ''); + $mysoc->code_client = $old_code_client; + + if (!$numExample) { + $numExample = $langs->trans('NotConfigured'); + } + return $numExample; + } + + /** + * Return next value + * + * @param Societe $objsoc Object third party + * @param Project $ticketsup Object ticketsup + * @return string Value if OK, 0 if KO + */ + public function getNextValue($objsoc, $ticketsup) + { + global $db, $conf; + + include_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; + + // On defini critere recherche compteur + $mask = $conf->global->TICKETSUP_UNIVERSAL_MASK; + + if (!$mask) { + $this->error = 'NotConfigured'; + return 0; + } + + $date = empty($ticketsup->date_c) ? dol_now() : $ticketsup->datec; + $numFinal = get_next_value($db, $mask, 'ticketsup', 'ref', '', $objsoc->code_client, $date); + + return $numFinal; + } + + /** + * Return next reference not yet used as a reference + * + * @param Societe $objsoc Object third party + * @param Project $ticketsup Object ticketsup + * @return string Next not used reference + */ + public function ticketsup_get_num($objsoc = 0, $ticketsup = '') + { + return $this->getNextValue($objsoc, $ticketsup); + } +} diff --git a/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php b/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php new file mode 100644 index 00000000000..4f757c268ac --- /dev/null +++ b/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php @@ -0,0 +1,308 @@ + + * 2016 Christophe Battarel + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php + * \ingroup core + * \brief Fichier + * \remarks Son propre fichier d'actions peut etre cree par recopie de celui-ci: + * - Le nom du fichier doit etre: interface_99_modMymodule_Mytrigger.class.php + * ou: interface_99_all_Mytrigger.class.php + * - Le fichier doit rester stocke dans core/triggers + * - Le nom de la classe doit etre InterfaceMytrigger + * - Le nom de la propriete name doit etre Mytrigger + */ +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; + +/** + * Class of triggers for ticketsup module + */ +class InterfaceTicketEmail extends DolibarrTriggers +{ + public $db; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + + $this->name = preg_replace('/^Interface/i', '', get_class($this)); + $this->family = "ticketsup"; + $this->description = "Triggers of the module ticketsup"; + $this->version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' or version + $this->picto = 'ticketsup@ticketsup'; + } + + /** + * Return name of trigger file + * + * @return string Name of trigger file + */ + public function getName() + { + return $this->name; + } + + /** + * Return description of trigger file + * + * @return string Description of trigger file + */ + public function getDesc() + { + return $this->description; + } + + /** + * Return version of trigger file + * + * @return string Version of trigger file + */ + public function getVersion() + { + global $langs; + $langs->load("admin"); + + if ($this->version == 'development') { + return $langs->trans("Development"); + } elseif ($this->version == 'experimental') { + return $langs->trans("Experimental"); + } elseif ($this->version == 'dolibarr') { + return DOL_VERSION; + } elseif ($this->version) { + return $this->version; + } else { + return $langs->trans("Unknown"); + } + } + + /** + * Function called when a Dolibarrr business event is done. + * All functions "run_trigger" are triggered if file is inside directory htdocs/core/triggers + * + * @param string $action Event action code + * @param Object $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) + { + $ok = 0; + + switch ($action) { + case 'TICKET_ASSIGNED': + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + + if ($object->fk_user_assign != $user->id) { + $userstat = new User($this->db); + $res = $userstat->fetch($object->fk_user_assign); + if ($res) { + // Send email to assigned user + $subject = '[' . $conf->global->MAIN_INFO_SOCIETE_NOM . '] ' . $langs->transnoentities('TicketAssignedToYou'); + $message = '

    ' . $langs->transnoentities('TicketAssignedEmailBody', $object->track_id, dolGetFirstLastname($user->firstname, $user->lastname)) . "

    "; + $message .= '
    • ' . $langs->trans('Title') . ' : ' . $object->subject . '
    • '; + $message .= '
    • ' . $langs->trans('Type') . ' : ' . $object->type_label . '
    • '; + $message .= '
    • ' . $langs->trans('Category') . ' : ' . $object->category_label . '
    • '; + $message .= '
    • ' . $langs->trans('Severity') . ' : ' . $object->severity_label . '
    • '; + // Extrafields + if (is_array($object->array_options) && count($object->array_options) > 0) { + foreach ($object->array_options as $key => $value) { + $message .= '
    • ' . $langs->trans($key) . ' : ' . $value . '
    • '; + } + } + + $message .= '
    '; + $message .= '

    ' . $langs->trans('Message') . ' :
    ' . $object->message . '

    '; + $message .= '

    ' . $langs->trans('SeeThisTicketIntomanagementInterface') . '

    '; + + $sendto = $userstat->email; + $from = dolGetFirstLastname($user->firstname, $user->lastname) . '<' . $user->email . '>'; + + // Init to avoid errors + $filepath = array(); + $filename = array(); + $mimetype = array(); + + $message = dol_nl2br($message); + + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO; + $conf->global->MAIN_MAIL_AUTOCOPY_TO = ''; + } + include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php'; + $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, '', '', 0, -1); + if ($mailfile->error) { + setEventMessage($mailfile->error, 'errors'); + } else { + $result = $mailfile->sendfile(); + } + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO; + } + + $ok = 1; + } + } + break; + + + case 'TICKET_CREATE': + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + + // Init to avoid errors + $filepath = array(); + $filename = array(); + $mimetype = array(); + + $langs->load('ticketsup@ticketsup'); + + $object->fetch('', $object->track_id); + + /* Send email to admin */ + $sendto = $conf->global->TICKETS_NOTIFICATION_EMAIL_TO; + $subject = '['.$conf->global->MAIN_INFO_SOCIETE_NOM.'] '.$langs->transnoentities('TicketNewEmailSubjectAdmin'); + $message_admin= $langs->transnoentities('TicketNewEmailBodyAdmin', $object->track_id)."\n\n"; + $message_admin.='
    • '.$langs->trans('Title').' : '.$object->subject.'
    • '; + $message_admin.='
    • '.$langs->trans('Type').' : '.$object->type_label.'
    • '; + $message_admin.='
    • '.$langs->trans('Category').' : '.$object->category_label.'
    • '; + $message_admin.='
    • '.$langs->trans('Severity').' : '.$object->severity_label.'
    • '; + $message_admin.='
    • '.$langs->trans('From').' : '.( $object->email_from ? $object->email_from : ( $object->fk_user_create > 0 ? $langs->trans('Internal') : '') ).'
    • '; + // Extrafields + if (is_array($object->array_options) && count($object->array_options) > 0) { + foreach ($object->array_options as $key => $value) { + $message_admin.='
    • '.$langs->trans($key).' : '.$value.'
    • '; + } + } + $message_admin.='
    '; + + if ($object->fk_soc > 0) { + $object->fetch_thirdparty(); + $message_admin.='

    '.$langs->trans('Company'). ' : '.$object->thirdparty->name.'

    '; + } + + $message_admin.='

    '.$langs->trans('Message').' :
    '.$object->message.'

    '; + $message_admin.='

    '.$langs->trans('SeeThisTicketIntomanagementInterface').'

    '; + + $from = $conf->global->MAIN_INFO_SOCIETE_NOM.'<'.$conf->global->TICKETS_NOTIFICATION_EMAIL_FROM.'>'; + $replyto = $from; + + $message_admin = dol_nl2br($message_admin); + + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO; + $conf->global->MAIN_MAIL_AUTOCOPY_TO = ''; + } + include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; + $mailfile = new CMailFile($subject, $sendto, $from, $message_admin, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, -1); + if ($mailfile->error) { + dol_syslog($mailfile->error, LOG_DEBUG); + } else { + $result=$mailfile->sendfile(); + } + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO; + } + + /* Send email to customer */ + $sendto = ''; + if (empty($user->socid) && empty($user->email)) { + $object->fetch_thirdparty(); + $sendto = $object->thirdparty->email; + } else { + $sendto = $user->email; + } + + if ($sendto && $object->notify_tiers_at_create) { + $subject = '['.$conf->global->MAIN_INFO_SOCIETE_NOM.'] '.$langs->transnoentities('TicketNewEmailSubjectCustomer'); + $message_customer= $langs->transnoentities('TicketNewEmailBodyCustomer', $object->track_id)."\n\n"; + $message_customer.='
    • '.$langs->trans('Title').' : '.$object->subject.'
    • '; + $message_customer.='
    • '.$langs->trans('Type').' : '.$object->type_label.'
    • '; + $message_customer.='
    • '.$langs->trans('Category').' : '.$object->category_label.'
    • '; + $message_customer.='
    • '.$langs->trans('Severity').' : '.$object->severity_label.'
    • '; + // Extrafields + if ($conf->global->TICKETS_EXTRAFIELDS_PUBLIC) { + if (is_array($object->array_options) && count($object->array_options) > 0) { + foreach ($object->array_options as $key => $value) { + $message_customer.='
    • '.$langs->trans($key).' : '.$value.'
    • '; + } + } + } + $message_customer.='
    '; + $message_customer.='

    '.$langs->trans('Message').' :
    '.$object->message.'

    '; + $url_public_ticket = ($conf->global->TICKETS_URL_PUBLIC_INTERFACE?$conf->global->TICKETS_URL_PUBLIC_INTERFACE.'/':dol_buildpath('/ticketsup/public/view.php', 2)).'?track_id='.$object->track_id; + $message_customer.='

    ' . $langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : '.$url_public_ticket.'

    '; + $message_customer.='

    '.$langs->trans('TicketEmailPleaseDoNotReplyToThisEmail').'

    '; + + + $from = $conf->global->MAIN_INFO_SOCIETE_NOM.'<'.$conf->global->TICKETS_NOTIFICATION_EMAIL_FROM.'>'; + $replyto = $from; + + // Init to avoid errors + $filepath = array(); + $filename = array(); + $mimetype = array(); + + $message_customer = dol_nl2br($message_customer); + + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO; + $conf->global->MAIN_MAIL_AUTOCOPY_TO = ''; + } + include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; + $mailfile = new CMailFile($subject, $sendto, $from, $message_customer, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, -1); + if ($mailfile->error) { + dol_syslog($mailfile->error, LOG_DEBUG); + } else { + $result=$mailfile->sendfile(); + } + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO; + } + } + $ok = 1; + + break; + + case 'TICKET_DELETE': + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + break; + + case 'TICKET_MODIFY': + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + break; + + case 'TICKET_MARK_READ': + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + break; + + case 'TICKET_CLOSED': + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + break; + } + + + return $ok; + } +} diff --git a/htdocs/install/mysql/data/llx_c_ticketsup_severity.sql b/htdocs/install/mysql/data/llx_c_ticketsup_severity.sql new file mode 100644 index 00000000000..9e356988256 --- /dev/null +++ b/htdocs/install/mysql/data/llx_c_ticketsup_severity.sql @@ -0,0 +1,9 @@ + +-- +-- Contenu de la table llx_c_ticketsup_severity +-- + +INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(1, 'LOW', '10', 'Bas', '', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(2, 'NORMAL', '20', 'Normal', '', 1, 1, NULL); +INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(3, 'LOWHIGH', '30', 'Important', '', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(4, 'HIGH', '40', 'Critique / bloquant', '', 1, 0, NULL); diff --git a/htdocs/install/mysql/data/llx_c_ticketsup_type.sql b/htdocs/install/mysql/data/llx_c_ticketsup_type.sql new file mode 100644 index 00000000000..e5bb1869e5d --- /dev/null +++ b/htdocs/install/mysql/data/llx_c_ticketsup_type.sql @@ -0,0 +1,8 @@ + +-- +-- Contenu de la table llx_c_ticketsup_type +-- +INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(1, 'COM', '10', 'Question commerciale', 1, 1, NULL); +INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(2, 'INCIDENT', '20', 'Demande d''assistance', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(3, 'PROJET', '30', 'Suivi projet', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(4, 'OTHER', '40', 'Autre', 1, 0, NULL); diff --git a/htdocs/install/mysql/data/llx_c_type_contact_ticketsup.sql b/htdocs/install/mysql/data/llx_c_type_contact_ticketsup.sql new file mode 100644 index 00000000000..2e7fe218827 --- /dev/null +++ b/htdocs/install/mysql/data/llx_c_type_contact_ticketsup.sql @@ -0,0 +1,5 @@ + +INSERT INTO llx_c_type_contact (rowid, element, source, code, libelle, active, module) VALUES(110120, 'ticketsup', 'internal', 'SUPPORTTEC', 'Utilisateur contact support', 1, NULL); +INSERT INTO llx_c_type_contact (rowid, element, source, code, libelle, active, module) VALUES(110121, 'ticketsup', 'internal', 'CONTRIBUTOR', 'Intervenant', 1, NULL); +INSERT INTO llx_c_type_contact (rowid, element, source, code, libelle, active, module) VALUES(110122, 'ticketsup', 'external', 'SUPPORTCLI', 'Contact client suivi incident', 1, NULL); +INSERT INTO llx_c_type_contact (rowid, element, source, code, libelle, active, module) VALUES(110123, 'ticketsup', 'external', 'CONTRIBUTOR', 'Intervenant', 1, NULL); diff --git a/htdocs/install/mysql/data/llx_ticketsup.sql b/htdocs/install/mysql/data/llx_ticketsup.sql new file mode 100644 index 00000000000..41c78d32d21 --- /dev/null +++ b/htdocs/install/mysql/data/llx_ticketsup.sql @@ -0,0 +1,17 @@ + +-- +-- Contenu de la table llx_c_ticketsup_type +-- +INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(1, 'COM', '10', 'Question commerciale', 1, 1, NULL); +INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(2, 'INCIDENT', '20', 'Demande d''assistance', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(3, 'PROJET', '30', 'Suivi projet', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(4, 'OTHER', '40', 'Autre', 1, 0, NULL); + +-- +-- Contenu de la table llx_c_ticketsup_severity +-- + +INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(1, 'LOW', '10', 'Bas', '', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(2, 'NORMAL', '20', 'Normal', '', 1, 1, NULL); +INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(3, 'LOWHIGH', '30', 'Important', '', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(4, 'HIGH', '40', 'Critique / bloquant', '', 1, 0, NULL); diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_category.key.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_category.key.sql new file mode 100644 index 00000000000..734fbcc8ece --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_category.key.sql @@ -0,0 +1,18 @@ +-- Copyright (C) 2018 Jean-François FERRY +-- +-- 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, see . +-- +-- + +ALTER TABLE llx_c_ticketsup_category ADD INDEX idx_code (code); diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_category.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_category.sql new file mode 100755 index 00000000000..33b49b12df8 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_category.sql @@ -0,0 +1,27 @@ +-- Copyright (C) 2013-2018 Jean-François FERRY +-- +-- 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, see . +-- +-- + +create table llx_c_ticketsup_category +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + code varchar(32) NOT NULL, + pos varchar(32) NOT NULL, + label varchar(128) NOT NULL, + active integer DEFAULT 1, + use_default integer DEFAULT 1, + description varchar(255) +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_severity.key.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_severity.key.sql new file mode 100644 index 00000000000..a873969876e --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_severity.key.sql @@ -0,0 +1,18 @@ +-- Copyright (C) 2018 Jean-François FERRY +-- +-- 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, see . +-- +-- + +ALTER TABLE llx_c_ticketsup_severity ADD INDEX idx_code (code); diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_severity.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_severity.sql new file mode 100755 index 00000000000..a825000831d --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_severity.sql @@ -0,0 +1,28 @@ +-- Copyright (C) 2013 Jean-François FERRY +-- +-- 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, see . +-- +-- + +create table llx_c_ticketsup_severity +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + code varchar(32) NOT NULL, + pos varchar(32) NOT NULL, + label varchar(128) NOT NULL, + color varchar(10) NOT NULL, + active integer DEFAULT 1, + use_default integer DEFAULT 1, + description varchar(255) +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_type.key.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_type.key.sql new file mode 100644 index 00000000000..d451cc51a39 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_type.key.sql @@ -0,0 +1,18 @@ +-- Copyright (C) 2018 Jean-François FERRY +-- +-- 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, see . +-- +-- + +ALTER TABLE llx_c_ticketsup_type ADD INDEX idx_code (code); diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_type.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_type.sql new file mode 100755 index 00000000000..8983159ec0d --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_type.sql @@ -0,0 +1,27 @@ +-- Copyright (C) 2013 Jean-François FERRY +-- +-- 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, see . +-- +-- + +create table llx_c_ticketsup_type +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + code varchar(32) NOT NULL, + pos varchar(32) NOT NULL, + label varchar(128) NOT NULL, + active integer DEFAULT 1, + use_default integer DEFAULT 1, + description varchar(255) +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_ticketsup.key.sql b/htdocs/install/mysql/tables/llx_ticketsup.key.sql new file mode 100755 index 00000000000..4e06a1d8f44 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_ticketsup.key.sql @@ -0,0 +1,17 @@ +-- SQL definition for module ticketsup +-- Copyright (C) 2013 Jean-François FERRY +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + +ALTER TABLE llx_ticketsup ADD UNIQUE uk_matable_field(rowid, track_id); diff --git a/htdocs/install/mysql/tables/llx_ticketsup.sql b/htdocs/install/mysql/tables/llx_ticketsup.sql new file mode 100644 index 00000000000..5449cf4825d --- /dev/null +++ b/htdocs/install/mysql/tables/llx_ticketsup.sql @@ -0,0 +1,41 @@ +-- SQL definition for module ticketsup +-- Copyright (C) 2013 Jean-François FERRY +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + +CREATE TABLE llx_ticketsup +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, + ref varchar(128) NOT NULL, + track_id varchar(128) NOT NULL, + fk_soc integer DEFAULT 0, + fk_project integer DEFAULT 0, + origin_email varchar(128), + fk_user_create integer, + fk_user_assign integer, + subject varchar(255), + message text, + fk_statut integer, + resolution integer, + progress varchar(100), + timing varchar(20), + type_code varchar(32), + category_code varchar(32), + severity_code varchar(32), + datec datetime, + date_read datetime, + date_close datetime, + tms timestamp +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_ticketsup_extrafields.sql b/htdocs/install/mysql/tables/llx_ticketsup_extrafields.sql new file mode 100644 index 00000000000..0dd82b2566e --- /dev/null +++ b/htdocs/install/mysql/tables/llx_ticketsup_extrafields.sql @@ -0,0 +1,24 @@ +-- Copyright (C) 2013 Jean-François FERRY +-- +-- 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, see . +-- +-- + +create table llx_ticketsup_extrafields +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp, + fk_object integer NOT NULL, -- ticket id + import_key varchar(14) -- import key +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_ticketsup_logs.key.sql b/htdocs/install/mysql/tables/llx_ticketsup_logs.key.sql new file mode 100755 index 00000000000..764a6dc313a --- /dev/null +++ b/htdocs/install/mysql/tables/llx_ticketsup_logs.key.sql @@ -0,0 +1,17 @@ +-- SQL definition for module ticketsup +-- Copyright (C) 2013 Jean-François FERRY +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + +ALTER TABLE llx_ticketsup_logs ADD CONSTRAINT fk_ticketsup_logs_fk_track_id FOREIGN KEY (fk_track_id) REFERENCES llx_ticketsup (fk_track_id); diff --git a/htdocs/install/mysql/tables/llx_ticketsup_logs.sql b/htdocs/install/mysql/tables/llx_ticketsup_logs.sql new file mode 100755 index 00000000000..f573bd5751b --- /dev/null +++ b/htdocs/install/mysql/tables/llx_ticketsup_logs.sql @@ -0,0 +1,25 @@ +-- SQL definition for module ticketsup +-- Copyright (C) 2013 Jean-François FERRY +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + +CREATE TABLE llx_ticketsup_logs +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, + fk_track_id varchar(128), + fk_user_create integer, + datec datetime, + message text +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_ticketsup_msg.key.sql b/htdocs/install/mysql/tables/llx_ticketsup_msg.key.sql new file mode 100755 index 00000000000..098183bdfa0 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_ticketsup_msg.key.sql @@ -0,0 +1,17 @@ +-- SQL definition for module ticketsup +-- Copyright (C) 2013 Jean-François FERRY +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + +ALTER TABLE llx_ticketsup_msg ADD CONSTRAINT fk_ticketsup_msg_fk_track_id FOREIGN KEY (fk_track_id) REFERENCES llx_ticketsup (track_id); diff --git a/htdocs/install/mysql/tables/llx_ticketsup_msg.sql b/htdocs/install/mysql/tables/llx_ticketsup_msg.sql new file mode 100755 index 00000000000..da96d5cfdb0 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_ticketsup_msg.sql @@ -0,0 +1,26 @@ +-- SQL definition for module ticketsup +-- Copyright (C) 2013 Jean-François FERRY +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . + +CREATE TABLE llx_ticketsup_msg +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, + fk_track_id varchar(128), + fk_user_action integer, + datec datetime, + message text, + private integer DEFAULT 0 +)ENGINE=innodb; diff --git a/htdocs/langs/en_US/ticketsup.lang b/htdocs/langs/en_US/ticketsup.lang new file mode 100644 index 00000000000..ebf1f89309a --- /dev/null +++ b/htdocs/langs/en_US/ticketsup.lang @@ -0,0 +1,301 @@ +# en_US lang file for module ticketsup +# Copyright (C) 2013 Jean-François FERRY +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# +# Generic +# + +Module110120Name = Tickets +Module110120Desc = Ticket system for incident management + +Permission110121=See tickets +Permission110122=Modify tickets +Permission110123=Delete tickets +Permission110124=Manage tickets +Permission110125=See tickets of all thirdparties (not effective for external users, always be limited to the thirdparty they depend on) + +TicketsupDictType=Tickets type +TicketsupDictCategory=Tickets categories +TicketsupDictSeverity=Severity classifications +TicketTypeShortBUGSOFT=Dysfonctionnement logiciel +TicketTypeShortBUGHARD=Dysfonctionnement matériel +TicketTypeShortCOM=Commercial question +TicketTypeShortINCIDENT=Request for assistance +TicketTypeShortPROJET=Project +TicketTypeShortOTHER=Other + +TicketSeverityShortLOW=Low +TicketSeverityShortNORMAL=Normal +TicketSeverityShortLOWHIGH=Important +TicketSeverityShortHIGH=Critical + +ErrorBadEmailAddress=Field '%s' incorrect +MenuTicketsupMyAssign=My tickets +MenuTicketsupMyAssignNonClosed=My tickets non closed +MenuListNonClosed=Non closed tickets + +TypeContact_ticketsup_internal_CONTRIBUTOR=Contributor +TypeContact_ticketsup_internal_SUPPORTTEC=Assigned user +TypeContact_ticketsup_external_SUPPORTCLI=Customer contact / incident tracking +TypeContact_ticketsup_external_CONTRIBUTOR=External contributor + +Notify_TICKETMESSAGE_SENTBYMAIL=Send ticket answer by email + +# Status +NotRead=Not read +Read=Read +Answered=Answered +Assigned=Assigned +InProgress=In progress +Waiting=Waiting +Closed=Closed +Deleted=Deleted + +# Dict +Type=Type +Category=Category +Severity=Severity + +# Email templates +MailToSendTicketsupMessage = To send email from ticket message + +# +# Admin page +# +TicketsupSetup = Ticket module setup +TicketSupSettings = Settings +TicketsupSetupPage = +TicketsupPublicAccess = A public interface requiring no identification is available at the following url +TicketsupSetupDictionaries = The type of application categories and severity level are configurable from dictionaries +TicketParamModule=Module variable setup +TicketParamMail=Email setup +TicketEmailNotificationFrom = Notification email from +TicketEmailNotificationFromHelp = Used into ticket message answer by example +TicketEmailNotificationTo = Notifications email to +TicketEmailNotificationToHelp = Send email notifications to this address. +TicketNewEmailBodyLabel=Text message sent after creating a ticket (public interface) +TicketNewEmailBodyHelp=The text specified here will be inserted into the email confirming the creation of a new ticket from the public interface. Information on the consultation of the ticket are automatically added. +TicketParamPublicInterface=Public interface setup +TicketsEmailMustExist=Require an existing email address to create a ticket +TicketsEmailMustExistHelp=In the public interface, the email address should already be filled in the database to create a new ticket. +PublicInterface=Public interface +TicketUrlPublicInterfaceLabelAdmin=Public interface URL +TicketUrlPublicInterfaceHelpAdmin=It is possible to define an alias to the web server and thus make available the public interface to another IP address. +TicketPublicInterfaceTextHomeLabelAdmin=Welcome text of the public interface +TicketPublicInterfaceTextHome=You can create a support ticket or view existing from its identifier tracking ticket. +TicketPublicInterfaceTextHomeHelpAdmin=The text defined here will appear on the home page of the public interface. +TicketPublicInterfaceTopicLabelAdmin=Interface title +TicketPublicInterfaceTopicHelp=This text will appear as the title of the public interface. +TicketPublicInterfaceTextHelpMessageLabelAdmin=Help text to the message entry +TicketPublicInterfaceTextHelpMessageHelpAdmin=This text will appear above the message input area of the user. +ExtraFieldsTicketSup=Extra attributes +TicketSupCkEditorEmailNotActivated=HTML editor is not activated. Please put FCKEDITOR_ENABLE_MAIL contant equal to 1 +TicketsDisableEmail=Do not send ticket creation or message send emails +TicketsDisableEmailHelp=By default, emails are sent when new tickets or messages created. Enable this option to disable *all* email notifications +TicketsLogEnableEmail=Enable log by email +TicketsLogEnableEmailHelp=At each change, an email will be sent **to each contact** associated with the ticket. +TicketParams=Params +TicketsShowModuleLogo=Display the logo of the module in the public interface +TicketsShowModuleLogoHelp=Enable this option to hide the logo module in the pages of the public interface +TicketsShowCompanyLogo=Display the logo of the company in the public interface +TicketsShowCompanyLogoHelp=Enable this option to hide the logo of the main company in the pages of the public interface +TicketsEmailAlsoSendToMainAddress=Also send notification to main email address +TicketsEmailAlsoSendToMainAddressHelp=Enable this option to send an email to "Notification email from" address (see setup below) +TicketsShowExtrafieldsIntoPublicArea=Show Extras fields in the public interface +TicketsShowExtrafieldsIntoPublicAreaHelp=When this option is enabled, additional attributes defined on the tickets will be shown in the public interface of ticket creation. +TicketsLimitViewAssignedOnly=Restrict the display to tickets assigned to the current user (not effective for external users, always be limited to the thirdparty they depend on) +TicketsLimitViewAssignedOnlyHelp=Only tickets assigned to the current user will be visible. Does not apply to a user with tickets management rights. +TicketsActivatePublicInterface=Activate public interface +TicketsActivatePublicInterfaceHelp=Public interface allow any visitors to create tickets. +TicketsAutoAssignTicket=Automatically assign the user who created the ticket +TicketsAutoAssignTicketHelp=When creating a ticket, the user can be automatically assigned to the ticket. +TicketSupNumberingModules=Tickets numbering module +TicketNotNotifyTiersAtCreate=Do not notify the company to the creation + +# +# About page +# +About = About +TicketSupAbout = About ticket module +TicketSupAboutModule = The development of this module has been initiated by the company Libr&thic. +TicketSupAboutModuleHelp=You can get help by using the contact form on the website librethic.io +TicketSupAboutModuleImprove=Feel free to suggest improvements! Please visit the project page on Doliforge website to report bugs and add tasks. +TicketSupAboutModuleThanks=Thanks to nwa who creates icons for this module./ + +# +# Index & list page +# +TicketsIndex=Ticket - home +TicketList=List of tickets +TicketAssignedToMeInfos=This page display ticket list which are assigned to current user +NoTicketsFound=No ticket found +TicketViewAllTickets=View all tickets +TicketViewNonClosedOnly=View only non closed tickets +TicketStatByStatus=Tickets par statut + +# +# Ticket card +# +Ticketsup=Incident ticket +TicketCard=Ticket card +CreateTicket=Create new ticket +EditTicket=Edit ticket +TicketsManagement=Tickets Management +CreatedBy=Created by +NewTicket=New Ticket +SubjectAnswerToTicket=Ticket answer +TicketTypeRequest=Request type +TicketCategory=Category +SeeTicket=See ticket +TicketMarkedAsRead=Ticket has been marked as read +TicketReadOn=Read on +TicketCloseOn=Clotured on +UserAssignedTo=User assigned +MarkAsRead=Mark ticket as read +TicketMarkedAsReadButLogActionNotSaved=Ticket marked as closed but no action saved +TicketHistory=Ticket history +AssignUser=Assign to user +TicketAssigned=Ticket is now assigned +TicketChangeType=Change type +TicketChangeCategory=Change category +TicketChangeSeverity=Change severity +TicketAddMessage=Add a message +TicketEditProperties=Edit properties +AddMessage=Add a message +MessageSuccessfullyAdded=Ticket added +TicketMessageSuccessfullyAdded=Message successfully added +TicketMessagesList=Message list +NoMsgForThisTicket=No message for this ticket +Properties=Classification +LastNewTickets=Last %s tickets newest (not read) +TicketSeverity=Severity +ShowTicket=See ticket +RelatedTickets=Related tickets +TicketAddIntervention=Create intervention +CloseTicket=Close ticket +CloseATicket=Close a ticket +ConfirmCloseAticket=Confirm ticket closing +ConfirmDeleteTicket=Please confirm ticket deleting +TicketDeletedSuccess=Ticket deleted with success +TicketMarkedAsClosed=Ticket marked as closed +TicketMarkedAsClosedButLogActionNotSaved=Ticket marked as closed but no log saved ! +TicketDurationAuto=Calculated duration +TicketDurationAutoInfos=Duration calculated automatically from intervention related +TicketUpdated=Ticket updated +SendMessageByEmail=Send message by email +TicketNewMessage=New message +ErrorMailRecipientIsEmptyForSendTicketMessage=Recipient is empty. No email send +TicketGoIntoContactTab=Please go into "Contacts" tab to select them +TicketMessageMailIntro=Introduction +TicketMessageMailIntroHelp=This text is added only at the beginning of the email and will not be saved. +TicketMessageMailIntroLabelAdmin=Introduction to the message when sending email +TicketMessageMailIntroText=

    Hello A new response was sent on a ticket that you contact. Here is the message: +TicketMessageMailIntroHelpAdmin=This text will be inserted before the text of the response to a ticket. +TicketMessageMailSignature=Signature +TicketMessageMailSignatureHelp=This text is added only at the end of the email and will not be saved. +TicketMessageMailSignatureText=

    Cordialement,

    --

    +TicketMessageMailSignatureLabelAdmin=Signature of response email +TicketMessageMailSignatureHelpAdmin=This text will be inserted after the response message. +TicketMessageHelp=Only this text will be saved in the message list on ticket card. +TicketMessageSubstitutionReplacedByGenericValues=Substitutions variables are replaced by generic values. +TicketTimeToRead=Time elapsed before ticket read +TicketContacts=Contacts ticket +TicketDocumentsLinked=Documents linked to ticket +ConfirmReOpenTicket=Confirm reopen this ticket ? +TicketMessageMailIntroAutoNewPublicMessage=A new message was posted on the ticket with the subject %s : +TicketAssignedToYou=Ticket assigned +TicketAssignedEmailBody=You have been assigned the ticket #%s by %s +MarkMessageAsPrivate=Mark message as private +TicketMessagePrivateHelp=This message will not display to external users +TicketEmailOriginIssuer=Issuer at origin of the tickets +InitialMessage=Initial Message +LinkToAContract=Link to a contract +TicketSupPleaseSelectAContract=Select a contract +UnableToCreateInterIfNoSocid=Can not create a response file without defining a thirdparty +TicketMailExchanges=Mail exchanges +TicketInitialMessageModified=Initial message modified +TicketMessageSuccesfullyUpdated=Message successfully updated +TicketChangeStatus=Change status +TicketConfirmChangeStatus=Confirm the status change : %s ? +TicketLogStatusChanged=Status changed : %s to %s +TicketNotNotifyTiersAtCreate=Not notify company at create + +# +# Logs +# +TicketLogMesgReadBy=Ticket read by %s +NoLogForThisTicket=No log for this ticket yet +TicketLogAssignedTo=Ticket assigned to %s +TicketAssignedButLogActionNotSaved=Ticket assigned but no log saved ! +TicketLogPropertyChanged=Change classification : from %s to %s +TicketLogClosedBy=Ticket closed by %s +TicketLogProgressSetTo=Progress change to %s percent +TicketLogReopen=Ticket re-opened + +# +# Public pages +# +TicketSystem=Ticket system +ShowListTicketWithTrackId=Display ticket list from track ID +ShowTicketWithTrackId=Display ticket from track ID +TicketPublicDesc=You can create a support ticket or check from an existing ID. +YourTicketSuccessfullySaved=Ticket has been successfully saved! +MesgInfosPublicTicketCreatedWithTrackId=A new ticket has been created with ID %s. +PleaseRememberThisId=Please keep the tracking number that we might ask you later. +TicketNewEmailSubject=Ticket creation confirmation +TicketNewEmailSubjectCustomer=New support ticket +TicketNewEmailBody=This is an automatic email to confirm you have registered a new ticket. +TicketNewEmailBodyCustomer=This is an automatic email to confirm a new ticket has just been created into your account. +TicketNewEmailBodyInfosTicket=Information for monitoring the ticket +TicketNewEmailBodyInfosTrackId=Ticket tracking number : %s +TicketNewEmailBodyInfosTrackUrl=You can view the progress of the ticket by clicking the link above. +TicketNewEmailBodyInfosTrackUrlCustomer=You can view the progress of the ticket in the specific interface by clicking the following link +TicketEmailPleaseDoNotReplyToThisEmail=Please do not reply directly to this email! Use the link to reply into the interface. +TicketPublicInfoCreateTicket=This form allows you to record a trouble ticket in our management system. +TicketPublicPleaseBeAccuratelyDescribe=Please accurately describe the problem. Provide the most information possible to allow us to correctly identify your request. +TicketPublicMsgViewLogIn=Please enter ticket tracking ID +TicketTrackId=Tracking ID +OneOfTicketTrackId=One of yours tracking ID +ErrorTicketNotFound=Ticket with tracking ID %s not found ! +Subject=Subject +ViewTicket=View ticket +ViewMyTicketList=View my ticket list +ErrorEmailMustExistToCreateTicket=Error : email address not found in our database +TicketNewEmailSubjectAdmin=New ticket created +TicketNewEmailBodyAdmin=

    Ticket has just been created with ID #%s, see informations :

    +SeeThisTicketIntomanagementInterface=See ticket in management interface +TicketPublicInterfaceForbidden=Access for this area : forbidden + +# notifications +TicketNotificationEmailSubject=Ticket %s updated +TicketNotificationEmailBody=This is an automatic message to notify you that ticket %s has just been updated +TicketNotificationRecipient=Notification recipient +TicketNotificationLogMessage=Log message +TicketNotificationEmailBodyInfosTrackUrlinternal=View ticket into interface +TicketNotificationNumberEmailSent=Notification email sent : %s + + +# +# Boxes +# +BoxLastTicketsup=Last tickets +BoxLastTicketsupDescription=Last %s tickets saved +BoxLastTicketsupContent= +BoxLastTicketsupNoRecordedTickets=No recent unread tickets +BoxLastModifiedTicketsup=Last modified tickets +BoxLastModifiedTicketsupDescription=Last %s tickets modified +BoxLastModifiedTicketsupContent= +BoxLastModifiedTicketsupNoRecordedTickets=No recent modified tickets diff --git a/htdocs/public/ticketsup/create_ticket.php b/htdocs/public/ticketsup/create_ticket.php new file mode 100644 index 00000000000..06c6b85cb02 --- /dev/null +++ b/htdocs/public/ticketsup/create_ticket.php @@ -0,0 +1,384 @@ + + * 2016 Christophe Battarel + * + * 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, see . + */ + +/** + * Display public form to add new ticket + * + * @package ticketsup + */ +if (!defined('NOREQUIREUSER')) { + define('NOREQUIREUSER', '1'); +} + +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); +} + +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +// If there is no menu to show +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +// If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); +define("NOLOGIN", 1); // This means this output page does not require to be logged. +define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. + +// Change this following line to use the correct relative path (../, ../../, etc) +$res = 0; +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} + +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} + +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} + +if (!$res) { + die("Include of main fails"); +} + +dol_include_once('/ticketsup/class/ticketsup.class.php'); +dol_include_once('/ticketsup/class/html.formticketsup.class.php'); +dol_include_once('/ticketsup/lib/ticketsup.lib.php'); + +require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; +require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php'; + +// Load traductions files requiredby by page +$langs->load("companies"); +$langs->load("other"); +$langs->load("mails"); +$langs->load("ticketsup@ticketsup"); + +// Get parameters +$id = GETPOST('id', 'int'); +$msg_id = GETPOST('msg_id', 'int'); + +$action = GETPOST('action', 'alpha'); + +$object = new Ticketsup($db); + +/* + * Add file in email form + */ +if (GETPOST('addfile') && !GETPOST('add_ticket')) { + ////$res = $object->fetch('',GETPOST('track_id')); + ////if($res > 0) + ////{ + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + + // Set tmp directory TODO Use a dedicated directory for temp mails files + $vardir = $conf->ticketsup->dir_output; + $upload_dir_tmp = $vardir . '/temp'; + if (!dol_is_dir($upload_dir_tmp)) { + dol_mkdir($upload_dir_tmp); + } + dol_add_file_process($upload_dir_tmp, 0, 0, 'addedfile'); + $action = 'create_ticket'; + ////} +} + +/* + * Remove file in email form + */ +if (GETPOST('removedfile') && !GETPOST('add_ticket')) { + ////$res = $object->fetch('',GETPOST('track_id')); + ////if($res > 0) + ////{ + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + + // Set tmp directory + $vardir = $conf->ticketsup->dir_output . '/'; + $upload_dir_tmp = $vardir . '/temp'; + + // TODO Delete only files that was uploaded from email form + dol_remove_file_process($_POST['removedfile'], 0); + $action = 'create_ticket'; + ////} +} +if ($action == 'create_ticket' && GETPOST('add_ticket')) { + $error = 0; + $origin_email = GETPOST('email', 'alpha'); + if (empty($origin_email)) { + $error++; + array_push($object->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Email"))); + $action = ''; + } else { + // Search company saved with email + $searched_companies = $object->searchSocidByEmail($origin_email, '0'); + + // Chercher un contact existant avec cette adresse email + // Le premier contact trouvé est utilisé pour déterminer le contact suivi + $contacts = $object->searchContactByEmail($origin_email); + + // Option to require email exists to create ticket + if (!empty($conf->global->TICKETS_EMAIL_MUST_EXISTS) && !$contacts[0]->socid) { + $error++; + array_push($object->errors, $langs->trans("ErrorEmailMustExistToCreateTicket")); + $action = ''; + } + } + + if (!GETPOST("subject")) { + $error++; + array_push($object->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Subject"))); + $action = ''; + } elseif (!GETPOST("message")) { + $error++; + array_push($object->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("message"))); + $action = ''; + } + + // Check email address + if (!isValidEmail($origin_email)) { + $error++; + array_push($object->errors, $langs->trans("ErrorBadEmailAddress", $langs->transnoentities("email"))); + $action = ''; + } + + if (!$error) { + $object->db->begin(); + + $object->track_id = generate_random_id(16); + + $object->subject = GETPOST("subject"); + $object->message = GETPOST("message"); + $object->origin_email = $origin_email; + + $object->type_code = GETPOST("type_code"); + $object->category_code = GETPOST("category_code"); + $object->severity_code = GETPOST("severity_code"); + if (is_array($searched_companies)) { + $object->fk_soc = $searched_companies[0]->id; + } + + if (is_array($contacts) and count($contacts) > 0) { + $object->fk_soc = $contacts[0]->socid; + $usertoassign = $contacts[0]->id; + } + + if (!empty($conf->global->TICKETS_EXTRAFIELDS_PUBLIC) && $conf->global->TICKETS_EXTRAFIELDS_PUBLIC == "1") { + $extrafields = new ExtraFields($db); + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); + } + + // Generate new ref + $object->ref = $object->getDefaultRef(); + if (!is_object($user)) { + $user = new User($db); + } + $id = $object->create($user, 1); // Disable trigger for email (send by this page) + if ($id <= 0) { + $error++; + $errors = ($object->error ? array($object->error) : $object->errors); + array_push($object->errors, $object->error ? array($object->error) : $object->errors); + $action = 'create_ticket'; + } + + if (!$error && $id > 0) { + if ($usertoassign > 0) { + $object->add_contact($usertoassign, "SUPPORTCLI", 'external', $notrigger = 0); + } + + $object->db->commit(); + + $res = $object->fetch($id); + if ($res) { + // Create form object + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + $formmail = new FormMail($db); + + // Init to avoid errors + $filepath = array(); + $filename = array(); + $mimetype = array(); + + $attachedfiles = $formmail->get_attached_files(); + $filepath = $attachedfiles['paths']; + $filename = $attachedfiles['names']; + $mimetype = $attachedfiles['mimes']; + + // Send email to customer + $subject = '[' . $conf->global->MAIN_INFO_SOCIETE_NOM . '] ' . $langs->transnoentities('TicketNewEmailSubject'); + $message .= ($conf->global->TICKETS_MESSAGE_MAIL_NEW ? $conf->global->TICKETS_MESSAGE_MAIL_NEW : $langs->transnoentities('TicketNewEmailBody')) . "\n\n"; + $message .= $langs->transnoentities('TicketNewEmailBodyInfosTicket') . "\n"; + + $url_public_ticket = ($conf->global->TICKETS_URL_PUBLIC_INTERFACE ? $conf->global->TICKETS_URL_PUBLIC_INTERFACE . '/' : dol_buildpath('/ticketsup/public/view.php', 2)) . '?track_id=' . $object->track_id; + $infos_new_ticket = $langs->transnoentities('TicketNewEmailBodyInfosTrackId', '' . $object->track_id . '') . "\n"; + $infos_new_ticket .= $langs->transnoentities('TicketNewEmailBodyInfosTrackUrl') . "\n\n"; + + $message .= dol_nl2br($infos_new_ticket); + $message .= $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE ? $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE : $langs->transnoentities('TicketMessageMailSignatureText'); + + $sendto = GETPOST('email'); + + $from = $conf->global->MAIN_INFO_SOCIETE_NOM . '<' . $conf->global->TICKETS_NOTIFICATION_EMAIL_FROM . '>'; + $replyto = $from; + + $message = dol_nl2br($message); + + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO; + $conf->global->MAIN_MAIL_AUTOCOPY_TO = ''; + } + include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php'; + $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, -1); + if ($mailfile->error) { + setEventMessage($mailfile->error, 'errors'); + } else { + $result = $mailfile->sendfile(); + } + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO; + } + + /* Send email to admin */ + $sendto = $conf->global->TICKETS_NOTIFICATION_EMAIL_TO; + $subject = '[' . $conf->global->MAIN_INFO_SOCIETE_NOM . '] ' . $langs->transnoentities('TicketNewEmailSubjectAdmin'); + $message_admin = $langs->transnoentities('TicketNewEmailBodyAdmin', $object->track_id) . "\n\n"; + $message_admin .= '
    • ' . $langs->trans('Title') . ' : ' . $object->subject . '
    • '; + $message_admin .= '
    • ' . $langs->trans('Type') . ' : ' . $object->type_label . '
    • '; + $message_admin .= '
    • ' . $langs->trans('Category') . ' : ' . $object->category_label . '
    • '; + $message_admin .= '
    • ' . $langs->trans('Severity') . ' : ' . $object->severity_label . '
    • '; + $message_admin .= '
    • ' . $langs->trans('From') . ' : ' . $object->origin_email . '
    • '; + if (is_array($object->array_options) && count($object->array_options) > 0) { + foreach ($object->array_options as $key => $value) { + $message_admin .= '
    • ' . $langs->trans($key) . ' : ' . $value . '
    • '; + } + } + $message_admin .= '
    '; + $message_admin .= '

    ' . $langs->trans('Message') . ' :
    ' . $object->message . '

    '; + $message_admin .= '

    ' . $langs->trans('SeeThisTicketIntomanagementInterface') . '

    '; + + $from = $conf->global->MAIN_INFO_SOCIETE_NOM . '<' . $conf->global->TICKETS_NOTIFICATION_EMAIL_FROM . '>'; + $replyto = $from; + + $message_admin = dol_nl2br($message_admin); + + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO; + $conf->global->MAIN_MAIL_AUTOCOPY_TO = ''; + } + include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php'; + $mailfile = new CMailFile($subject, $sendto, $from, $message_admin, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, -1); + if ($mailfile->error) { + setEventMessage($mailfile->error, 'errors'); + } else { + $result = $mailfile->sendfile(); + } + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO; + } + + // Copy files into ticket directory + $destdir = $conf->ticketsup->dir_output . '/' . $object->track_id; + if (!dol_is_dir($destdir)) { + dol_mkdir($destdir); + } + foreach ($filename as $i => $val) { + dol_move($filepath[$i], $destdir . '/' . $filename[$i], 0, 1); + $formmail->remove_attached_files($i); + } + } + + setEventMessage($langs->trans('YourTicketSuccessfullySaved')); + $action = "infos_success"; + } else { + $object->db->rollback(); + setEventMessage($object->errors, 'errors'); + $action = 'create_ticket'; + } + } else { + setEventMessage($object->errors, 'errors'); + } +} + +/*************************************************** + * PAGE + * + ****************************************************/ + +$arrayofjs = array(); +$arrayofcss = array('/opensurvey/css/style.css', '/ticketsup/css/styles.css', '/ticketsup/css/bg.css.php'); +llxHeaderTicket($langs->trans("CreateTicket"), "", 0, 0, $arrayofjs, $arrayofcss); + +$form = new Form($db); +$formticket = new FormTicketsup($db); + +if (!$conf->global->TICKETS_ENABLE_PUBLIC_INTERFACE) { + print '
    ' . $langs->trans('TicketPublicInterfaceForbidden') . '
    '; + $db->close(); + exit(); +} + +print '
    '; + +if ($action != "infos_success") { + $formticket->withfromsocid = isset($socid) ? $socid : $user->societe_id; + $formticket->withtitletopic = 1; + $formticket->withcompany = 0; + $formticket->withusercreate = 1; + $formticket->fk_user_create = 0; + $formticket->withemail = 1; + $formticket->ispublic = 1; + $formticket->withfile = 2; + if (!empty($conf->global->TICKETS_EXTRAFIELDS_PUBLIC)) { + $formticket->withextrafields = $conf->global->TICKETS_EXTRAFIELDS_PUBLIC; + } + $formticket->action = 'create_ticket'; + + $formticket->param = array('returnurl' => $_SERVER['PHP_SELF']); + + if (empty($defaultref)) { + $defaultref = ''; + } + + print load_fiche_titre($langs->trans('NewTicket'), '', 'ticketsup-32@ticketsup', 0); + + print '
    ' . $langs->trans('TicketPublicInfoCreateTicket') . '
    '; + $formticket->showForm(); +} else { + print '
    ' . $langs->trans('MesgInfosPublicTicketCreatedWithTrackId', '' . $object->track_id . ''); + print '
    '; + print $langs->trans('PleaseRememberThisId'); +} +print '
    '; + +/*************************************************** + * LINKED OBJECT BLOCK + * + * Put here code to view linked object + ****************************************************/ +//$somethingshown=$object->showLinkedObjectBlock(); + +// End of page +$db->close(); +llxFooter(''); diff --git a/htdocs/public/ticketsup/img/bg_ticket.png b/htdocs/public/ticketsup/img/bg_ticket.png new file mode 100644 index 0000000000000000000000000000000000000000..344950d68f39ba20447be510b99302b0932a397d GIT binary patch literal 13264 zcmX|o1z6MH_dlb%rE`RIHv-ZiAqb;mv~-8$00jw&4~le34Qc5bEhW;UWORqLAn3bQ zl{5`;fk!B={d?eVJTDDXUts+Fzb8nED?12ylh#kw#LvLf(J#=(#{n%cFi^nR!`0W$ z#>+v#)5j_M_!%7<8Vj1HilSjq&QWe)3%lxN_iDo^c0Ef0Sc8&M5mT7d@_8y@6AJym zKRjSD+H|a8K7tlZ_muqdw;c3z9C$o@T>4~BQn(aVNHxhNeyxOrM;MO(>S_qw{?R#Y z36YyVIbX(UYA-wRdpYX_*M;P=A%-H4BB^2RkjrjE;34%~B^{#+?JME(GbKnqS{F$u zWss2y6Itqps=aD*fRUl09~Zd3Xf{I~<|Mp$9tH_hG87M4i-k?Y?$JP{pwAc;@E=|t zZ&X!P)mgv^Xk@j5wbBI$2ZSd4cI59tebmQ4r)CIK1o73+cEm)a7UVKdiNB`2e3wSW zo&p*HrG|Qk+;F0#AYq}A2RP(k#>OQux(Grgd~d8!l#qK%D>Y+41uF2FDvA=iF}9|F zK2*McLLXk8$>QMA#VbT>!tZ+{k1~YZk9!eT19G3K*z=<7p~YisPLXl&+Xh92)p(YL zC^gV3x-NS9a84UDn|5=viyxq{6D!zy5O*>rv#-W3bn5XXB*d)kWo6Vy?jSrUx)-Go zr|&)}5&xI?7kU7Ok5pu|v9xkw^1eY5UIJcC@Gj9WcSMjBk(jT2yS z6b(uWnmSey0gA13S)99HdcuxIW=bhVCPhy3N&51c*IW1l{78w1ho=J!mc`fsRoW9@ zBkjs6_b-}8zbmI~uWE1FAyg4mfEpMKrSO;AMkcDN?9qSnwoTg&$m*)U1kTUvxB2}s;g6)F3*ci3~@gMDwrER@Rxm_`_ z_eL4AU{j6c1QQ}(LYR5JpyK1>o5)g$gv@2rAL6`0eY$Eoy!ZG%y(Pi-ychz!$#H4>814 zinf}J5MCF9FuqrIy6&^4fuT745JF{&;Q&dDp*Z0@c(e z%r<&J^pCr2ow(~1xnOlaRoM(flpu^nVjpoBzQE`I)QzAlQ_xiGvBpR}&d1iMVZY(G z>Vj(iAo4Ocp}uYL$mH4kYh^6zNBmRDQ~Q;O#|q7vrNihaed;Rm1QyA0HkNjDj_3x6y_$c3OSRNYsR)43$;n<7kH*hZ?(k`AC9BlObEm>wX+#RC)YD zauXzXjpgnSAO3K3Q?wYQ?dInlaT9^-DIH}Z%Es1)U^SKdY~f$&GEkU!+b3LkgbXp7 z5@>_x-Pv$?)Oal{RqCEpEyxA^8{9epe@FTj(Nc4{t&7yO5CB&hE-YHa?m5D`RvVbemjHf=EIS4qWLtm5;t+DG4 zp~>2+ymr0y^!rL9<14%dDMOcZAs@eTds&TSU7XA?-8ZvrrABH&@~<6{q}-oaK<~e6 zXy1&b?a|Y(#+$1Dj*;y1QCjzVqCKz}{g9x_d$tjQ5Jynz6itcEslESxC#=+7B{vg| zcki1H|8ee!6ynNdnXQ#gtLgn(0oss6>Of8|on}w#4&EjW;p)%Q`}A2P3gw#4`Rjt~ zg&nD?wqJ(gBOAVwiM`;}5K>6LehK@1_0wWZY2^H`skj(mMgzE$0zr%BCW?ZCdm*Kq zldGZh(>!1wcE>`yBb>uv6zrL;`CZY>Kl@4Q4HafPD%29b^NAvQ;Pk$gMq%DgyfwVp z;e`IjIT_tWpW;TTYDRTsgE_q4KPd4HNIVN)zI*(oFsSFANnp-ON~g|DIGL zY1m`~_mlBIj9xLElPg_B!(i|zI(HbEiS^K!#OmGz{O>M}B06d6Cn4*(+pC`h2x9nc zhGa2c!2Qp67pu=L$mFMC%1R~^>|j^BU@zV!WfHq^KUqh59d$hNvDJVxl#9G zOW=3V`rHd>7s5LJdtJ4As?-M|bGoEL@?sHD{BuTmn{I`(+#7JjG!gus&WsdpQlV^EWS>Xu>9hQyfA@dB8DEL9l6adCNNjTHcy zRiHGjekt?Mv^V<@g0P7Nlqx2 zPt~q|Mk99O&P(SqkNb*|-4O$p+rYiygU z_%geJ`L^9rXgWpK-)=$ehFe33`J+PGjId0rbok8|UM#$AC+ikklR2hfQlu&5ar(m7 z@x26A!`FhMA~HO$3#hUb*&i0i7u^zjXLPk;&5lcZX8(+57G`Z%?+J^esV#;-I3Nzj zNsofHuafXZH*=FrL-8GR$BHfn6i)(}&<7>ydgHza)9m=WmpzCgB;aPdK2a%qF8`!B z2z|0u4%wB1QbRgBSN$ComrMK}NZkcEVGjmZC(fwui5PLlIm!|6&*;TL`{BM$X!r@=c zI44?Z@~56OMe2Z(P93ZjFVG`;4rAeX69x$1EEQi%8W!(1QninBUtX5a;mj4E2ax3? z)An92dW|WRzD)E)xOrynjki57#{|5IP3Z2^ZKyJvdhVFwd==5*{%Cd18;0z8!WOMG zuJ6wR$;-4r8@r>t&FRL`XB$oy9ZPm&2h!rcd>~@u+3Fwvy(%XEBBQb?H5Sa#w`d(B z7>e=bqetpar0njf<=l)7GY@$g^B2LL<#Ys3I6oaW-0M0SRTrKIi-QNJ3#KW3A^!qO z8Tb`JKD~N)_r(0Np>~$6_UA5VK7Nd(uohiu41@hwMmMka&d3#5iCng*lJ(IJI|d->zct8g&u8o5VILYlPuGqz}(?R*DlDT$Bn70 zWM#J3p+}$xNzA6ZL}sh<&h(^*->H|kF=YkaS_*A$VcQfns_OZZpZ*hz0}%B|8VC_8 zI5&5mHj5;gf-khfXab&*QCT-l@>`s%C*oR`X&T-p@*c5x--c@^JA0xU^2UWb?&y|- zWI7;AB)qkMB2VK4XRCvrAl1@dBOEwaG&nS<;->j`6QrkyD5gD1S!F1YQ z(JMT1V5aJYnz5ZxOyEz3w|#apdUqM_30ZhHu}T3-R_n z4O9x4C9O4$d}=#|BmM}YBPMyoKW_i;kNglBo6SKnbaq1g-XtayVU(qEz3E}DxoZX} zYl(9sr>tXq->ZCjz%5i$c7kkM>fyZGYBkyep$c4H8xaO@U1Quf5j4i~Ec?>_JxcGg zV^i;uQ12U2{&jVu02S3KQunQ^viB=t(afnPTqfXC_)6b#W8AX!^`Yq7t=egcvW_Z) zyr*sN>VrvI`CS)HtVRxgX_=qI>4VMcYb%n!S9gvY)^?j*$YZIS?`1I|^PeL>h{svc zG+A<#9AIj$`0g>ZIK!OyM77#7nt+U;Fli!Zt99Q{ULL+V6vFD04dgFyyUV-9kIBm7k*}9mK+-7WeGOqk6RS-n|~B~s&+2M zyFj6+;@XWssP-rU7xMt&#PRq*X}k@q_wAc8A&<^>4x_Rq8+SSNo>}d*ZL_~+RQA=T&bd$3^ zz9yGL3&n2GhFVQ0IQ^Xn9WoV0H=sVFU=#Ac#5NCXkE-5fT_6R|qiqmyqt>i@!VK=1 z&CjB1&$&Ms`9I)&O!n_()^9{uQT_QCz5U?*Z;EG~R<7o98< zP3*-R-!`~W?PmdgJ zF`>K{mqfbxT;MeNoJua5yJPye$;7c{j7vj1QUZLprg zh-8MymHe$eIa3#-E_PicV*@xEleU1=Jgu|3-J*&!w>t?C1&vW)$Mz4xvMsKRp=^-x0TMQV8J`N(sxV#Cqgzk2-)3%z z_!fSQvbVESzzaosPlmXXTW0PMsoHZSriEm3ezvTDhwPYoG_!&YB0IAz&SVDT?k6lp zFVFk_c%tka5(g~jSeNQrsEbF>sMye!&<5>{f+cMQ$+*SXZJye#T8av1C3xHJ@Tj3R zmHBx8x@LS!Vled{t%QO-Zkhvz^sY-5O{8r!(w~(TPQ}aiZhC*SEM)QGP}a4rmP~3e z97oj~(@|>oKV;LVSNbxF=){iY3yw>6*tM0M`dSGaF$r)hSlp|h@5LiMpExVWp7D>h zyY~BEtx(70qWz&e^+?^C`7N()&i$n1j8!v7Aj%X?0?Lydg|trF6`{t8`~F|XY!9=u z*YE*iA8y7hS73{Fc=s3Q!@aK{dcNPKJcn-J&=Fn9JnU1#gYbA-{bdSqe-(}8&Wl7e zw?1U-AS-`*4kk{wd}^Htd4U1Tv|Y317(&zZZ7qhVVllutWnuSJ+pkeXpSKp84DesDX&}N|Mwo1Gk~k+TiAP6$ z&`+DOcLt$8lg46BBHNZk{i~{%zoIuP}Q@yfXKUIyjy>oQBG2w0bSBN{iu`ztJ(0ts6xm2qq|)W zPXIKGTerCf9U-%1L&qgh&)`@|K~ zc6DO6h~nX0m<%(h3-#=r12y8_jx^B3LLe<+mdXiq{b_5_!c`^s?;)E zv8qJ46^X?P>OvE|?z0t~f(-o0rQbVy#TfIwF=L=s06E!I0mU;*fmy=pl18!)mr~_$ zaqNt!=Fh{Ib=hJ^yfXszClW9_-u23~O!yftn`md_r~kwnhEShl(Op09U;*>Sf2V7V zSb8!LB6`YmtgPDae-RC>oe1AWD+`Y7Y^bbLwI?F`{Ym2+nF5A|>KnpfB-Ph{lnB#p zyS$}AJTB|q<7p2UN`&5o5Dn6q9a(lqjjbEtU;@h-LvYvrXgndzVE%F>GS*Iny(Ajg zi1Zg-YKmevQSAMi?M2pg>7dO)^nnS=Mz!2^#)vw>u;|Wz-;(u#5c_Tnqe|sLcH7cH zn&DhGB)-X&#sX`TDcKqAEo`3s9iK*ZTe`vGhh$6AMm14W6{8x)Z@h`uc0H>81j1f) zySh%~1dfThIESAtKe(^jR8f=Xuq-g$LcO!kz(^bOlz;XHIu*uI?IgBXFUVQba}{HY zbZzK)fLy*L%&FU~T=`bgFMnW+BPBl2RlMjQl{rr5OoH`PBV8-fnBn8O@X}xun}%X< zZdAm}wAXFL^)WAw=EK-)B?#1ppV3kncQ9FJ8iWb`Y>*$0diX|jPV5@B>C0@c?Dn$L z^h@kBy!y|SIRK1Fm;r%$hJxGF+=lht>voa8D)zIBAV}^9+P2w=Hg{HV^?9W9ko*Rf ze{6`ba^phgff3e^!pE~zy$}uPTyJZwXW-IY6j(|TeQrpHv`JPh&MH9fhgU_-M>bgH zL5v3p+78L-LW7KSes)+>WU%_qQs94`$1YS~cY5%Fy2}B=ojBf%Y8nusqPV!MFWu@y zI!pn{jg5PzXGh5yVSaCvN)hR_pHvk)Y(G_zIP}ae-AU*KJgS%xn4Y_BeCMG&2wCx) zoipQ9QG}nwQ1|$;`0MGm&q(IfAzBySr%F_;J@85S$re*c{#taBDL(cRtc{T9DGpQL zsYktd{5gP&Qq%6AD)OG3i&4>wviB|WTrVgWgE|GIN77AbjAecLQ@$_9m!b4V97T_{ zu$ATs&Ep?^cg1Mm8ZZAeARUD@EYobs{&~5-sTGR*A_X>qo*={Zba%}xCekQ58C`-j zHMlMl_nCR%p$eJzZ~0tkeo45=6`wz=9S~Ark;eA1P2g@af&Ja03<+w&LcISH1U5&- zh=Zxp`UAuQ%WJ^WuaGS=&QxQOAk>Y8tEZI zA$$p(M$_*3GMC;Jmqhx4JVP?sy%N;4$C=?@JV?Q81LirNXi{FUqVLo4x7Ln@2b z+!9KFI$)vTih^$WFH*39avoo8VRVs)pPrhPnCr7**hGTHy?iy^#iN5|)Q|650nfHg zT{@myuH)PZ$iF-vZzv&UPe^EMD|8Q0Bu!+ok&vUxRdB&RMHCpn>w|u9;`1teKlYNO z1bzZ~G!9(p0Z(z!dz_jq9oW&`=ZDQLijUec+(nC5i{MT5Q7SA+U{7B~v9K%pO!{}I zr*R=wy)k}{P{qE3@z&!QUJ~D)OwwcIWEERhOMiM$F#3#i8uP&#k984`T9yzY%~Cms z-Lg89VT!sDXr>HGb8YD2IBaV2c5fF)>ZsUHv~8$kJdXSg@g)1B;*l=hyO{H#@kA_7c{44Jq~=%O9g>Zr0mQ6@@-2=!=wFr zbQ3gCU$TmqtYPe@Cu7~ClzHr~2i?LGBFuMRvqirRr@X@ZFZUsTyMT+@-Ahl2jGemB z*fO-@jp&R&<%SL;~?r%FxGpS#D7Glf43ld zt>_q=>_LiB(Wmf7pfneoXUw^)Jl&1=6%77M=~4Bg1FnB|qc=P(hEJhX{Aqw($v&&; zv5%hGtn!H7H<@enmy{N2WQ0!f!GxzAWEB(L{xo5VoAX4ipY7ev=O51VX_gvx0zqB< zr*l=G92XV(L@7N3|M%HP(Vx#BqJ@`VNKxI?z2`HKEr37v^^?IbNjZrxdY+dr%wZ%p zH(@~Y_l5`+B46)e4&TZjNb2tB%qmCyF;|QKL2+r=b1fJj03fwbPE)=gec{l$VxnU4 zHkg)tuJpr^LUMzIQ|sF+ql?eFDSWE)YoC;mO6!&>u;f=AjMeo~+d8tHZFPtyaJ}zU z0X$EAm8pW%z-!*EZE{hD`HpXC$}0F$c4lr&MIYe+{z{gu z->zLk{;ZmYm;ASXH7T%fQ=W4E+>s2fJYF6k%n=AF|JWG2SwtLi&GwE(W0WLZbIETb zrE1Uw`jl)zK168aC7mF+a#K&&+=PBm6t?<(v5Vq}Xx8N;B*kLJhT6T3n-zCz9cwiL z`}9?h1Eng-J==5Q&%%f;@LAWP;z4oiJ1o)68x#vF9rRc2q;HdFluhizs~`RvugN>H zXRhhaOLv>3xK>y+CKk4?9lpe3HN+8qR)yKaHtznL&?~p3D*fSUuPM~DqbSJngk5XW z;PDfS{$DMwTjLUq?G$Um-FK0es`dwmijXiZ$icLqtU6>PxI4Ac-}sDT?9Io(MP@kD ze-!cIcqhc+nzfta_Laie89ZPu!r&68uOAGCCF5T^$GW8#9r$o)7)H$`K8tk|r@|=R z44nXHMAeDE9Fe!L#2f~FViD&&VIt31n+VFjme=^|zA?Po47p6nGQcAT{#T5vh%QQK zRtdY?9x$U!J1r#tvTYcp^00CiJi@2p%cYjGO|HkV1)@UB192I@^KX)Eqp7U!ku41{Tf$3kChkq&ht1b?x%6PI~j>+v7pGSs2lDvtC zz}(7nsKl($aQlkN#G*EEROGpxen)j8T84UIzaUoSxYKC5^s zIeUBr9xqksBlu73J+IF;8|6PGi{D&yPSn5pKPl_hy*L2ZB7mGn7&sseV}Q-;fq2*-gk3NDYGqf&R!70uGS z1P9<O9B@F$$@v zuJ-zkBI5Sf2|B+8G_q7`4E`b;XXL)n!GncQpT?VNZHy)xetdjQeERh6hfHMA!D)6A zfABy%i)p;kwm7?PXN}sAxEh1R?t#zD&I|)`6Y~TuHG=WStZz;j6{VsKFOdFZ(05Uz zUQz$pI_}uWpSdnzw{DUhK{$(nkYE5ZtaP3hnv(}MT=f)-@^dxf5n!wp*0SQmm2^&Ap`xBNU@ zj$=Oj%d>m+1{nRJ>>kb6$MRjP0}E~X3tiHvFPbya**eMDvRr-QtG$PcBfN!Qv=m-h zIdE??hVqu(z3bnmWRBWqZXybPimO<^d{B^>MArl=-(Ny7ZO-@kt*ehLM2Jx%`??Zz z`&4uNC$G%F?21|2z%UASG{`-p7x$m9>j7JUs`6kNik6wKXx;w*KdxzNZmT(`Ks_DQFxvgv;$PZUO99Ah&xf)IUK|H0b%;~S zDz*hRu(XkK_nh3+zD}inRm-rcrcM@MB%eTAQtr3h0%mxyf*0tBWCj0{ZEI5@3(o?Y z-)i8kZyZfqtr!%wS#;2n+P~*QJo0-W5cc_XO_||0V8@UCByZc~{g!Ptp+mw(Ge6$hw}d|el@&IqJE+PSCiXUk%`}P}AZP-cF63p54GT@6 zG+|cFSXnVTHgM~Zdi^y+_2X-S?M%)cC;cFeoa*Fkq@g0wd_f2no=o>=z$5DHTa=rN z{%UN{bZK1Kio{apz8jFN-go5C;6DwCU!BK36_1;q1lAV=mnUKvJ&o~D{gWDV03gBO znqOg;D#eI*cwA84n$bi>*@Fi#{w2f_!1(EqJ&Mv@f8ae|<#m$E*Bo1W>U8^^+fcXTphLs%N>q>{@jQ#0VjI2Jtj@`ItN&=^P4AlF zUHFF+KZ7+}Z&G6bt%(jj-K$qN(&Ya$mFa~rhLTPH-(hr${T0eZeZZa9yDhJ{-ogj_ z)SS$;Gyrfh;$@YChc6w#4!mB85F=ha;iIr$Di?dY6jrp&+~ZDC?=NtCn!I5hU}DkI)qUZHh=n=lIy z=>I^Yi0WkHie<4>J?KjaSTJ1oV^(+AN&-rprq*XYAYDPCzvaisLPRzp(^*OE6@b*C zTvp*+y7EENBd%SD95bfJw+V|EK*IxuHBf=@(>BM?0!lFd%0J|>s(EbQxAL)DTf>G0 znZDt&WYPs!B#2-ce;VJnLXFwgC_l#6;GToJX4Dc1}bE30r*`dEiN!WEq zFT%~d>E@B>4b4Poklc51xifAU$6ohd^L*&^8Q=uOIzZ*2Hw9=6$ogev@Ju5JQ-O^<7H`%mB zyyVaw6=HwgsDFia4N8Nh4bK483a#_nX5}+BqICuMyW;WqRb1C;cGnH47M2U9poWCZ z-sN+10_|80mnCgyFY%=DG);s6@u)eq=#p5N?A{2%T3AT*6|$1fHDm z{dY#*Xs>^nYxtKT^KZ^M_uBU^rx)jv_7Z8)u#i+Wd8&hK1C-hM0BC%RG%{)0H0Mzw02bfI^GV+G|O}SyrNMReND5MdI@#(2S8wO(i^;aLY;nh+udP z!M`|~Uz5*v-=Vl?Q~3MhS}r+27GUqTwhfV3rGVFdd2n65*`*kuW^BY2V23hoF1$&_ zZVO;?1Z}2tD?q{~%iMNoK73OLReG z1U9!u25t3(tiU-$dx?vq7Nu{1*dszLR)EBY=_ix0<~PPib` zIE?AZ#Z7;T3=s}F3_TSo{SipW$nlRq+gwSB6NnkHSK6vLhs|SE z?z<9?X2mRgdhA6jvqsZxns2EeT4KzOY&ka36 zx1MBg>nkRDf(58X>nJhqz?B-TJH;*&b~-wus(zUwqKzIJ-?NUW0tw`OeNEB6`#a!o z{3PQ?p>G_)M&GRY9)|PW`Z=zIbw=kw9mx)FWRL%L+@rMDv0}#rtgf$`7qSxplrbkUW?WYZ1gt}g zl94zsDD&HUZK*qd#YPCDOEsho;L2D4TMliazHzifvBpiWgwem6qyz4Wv6!&skCv#k z8RZ9>$yBE&m79QfM=>J$S6?g!hrc(qG$&d^?|Lsf-=RokK9U+5CE?6>Wn$`(JxfsR1$HsMoqsI9DfFh_|l0NYn6Qd$V8{xMfO_S|MqfX=e22I%R_vaZYA;eb~bW z%&vE=H$3f>Gw5ob-6yxIU)GXa1C6|Fh|Do-Z9dX2a#TF7?R=D*CeEOzKR^b@WUfIP zLs&m;mv2?=roa_&?DdP#zXSSoi6KG>+{{<*8c%H`W{ zv?|AR26VXYC0rZXzIYVm)Li=nMCvPd?Np7Na5~ZcUyP!{`kdRgF|UnpCD_G)gFRrT z5`j5>M6liBF`bZlzavks_+s#`?`>>EdQjk>FKIT~v8O710>T$=^E4)_(NPCzu zy7^sG$#W}=JoLP;cPGAYRKY1yjB%Pz8aX-ZY_GamJ=VS_EWtW~L)o>v#x76@0tc8P zFj0OZJBJ>zOk;W*D`Ts&{*U4FR_#G6tK`5d1)-6`qpnPX9NZjBor7jI4h?0Mbw7$R z?K%7|_X^ys&#)Dsi{iJtMkX%*rqU@A|B4%BwAy5dISRB2sD7d$N_~+M6UjMAkGRSZ zVzq1}tt;a87529cF<0k_(Ga(HrHGp*0(yeKnzqCjo`Y+%IVbPCh`2=|Bo#VtSQaD= zxOGLctxP60AWpx_Q0_|AQhr!zFML?WW+>9U`0A-F1E_^RSZdb=b6I({@CGl<{f4@W zXwM$bYTkpy|LcvifODWb*b8j8-vx1~4H#UeFaT75%8R^~cQ#pZ_X1r3LwA}zc)3}4 zMTtX$377&S1NTrf@F;;7!#A=L_OEa1PNH-PXuV@2FXOe5I6Njv{OzXOEJ{zoap9&@ z6mct2YF>fK4cMQ;TTKBkmMsz`BZ*QB1QWVpVR;Q`dXV71<#iE)TQ=@)LgW#_sAE`OThK@(i3+dC8x{%9lE@i~em19=CMSgs4 zZrATDJCepw_uA36zF!;5gEwTq%mZlR`wvKEbZOmP=>ogHh}Si0t#-txEMa@OOh4JP zHs-&?2LJ;405~v_8S;_0VnS1u`hSE;(wZtbpI-x=(5J4iRPzA4TLXMIa@e~Gs}{8N zLfTMk{DM>sc09)(JXE9kL=`Y+Y5;D^T5Po(mk3uV`sfFLw;z1k1r24w>jrlrW@)?p zLrsQ3fUm^=L0-%<_u$U(WDI0pw$9Pr_e8ZW(%p9wJxeCbqgH--V7Zp`ND@{X-rj_- Thy#5422E2{SEX7B8ukAGDh4S+ literal 0 HcmV?d00001 diff --git a/htdocs/public/ticketsup/index.php b/htdocs/public/ticketsup/index.php new file mode 100644 index 00000000000..ed141b32922 --- /dev/null +++ b/htdocs/public/ticketsup/index.php @@ -0,0 +1,107 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file ticketsup/public/index.php + * \ingroup ticketsup + * \brief Public file to add and manage ticket + */ + +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +// Do not check anti CSRF attack test +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +// If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); +} +// If this page is public (can be called outside logged session) + +// Change this following line to use the correct relative path (../, ../../, etc) +$res = 0; +if (!$res && file_exists("../main.inc.php")) { + $res = @include '../main.inc.php'; +} + +if (!$res && file_exists("../../main.inc.php")) { + $res = @include '../../main.inc.php'; +} + +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include '../../../main.inc.php'; +} + +if (!$res) { + die("Include of main fails"); +} + +require_once DOL_DOCUMENT_ROOT . '/core/lib/security.lib.php'; + +// Change this following line to use the correct relative path from htdocs +dol_include_once('/ticketsup/class/ticketsup.class.php'); +dol_include_once('/ticketsup/class/html.formticketsup.class.php'); +dol_include_once('/ticketsup/lib/ticketsup.lib.php'); + +// Load traductions files requiredby by page +$langs->load("companies"); +$langs->load("other"); +$langs->load("ticketsup@ticketsup"); +$langs->load("errors"); + +// Get parameters +$track_id = GETPOST('track_id', 'alpha'); +$action = GETPOST('action', 'alpha'); + +/*************************************************** + * VIEW + * + ****************************************************/ +$form = new Form($db); +$formticket = new FormTicketsup($db); + +$arrayofjs = array(); +$arrayofcss = array('/ticketsup/css/styles.css', '/ticketsup/css/bg.css.php'); +llxHeaderTicket($langs->trans("Tickets"), "", 0, 0, $arrayofjs, $arrayofcss); + +if (!$conf->global->TICKETS_ENABLE_PUBLIC_INTERFACE) { + print '
    ' . $langs->trans('TicketPublicInterfaceForbidden') . '
    '; +} else { + print '
    '; + print '

    ' . ($conf->global->TICKETS_PUBLIC_TEXT_HOME ? $conf->global->TICKETS_PUBLIC_TEXT_HOME : $langs->trans("TicketPublicDesc")) . '

    '; + print ''; + print '
    '; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/public/ticketsup/list.php b/htdocs/public/ticketsup/list.php new file mode 100644 index 00000000000..0cbbd65f6b2 --- /dev/null +++ b/htdocs/public/ticketsup/list.php @@ -0,0 +1,703 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file ticketsup/public/index.php + * \ingroup ticketsup + * \brief Public file to add and manage ticket + */ + +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +// Do not check anti CSRF attack test +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +// If there is no need to load and show top and left menu +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); +} +// If this page is public (can be called outside logged session) + +// Change this following line to use the correct relative path (../, ../../, etc) +$res = 0; +if (!$res && file_exists("../main.inc.php")) { + $res = @include '../main.inc.php'; +} + +if (!$res && file_exists("../../main.inc.php")) { + $res = @include '../../main.inc.php'; +} + +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include '../../../main.inc.php'; +} + +if (!$res) { + die("Include of main fails"); +} + +// Change this following line to use the correct relative path from htdocs +dol_include_once('/ticketsup/class/actions_ticketsup.class.php'); +dol_include_once('/ticketsup/class/html.formticketsup.class.php'); +dol_include_once('/ticketsup/lib/ticketsup.lib.php'); + +// Load traductions files requiredby by page +$langs->load("companies"); +$langs->load("other"); +$langs->load("ticketsup@ticketsup"); + +// Get parameters +$track_id = GETPOST('track_id', 'alpha'); +$action = GETPOST('action', 'alpha', 3); +$email = GETPOST('email', 'alpha'); + +if (GETPOST('btn_view_ticket_list')) { + unset($_SESSION['track_id_customer']); + unset($_SESSION['email_customer']); +} +if (isset($_SESSION['track_id_customer'])) { + $track_id = $_SESSION['track_id_customer']; +} +if (isset($_SESSION['email_customer'])) { + $email = $_SESSION['email_customer']; +} + +$object = new ActionsTicketsup($db); + +if ($action == "view_ticketlist") { + $error = 0; + $display_ticket_list = false; + if (!strlen($track_id)) { + $error++; + array_push($object->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("TicketTrackId"))); + $action = ''; + } + + if (!strlen($email)) { + $error++; + array_push($object->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Email"))); + $action = ''; + } else { + if (!isValidEmail($email)) { + $error++; + array_push($object->errors, $langs->trans("ErrorEmailInvalid")); + $action = ''; + } + } + + if (!$error) { + $ret = $object->fetch('', $track_id); + if ($ret && $object->dao->id > 0) { + // vérifie si l'adresse email est bien dans les contacts du ticket + $contacts = $object->dao->liste_contact(-1, 'external'); + foreach ($contacts as $contact) { + if ($contact['email'] == $email) { + $display_ticket_list = true; + $_SESSION['email_customer'] = $email; + $_SESSION['track_id_customer'] = $track_id; + break; + } else { + $display_ticket_list = false; + } + } + + if ($object->dao->fk_soc > 0) { + $object->dao->fetch_thirdparty(); + } + + if ($email == $object->dao->origin_email || $email == $object->dao->thirdparty->email) { + $display_ticket_list = true; + $_SESSION['email_customer'] = $email; + $_SESSION['track_id_customer'] = $track_id; + } + } else { + $error++; + array_push($object->errors, $langs->trans("ErrorTicketNotFound", $track_id)); + $action = ''; + } + } + + if ($error) { + setEventMessage($object->errors, 'errors'); + $action = ''; + } +} +$object->doActions($action); + +/*************************************************** + * VIEW + * + ****************************************************/ + +$form = new Form($db); +$user_assign = new User($db); +$user_create = new User($db); +$formticket = new FormTicketsup($db); + +$arrayofjs = array(); +$arrayofcss = array('/ticketsup/css/styles.css', '/ticketsup/css/bg.css.php'); +llxHeaderTicket($langs->trans("Tickets"), "", 0, 0, $arrayofjs, $arrayofcss); + +if (!$conf->global->TICKETS_ENABLE_PUBLIC_INTERFACE) { + print '
    ' . $langs->trans('TicketPublicInterfaceForbidden') . '
    '; + $db->close(); + exit(); +} + +print '
    '; + +if ($action == "view_ticketlist") { + if ($display_ticket_list) { + // Filters + $search_fk_status = GETPOST("search_fk_status", 'alpha'); + $search_subject = GETPOST("search_subject"); + $search_type = GETPOST("search_type", 'alpha'); + $search_category = GETPOST("search_category", 'alpha'); + $search_severity = GETPOST("search_severity", 'alpha'); + $search_fk_user_create = GETPOST("search_fk_user_create", 'int'); + $search_fk_user_assign = GETPOST("search_fk_user_assign", 'int'); + + // Store current page url + $url_page_current = dol_buildpath('/ticketsup/public/list.php', 1); + + // Do we click on purge search criteria ? + if (GETPOST("button_removefilter_x")) { + $search_fk_status = ''; + $search_subject = ''; + $search_type = ''; + $search_category = ''; + $search_severity = ''; + $search_fk_user_create = ''; + $search_fk_user_assign = ''; + } + + // fetch optionals attributes and labels + $extrafields = new ExtraFields($db); + $extralabels = $extrafields->fetch_name_optionals_label('ticketsup'); + $search_array_options = $extrafields->getOptionalsFromPost($extralabels, '', 'search_'); + + $filter = array(); + $param = ''; + + // Definition of fields for list + $arrayfields = array( + 't.datec' => array('label' => $langs->trans("Date"), 'checked' => 1), + 't.date_read' => array('label' => $langs->trans("TicketReadOn"), 'checked' => 0), + 't.date_close' => array('label' => $langs->trans("TicketCloseOn"), 'checked' => 0), + 't.ref' => array('label' => $langs->trans("Ref"), 'checked' => 1), + 't.fk_statut' => array('label' => $langs->trans("Statut"), 'checked' => 1), + 't.subject' => array('label' => $langs->trans("Subject"), 'checked' => 1), + 'type.code' => array('label' => $langs->trans("Type"), 'checked' => 1), + 'category.code' => array('label' => $langs->trans("Category"), 'checked' => 1), + 'severity.code' => array('label' => $langs->trans("Severity"), 'checked' => 1), + 't.progress' => array('label' => $langs->trans("Progression"), 'checked' => 0), + //'t.fk_contract' => array('label' => $langs->trans("Contract"), 'checked' => 0), + 't.fk_user_create' => array('label' => $langs->trans("Author"), 'checked' => 1), + 't.fk_user_assign' => array('label' => $langs->trans("AuthorAssign"), 'checked' => 0), + + //'t.entity'=>array('label'=>$langs->trans("Entity"), 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode))), + //'t.datec' => array('label' => $langs->trans("DateCreation"), 'checked' => 0, 'position' => 500), + //'t.tms' => array('label' => $langs->trans("DateModificationShort"), 'checked' => 0, 'position' => 2) + //'t.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + ); + + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { + foreach ($extrafields->attribute_label as $key => $val) { + if ($extrafields->attribute_type[$key] != 'separate') { + $arrayfields["ef." . $key] = array('label' => $extrafields->attribute_label[$key], 'checked' => $extrafields->attribute_list[$key], 'position' => $extrafields->attribute_pos[$key], 'enabled' => $extrafields->attribute_perms[$key]); + } + } + } + if (!empty($search_subject)) { + $filter['t.subject'] = $search_subject; + $param .= '&search_subject=' . $search_subject; + } + if (!empty($search_type)) { + $filter['t.type_code'] = $search_type; + $param .= '&search_type=' . $search_type; + } + if (!empty($search_category)) { + $filter['t.category_code'] = $search_category; + $param .= '&search_category=' . $search_category; + } + if (!empty($search_severity)) { + $filter['t.severity_code'] = $search_severity; + $param .= '&search_severity=' . $search_severity; + } + if (!empty($search_fk_user_assign)) { + // -1 value = all so no filter + if ($search_fk_user_assign > 0) { + $filter['t.fk_user_assign'] = $search_fk_user_assign; + $param .= '&search_fk_user_assign=' . $search_fk_user_assign; + } + } + if (!empty($search_fk_user_create)) { + // -1 value = all so no filter + if ($search_fk_user_create > 0) { + $filter['t.fk_user_create'] = $search_fk_user_create; + $param .= '&search_fk_user_create=' . $search_fk_user_create; + } + } + + if ((isset($search_fk_status) && $search_fk_status != '') && $search_fk_status != '-1' && $search_fk_status != 'non_closed') { + $filter['t.fk_statut'] = $search_fk_status; + $param .= '&search_fk_status=' . $search_fk_status; + } + + if (isset($search_fk_status) && $search_fk_status == 'non_closed') { + $filter['t.fk_statut'] = array(0, 1, 3, 4, 5, 6); + $param .= '&search_fk_status=non_closed'; + } + + require DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php'; + + $sortfield = GETPOST("sortfield", 'alpha'); + $sortorder = GETPOST("sortorder", 'alpha'); + + if (!$sortfield) { + $sortfield = 't.datec'; + } + + if (!$sortorder) { + $sortorder = 'DESC'; + } + + $limit = $conf->liste_limit; + + $page = GETPOST("page", 'int'); + if ($page == -1) { + $page = 0; + } + $offset = $limit * $page; + $pageprev = $page - 1; + $pagenext = $page + 1; + + // Request SQL + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.ref,"; + $sql .= " t.track_id,"; + $sql .= " t.fk_soc,"; + $sql .= " t.fk_project,"; + $sql .= " t.origin_email,"; + $sql .= " t.fk_user_create, uc.lastname as user_create_lastname, uc.firstname as user_create_firstname,"; + $sql .= " t.fk_user_assign, ua.lastname as user_assign_lastname, ua.firstname as user_assign_firstname,"; + $sql .= " t.subject,"; + $sql .= " t.message,"; + $sql .= " t.fk_statut,"; + $sql .= " t.resolution,"; + $sql .= " t.progress,"; + $sql .= " t.timing,"; + $sql .= " t.type_code,"; + $sql .= " t.category_code,"; + $sql .= " t.severity_code,"; + $sql .= " t.datec,"; + $sql .= " t.date_read,"; + $sql .= " t.date_close,"; + $sql .= " t.tms"; + $sql .= ", type.label as type_label, category.label as category_label, severity.label as severity_label"; + // Add fields for extrafields + foreach ($extrafields->attribute_list as $key => $val) { + $sql .= ($extrafields->attribute_type[$key] != 'separate' ? ",ef." . $key . ' as options_' . $key : ''); + } + $sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup as t"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_type as type ON type.code=t.type_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_category as category ON category.code=t.category_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_severity as severity ON severity.code=t.severity_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid=t.fk_soc"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user as uc ON uc.rowid=t.fk_user_create"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user as ua ON ua.rowid=t.fk_user_assign"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "element_contact as ec ON ec.element_id=t.rowid"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_type_contact as tc ON ec.fk_c_type_contact=tc.rowid"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "socpeople sp ON ec.fk_socpeople=sp.rowid"; + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "ticketsup_extrafields as ef on (t.rowid = ef.fk_object)"; + } + $sql .= " WHERE t.entity IN (" . getEntity('ticketsup') . ")"; + $sql .= " AND tc.source = 'external'"; + $sql .= " AND tc.element='" . $object->dao->element . "'"; + $sql .= " AND tc.active=1"; + $sql .= " AND (sp.email='" . $db->escape($_SESSION['email_customer']) . "'"; + $sql .= " OR s.email='" . $db->escape($_SESSION['email_customer']) . "'"; + $sql .= " OR t.origin_email='" . $db->escape($_SESSION['email_customer']) . "')"; + // Manage filter + if (!empty($filter)) { + foreach ($filter as $key => $value) { + if (strpos($key, 'date')) { // To allow $filter['YEAR(s.dated)']=>$year + $sql .= ' AND ' . $key . ' = \'' . $value . '\''; + } elseif (($key == 't.fk_user_assign') || ($key == 't.type_code') || ($key == 't.category_code') || ($key == 't.severity_code')) { + $sql .= " AND " . $key . " = '" . $db->escape($value) ."'"; + } elseif ($key == 't.fk_statut') { + if (is_array($value) && count($value) > 0) { + $sql .= 'AND ' . $key . ' IN (' . implode(',', $value) . ')'; + } else { + $sql .= ' AND ' . $key . ' = ' . $db->escape($value); + } + } else { + $sql .= ' AND ' . $key . ' LIKE \'%' . $value . '%\''; + } + } + } + $sql .= " GROUP BY t.track_id"; + $sql .= " ORDER BY " . $sortfield . ' ' . $sortorder; + + $resql = $db->query($sql); + if ($resql) { + $num_total = $db->num_rows($resql); + if (!empty($limit)) { + $sql .= ' ' . $db->plimit($limit + 1, $offset); + } + + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + print_barre_liste($langs->trans('TicketList'), $page, 'public/list.php', $param, $sortfield, $sortorder, '', $num, $num_total, 'ticketsup-32@ticketsup'); + + /* + * Search bar + */ + print '
    ' . "\n"; + print ''; + print ''; + print ''; + print ''; + + $varpage = empty($contextpage) ? $url_page_current : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + + print ''; + + print ''; + if (!empty($arrayfields['t.datec']['checked'])) { + print_liste_field_titre($arrayfields['t.datec']['label'], $url_page_current, 't.datec', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.date_read']['checked'])) { + print_liste_field_titre($arrayfields['t.date_read']['label'], $url_page_current, 't.date_read', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.date_close']['checked'])) { + print_liste_field_titre($arrayfields['t.date_close']['label'], $url_page_current, 't.date_close', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.ref']['checked'])) { + print_liste_field_titre($arrayfields['t.ref']['label'], $url_page_current, 't.ref', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['t.fk_statut']['label'], $url_page_current, 't.fk_statut', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.subject']['checked'])) { + print_liste_field_titre($arrayfields['t.subject']['label']); + } + if (!empty($arrayfields['type.code']['checked'])) { + print_liste_field_titre($arrayfields['type.code']['label'], $url_page_current, 'type.code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['category.code']['checked'])) { + print_liste_field_titre($arrayfields['category.code']['label'], $url_page_current, 'category.code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['severity.code']['checked'])) { + print_liste_field_titre($arrayfields['severity.code']['label'], $url_page_current, 'severity.code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.progress']['checked'])) { + print_liste_field_titre($arrayfields['t.progress']['label'], $url_page_current, 't.progress', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.fk_user_create']['checked'])) { + print_liste_field_titre($arrayfields['t.fk_user_create']['label'], $url_page_current, 't.fk_user_create', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.fk_user_assign']['checked'])) { + print_liste_field_titre($arrayfields['t.fk_user_assign']['label'], $url_page_current, 't.fk_user_assign', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['t.tms']['checked'])) { + print_liste_field_titre($arrayfields['t.tms']['label'], $url_page_current, 't.tms', '', $param, '', $sortfield, $sortorder); + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { + foreach ($extrafields->attribute_label as $key => $val) { + if (!empty($arrayfields["ef." . $key]['checked'])) { + $align = $extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key], $url_page_current, "ef." . $key, "", $param, ($align ? 'align="' . $align . '"' : ''), $sortfield, $sortorder); + } + } + } + print_liste_field_titre($selectedfields, $url_page_current, "", '', '', 'align="right"', $sortfield, $sortorder, 'maxwidthsearch '); + print ''; + + /* + * Filter bar + */ + $formTicket = new FormTicketsup($db); + + print ''; + + if (!empty($arrayfields['t.datec']['checked'])) { + print ''; + } + + if (!empty($arrayfields['t.date_read']['checked'])) { + print ''; + } + if (!empty($arrayfields['t.date_close']['checked'])) { + print ''; + } + + if (!empty($arrayfields['t.ref']['checked'])) { + print ''; + } + + // Status + if (!empty($arrayfields['t.fk_statut']['checked'])) { + print ''; + } + + if (!empty($arrayfields['t.subject']['checked'])) { + print ''; + } + + if (!empty($arrayfields['type.code']['checked'])) { + print ''; + } + + if (!empty($arrayfields['category.code']['checked'])) { + print ''; + } + + if (!empty($arrayfields['severity.code']['checked'])) { + print ''; + } + + if (!empty($arrayfields['t.progress']['checked'])) { + print ''; + } + + if (!empty($arrayfields['t.fk_user_create']['checked'])) { + print ''; + } + + if (!empty($arrayfields['t.fk_user_assign']['checked'])) { + print ''; + } + + if (!empty($arrayfields['t.tms']['checked'])) { + print ''; + } + + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { + foreach ($extrafields->attribute_label as $key => $val) { + if (!empty($arrayfields["ef." . $key]['checked'])) { + print ''; + } + } + } + + print ''; + print ''; + + $var = true; + while ($obj = $db->fetch_object($resql)) { + $var = !$var; + print ""; + + // Date ticket + if (!empty($arrayfields['t.datec']['checked'])) { + print ''; + } + + // Date read + if (!empty($arrayfields['t.date_read']['checked'])) { + print ''; + } + + // Date close + if (!empty($arrayfields['t.date_close']['checked'])) { + print ''; + } + + // ref + if (!empty($arrayfields['t.ref']['checked'])) { + print ''; + } + + // Statut + if (!empty($arrayfields['t.fk_statut']['checked'])) { + print ''; + } + + // Subject + if (!empty($arrayfields['t.subject']['checked'])) { + print ''; + } + + // Type + if (!empty($arrayfields['type.code']['checked'])) { + print ''; + } + + // Category + if (!empty($arrayfields['category.code']['checked'])) { + print ''; + } + + // Severity + if (!empty($arrayfields['severity.code']['checked'])) { + print ''; + } + + // Progression + if (!empty($arrayfields['t.progress']['checked'])) { + print ''; + } + + // Message author + if (!empty($arrayfields['t.fk_user_create']['checked'])) { + print ''; + } + + // Assigned author + if (!empty($arrayfields['t.fk_user_assign']['checked'])) { + print ''; + } + + if (!empty($arrayfields['t.tms']['checked'])) { + print ''; + } + + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { + foreach ($extrafields->attribute_label as $key => $val) { + if (!empty($arrayfields["ef." . $key]['checked'])) { + print 'getAlignFlag($key); + if ($align) { + print ' align="' . $align . '"'; + } + print '>'; + $tmpkey = 'options_' . $key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + } + } + } + print ''; + $i++; + print ''; + } + + print '
    '; + $selected = ($search_fk_status != "non_closed" ? $search_fk_status : ''); + $object->printSelectStatus($selected); + print ''; + print ''; + print ''; + $formTicket->selectTypesTickets($search_type, 'search_type', '', 2, 1, 1); + print ''; + $formTicket->selectCategoriesTickets($search_category, 'search_category', '', 2, 1, 1); + print ''; + $formTicket->selectSeveritiesTickets($search_severity, 'search_severity', '', 2, 1, 1); + print ''; + print ''; + print ''; + print '
    '; + print dol_print_date($obj->datec, 'dayhour'); + print ''; + print dol_print_date($obj->date_read, 'dayhour'); + print ''; + print dol_print_date($obj->date_close, 'dayhour'); + print ''; + print $obj->ref; + print ''; + $object->fk_statut = $obj->fk_statut; + print $object->getLibStatut(2); + print ''; + print '' . $obj->subject . ''; + print ''; + print $obj->type_label; + print ''; + print $obj->category_label; + print ''; + print $obj->severity_label; + print ''; + print $obj->progress; + print ''; + if ($obj->fk_user_create) { + $user_create->firstname = (!empty($obj->user_create_firstname) ? $obj->user_create_firstname : ''); + $user_create->name = (!empty($obj->user_create_lastname) ? $obj->user_create_lastname : ''); + $user_create->id = (!empty($obj->fk_user_create) ? $obj->fk_user_create : ''); + print $user_create->getFullName(); + } else { + print $langs->trans('Email'); + } + print ''; + if ($obj->fk_user_assign) { + $user_assign->firstname = (!empty($obj->user_assign_firstname) ? $obj->user_assign_firstname : ''); + $user_assign->lastname = (!empty($obj->user_assign_lastname) ? $obj->user_assign_lastname : ''); + $user_assign->id = (!empty($obj->fk_user_assign) ? $obj->fk_user_assign : ''); + print $user_assign->getFullName(); + } else { + print $langs->trans('None'); + } + print '' . dol_print_date($obj->tms, 'dayhour') . '
    '; + print '
    '; + + print '"; + print ''; + } + } + } else { + print ''; + } +} else { + print '

    ' . $langs->trans("TicketPublicMsgViewLogIn") . '

    '; + + print '
    '; + print '
    '; + print ''; + print ''; + print ''; + + print '

    '; + print ''; + print '

    '; + + print '

    '; + print ''; + print '

    '; + + print '

    '; + print ''; + print "

    \n"; + + print "
    \n"; + print "
    \n"; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/public/ticketsup/view.php b/htdocs/public/ticketsup/view.php new file mode 100644 index 00000000000..036d1d17b86 --- /dev/null +++ b/htdocs/public/ticketsup/view.php @@ -0,0 +1,337 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file ticketsup/public/index.php + * \ingroup ticketsup + * \brief Public file to add and manage ticket + */ + +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); +} +// Do not check anti CSRF attack test +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +// If there is no need to load and show top and left menu +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); +} +// If this page is public (can be called outside logged session) + +// Change this following line to use the correct relative path (../, ../../, etc) +$res = 0; +if (!$res && file_exists("../main.inc.php")) { + $res = @include '../main.inc.php'; +} + +if (!$res && file_exists("../../main.inc.php")) { + $res = @include '../../main.inc.php'; +} + +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include '../../../main.inc.php'; +} + +if (!$res) { + die("Include of main fails"); +} + +// Change this following line to use the correct relative path from htdocs +dol_include_once('/ticketsup/class/actions_ticketsup.class.php'); +dol_include_once('/ticketsup/class/html.formticketsup.class.php'); +dol_include_once('/ticketsup/lib/ticketsup.lib.php'); + +// Load traductions files requiredby by page +$langs->load("companies"); +$langs->load("other"); +$langs->load("ticketsup@ticketsup"); + +// Get parameters +$track_id = GETPOST('track_id', 'alpha'); +$action = GETPOST('action', 'alpha', 3); +$email = GETPOST('email', 'alpha'); + +if (GETPOST('btn_view_ticket')) { + unset($_SESSION['email_customer']); +} +if (isset($_SESSION['email_customer'])) { + $email = $_SESSION['email_customer']; +} + +$object = new ActionsTicketsup($db); + +if ($action == "view_ticket" || $action == "add_message" || $action == "close" || $action == "confirm_public_close" || $action == "new_public_message") { + $error = 0; + $display_ticket = false; + if (!strlen($track_id)) { + $error++; + array_push($object->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("TicketTrackId"))); + $action = ''; + } + + if (!strlen($email)) { + $error++; + array_push($object->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Email"))); + $action = ''; + } else { + if (!isValidEmail($email)) { + $error++; + array_push($object->errors, $langs->trans("ErrorEmailInvalid")); + $action = ''; + } + } + + if (!$error) { + $ret = $object->fetch('', $track_id); + if ($ret && $object->dao->id > 0) { + // vérifie si l'adresse email est bien dans les contacts du ticket + $contacts = $object->dao->liste_contact(-1, 'external'); + foreach ($contacts as $contact) { + if ($contact['email'] == $email) { + $display_ticket = true; + $_SESSION['email_customer'] = $email; + break; + } else { + $display_ticket = false; + } + } + + if ($object->dao->fk_soc > 0) { + $object->dao->fetch_thirdparty(); + } + + if ($email == $object->dao->origin_email || $email == $object->dao->thirdparty->email) { + $display_ticket = true; + $_SESSION['email_customer'] = $email; + } + } else { + $error++; + array_push($object->errors, $langs->trans("ErrorTicketNotFound", $track_id)); + $action = ''; + } + } + + if ($error) { + setEventMessage($object->errors, 'errors'); + $action = ''; + } +} +$object->doActions($action); + +/*************************************************** + * VIEW + * + ****************************************************/ + +$form = new Form($db); +$formticket = new FormTicketsup($db); + +$arrayofjs = array(); +$arrayofcss = array('/ticketsup/css/styles.css', '/ticketsup/css/bg.css.php'); +llxHeaderTicket($langs->trans("Tickets"), "", 0, 0, $arrayofjs, $arrayofcss); + +if (!$conf->global->TICKETS_ENABLE_PUBLIC_INTERFACE) { + print '
    ' . $langs->trans('TicketPublicInterfaceForbidden') . '
    '; + $db->close(); + exit(); +} + +print '
    '; + +if ($action == "view_ticket" || $action == "add_message" || $action == "close" || $action == "confirm_public_close") { + if ($display_ticket) { + // Confirmation close + if ($action == 'close') { + $ret = $form->form_confirm($_SERVER["PHP_SELF"] . "?track_id=" . $track_id, $langs->trans("CloseATicket"), $langs->trans("ConfirmCloseAticket"), "confirm_public_close", '', '', 1); + if ($ret == 'html') { + print '
    '; + } + } + + print '
    '; + + print ''; + + // Ref + print ''; + + // Tracking ID + print ''; + + // Subject + print ''; + + // Statut + print ''; + + // Type + print ''; + + // Category + print ''; + + // Severity + print ''; + + // Creation date + print ''; + + // Author + print ''; + + // Read date + if (!empty($object->dao->date_read)) { + print ''; + } + + // Close date + if (!empty($object->dao->date_close)) { + print ''; + } + + // User assigned + print ''; + + // Progression + print ''; + + print '
    ' . $langs->trans("Ref") . ''; + print $object->dao->ref; + print '
    ' . $langs->trans("TicketTrackId") . ''; + print $object->dao->track_id; + print '
    ' . $langs->trans("Subject") . ''; + print $object->dao->subject; + print '
    ' . $langs->trans("Status") . ''; + print $object->dao->getLibStatut(2); + print '
    ' . $langs->trans("Type") . ''; + print $object->dao->type_label; + print '
    ' . $langs->trans("Category") . ''; + print $object->dao->category_label; + print '
    ' . $langs->trans("Severity") . ''; + print $object->dao->severity_label; + print '
    ' . $langs->trans("DateCreation") . ''; + print dol_print_date($object->dao->datec, 'dayhour'); + print '
    ' . $langs->trans("Author") . ''; + if ($object->dao->fk_user_create > 0) { + $langs->load("users"); + $fuser = new User($db); + $fuser->fetch($object->dao->fk_user_create); + print $fuser->getFullName($langs); + } else { + print $object->dao->origin_email; + } + + print '
    ' . $langs->trans("TicketReadOn") . ''; + print dol_print_date($object->dao->date_read, 'dayhour'); + print '
    ' . $langs->trans("TicketCloseOn") . ''; + print dol_print_date($object->dao->date_close, 'dayhour'); + print '
    ' . $langs->trans("UserAssignedTo") . ''; + if ($object->dao->fk_user_assign > 0) { + $fuser = new User($db); + $fuser->fetch($object->dao->fk_user_assign); + print $fuser->getFullName($langs, 1); + } else { + print $langs->trans('None'); + } + print '
    ' . $langs->trans("Progression") . ''; + print ($object->dao->progress > 0 ? $object->dao->progress : '0') . '%'; + print '
    '; + + print '
    '; + + print '
    '; + + if ($action == 'add_message') { + print load_fiche_titre($langs->trans('TicketAddMessage'), '', 'messages@ticketsup'); + + $formticket = new FormTicketsup($db); + + $formticket->action = "new_public_message"; + $formticket->track_id = $object->dao->track_id; + $formticket->id = $object->dao->id; + + $formticket->param = array('fk_user_create' => '-1'); + + $formticket->withfile = 2; + $formticket->showMessageForm('100%'); + } else { + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print "
    \n"; + + print '
    '; + // List ticket + print ''; + + if ($object->dao->fk_statut < 8) { + // New message + print ''; + + // Close ticket + if ($object->dao->fk_statut > 0 && $object->dao->fk_statut < 8) { + print ''; + } + } + + print '
    '; + } + + // Message list + print load_fiche_titre($langs->trans('TicketMessagesList'), '', 'messages@ticketsup'); + $object->viewTicketMessages(false); + + print '
    '; + + // Logs list + print load_fiche_titre($langs->trans('TicketHistory'), '', 'history@ticketsup'); + $object->viewTicketLogs(false); + } else { + print ''; + } +} else { + print '

    ' . $langs->trans("TicketPublicMsgViewLogIn") . '

    '; + + print '
    '; + print '
    '; + print ''; + print ''; + + print '

    '; + print ''; + print '

    '; + + print '

    '; + print ''; + print '

    '; + + print '

    '; + print ''; + print "

    \n"; + + print "
    \n"; + print "
    \n"; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/ticketsup/.gitignore b/htdocs/ticketsup/.gitignore new file mode 100755 index 00000000000..32dd28ee407 --- /dev/null +++ b/htdocs/ticketsup/.gitignore @@ -0,0 +1,19 @@ +# Generated binaries +/build/*.zip +# Doxygen generated documentation +/build/doxygen/doxygen_warnings.log +/doc/code/doxygen +# Composer managed dependencies +/vendor/ +/dev/bin +# PHPdocumentor generated files +/build/phpdoc +/doc/code/phpdoc +# Sphinx generated files +/doc/user/build +/.settings/ +/.buildpath +/.project +/test/report +# PhpStorm generated files +/.idea/ diff --git a/htdocs/ticketsup/.tx/config b/htdocs/ticketsup/.tx/config new file mode 100644 index 00000000000..9af4e566424 --- /dev/null +++ b/htdocs/ticketsup/.tx/config @@ -0,0 +1,10 @@ +[main] +host = https://www.transifex.com + +[dolibarr_tickets.ticketsuplang] +file_filter = langs//ticketsup.lang +source_file = langs/en_US/ticketsup.lang +source_lang = en_US +type = MOZILLAPROPERTIES + + diff --git a/htdocs/ticketsup/card.php b/htdocs/ticketsup/card.php new file mode 100644 index 00000000000..cd638fb3eff --- /dev/null +++ b/htdocs/ticketsup/card.php @@ -0,0 +1,795 @@ + + * 2016 Christophe Battarel + * + * 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, see . + */ + +/** + * Card of ticket + * + * @package ticketsup + */ + +// Change this following line to use the correct relative path (../, ../../, etc) +$res = 0; +if (file_exists("../main.inc.php")) { + $res = include "../main.inc.php"; // From htdocs directory +} elseif (!$res && file_exists("../../main.inc.php")) { + $res = include "../../main.inc.php"; // From "custom" directory +} else { + die("Include of main fails"); +} + +require_once 'class/actions_ticketsup.class.php'; +require_once 'class/html.formticketsup.class.php'; +require_once 'lib/ticketsup.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; +if (!empty($conf->projet->enabled)) { + include DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; + include_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php'; +} +if (!empty($conf->contrat->enabled)) { + include_once DOL_DOCUMENT_ROOT . '/core/lib/contract.lib.php'; + include_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php'; + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formcontract.class.php'; +} + +if (!class_exists('Contact')) { + include DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; +} + +// Load traductions files requiredby by page +$langs->load("companies"); +$langs->load("other"); +$langs->load("ticketsup@ticketsup"); + +// Get parameters +$id = GETPOST('id', 'int'); +$track_id = GETPOST('track_id', 'alpha', 3); +$action = GETPOST('action', 'alpha', 3); +$ref = GETPOST('ref', 'alpha'); +$projectid = GETPOST('projectid', 'int'); + +// Initialize technical object to manage hooks of ticketsup. Note that conf->hooks_modules contains array array +$hookmanager->initHooks(array('ticketsupcard','globalcard')); + +$object = new ActionsTicketsup($db); +$object->doActions($action); + +$extrafields = new ExtraFields($db); +$extralabels = $extrafields->fetch_name_optionals_label($object->dao->table_element); + +if (!$action) { + $action = 'view'; +} +//Select mail models is same action as add_message +if (GETPOST('modelselected')) { + $action = 'add_message'; +} + +// Store current page url +$url_page_current = dol_buildpath('/ticketsup/card.php', 1); + +/*************************************************** + * PAGE + * + ****************************************************/ + +$userstat = new User($db); +$form = new Form($db); +$formticket = new FormTicketsup($db); + +if ($action == 'view' || $action == 'add_message' || $action == 'close' || $action == 'delete' || $action == 'editcustomer' || $action == 'progression' || $action == 'reopen' || $action == 'editsubject' || $action == 'edit_extrafields' || $action == 'set_extrafields' || $action == 'classify' || $action == 'sel_contract' || $action == 'edit_message_init' || $action == 'set_status' || $action == 'dellink') { + $res = $object->fetch($id, $track_id, $ref); + + if ($res > 0) { + // Security check + $result = restrictedArea($user, 'ticketsup', $object->dao->id); + + // or for unauthorized internals users + if (!$user->societe_id && ($conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY && $object->dao->fk_user_assign != $user->id) && !$user->rights->ticketsup->manage) { + accessforbidden('', 0); + } + + + $permissiondellink = $user->rights->ticketsup->write; + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + + + $help_url = 'FR:DocumentationModuleTicket'; + $page_title = $object->getTitle($action); + llxHeader('', $page_title, $help_url); + + // Confirmation close + if ($action == 'close') { + print $form->formconfirm($url_page_current . "?track_id=" . $track_id, $langs->trans("CloseATicket"), $langs->trans("ConfirmCloseAticket"), "confirm_close", '', '', 1); + if ($ret == 'html') { + print '
    '; + } + } + // Confirmation delete + if ($action == 'delete') { + print $form->formconfirm($url_page_current . "?track_id=" . $track_id, $langs->trans("Delete"), $langs->trans("ConfirmDeleteTicket"), "confirm_delete_ticket", '', '', 1); + } + // Confirm reopen + if ($action == 'reopen') { + print $form->formconfirm($url_page_current . '?track_id=' . $track_id, $langs->trans('ReOpen'), $langs->trans('ConfirmReOpenTicket'), 'confirm_reopen', '', '', 1); + } + // Confirmation status change + if ($action == 'set_status') { + $new_status = GETPOST('new_status'); + print $form->formconfirm($url_page_current . "?track_id=" . $track_id . "&new_status=" . GETPOST('new_status'), $langs->trans("TicketChangeStatus"), $langs->trans("TicketConfirmChangeStatus", $langs->transnoentities($object->dao->statuts_short[$new_status])), "confirm_set_status", '', '', 1); + } + + // project info + if ($projectid) { + $projectstat = new Project($db); + if ($projectstat->fetch($projectid) > 0) { + $projectstat->fetch_thirdparty(); + + // To verify role of users + //$userAccess = $object->restrictedProjectArea($user,'read'); + $userWrite = $projectstat->restrictedProjectArea($user, 'write'); + //$userDelete = $object->restrictedProjectArea($user,'delete'); + //print "userAccess=".$userAccess." userWrite=".$userWrite." userDelete=".$userDelete; + + $head = project_prepare_head($projectstat); + dol_fiche_head($head, 'ticketsup', $langs->trans("Project"), 0, ($projectstat->public ? 'projectpub' : 'project')); + + /* + * Projet synthese pour rappel + */ + print ''; + + $linkback = '' . $langs->trans("BackToList") . ''; + + // Ref + print ''; + + // Label + print ''; + + // Customer + print ""; + print ''; + + // Visibility + print ''; + + // Statut + print ''; + + print "
    ' . $langs->trans('Ref') . ''; + // Define a complementary filter for search of next/prev ref. + if (!$user->rights->projet->all->lire) { + $objectsListId = $projectstat->getProjectsAuthorizedForUser($user, $mine, 0); + $projectstat->next_prev_filter = " rowid in (" . (count($objectsListId) ? join(',', array_keys($objectsListId)) : '0') . ")"; + } + print $form->showrefnav($projectstat, 'ref', $linkback, 1, 'ref', 'ref', ''); + print '
    ' . $langs->trans("Label") . '' . $projectstat->title . '
    " . $langs->trans("ThirdParty") . "'; + if ($projectstat->thirdparty->id > 0) { + print $projectstat->thirdparty->getNomUrl(1); + } else { + print ' '; + } + + print '
    ' . $langs->trans("Visibility") . ''; + if ($projectstat->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } + + print '
    ' . $langs->trans("Status") . '' . $projectstat->getLibStatut(4) . '
    "; + + print '
    '; + } else { + print "ErrorRecordNotFound"; + } + } elseif ($object->dao->fk_soc > 0) { + $object->dao->fetch_thirdparty(); + $head = societe_prepare_head($object->dao->thirdparty); + dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); + dol_banner_tab($object->dao->thirdparty, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); + dol_fiche_end(); + } + + if (!$user->societe_id && $conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY) { + $object->dao->next_prev_filter = "te.fk_user_assign = '" . $user->id . "'"; + } elseif ($user->societe_id > 0) { + $object->dao->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; + } + + $head = ticketsup_prepare_head($object->dao); + dol_fiche_head($head, 'tabTicketsup', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + $object->dao->label = $object->dao->ref; + // Author + if ($object->dao->fk_user_create > 0) { + $object->dao->label .= ' - ' . $langs->trans("CreatedBy") . ' '; + + $langs->load("users"); + $fuser = new User($db); + $fuser->fetch($object->dao->fk_user_create); + $object->dao->label .= $fuser->getNomUrl(0); + } + if (!empty($object->dao->origin_email)) { + $object->dao->label .= ' - ' . $langs->trans("CreatedBy") . ' '; + $object->dao->label .= $object->dao->origin_email . ' (' . $langs->trans("TicketEmailOriginIssuer") . ')'; + } + $linkback = '' . $langs->trans("BackToList") . ' '; + $object->dao->ticketsup_banner_tab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + + print '
    '; + print '
    '; + print ''; + + // Track ID + print ''; + + // Subject + print ''; + + // Creation date + print ''; + + // Read date + if (!empty($object->dao->date_read)) { + print ''; + + print ''; + } + + // Close date + if (!empty($object->dao->date_close)) { + print ''; + } + + print ''; + + // Customer + print ''; + + // Project + if (!empty($conf->projet->enabled)) { + $langs->load('projects'); + print ''; + } + + // User assigned + print ''; + + // Progression + print ''; + print ''; + + // Timing (Duration sum of linked fichinter + $object->dao->fetchObjectLinked(); + $num = count($object->dao->linkedObjects); + $timing = 0; + if ($num) { + foreach ($object->dao->linkedObjects as $objecttype => $objects) { + if ($objecttype = "fichinter") { + foreach ($objects as $fichinter) { + $timing += $fichinter->duration; + } + } + } + } + print ''; + + // Other attributes + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if (empty($reshook) && !empty($extrafields->attribute_label)) { + if ($action == "edit_extrafields") { + print ''; + print ''; + print ''; + print ''; + + print $object->dao->showOptionals($extrafields, 'edit'); + print ''; + print ''; + } else { + print $object->dao->showOptionals($extrafields); + if ($user->rights->ticketsup->write) { + print ''; + } + } + } + print '
    ' . $langs->trans("TicketTrackId") . ''; + if (!empty($object->dao->track_id)) { + if (empty($object->dao->ref)) { + $object->ref = $object->dao->id; + print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'track_id'); + } else { + print $object->dao->track_id; + } + } else { + print $langs->trans('None'); + } + print '
    '; + print $form->editfieldkey("Subject", 'subject', $object->dao->subject, $object->dao, $user->rights->ticketsup->write && !$user->societe_id, 'string'); + print ''; + print $form->editfieldval("Subject", 'subject', $object->dao->subject, $object->dao, $user->rights->ticketsup->write && !$user->societe_id, 'string'); + print '
    ' . $langs->trans("DateCreation") . ''; + print dol_print_date($object->dao->datec, 'dayhour'); + print '
    ' . $langs->trans("TicketReadOn") . ''; + print dol_print_date($object->dao->date_read, 'dayhour'); + print '
    ' . $langs->trans("TicketTimeToRead") . ''; + print '' . convertSecondToTime($object->dao->date_read - $object->dao->datec) . ''; + print '
    ' . $langs->trans("TicketCloseOn") . ''; + print dol_print_date($object->dao->date_close, 'dayhour'); + print '
    '; + print ''; + if ($action != 'editcustomer' && $object->dao->fk_statut < 8 && !$user->societe_id && $user->rights->ticketsup->write) { + print ''; + } + print '
    '; + print $langs->trans('Customer'); + print '' . img_edit($langs->transnoentitiesnoconv('Edit'), 1) . '
    '; + print '
    '; + + if ($action == 'editcustomer') { + $form->form_thirdparty($url_page_current . '?track_id=' . $object->dao->track_id, $object->dao->fk_soc, 'editcustomer', ($object->dao->fk_soc ? 's.rowid <> ' . $object->dao->fk_soc : ''), 1); + } else { + $form->form_thirdparty($url_page_current . '?track_id=' . $object->dao->track_id, $object->dao->fk_soc, 'none', 's.rowid <> ' . $object->dao->fk_soc, 1); + } + print '
    '; + print ''; + if ($action != 'classify' && $user->rights->ticketsup->write) { + print ''; + } + + print '
    '; + print $langs->trans('Project'); + print '' . img_edit($langs->trans('SetProject')) . '
    '; + print '
    '; + if ($action == 'classify') { + $form->form_project($url_page_current . '?track_id=' . $object->dao->track_id, $object->dao->socid, $object->dao->fk_project, 'projectid'); + } else { + $form->form_project($url_page_current . '?track_id=' . $object->dao->track_id, $object->dao->socid, $object->dao->fk_project, 'none'); + } + print '
    ' . $langs->trans("UserAssignedTo") . ''; + if ($object->dao->fk_user_assign > 0) { + $userstat->fetch($object->dao->fk_user_assign); + print $userstat->getNomUrl(1); + } else { + print $langs->trans('None'); + } + + // Show user list to assignate one if status is "read" + if (GETPOST('set') == "assign_ticket" && $object->dao->fk_statut < 8 && !$user->societe_id && $user->rights->ticketsup->write) { + print '
    '; + print ''; + print ''; + print ''; + print ' '; + print $form->select_dolusers($user->id, 'fk_user_assign', 0); + print ' '; + print '
    '; + } + if ($object->dao->fk_statut < 8 && GETPOST('set') != "assign_ticket" && $user->rights->ticketsup->manage) { + print '' . img_picto('', 'edit') . ' ' . $langs->trans('Modify') . ''; + } + print '
    '; + print ''; + if ($action != 'progression' && $object->dao->fk_statut < 8 && !$user->societe_id) { + print ''; + } + print '
    '; + print $langs->trans('Progression') . ''; + print '' . img_edit($langs->trans('Modify')) . '
    '; + print '
    '; + if ($user->rights->ticketsup->write && $action == 'progression') { + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ' '; + print '
    '; + } else { + print($object->dao->progress > 0 ? $object->dao->progress : '0') . '%'; + } + print '
    '; + + print $form->textwithpicto($langs->trans("TicketDurationAuto"), $langs->trans("TicketDurationAutoInfos"), 1); + print ''; + print convertSecondToTime($timing, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY); + print '
    '; + print ' '; + print ' '; + print '
    '; + print '' . img_picto('', 'edit') . ' ' . $langs->trans('Edit') . ''; + print '
    '; + + // View Original message + $object->viewTicketOriginalMessage($user, $action); + + + + // Fin colonne gauche et début colonne droite + print '
    '; + + /*************************************************** + * + * Classification and actions on ticket + * + ***************************************************/ + /* + * Ticket properties + */ + print ''; + print ''; + print ''; + print ''; + if (GETPOST('set') == 'properties' && $user->rights->ticketsup->write) { + /* + * Form to change ticket properties + */ + $j = 0; + $ticketprop[$j] = array( + 'dict' => 'type', + 'list_function' => 'selectTypesTickets', + 'label' => 'TicketChangeType', + ); + $j++; + $ticketprop[$j] = array( + 'dict' => 'category', + 'list_function' => 'selectCategoriesTickets', + 'label' => 'TicketChangeCategory', + ); + $j++; + $ticketprop[$j] = array( + 'dict' => 'severity', + 'list_function' => 'selectSeveritiesTickets', + 'label' => 'TicketChangeSeverity', + ); + foreach ($ticketprop as $property) { + print ''; + print ''; + print ''; + } + } else { + // Type + print ''; + + // Category + print ''; + + // Severity + print ''; + } + print '
    '; + print $langs->trans('Properties'); + print '
    '; + + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '; + print ' '; + print ''; + print $formticket->{$property['list_function']}($object->dao->type_code, 'update_value', '', 0); + print ''; + print ' '; + print '
    '; + print '
    '; + + print '
    ' . $langs->trans("Type") . ''; + print $object->dao->type_label; + if ($user->admin && !$noadmininfo) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } + + print '
    ' . $langs->trans("Category") . ''; + print $object->dao->category_label; + if ($user->admin && !$noadmininfo) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } + + print '
    ' . $langs->trans("TicketSeverity") . ''; + print $object->dao->severity_label; + if ($user->admin && !$noadmininfo) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } + + print '
    '; // End table actions + + // Display navbar with links to change ticket status + if (!$user->societe_id && $user->rights->ticketsup->write && $object->dao->fk_status < 8 && GETPOST('set') !== 'properties') { + $object->viewStatusActions(); + } + + print load_fiche_titre($langs->trans('Contacts'), '', 'title_companies.png'); + + print '
    '; + + print '
    '; + + print '
    ' . $langs->trans("Source") . '
    +
    ' . $langs->trans("Company") . '
    +
    ' . $langs->trans("Contacts") . '
    +
    ' . $langs->trans("ContactType") . '
    +
    ' . $langs->trans("Phone") . '
    +
    ' . $langs->trans("Status") . '
    '; + print '
    '; + + // Contact list + $companystatic = new Societe($db); + $contactstatic = new Contact($db); + $userstatic = new User($db); + foreach (array('internal', 'external') as $source) { + $tmpobject = $object->dao; + $tab = $tmpobject->liste_contact(-1, $source); + $num = count($tab); + $i = 0; + while ($i < $num) { + $var = !$var; + print '
    '; + + print '
    '; + if ($tab[$i]['source'] == 'internal') { + echo $langs->trans("User"); + } + + if ($tab[$i]['source'] == 'external') { + echo $langs->trans("ThirdPartyContact"); + } + + print '
    '; + print '
    '; + + if ($tab[$i]['socid'] > 0) { + $companystatic->fetch($tab[$i]['socid']); + echo $companystatic->getNomUrl(1); + } + if ($tab[$i]['socid'] < 0) { + echo $conf->global->MAIN_INFO_SOCIETE_NOM; + } + if (!$tab[$i]['socid']) { + echo ' '; + } + print '
    '; + + print '
    '; + if ($tab[$i]['source'] == 'internal') { + if ($userstatic->fetch($tab[$i]['id'])) { + print $userstatic->getNomUrl(1); + } + } + if ($tab[$i]['source'] == 'external') { + if ($contactstatic->fetch($tab[$i]['id'])) { + print $contactstatic->getNomUrl(1); + } + } + print '
    +
    ' . $tab[$i]['libelle'] . '
    '; + + print '
    '; + + print dol_print_phone($tab[$i]['phone'], '', '', '', AC_TEL).'
    '; + + if (! empty($tab[$i]['phone_perso'])) { + //print img_picto($langs->trans('PhonePerso'),'object_phoning.png','',0,0,0).' '; + print '
    '.dol_print_phone($tab[$i]['phone_perso'], '', '', '', AC_TEL).'
    '; + } + if (! empty($tab[$i]['phone_mobile'])) { + //print img_picto($langs->trans('PhoneMobile'),'object_phoning.png','',0,0,0).' '; + print dol_print_phone($tab[$i]['phone_mobile'], '', '', '', AC_TEL).'
    '; + } + print '
    '; + + print ''; + + print '
    '; + + $i++; + } + } + + print '
    '; + + // Contract + if ($action == 'sel_contract') { + if (!empty($conf->contrat->enabled)) { + $langs->load('contrats'); + print load_fiche_titre($langs->trans('LinkToAContract'), '', 'title_commercial.png'); + + $form_contract = new FormContract($db); + $form_contract->formSelectContract( + $url_page_current.'?track_id='.$object->dao->track_id, + $object->dao->fk_soc, + GETPOST('contractid'), + 'contractid' + ); + } + } + + print '
    '; + print '
    '; + + print dol_fiche_end(); + + /* ActionBar */ + print '
    '; + + // Show button to mark as read + if (($object->dao->fk_statut == '0' || empty($object->dao->date_read)) && !$user->societe_id) { + print '
    '; + print '' . img_picto('', 'mark-read@ticketsup') . ' ' . $langs->trans('MarkAsRead') . ''; + print 'dao->fk_statut < 8 && $action != "add_message") { + print ''; + } + + // Link to create an intervention + // socid is needed otherwise fichinter ask it and forgot origin after form submit :\ + if (!$object->dao->fk_soc && $user->rights->ficheinter->creer) { + print ''; + } + if ($object->dao->fk_soc > 0 && $object->dao->fk_statut < 8 && $user->rights->ficheinter->creer) { + print ''; + } + + // Button to edit Properties + if ($object->dao->fk_statut < 5 && $user->rights->ticketsup->write) { + print ''; + } + + // Button to link to a contract + if ($user->rights->ticketsup->write && $object->dao->fk_statut < 5 && $user->rights->contrat->creer) { + print ''; + } + + // Close ticket if statut is read + if ($object->dao->fk_statut > 0 && $object->dao->fk_statut < 8 && $user->rights->ticketsup->write) { + print ''; + } + + // Re-open ticket + if (!$user->socid && $object->dao->fk_statut == 8 && !$user->societe_id) { + print ''; + } + + // Delete ticket + if ($user->rights->ticketsup->delete && !$user->societe_id) { + print ''; + } + print '
    '; + + if ($action == 'view' || $action == 'edit_message_init') { + print '
    ' + . '
    '; + + //print '
    '; + // Message list + print load_fiche_titre($langs->trans('TicketMessagesList'), '', 'messages@ticketsup'); + $show_private_message = ($user->societe_id ? 0 : 1); + $object->viewTicketTimelineMessages($show_private_message); + + print '
    '; + + print '
    '; + print '
    '; + } elseif ($action == 'add_message') { + $action='new_message'; + $modelmail='ticketsup_send'; + + print '
    '; + print load_fiche_titre($langs->trans('TicketAddMessage'), '', 'messages@ticketsup'); + + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) { + $newlang = $_REQUEST['lang_id']; + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $object->default_lang; + } + + $formticket = new FormTicketsup($db); + + $formticket->action = $action; + $formticket->track_id = $object->dao->track_id; + $formticket->id = $object->dao->id; + + $formticket->withfile = 2; + $formticket->param = array('fk_user_create' => $user->id); + $formticket->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); + + // Tableau des parametres complementaires du post + $formticket->param['models']=$modelmail; + $formticket->param['models_id']=GETPOST('modelmailselected', 'int'); + //$formticket->param['socid']=$object->dao->fk_soc; + $formticket->param['returnurl']=$_SERVER["PHP_SELF"].'?track_id='.$object->dao->track_id; + + + $formticket->withsubstit = 1; + + if ($object->dao->fk_soc > 0) { + $object->dao->fetch_thirdparty(); + $formticket->substit['__THIRDPARTY_NAME__'] = $object->dao->thirdparty->name; + } + $formticket->substit['__SIGNATURE__'] = $user->signature; + $formticket->substit['__TICKETSUP_TRACKID__'] = $object->dao->track_id; + $formticket->substit['__TICKETSUP_REF__'] = $object->dao->ref; + $formticket->substit['__TICKETSUP_SUBJECT__'] = $object->dao->subject; + $formticket->substit['__TICKETSUP_TYPE__'] = $object->dao->type_code; + $formticket->substit['__TICKETSUP_CATEGORY__'] = $object->dao->category_code; + $formticket->substit['__TICKETSUP_SEVERITY__'] = $object->dao->severity_code; + $formticket->substit['__TICKETSUP_MESSAGE__'] = $object->dao->message; + $formticket->substit['__TICKETSUP_PROGRESSION__'] = $object->dao->progress; + if ($object->dao->fk_user_assign > 0) { + $userstat->fetch($object->dao->fk_user_assign); + $formticket->substit['__TICKETSUP_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname); + } + + if ($object->dao->fk_user_create > 0) { + $userstat->fetch($object->dao->fk_user_create); + $formticket->substit['__TICKETSUP_USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname); + } + + + $formticket->showMessageForm('100%'); + print '
    '; + } + } +} // End action view + +/*************************************************** + * LINKED OBJECT BLOCK + * + * Put here code to view linked object + ****************************************************/ +$somethingshown = $form->showLinkedObjectBlock($object->dao); + +// End of page +llxFooter(''); +$db->close(); diff --git a/htdocs/ticketsup/class/actions_ticketsup.class.php b/htdocs/ticketsup/class/actions_ticketsup.class.php new file mode 100644 index 00000000000..d72e8388905 --- /dev/null +++ b/htdocs/ticketsup/class/actions_ticketsup.class.php @@ -0,0 +1,1523 @@ + + * 2016 Christophe Battarel + * + * 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. + */ + +/** + * \file ticketsup/class/actions_ticketsup.class.php + * \ingroup ticketsup + * \brief File Class ticketsup + */ + +require_once "ticketsup.class.php"; + +require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; +require_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php'; +require_once DOL_DOCUMENT_ROOT . '/fichinter/class/fichinter.class.php'; + +/** + * \class ActionsTicketsup + * \brief Class Actions of the module ticketsup + */ +class ActionsTicketsup +{ + public $db; + public $dao; + + public $mesg; + public $error; + public $errors = array(); + //! Numero de l'erreur + public $errno = 0; + + public $template_dir; + public $template; + + public $label; + public $description; + + public $fk_statut; + public $fk_soc; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + /** + * Instantiation of DAO class + * + * @return void + */ + public function getInstanceDao() + { + if (!is_object($this->dao)) { + $this->dao = new Ticketsup($this->db); + } + } + + /** + * Enter description here ... + * + * @param string $action Action type + */ + public function doActions(&$action = '') + { + global $conf, $user, $langs, $mysoc; + + $this->getInstanceDao(); + + /* + * Add file in email form + */ + if (GETPOST('addfile')) { + // altairis : allow files from public interface + if (GETPOST('track_id')) { + $res = $this->dao->fetch('', GETPOST('track_id')); + } + + ////if($res > 0) + ////{ + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + + // Set tmp directory TODO Use a dedicated directory for temp mails files + $vardir = $conf->ticketsup->dir_output . (!empty($this->dao->track_id) ? '/' . dol_sanitizeFileName($this->dao->track_id) : ''); + $upload_dir_tmp = $vardir . '/temp'; + if (!dol_is_dir($upload_dir_tmp)) { + dol_mkdir($upload_dir_tmp); + } + dol_add_file_process($upload_dir_tmp, 0, 0, 'addedfile', dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '-__file__'); + $action = !empty($this->dao->track_id) ? 'add_message' : 'create_ticket'; + ////} + } + + /* + * Remove file in email form + */ + if (GETPOST('removedfile')) { + // altairis : allow files from public interface + if (GETPOST('track_id')) { + $res = $this->dao->fetch('', GETPOST('track_id')); + } + + ////if($res > 0) + ////{ + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + + // Set tmp directory + $vardir = $conf->ticketsup->dir_output . (!empty($this->dao->track_id) ? '/' . dol_sanitizeFileName($this->dao->track_id) : ''); + $upload_dir_tmp = $vardir . '/temp'; + + // TODO Delete only files that was uploaded from email form + dol_remove_file_process($_POST['removedfile'], 0); + $action = !empty($this->dao->track_id) ? 'add_message' : 'create_ticket'; + ////} + } + + if (GETPOST('add_ticket') && $user->rights->ticketsup->create) { + $error = 0; + + if (!GETPOST("subject")) { + $error++; + array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Subject"))); + $action = 'create_ticket'; + } elseif (!GETPOST("message")) { + $error++; + array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("message"))); + $action = 'create_ticket'; + } + + if (!$error) { + $this->db->begin(); + + $this->dao->track_id = generate_random_id(16); + + $this->dao->ref = GETPOST("ref", 'alpha'); + $this->dao->fk_soc = GETPOST("socid", 'int'); + $this->dao->subject = GETPOST("subject", 'alpha'); + $this->dao->message = GETPOST("message"); + + $this->dao->type_code = GETPOST("type_code", 'alpha'); + $this->dao->category_code = GETPOST("category_code", 'alpha'); + $this->dao->severity_code = GETPOST("severity_code", 'alpha'); + $notNotifyTiers = GETPOST("not_notify_tiers_at_create", 'alpha'); + $this->dao->notify_tiers_at_create = empty($notNotifyTiers) ? 1 : 0; + + $extrafields = new ExtraFields($this->db); + $extralabels = $extrafields->fetch_name_optionals_label($this->dao->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $this->dao); + + $id = $this->dao->create($user); + if ($id <= 0) { + $error++; + $errors = ($this->dao->error ? array($this->dao->error) : $this->dao->errors); + array_push($this->errors, $this->dao->error ? array($this->dao->error) : $this->dao->errors); + $action = 'create_ticket'; + } + + if (!$error && $id > 0) { + $this->db->commit(); + + // File transfer + $this->copyFilesForTicket(); + + // Add contact + $contactid = GETPOST('contactid', 'int'); + $type_contact = GETPOST("type", 'alpha'); + + if ($contactid > 0 && $type_contact) { + $result = $this->dao->add_contact($contactid, GETPOST("type"), 'external'); + } + + // altairis: link ticket to project + if (GETPOST('projectid')) { + $this->dao->setProject(GETPOST('projectid')); + } + + // Auto assign user + if ($conf->global->TICKETS_AUTO_ASSIGN_USER_CREATE) { + $result = $this->dao->assignUser($user, $user->id, 1); + $this->dao->add_contact($user->id, "SUPPORTTEC", 'internal'); + } + + // Auto assign contrat + $contractid = 0; + if ($conf->global->TICKETS_AUTO_ASSIGN_CONTRACT_CREATE) { + $contrat = new Contrat($this->db); + $contrat->socid = $this->dao->fk_soc; + $list = $contrat->getListOfContracts(); + + if (is_array($list) && !empty($list)) { + if (count($list) == 1) { + $contractid = $list[0]->id; + $this->dao->setContract($contractid); + } else { + } + } + } + + // Auto create fiche intervention + if ($conf->global->TICKETS_AUTO_CREATE_FICHINTER_CREATE) { + $fichinter = new Fichinter($this->db); + $fichinter->socid = $this->dao->fk_soc; + $fichinter->fk_project = GETPOST('projectid', 'int'); + $fichinter->fk_contrat = $contractid; + $fichinter->author = $user->id; + $fichinter->modelpdf = 'soleil'; + $fichinter->origin = $this->dao->element; + $fichinter->origin_id = $this->dao->id; + + // Extrafields + $extrafields = new ExtraFields($this->db); + $extralabels = $extrafields->fetch_name_optionals_label($fichinter->table_element); + $array_options = $extrafields->getOptionalsFromPost($extralabels); + $fichinter->array_options = $array_options; + + $id = $fichinter->create($user); + if ($id <= 0) { + setEventMessage($fichinter->error, 'errors'); + } + } + + if (!empty($backtopage)) { + $url = $backtopage; + } else { + $url = 'card.php?track_id=' . $this->dao->track_id; + } + + header("Location: " . $url); + exit; + } else { + $this->db->rollback(); + setEventMessage($this->errors, 'errors'); + } + } else { + setEventMessage($this->errors, 'errors'); + } + } + + if ($action == 'edit' && $user->rights->ticketsup->write) { + $error = 0; + + if ($this->dao->fetch(GETPOST('id')) < 0) { + $error++; + array_push($this->errors, $langs->trans("ErrorTicketIsNotValid")); + $_GET["action"] = $_POST["action"] = ''; + } + } + + if (GETPOST('update') && GETPOST('id') && $user->rights->ticketsup->write) { + $error = 0; + + $ret = $this->dao->fetch(GETPOST('id')); + if ($ret < 0) { + $error++; + array_push($this->errors, $langs->trans("ErrorTicketIsNotValid")); + $action = ''; + } elseif (!GETPOST("label")) { + $error++; + array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label"))); + $action = 'edit'; + } elseif (!GETPOST("subject")) { + $error++; + array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Subject"))); + $action = 'edit'; + } + + if (!$error) { + $this->db->begin(); + + $this->dao->label = GETPOST("label"); + $this->dao->description = GETPOST("description"); + + //... + $ret = $this->dao->update(GETPOST('id'), $user); + if ($ret <= 0) { + $error++; + $errors = ($this->dao->error ? array($this->dao->error) : $this->dao->errors); + $action = 'edit'; + } + + if (!$error && $ret > 0) { + $this->db->commit(); + } else { + $this->db->rollback(); + } + } + } + + if ($action == "mark_ticket_read" && $user->rights->ticketsup->write) { + $this->dao->fetch('', GETPOST("track_id")); + + if ($this->dao->markAsRead($user) > 0) { + // Log action in ticket logs table + $log_action = $langs->trans('TicketLogMesgReadBy', $user->getFullName($langs)); + $ret = $this->dao->createTicketLog($user, $log_action); + if ($ret > 0) { + setEventMessage($langs->trans('TicketMarkedAsRead')); + } else { + setEventMessage($langs->trans('TicketMarkedAsReadButLogActionNotSaved'), 'errors'); + } + header("Location: card.php?track_id=" . $this->dao->track_id . "&action=view"); + exit; + } else { + array_push($this->errors, $this->dao->error); + } + $action = 'view'; + } + + if ($action == "assign_user" && GETPOST('btn_assign_user') && $user->rights->ticketsup->write) { + $this->dao->fetch('', GETPOST("track_id")); + + $useroriginassign = $this->dao->fk_user_assign; + $usertoassign = GETPOST('fk_user_assign'); + if (!$usertoassign) { + $error++; + array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("UserAssignedTo"))); + $action = 'view'; + } + + if (!$error) { + $ret = $this->dao->assignUser($user, $usertoassign); + + if ($ret) { + // Si déjà un user assigné on le supprime des contacts + if ($useroriginassign > 0) { + $internal_contacts = $this->dao->liste_contact(-1, 'internal'); + + foreach ($internal_contacts as $key => $contact) { + if ($contact['code'] == "SUPPORTTEC" && $contact['id'] == $useroriginassign) { + } + { + //print "user à effacer : ".$useroriginassign; + $this->dao->delete_contact($contact['rowid']); + } + } + } + $this->dao->add_contact($usertoassign, "SUPPORTTEC", 'internal', $notrigger = 0); + } + + // Log action in ticket logs table + $this->dao->fetch_user($usertoassign); + $log_action = $langs->trans('TicketLogAssignedTo', $this->dao->user->getFullName($langs)); + $ret = $this->dao->createTicketLog($user, $log_action); + if ($ret > 0) { + setEventMessage($langs->trans('TicketAssigned')); + } else { + setEventMessage($langs->trans('TicketAssignedButLogActionNotSaved'), 'errors'); + } + header("Location: card.php?track_id=" . $this->dao->track_id . "&action=view"); + exit; + } else { + array_push($this->errors, $this->dao->error); + } + $action = 'view'; + } + + if ($action == "change_property" && GETPOST('btn_update_ticket_prop') && $user->rights->ticketsup->write) { + $this->fetch('', GETPOST('track_id')); + + $fieldtomodify = GETPOST('property') . '_code'; + $fieldtomodify_label = GETPOST('property') . '_label'; + + $oldvalue_code = $this->dao->$fieldtomodify; + $newvalue_code = $this->dao->getValueFrom('c_ticketsup_' . GETPOST('property'), GETPOST('update_value'), 'code'); + + $oldvalue_label = $this->dao->$fieldtomodify_label; + $newvalue_label = $this->dao->getValueFrom('c_ticketsup_' . GETPOST('property'), GETPOST('update_value'), 'label'); + + $this->dao->$fieldtomodify = $newvalue_code; + + $ret = $this->dao->update($user); + if ($ret > 0) { + $log_action = $langs->trans('TicketLogPropertyChanged', $oldvalue_label, $newvalue_label); + $ret = $this->dao->createTicketLog($user, $log_action); + if ($ret > 0) { + setEventMessage($langs->trans('TicketUpdated')); + } + } + $action = 'view'; + } + + if ($action == "new_message" && GETPOST('btn_add_message') && $user->rights->ticketsup->read) { + $ret = $this->newMessage($user, $action); + if ($ret) { + if (!empty($backtopage)) { + $url = $backtopage; + } else { + $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + } + + header("Location: " . $url); + exit; + } else { + setEventMessage($this->dao->error, 'errors'); + $action = 'add_message'; + } + } + + if ($action == "new_public_message" && GETPOST('btn_add_message')) { + $this->newMessagePublic($user, $action); + } + + if ($action == "confirm_close" && GETPOST('confirm', 'alpha') == 'yes' && $user->rights->ticketsup->write) { + $this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')); + if ($this->dao->close()) { + // Log action in ticket logs table + $log_action = $langs->trans('TicketLogClosedBy', $user->getFullName($langs)); + $ret = $this->dao->createTicketLog($user, $log_action); + if ($ret > 0) { + setEventMessage('
    ' . $langs->trans('TicketMarkedAsClosed') . '
    '); + } else { + setEventMessage($langs->trans('TicketMarkedAsClosedButLogActionNotSaved'), 'warnings'); + } + $url = 'card.php?action=view&track_id=' . GETPOST('track_id', 'alpha'); + header("Location: " . $url); + } else { + $action = ''; + setEventMessage($this->error, 'errors'); + } + } + + if ($action == "confirm_public_close" && GETPOST('confirm', 'alpha') == 'yes') { + $this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')); + if (($_SESSION['email_customer'] == $this->dao->origin_email || $_SESSION['email_customer'] == $this->dao->thirdparty->email) && $this->dao->close()) { + // Log action in ticket logs table + $log_action = $langs->trans('TicketLogClosedBy', $_SESSION['email_customer']); + $ret = $this->dao->createTicketLog($user, $log_action); + if ($ret > 0) { + setEventMessage('
    ' . $langs->trans('TicketMarkedAsClosed') . '
    '); + } else { + setEventMessage($langs->trans('TicketMarkedAsClosedButLogActionNotSaved'), 'warnings'); + } + $url = 'view.php?action=view_ticket&track_id=' . GETPOST('track_id', 'alpha'); + header("Location: " . $url); + } else { + setEventMessage($this->error, 'errors'); + $action = ''; + } + } + + if ($action == 'confirm_delete_ticket' && GETPOST('confirm', 'alpha') == "yes" && $user->rights->ticketsup->delete) { + if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { + if ($this->dao->delete($user) > 0) { + setEventMessage('
    ' . $langs->trans('TicketDeletedSuccess') . '
    '); + Header("Location: index.php"); + exit; + } else { + $langs->load("errors"); + $mesg = '
    ' . $langs->trans($this->error) . '
    '; + $action = ''; + } + } + } + + // Set parent company + if ($action == 'set_thirdparty' && $user->rights->societe->creer) { + if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { + $result = $this->dao->set_customer(GETPOST('editcustomer', 'int')); + $url = 'card.php?action=view&track_id=' . GETPOST('track_id', 'alpha'); + header("Location: " . $url); + exit(); + } + } + + if ($action == 'set_progression' && $user->rights->ticketsup->write) { + if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { + $result = $this->dao->setProgression(GETPOST('progress')); + // Log action in ticket logs table + $log_action = $langs->trans('TicketLogProgressSetTo', GETPOST('progress')); + $ret = $this->dao->createTicketLog($user, $log_action); + $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + header("Location: " . $url); + exit(); + } + } + + if ($action == 'setsubject') { + if ($this->fetch(GETPOST('id', 'int'))) { + if ($action == 'setsubject') { + $this->dao->subject = trim(GETPOST('subject', 'alpha')); + } + + if ($action == 'setsubject' && empty($this->dao->subject)) { + $mesg .= ($mesg ? '
    ' : '') . $langs->trans("ErrorFieldRequired", $langs->transnoentities("Subject")); + } + + if (!$mesg) { + if ($this->dao->update($user) >= 0) { + header("Location: " . $_SERVER['PHP_SELF'] . "?track_id=" . $this->dao->track_id); + exit; + } + $mesg = $this->dao->error; + } + } + } + + if ($action == "set_extrafields" && GETPOST('btn_edit_extrafields') && $user->rights->ticketsup->write && !GETPOST('cancel')) { + $res = $this->fetch('', GETPOST('track_id')); + + $extrafields = new ExtraFields($this->db); + $extralabels = $extrafields->fetch_name_optionals_label($this->dao->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $this->dao); + + $ret = $this->dao->update($user); + if ($ret > 0) { + setEventMessage($langs->trans('TicketUpdated')); + $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + header("Location: " . $url); + exit(); + } + + $action = 'view'; + } // Reopen ticket + elseif ($action == 'confirm_reopen' && $user->rights->ticketsup->manage && !GETPOST('cancel')) { + if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { + // prevent browser refresh from reopening ticket several times + if ($this->dao->fk_statut == 8) { + $res = $this->dao->setStatut(4); + if ($res) { + // Log action in ticket logs table + $log_action = $langs->trans('TicketLogReopen'); + $ret = $this->dao->createTicketLog($user, $log_action); + $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + header("Location: " . $url); + exit(); + } + } + } + } // Categorisation dans projet + elseif ($action == 'classin' && $user->rights->ticketsup->write) { + if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { + $this->dao->setProject(GETPOST('projectid')); + $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + header("Location: " . $url); + exit(); + } + } // Categorisation dans contrat + elseif ($action == 'setcontract' && $user->rights->ticketsup->write) { + if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { + $this->dao->setContract(GETPOST('contractid')); + $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + header("Location: " . $url); + exit(); + } + } elseif ($action == "set_message" && $user->rights->ticketsup->manage) { + // altairis: manage cancel button + if (!GETPOST('cancel')) { + $this->fetch('', GETPOST('track_id')); + $oldvalue_message = $this->dao->message; + $fieldtomodify = GETPOST('message_initial'); + + $this->dao->message = $fieldtomodify; + $ret = $this->dao->update($user); + if ($ret > 0) { + $log_action = $langs->trans('TicketInitialMessageModified') . " \n"; + // include the Diff class + dol_include_once('/ticketsup/class/utils_diff.class.php'); + // output the result of comparing two files as plain text + $log_action .= Diff::toString(Diff::compare(strip_tags($oldvalue_message), strip_tags($this->dao->message))); + + $ret = $this->dao->createTicketLog($user, $log_action); + if ($ret > 0) { + setEventMessage($langs->trans('TicketMessageSuccesfullyUpdated')); + } + } + } + + $action = 'view'; + } // Reopen ticket + elseif ($action == 'confirm_set_status' && $user->rights->ticketsup->write && !GETPOST('cancel')) { + if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { + $new_status = GETPOST('new_status', 'int'); + $old_status = $this->dao->fk_statut; + $res = $this->dao->setStatut($new_status); + if ($res) { + // Log action in ticket logs table + $log_action = $langs->trans('TicketLogStatusChanged', $langs->transnoentities($this->dao->statuts_short[$old_status]), $langs->transnoentities($this->dao->statuts_short[$new_status])); + $ret = $this->dao->createTicketLog($user, $log_action); + $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + header("Location: " . $url); + exit(); + } + } + } + } + + /** + * Add new message on a ticket (private area) + * + * @param unknown $user + * @param unknown $action + */ + private function newMessage($user, &$action) + { + + global $mysoc, $conf, $langs; + + if (!class_exists('Contact')) { + include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; + } + + $contactstatic = new Contact($this->db); + + $error = 0; + $ret = $this->dao->fetch('', GETPOST('track_id')); + $this->dao->socid = $this->dao->fk_soc; + $this->dao->fetch_thirdparty(); + if ($ret < 0) { + $error++; + array_push($this->errors, $langs->trans("ErrorTicketIsNotValid")); + $action = ''; + } + + if (!GETPOST("message")) { + $error++; + array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("message"))); + $action = 'add_message'; + } + + if (!$error) { + $this->dao->message = GETPOST("message"); + $this->dao->private = GETPOST("private_message"); + $send_email = GETPOST('send_email', 'int'); + + $id = $this->dao->createTicketMessage($user); + if ($id <= 0) { + $error++; + $errors = ($this->dao->error ? array($this->dao->error) : $this->dao->errors); + array_push($this->errors, $this->dao->error ? array($this->dao->error) : $this->dao->errors); + $action = 'add_message'; + } + + if (!$error && $id > 0) { + setEventMessage($langs->trans('TicketMessageSuccessfullyAdded')); + + /* + * Send email to linked contacts + */ + if ($send_email > 0) { + // Retrieve internal contact datas + $internal_contacts = $this->dao->getInfosTicketInternalContact(); + $sendto = array(); + if (is_array($internal_contacts) && count($internal_contacts) > 0) { + // altairis: set default subject + $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE; + $subject = GETPOST('subject') ? GETPOST('subject') : '[' . $label_title . '- ticket #' . $this->dao->track_id . '] ' . $langs->trans('TicketNewMessage'); + + $message_intro = $langs->trans('TicketNotificationEmailBody', "#" . $this->dao->id); + $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE; + + $message = $langs->trans('TicketMessageMailIntroText'); + $message .= "\n\n"; + $message .= GETPOST('message'); + + // Coordonnées client + $message .= "\n\n"; + $message .= "==============================================\n"; + $message .= !empty($this->dao->thirdparty->name) ? $langs->trans('Thirdparty') . " : " . $this->dao->thirdparty->name : ''; + $message .= !empty($this->dao->thirdparty->town) ? "\n" . $langs->trans('Town') . " : " . $this->dao->thirdparty->town : ''; + $message .= !empty($this->dao->thirdparty->phone) ? "\n" . $langs->trans('Phone') . " : " . $this->dao->thirdparty->phone : ''; + + // Build array to display recipient list + foreach ($internal_contacts as $key => $info_sendto) { + // altairis: avoid duplicate notifications + if ($info_sendto['id'] == $user->id) { + continue; + } + + if ($info_sendto['email'] != '') { + if(!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . ">"; + + //Contact type + $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1') . ' (' . strtolower($info_sendto['libelle']) . ')'; + $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient') . ' : ' . $recipient . "\n" : ''); + } + } + $message .= "\n"; + // URL ticket + $url_internal_ticket = dol_buildpath('/ticketsup/card.php', 2) . '?track_id=' . $this->dao->track_id; + + // altairis: make html link on url + $message .= "\n" . $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal') . ' : ' . '' . $this->dao->track_id . '' . "\n"; + + // Add global email address recipient + // altairis: use new TICKETS_NOTIFICATION_EMAIL_TO configuration variable + if ($conf->global->TICKETS_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKETS_NOTIFICATION_EMAIL_TO, $sendto)) { + if(!empty($conf->global->TICKETS_NOTIFICATION_EMAIL_TO)) $sendto[] = $conf->global->TICKETS_NOTIFICATION_EMAIL_TO; + } + + // altairis: dont try to send email if no recipient + if (!empty($sendto)) { + $this->sendTicketMessageByEmail($subject, $message, '', $sendto); + } + } + + /* + * Email for externals users if not private + */ + if (empty($this->dao->private)) { + // Retrieve email of all contacts (external) + $external_contacts = $this->dao->getInfosTicketExternalContact(); + + // If no contact, get email from thirdparty + if (is_array($external_contacts) && count($external_contacts) === 0) { + if (!empty($this->dao->fk_soc)) { + $this->dao->fetch_thirdparty($this->dao->fk_soc); + $array_company = array(array('firstname' => '', 'lastname' => $this->dao->thirdparty->name, 'email' => $this->dao->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $this->dao->thirdparty->id)); + $external_contacts = array_merge($external_contacts, $array_company); + } elseif (empty($this->dao->fk_soc) && !empty($this->dao->origin_email)) { + $array_external = array(array('firstname' => '', 'lastname' => $this->dao->origin_email, 'email' => $this->dao->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $this->dao->thirdparty->id)); + $external_contacts = array_merge($external_contacts, $array_external); + } + } + + $sendto = array(); + if (is_array($external_contacts) && count($external_contacts) > 0) { + // altairis: get default subject for email to external contacts + $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE; + $subject = GETPOST('subject') ? GETPOST('subject') : '[' . $label_title . '- ticket #' . $this->dao->track_id . '] ' . $langs->trans('TicketNewMessage'); + + $message_intro = GETPOST('mail_intro') ? GETPOST('mail_intro') : $conf->global->TICKETS_MESSAGE_MAIL_INTRO; + $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE; + + // We put intro after + $message = GETPOST('message'); + $message .= "\n\n"; + + foreach ($external_contacts as $key => $info_sendto) { + // altairis: avoid duplicate emails to external contacts + if ($info_sendto['id'] == $user->contactid) { + continue; + } + + if ($info_sendto['email'] != '' && $info_sendto['email'] != $this->dao->origin_email) { + if(!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . ">"; + + $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1') . ' (' . strtolower($info_sendto['libelle']) . ')'; + $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient') . ' : ' . $recipient . "\n" : ''); + } + } + + // If public interface is not enable, use link to internal page into mail + $url_public_ticket = (!empty($conf->global->TICKETS_ENABLE_PUBLIC_INTERFACE) ? + (!empty($conf->global->TICKETS_URL_PUBLIC_INTERFACE) ? + $conf->global->TICKETS_URL_PUBLIC_INTERFACE . '/view.php' : + dol_buildpath('/ticketsup/public/view.php', 2) + ) : + dol_buildpath('/ticketsup/card.php', 2) + ) . '?track_id=' . $this->dao->track_id; + $message .= "\n" . $langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : ' . '' . $this->dao->track_id . '' . "\n"; + + // Build final message + $message = $message_intro . $message; + + // Add signature + $message .= '
    ' . $message_signature; + + if (!empty($this->dao->origin_email)) { + $sendto[] = $this->dao->origin_email; + } + + if ($this->dao->fk_soc > 0 && ! in_array($this->dao->origin_email, $sendto)) { + $this->dao->socid = $this->dao->fk_soc; + $this->dao->fetch_thirdparty(); + if(!empty($this->dao->thirdparty->email)) $sendto[] = $this->dao->thirdparty->email; + } + + // altairis: Add global email address reciepient + if ($conf->global->TICKETS_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKETS_NOTIFICATION_EMAIL_TO, $sendto)) { + if(!empty($conf->global->TICKETS_NOTIFICATION_EMAIL_TO)) $sendto[] = $conf->global->TICKETS_NOTIFICATION_EMAIL_TO; + } + + // altairis: dont try to send email when no recipient + if (!empty($sendto)) { + $this->sendTicketMessageByEmail($subject, $message, '', $sendto); + } + } + } + } + + $this->copyFilesForTicket(); + + // Set status to "answered" if not set yet, only for internal users + if ($this->dao->fk_statut < 3 && !$user->societe_id) { + $this->dao->setStatut(3); + } + + return 1; + } else { + return -1; + setEventMessage($this->dao->error, 'errors'); + } + } else { + return -1; + setEventMessage($this->errors, 'errors'); + } + } + + /** + * Add new message on a ticket (public area) + * + * @param unknown $user + * @param unknown $action + */ + private function newMessagePublic($user, &$action) + { + + global $mysoc, $conf, $langs; + + $error = 0; + $ret = $this->dao->fetch('', GETPOST('track_id')); + $this->dao->socid = $this->dao->fk_soc; + $this->dao->fetch_thirdparty(); + if ($ret < 0) { + $error++; + array_push($this->errors, $langs->trans("ErrorTicketIsNotValid")); + $action = ''; + } + + if (!GETPOST("message")) { + $error++; + array_push($this->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("message"))); + $action = 'add_message'; + } + + if (!$error) { + $this->dao->message = GETPOST("message"); + $id = $this->dao->createTicketMessage($user); + if ($id <= 0) { + $error++; + $errors = ($this->dao->error ? array($this->dao->error) : $this->dao->errors); + array_push($this->errors, $this->dao->error ? array($this->dao->error) : $this->dao->errors); + $action = 'add_message'; + } + + if (!$error && $id > 0) { + setEventMessage($langs->trans('TicketMessageSuccessfullyAdded')); + + // Retrieve internal contact datas + $internal_contacts = $this->dao->getInfosTicketInternalContact(); + $sendto = array(); + if (is_array($internal_contacts) && count($internal_contacts) > 0) { + $subject = '[' . $mysoc->name . '- ticket #' . $this->dao->track_id . '] ' . $langs->trans('TicketNewMessage'); + + $message = $langs->trans('TicketMessageMailIntroAutoNewPublicMessage', $this->dao->subject); + $message .= "\n"; + $message .= GETPOST('message'); + $message .= "\n"; + + // Coordonnées client + if ($this->dao->thirdparty->id > 0) { + $message .= "\n\n"; + $message .= "==============================================\n"; + $message .= $langs->trans('Thirparty') . " : " . $this->dao->thirdparty->name; + $message .= !empty($this->dao->thirdparty->town) ? $langs->trans('Town') . " : " . $this->dao->thirdparty->town : ''; + $message .= "\n"; + $message .= !empty($this->dao->thirdparty->phone) ? $langs->trans('Phone') . " : " . $this->dao->thirdparty->phone : ''; + $message .= "\n"; + } + + // Build array to display recipient list + foreach ($internal_contacts as $key => $info_sendto) { + if ($info_sendto['email'] != '') { + $sendto[] = trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . ">"; + } + + // Contact type + $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1') . ' (' . strtolower($info_sendto['libelle']) . ')'; + $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient') . ' : ' . $recipient . "\n" : ''); + $message .= "\n"; + } + + // URL ticket + $url_internal_ticket = dol_buildpath('/ticketsup/card.php', 2) . '?track_id=' . $this->dao->track_id; + $message .= "\n" . $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal') . ' : ' . $url_internal_ticket . "\n"; + + $message .= "\n\n"; + + $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE; + + // Add global email address reciepient + if ($conf->global->TICKETS_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKETS_NOTIFICATION_EMAIL_FROM, $sendto)) { + $sendto[] = $conf->global->TICKETS_NOTIFICATION_EMAIL_FROM; + } + + $this->sendTicketMessageByEmail($subject, $message, '', $sendto); + } + + /* + * Email for externals users if not private + */ + + // Retrieve email of all contacts external + $external_contacts = $this->dao->getInfosTicketExternalContact(); + $sendto = array(); + if (is_array($external_contacts) && count($external_contacts) > 0) { + $subject = '[' . $mysoc->name . '- ticket #' . $this->dao->track_id . '] ' . $langs->trans('TicketNewMessage'); + + $message = $langs->trans('TicketMessageMailIntroAutoNewPublicMessage', $this->dao->subject); + $message .= "\n"; + + $message .= GETPOST('message'); + $message .= "\n\n"; + + $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE; + foreach ($external_contacts as $key => $info_sendto) { + if ($info_sendto['email'] != '') { + $sendto[] = trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . ">"; + } + $recipient = ''; + $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1') . ' (' . strtolower($info_sendto['libelle']) . ')'; + $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient') . ' : ' . $recipient . "\n" : ''); + } + + $url_public_ticket = ($conf->global->TICKETS_URL_PUBLIC_INTERFACE ? $conf->global->TICKETS_URL_PUBLIC_INTERFACE . '/view.php' : dol_buildpath('/ticketsup/public/view.php', 2)) . '?track_id=' . $this->dao->track_id; + $message .= "\n\n" . $langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : ' . $url_public_ticket . "\n"; + + // Add signature + $message .= '\n\n' . $message_signature; + + if (!empty($this->dao->origin_email) && !in_array($this->dao->origin_email, $sendto)) { + $sendto[] = $this->dao->origin_email; + } + if ($this->dao->fk_soc > 0 && !in_array($this->dao->origin_email, $sendto)) { + $sendto[] = $this->dao->thirdparty->email; + } + $this->sendTicketMessageByEmail($subject, $message, '', $sendto); + } + + $this->copyFilesForTicket(); + + $url = 'view.php?action=view_ticket&track_id=' . $this->dao->track_id; + header("Location: " . $url); + exit; + } else { + setEventMessage($this->dao->error, 'errors'); + } + } else { + setEventMessage($this->errors, 'errors'); + } + } + + /** + * Fetch object + * + * @return void + */ + public function fetch($id = '', $track_id = '', $ref = '') + { + $this->getInstanceDao(); + return $this->dao->fetch($id, $track_id, $ref); + } + + /** + * print statut + * + * @return void + */ + public function getLibStatut($mode = 0) + { + $this->getInstanceDao(); + $this->dao->fk_statut = $this->fk_statut; + return $this->dao->getLibStatut($mode); + } + + /** + * Get ticket info + * + * @param id Object id + */ + public function getInfo($id) + { + $this->getInstanceDao(); + $this->dao->fetch($id, $track_id); + + $this->label = $this->dao->label; + $this->description = $this->dao->description; + } + + /** + * Get action title + * + * @param action Type of action + */ + public function getTitle($action = '') + { + global $langs; + + if ($action == 'create_ticket') { + return $langs->trans("CreateTicket"); + } elseif ($action == 'edit') { + return $langs->trans("EditTicket"); + } elseif ($action == 'view') { + return $langs->trans("TicketCard"); + } elseif ($action == 'add_message') { + return $langs->trans("AddMessage"); + } else { + return $langs->trans("TicketsManagement"); + } + } + + /** + * View html list of logs + * + * @param boolean $show_user Show user who make action + */ + public function viewTicketLogs($show_user = true) + { + global $conf, $langs, $bc; + + // Load logs in cache + $ret = $this->dao->loadCacheLogsTicket(); + + if (is_array($this->dao->cache_logs_ticket) && count($this->dao->cache_logs_ticket) > 0) { + print ''; + + print ''; + + print ''; + + if ($show_user) { + print ''; + } + + $var = true; + + foreach ($this->dao->cache_logs_ticket as $id => $arraylogs) { + $var = !$var; + print ""; + print ''; + + if ($show_user) { + print ''; + } + print ''; + print ""; + print ''; + print ''; + } + + print '
    '; + print $langs->trans('DateCreation'); + print ''; + print $langs->trans('User'); + print '
    '; + print dol_print_date($arraylogs['datec'], 'dayhour'); + print ''; + if ($arraylogs['fk_user_create'] > 0) { + $userstat = new User($this->db); + $res = $userstat->fetch($arraylogs['fk_user_create']); + if ($res) { + print $userstat->getNomUrl(1); + } + } + print '
    '; + print dol_nl2br($arraylogs['message']); + + print '
    '; + } else { + print '
    ' . $langs->trans('NoLogForThisTicket') . '
    '; + } + } + + /** + * View list of logs with timeline view + * + * @param boolean $show_user Show user who make action + */ + public function viewTimelineTicketLogs($show_user = true) + { + global $conf, $langs, $bc; + + // Load logs in cache + $ret = $this->dao->loadCacheLogsTicket(); + + if (is_array($this->dao->cache_logs_ticket) && count($this->dao->cache_logs_ticket) > 0) { + print '
    '; + + foreach ($this->dao->cache_logs_ticket as $id => $arraylogs) { + print '
    '; + print '
    '; + //print ''; + print '
    '; + + print '
    '; + print dol_nl2br($arraylogs['message']); + + print ''; + print dol_print_date($arraylogs['datec'], 'dayhour'); + + if ($show_user) { + if ($arraylogs['fk_user_create'] > 0) { + $userstat = new User($this->db); + $res = $userstat->fetch($arraylogs['fk_user_create']); + if ($res) { + print '
    '.$userstat->getNomUrl(1).''; + } + } + } + print '
    '; + print '
    '; + print '
    '; + } + print '
    '; + } else { + print '
    ' . $langs->trans('NoLogForThisTicket') . '
    '; + } + } + + /** + * Show ticket original message + * + * @param User $user $user wich display + * @param string $action + */ + public function viewTicketOriginalMessage($user, $action = '') + { + global $langs; + if (!empty($user->rights->ticketsup->manage) && $action == 'edit_message_init') { + // MESSAGE + + print '
    '; + print ''; + print ''; + print ''; + } + + // Initial message + print ''; + print ''; + + print ''; + + print ''; + print ''; + print '
    '; + print '' . $langs->trans("InitialMessage") . ' '; + if ($user->rights->ticketsup->manage) { + print '' . img_edit($langs->trans('Modify')) . ' ' . $langs->trans('Modify') . ''; + } + print '
    '; + if (!empty($user->rights->ticketsup->manage) && $action == 'edit_message_init') { + // MESSAGE + $msg = GETPOST('message_initial', 'alpha') ? GETPOST('message_initial', 'alpha') : $this->dao->message; + include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + $uselocalbrowser = true; + $doleditor = new DolEditor('message_initial', $msg, '100%', 250, 'dolibarr_details', 'In', true, $uselocalbrowser); + $doleditor->Create(); + } else { + // Deal with format differences (text / HTML) + if (dol_textishtml($this->dao->message)) { + print $this->dao->message; + } else { + print dol_nl2br($this->dao->message); + } + + //print '
    ' . $this->dao->message . '
    '; + } + print '
    '; + if ($user->rights->ticketsup->manage && $action == 'edit_message_init') { + print ' '; + print ' '; + print '
    '; + } + } + /** + * View html list of message for ticket + * + * @param boolean $show_private Show private messages + * @param boolean $show_user Show user who make action + */ + public function viewTicketMessages($show_private, $show_user = true) + { + global $conf, $langs, $user, $bc; + + // Load logs in cache + $ret = $this->dao->loadCacheMsgsTicket(); + $action = GETPOST('action'); + + $this->viewTicketOriginalMessage($user, $action); + + if (is_array($this->dao->cache_msgs_ticket) && count($this->dao->cache_msgs_ticket) > 0) { + print_titre($langs->trans('TicketMailExchanges')); + + print ''; + + print ''; + + print ''; + + if ($show_user) { + print ''; + } + + foreach ($this->dao->cache_msgs_ticket as $id => $arraymsgs) { + if (!$arraymsgs['private'] + || ($arraymsgs['private'] == "1" && $show_private) + ) { + //print ''; + $var = !$var; + print ""; + print ''; + if ($show_user) { + print ''; + } + print ''; + print ""; + print ''; + print ''; + } + } + + print '
    '; + print $langs->trans('DateCreation'); + print ''; + print $langs->trans('User'); + print '
    '; + print dol_print_date($arraymsgs['datec'], 'dayhour'); + print ''; + if ($arraymsgs['fk_user_action'] > 0) { + $userstat = new User($this->db); + $res = $userstat->fetch($arraymsgs['fk_user_action']); + if ($res) { + print $userstat->getNomUrl(0); + } + } else { + print $langs->trans('Customer'); + } + print '
    '; + print $arraymsgs['message']; + print '
    '; + } else { + print '
    ' . $langs->trans('NoMsgForThisTicket') . '
    '; + } + } + + /** + * View list of message for ticket with timeline display + * + * @param boolean $show_private Show private messages + * @param boolean $show_user Show user who make action + */ + public function viewTicketTimelineMessages($show_private, $show_user = true) + { + global $conf, $langs, $user, $bc; + + // Load logs in cache + $ret = $this->dao->loadCacheMsgsTicket(); + $action = GETPOST('action'); + + if (is_array($this->dao->cache_msgs_ticket) && count($this->dao->cache_msgs_ticket) > 0) { + print '
    '; + + foreach ($this->dao->cache_msgs_ticket as $id => $arraymsgs) { + if (!$arraymsgs['private'] + || ($arraymsgs['private'] == "1" && $show_private) + ) { + print '
    '; + print '
    '; + print ''; + print '
    '; + + print '
    '; + print $arraymsgs['message']; + + print ''; + print dol_print_date($arraymsgs['datec'], 'dayhour'); + + if ($show_user) { + if ($arraymsgs['fk_user_action'] > 0) { + $userstat = new User($this->db); + $res = $userstat->fetch($arraymsgs['fk_user_action']); + if ($res) { + print '
    '; + print $userstat->getNomUrl(1); + } + } else { + print '
    '; + print $langs->trans('Customer'); + } + } + print '
    '; + print '
    '; + print '
    '; + } + } + print '
    '; + } else { + print '
    ' . $langs->trans('NoMsgForThisTicket') . '
    '; + } + } + + public function load_previous_next_ref($filter, $fieldid) + { + $this->getInstanceDao(); + return $this->dao->load_previous_next_ref($filter, $fieldid); + } + + /** + * Send ticket by email to linked contacts + * + * @param string $subject Email subject + * @param string $message Email message + * @param int $send_internal_cc Receive a copy on internal email ($conf->global->TICKETS_NOTIFICATION_EMAIL_FROM) + * @param array $array_receiver Array of receiver. exemple array('name' => 'John Doe', 'email' => 'john@doe.com', etc...) + */ + public function sendTicketMessageByEmail($subject, $message, $send_internal_cc = 0, $array_receiver = array()) + { + global $conf, $langs; + + if ($conf->global->TICKETS_DISABLE_ALL_MAILS) { + dol_syslog(get_class($this) . '::sendTicketMessageByEmail: Emails are disable into ticketsup setup by option TICKETSUP_DISABLE_ALL_MAILS', LOG_WARNING); + return ''; + } + + $langs->load("mails"); + + if (!class_exists('Contact')) { + include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; + } + + $contactstatic = new Contact($this->db); + + // If no receiver defined, load all ticket linked contacts + if (!is_array($array_receiver) || !count($array_receiver) > 0) { + $array_receiver = $this->dao->getInfosTicketInternalContact(); + $array_receiver = array_merge($array_receiver, $this->dao->getInfosTicketExternalContact()); + } + + if ($send_internal_cc) { + $sendtocc = $conf->global->TICKETS_NOTIFICATION_EMAIL_FROM; + } + + $from = $conf->global->TICKETS_NOTIFICATION_EMAIL_FROM; + if (is_array($array_receiver) && count($array_receiver) > 0) { + foreach ($array_receiver as $key => $receiver) { + // Create form object + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + $formmail = new FormMail($this->db); + + $attachedfiles = $formmail->get_attached_files(); + $filepath = $attachedfiles['paths']; + $filename = $attachedfiles['names']; + $mimetype = $attachedfiles['mimes']; + + $message_to_send = dol_nl2br($message); + + // Envoi du mail + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO; + $conf->global->MAIN_MAIL_AUTOCOPY_TO = ''; + } + include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php'; + $mailfile = new CMailFile($subject, $receiver, $from, $message_to_send, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, -1); + if ($mailfile->error) { + setEventMessage($mailfile->error, 'errors'); + } else { + $result = $mailfile->sendfile(); + if ($result) { + setEventMessage($langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($receiver, 2)), 'mesgs'); + } else { + $langs->load("other"); + if ($mailfile->error) { + setEventMessage($langs->trans('ErrorFailedToSendMail', $from, $receiver), 'errors'); + dol_syslog($langs->trans('ErrorFailedToSendMail', $from, $receiver) . ' : ' . $mailfile->error); + } else { + setEventMessage('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', 'errors'); + } + } + } + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO; + } + } + } else { + $langs->load("other"); + setEventMessage($langs->trans('ErrorMailRecipientIsEmptyForSendTicketMessage') . '!', 'warnings'); + } + } + + /** + * Copy files into ticket directory + * + * Used for files linked into messages + */ + public function copyFilesForTicket() + { + + global $conf; + + // Create form object + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php'; + + $maxwidthsmall = 270; + $maxheightsmall = 150; + $maxwidthmini = 128; + $maxheightmini = 72; + + $formmail = new FormMail($this->db); + + $attachedfiles = $formmail->get_attached_files(); + $filepath = $attachedfiles['paths']; + $filename = $attachedfiles['names']; + $mimetype = $attachedfiles['mimes']; + + // Copy files into ticket directory + $destdir = $conf->ticketsup->dir_output . '/' . $this->dao->track_id; + + if (!dol_is_dir($destdir)) { + dol_mkdir($destdir); + } + foreach ($filename as $i => $val) { + $res = dol_move($filepath[$i], $destdir . '/' . $filename[$i]); + if (image_format_supported($destdir . '/' . $filename[$i]) == 1) { + // Create small thumbs for image (Ratio is near 16/9) + // Used on logon for example + $imgThumbSmall = vignette($destdir . '/' . $filename[$i], $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs"); + // Create mini thumbs for image (Ratio is near 16/9) + // Used on menu or for setup page for example + $imgThumbMini = vignette($destdir . '/' . $filename[$i], $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs"); + } + $formmail->remove_attached_files($i); + } + } + + /** + * Print html navbar with link to set ticket status + * + * @global type $langs + * @param type $selected : 0=>'NotRead', 1=>'Read', 3=>'Answered', 4=>'Assigned', 5 => 'InProgress', 6=> 'Waiting', 8=>'Closed', 9=>'Deleted' + */ + public function viewStatusActions() + { + global $langs; + + print '
    '; + print '
    '; + print '
    '; + print '' . $langs->trans('TicketChangeStatus') . ''; + print '
    '; + // Exclude status which requires specific method + $exclude_status = array(4, 9, 8); + // Exclude actual status + $exclude_status = array_merge($exclude_status, array(intval($this->dao->fk_statut))); + + // If status is new, don't show link which allow mark ticket as read + // Specific method exists to mark a ticket as read + if ($this->dao->fk_statut === '0') { + $exclude_status = array_merge($exclude_status, array(1)); + } + + // Sort results to be similar to status object list + sort($exclude_status); + + //print '
    '; + foreach ($this->dao->statuts_short as $status => $statut_label) { + if (!in_array($status, $exclude_status)) { + print ''; + } + } + print '

    '; + } + + + + public function deleteObjectLinked() + { + return $this->dao->deleteObjectLinked(); + } + + /** + * Hook to add email element template + * + * @param array $parameters + * @param Object $object + * @param string $action + * @param HookManager $hookmanager + * @return int + */ + public function emailElementlist($parameters, &$object, &$action, $hookmanager) + { + global $langs; + + $error = 0; + + if (in_array('admin', explode(':', $parameters['context']))) { + $this->results = array('ticketsup_send' => $langs->trans('MailToSendTicketsupMessage')); + } + + if (! $error) { + return 0; // or return 1 to replace standard code + } else { + $this->errors[] = 'Error message'; + return -1; + } + } +} diff --git a/htdocs/ticketsup/class/api_dictionaryticketsupcategories.class.php b/htdocs/ticketsup/class/api_dictionaryticketsupcategories.class.php new file mode 100644 index 00000000000..ce81bc67f6c --- /dev/null +++ b/htdocs/ticketsup/class/api_dictionaryticketsupcategories.class.php @@ -0,0 +1,100 @@ + + * Copyright (C) 2016 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +use Luracast\Restler\RestException; + +require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; + +/** + * API class for ticketsup types + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class DictionaryTicketsupCategories extends DolibarrApi +{ + private $translations = null; + + /** + * Constructor + */ + function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of ticketsup types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return List of events types + * + * @throws RestException + */ + function index($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, description"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_ticketsup_category as t"; + $sql.= " WHERE t.active = 1"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticketsup categories : '.$this->db->lasterror()); + } + + return $list; + } + + +} diff --git a/htdocs/ticketsup/class/api_dictionaryticketsupseverities.class.php b/htdocs/ticketsup/class/api_dictionaryticketsupseverities.class.php new file mode 100644 index 00000000000..c41f66a379e --- /dev/null +++ b/htdocs/ticketsup/class/api_dictionaryticketsupseverities.class.php @@ -0,0 +1,100 @@ + + * Copyright (C) 2016 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +use Luracast\Restler\RestException; + +require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; + +/** + * API class for ticketsup severities + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class DictionaryTicketsupSeverities extends DolibarrApi +{ + private $translations = null; + + /** + * Constructor + */ + function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of ticketsup types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return List of events types + * + * @throws RestException + */ + function index($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, color, description"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_ticketsup_severity as t"; + $sql.= " WHERE t.active = 1"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticketsup severities : '.$this->db->lasterror()); + } + + return $list; + } + + +} diff --git a/htdocs/ticketsup/class/api_dictionaryticketsuptypes.class.php b/htdocs/ticketsup/class/api_dictionaryticketsuptypes.class.php new file mode 100644 index 00000000000..008e2be337a --- /dev/null +++ b/htdocs/ticketsup/class/api_dictionaryticketsuptypes.class.php @@ -0,0 +1,102 @@ + + * Copyright (C) 2016 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +use Luracast\Restler\RestException; + +require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; + +/** + * API class for ticketsup types + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class DictionaryTicketsupTypes extends DolibarrApi +{ + private $translations = null; + + /** + * Constructor + */ + function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of ticketsup types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return List of events types + * + * @throws RestException + */ + function index($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, description"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_ticketsup_type as t"; + $sql.= " WHERE t.active = 1"; + if ($type) $sql.=" AND t.type LIKE '%" . $this->db->escape($type) . "%'"; + if ($module) $sql.=" AND t.module LIKE '%" . $this->db->escape($module) . "%'"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticketsup types : '.$this->db->lasterror()); + } + + return $list; + } + + +} diff --git a/htdocs/ticketsup/class/api_ticketsups.class.php b/htdocs/ticketsup/class/api_ticketsups.class.php new file mode 100644 index 00000000000..019ecc05934 --- /dev/null +++ b/htdocs/ticketsup/class/api_ticketsups.class.php @@ -0,0 +1,543 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + use Luracast\Restler\RestException; + +require 'ticketsup.class.php'; +dol_include_once('/ticketsup/lib/ticketsup.lib.php'); + +/** + * API class for ticketsup object + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + * + * + */ +class Ticketsups extends DolibarrApi +{ + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + public static $FIELDS = array( + 'subject', + 'message' + ); + + /** + * @var array $FIELDS_MESSAGES Mandatory fields, checked when create and update object + */ + public static $FIELDS_MESSAGES = array( + 'track_id', + 'message' + ); + + /** + * @var Ticketsup $ticketsup {@type Ticketsup} + */ + public $ticketsup; + + /** + * Constructor + * + * @url GET ticketsup/ + * + */ + public function __construct() + { + global $db; + $this->db = $db; + $this->ticketsup = new Ticketsup($this->db); + } + + /** + * Get properties of a ticketsup object + * + * Return an array with ticketsup informations + * + * @param int $id ID of ticketsup + * @param string $track_id Tracking ID of ticket + * @param string $ref Reference for ticket + * @return array|mixed data without useless information + * + * @url GET track_id/{track_id} + * @url GET ref/{ref} + * @url GET {id} + * @throws RestException + */ + public function get($id = 0, $track_id = '', $ref = '') + { + if (! DolibarrApiAccess::$user->rights->ticketsup->read) { + throw new RestException(401); + } + + // Check parameters + if (!$id && !$track_id && !$ref) { + throw new RestException(401, 'Wrong parameters'); + } + + $result = $this->ticketsup->fetch($id, $track_id, $ref); + if (! $result) { + throw new RestException(404, 'Ticketsup not found'); + } + + // String for user assigned + if ($this->ticketsup->fk_user_assign > 0) { + $userStatic = new User($this->db); + $userStatic->fetch($this->ticketsup->fk_user_assign); + $this->ticketsup->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname; + } + + // Messages of ticket + $messages = array(); + $this->ticketsup->loadCacheMsgsTicket(); + if (is_array($this->ticketsup->cache_msgs_ticket) && count($this->ticketsup->cache_msgs_ticket) > 0) { + $num = count($this->ticketsup->cache_msgs_ticket); + $i = 0; + while ($i < $num) { + if ($this->ticketsup->cache_msgs_ticket[$i]['fk_user_action'] > 0) { + $user_action = new User($this->db); + $user_action->fetch($this->ticketsup->cache_msgs_ticket[$i]['fk_user_action']); + } + + // Now define messages + $messages[] = array( + 'id' => $this->ticketsup->cache_msgs_ticket[$i]['id'], + 'fk_user_action' => $this->ticketsup->cache_msgs_ticket[$i]['fk_user_action'], + 'fk_user_action_socid' => $user_action->socid, + 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname), + 'message' => $this->ticketsup->cache_msgs_ticket[$i]['message'], + 'datec' => $this->ticketsup->cache_msgs_ticket[$i]['datec'], + 'private' => $this->ticketsup->cache_msgs_ticket[$i]['private'] + ); + $i++; + } + $this->ticketsup->messages = $messages; + } + + // History + $history = array(); + $this->ticketsup->loadCacheLogsTicket(); + if (is_array($this->ticketsup->cache_logs_ticket) && count($this->ticketsup->cache_logs_ticket) > 0) { + $num = count($this->ticketsup->cache_logs_ticket); + $i = 0; + while ($i < $num) { + if ($this->ticketsup->cache_logs_ticket[$i]['fk_user_create'] > 0) { + $user_action = new User($this->db); + $user_action->fetch($this->ticketsup->cache_logs_ticket[$i]['fk_user_create']); + } + + // Now define messages + $history[] = array( + 'id' => $this->ticketsup->cache_logs_ticket[$i]['id'], + 'fk_user_action' => $this->ticketsup->cache_logs_ticket[$i]['fk_user_create'], + 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname), + 'message' => $this->ticketsup->cache_logs_ticket[$i]['message'], + 'datec' => $this->ticketsup->cache_logs_ticket[$i]['datec'], + ); + $i++; + } + $this->ticketsup->history = $history; + } + + + if (! DolibarrApi::_checkAccessToResource('ticketsup', $this->ticketsup->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + return $this->_cleanObjectDatas($this->ticketsup); + } + + /** + * List ticketsups + * + * Get a list of ticketsups + * + * @param int $socid Filter list with thirdparty ID + * @param string $mode Use this param to filter list + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * + * @return array Array of ticketsup objects + * + */ + public function index($socid = 0, $mode = "", $sortfield = "s.rowid", $sortorder = "ASC", $limit = 0, $page = 0, $sqlfilters = '') + { + global $db, $conf; + + $obj_ret = array(); + + if (!$socid && DolibarrApiAccess::$user->societe_id) { + $socid = DolibarrApiAccess::$user->societe_id; + } + + // If the internal user must only see his customers, force searching by him + if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) { + $search_sale = DolibarrApiAccess::$user->id; + } + + $sql = "SELECT s.rowid"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } + $sql.= " FROM ".MAIN_DB_PREFIX."ticketsup as s"; + + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } + + $sql.= ' WHERE s.entity IN ('.getEntity('ticketsup', 1).')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql.= " AND s.fk_soc = sc.fk_soc"; + } + if ($socid > 0) { + $sql.= " AND s.fk_soc = ".$socid; + } + if ($search_sale > 0) { + $sql.= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } + + // Example of use $mode + if ($mode == 'new') { + $sql.= " AND s.fk_statut IN (0)"; + } + if ($mode == 'read') { + $sql.= " AND s.fk_statut IN (1)"; + } + if ($mode == 'answered') { + $sql.= " AND s.fk_statut IN (3)"; + } + if ($mode == 'assign') { + $sql.= " AND s.fk_statut IN (4)"; + } + if ($mode == 'inprogress') { + $sql.= " AND s.fk_statut IN (5)"; + } + if ($mode == 'waiting') { + $sql.= " AND s.fk_statut IN (6)"; + } + if ($mode == 'closed') { + $sql.= " AND s.fk_statut IN (8)"; + } + if ($mode == 'deleted') { + $sql.= " AND s.fk_statut IN (9)"; + } + + // Insert sale filter + if ($search_sale > 0) { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + if ($sqlfilters) { + if (! DolibarrApi::_checkFilters($sqlfilters)) { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $db->order($sortfield, $sortorder); + + $nbtotalofrecords = 0; + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + } + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql.= $db->plimit($limit + 1, $offset); + } + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + while ($i < $num) { + $obj = $db->fetch_object($result); + $ticketsup_static = new Ticketsup($db); + if ($ticketsup_static->fetch($obj->rowid)) { + if ($ticketsup_static->fk_user_assign > 0) { + $userStatic = new User($this->db); + $userStatic->fetch($ticketsup_static->fk_user_assign); + $ticketsup_static->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname; + } + $obj_ret[] = $this->_cleanObjectDatas($ticketsup_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve ticketsup list'); + } + if (! count($obj_ret)) { + throw new RestException(404, 'No ticketsup found'); + } + return $obj_ret; + } + + /** + * Create ticketsup object + * + * @param array $request_data Request datas + * @return int ID of ticketsup + * + */ + public function post($request_data = null) + { + $ticketstatic = new Ticketsup($this->db); + if (! DolibarrApiAccess::$user->rights->ticketsup->create) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validate($request_data); + + foreach ($request_data as $field => $value) { + $this->ticketsup->$field = $value; + } + if (empty($this->ticketsup->ref)) { + $this->ticketsup->ref = $ticketstatic->getDefaultRef(); + } + if (empty($this->ticketsup->track_id)) { + $this->ticketsup->track_id = generate_random_id(16); + } + if (! $this->ticketsup->create(DolibarrApiAccess::$user)) { + throw new RestException(500); + } + return $this->ticketsup->id; + } + + /** + * Create ticketsup object + * + * @param array $request_data Request datas + * @return int ID of ticketsup + * + */ + public function postNewMessage($request_data = null) + { + $ticketstatic = new Ticketsup($this->db); + if (! DolibarrApiAccess::$user->rights->ticketsup->create) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validateMessage($request_data); + + foreach ($request_data as $field => $value) { + $this->ticketsup->$field = $value; + } + $ticketMessageText = $this->ticketsup->message; + $result = $this->ticketsup->fetch('', $this->ticketsup->track_id); + if (! $result) { + throw new RestException(404, 'Ticketsup not found'); + } + $this->ticketsup->message = $ticketMessageText; + if (! $this->ticketsup->createTicketMessage(DolibarrApiAccess::$user)) { + throw new RestException(500); + } + return $this->ticketsup->id; + } + + /** + * Update ticketsup + * + * @param int $id Id of ticketsup to update + * @param array $request_data Datas + * @return int + * + */ + public function put($id, $request_data = null) + { + if (! DolibarrApiAccess::$user->rights->ticketsup->create) { + throw new RestException(401); + } + + $result = $this->ticketsup->fetch($id); + if (! $result) { + throw new RestException(404, 'Ticketsup not found'); + } + + if (! DolibarrApi::_checkAccessToResource('ticketsup', $this->ticketsup->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + foreach ($request_data as $field => $value) { + $this->ticketsup->$field = $value; + } + + if ($this->ticketsup->update($id, DolibarrApiAccess::$user)) { + return $this->get($id); + } + + return false; + } + + /** + * Delete ticketsup + * + * @param int $id Ticketsup ID + * @return array + * + */ + public function delete($id) + { + if (! DolibarrApiAccess::$user->rights->ticketsup->supprimer) { + throw new RestException(401); + } + $result = $this->ticketsup->fetch($id); + if (! $result) { + throw new RestException(404, 'Ticketsup not found'); + } + + if (! DolibarrApi::_checkAccessToResource('ticketsup', $this->ticketsup->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if (!$this->ticketsup->delete($id)) { + throw new RestException(500); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Ticketsup deleted' + ) + ); + } + + /** + * Validate fields before create or update object + * + * @param array $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $ticketsup = array(); + foreach (Ticketsups::$FIELDS as $field) { + if (!isset($data[$field])) { + throw new RestException(400, "$field field missing"); + } + $ticketsup[$field] = $data[$field]; + } + return $ticketsup; + } + + /** + * Validate fields before create or update object message + * + * @param array $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validateMessage($data) + { + $ticketsup = array(); + foreach (Ticketsups::$FIELDS_MESSAGES as $field) { + if (!isset($data[$field])) { + throw new RestException(400, "$field field missing"); + } + $ticketsup[$field] = $data[$field]; + } + return $ticketsup; + } + + + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + * + * @todo use an array for properties to clean + * + */ + public function _cleanObjectDatas($object) + { + + // Remove $db object property for object + unset($object->db); + + $attr2clean = array( + "contact", + "contact_id", + "ref_previous", + "ref_next", + "ref_ext", + "table_element_line", + "statut", + "country", + "country_id", + "country_code", + "barcode_type", + "barcode_type_code", + "barcode_type_label", + "barcode_type_coder", + "mode_reglement_id", + "cond_reglement_id", + "cond_reglement", + "fk_delivery_address", + "shipping_method_id", + "modelpdf", + "fk_account", + "note_public", + "note_private", + "note", + "total_ht", + "total_tva", + "total_localtax1", + "total_localtax2", + "total_ttc", + "fk_incoterms", + "libelle_incoterms", + "location_incoterms", + "name", + "lastname", + "firstname", + "civility_id", + "cache_msgs_ticket", + "cache_logs_ticket" + ); + foreach ($attr2clean as $toclean) { + unset($object->$toclean); + } + + // If object has lines, remove $db property + if (isset($object->lines) && count($object->lines) > 0) { + $nboflines = count($object->lines); + for ($i=0; $i < $nboflines; $i++) { + $this->_cleanObjectDatas($object->lines[$i]); + } + } + + // If object has linked objects, remove $db property + if (isset($object->linkedObjects) && count($object->linkedObjects) > 0) { + foreach ($object->linkedObjects as $type_object => $linked_object) { + foreach ($linked_object as $object2clean) { + $this->_cleanObjectDatas($object2clean); + } + } + } + return $object; + } +} diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php new file mode 100644 index 00000000000..289a865b4e8 --- /dev/null +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -0,0 +1,2788 @@ + + * 2016 Christophe Battarel + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file ticketsup/class/ticketsup.class.php + * \ingroup ticketsup + * \brief Class file for object ticketsup + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT . "/core/class/commonobject.class.php"; +require_once DOL_DOCUMENT_ROOT . '/fichinter/class/fichinter.class.php'; +//require_once(DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); +//require_once(DOL_DOCUMENT_ROOT."/product/class/product.class.php"); + +/** + * Put here description of your class + */ +class Ticketsup extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element = 'ticketsup'; + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'ticketsup'; + /** + * @var int Does ticketsupcore support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 0; + /** + * @var int Does ticketsupcore support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 1; + /** + * @var string String with name of icon for ticketsupcore. Must be the part after the 'object_' into object_ticketsupcore.png + */ + public $picto = 'ticketsup@ticketsup'; + + + /** + * @var string Hash to identify ticket + */ + public $track_id; + + /** + * @var int Thirdparty ID + */ + public $fk_soc; + + /** + * @var int Project ID + */ + public $fk_project; + + /** + * @var string Person email who have create ticket + */ + public $origin_email; + + /** + * @var int User id who have create ticket + */ + public $fk_user_create; + + /** + * @var int User id who have ticket assigned + */ + public $fk_user_assign; + + /** + * var string Ticket subject + */ + public $subject; + + /** + * @var string Ticket message + */ + public $message; + + /** + * @var int Ticket statut + */ + public $fk_statut; + + /** + * @var string State resolution + */ + public $resolution; + + /** + * @var int Progress in percent + */ + public $progress; + + /** + * @var int Duration for ticket + */ + public $timing; + + /** + * @var string Type code + */ + public $type_code; + + /** + * @var string Category code + */ + public $category_code; + + /** + * @var string Severity code + */ + public $severity_code; + + /** + * @var int Création date + */ + public $datec = ''; + + /** + * @var int Read date + */ + public $date_read = ''; + + /** + * @var int Close ticket date + */ + public $date_close = ''; + + /** + * @var array cache_types_tickets + */ + public $cache_types_tickets; + + /** + * @var array tickets categories + */ + public $cache_category_tickets; + + /** + * @var int Notify tiers at create + */ + public $notify_tiers_at_create; + + public $lines; + + /** + * @var string Regex pour les images + */ + public $regeximgext = '\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff'; + + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id"), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1), + 'notify_tiers_at_create' => array('type'=>'integer', 'label'=>'NotifyThirdparty', 'visible'=>-2, 'enabled'=>0, 'position'=>20, 'notnull'=>1, 'index'=>1), + 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object"), + 'track_id' => array('type'=>'varchar(255)', 'label'=>'TrackID', 'visible'=>0, 'enabled'=>1, 'position'=>30, 'notnull'=>-1, 'searchall'=>1, 'help'=>"Help text"), + 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>1, 'help'=>"LinkToThirparty"), + 'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php', 'label'=>'Project', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>1, 'help'=>"LinkToProject"), + 'origin_email' => array('type'=>'mail', 'label'=>'OriginEmail', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object"), + 'fk_user_create' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Author', 'visible'=>1, 'enabled'=>1, 'position'=>510, 'notnull'=>1), + 'fk_user_assign' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'AuthorAssign', 'visible'=>1, 'enabled'=>1, 'position'=>510, 'notnull'=>1), + 'subject' => array('type'=>'varchar(255)', 'label'=>'Subject', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), + 'message' => array('type'=>'text', 'label'=>'Message', 'visible'=>-2, 'enabled'=>1, 'position'=>60, 'notnull'=>-1,), + 'fk_statut' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array(0 => 'NotRead', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted')), + 'resolution' => array('type'=>'integer', 'label'=>'Resolution', 'visible'=>-2, 'enabled'=>1, 'position'=>40, 'notnull'=>1), + 'progress' => array('type'=>'varchar(100)', 'label'=>'Progression', 'visible'=>1, 'enabled'=>1, 'position'=>41, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), + 'timing' => array('type'=>'varchar(20)', 'label'=>'Timing', 'visible'=>-1, 'enabled'=>1, 'position'=>42, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), + 'type_code' => array('type'=>'varchar(32)', 'label'=>'Type', 'visible'=>1, 'enabled'=>1, 'position'=>20, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), + 'category_code' => array('type'=>'varchar(32)', 'label'=>'Category', 'visible'=>1, 'enabled'=>1, 'position'=>21, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), + 'severity_code' => array('type'=>'varchar(32)', 'label'=>'Severity', 'visible'=>1, 'enabled'=>1, 'position'=>22, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), + 'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1), + 'date_read' => array('type'=>'datetime', 'label'=>'TicketReadOn', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1), + 'date_close' => array('type'=>'datetime', 'label'=>'TicketCloseOn', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1), + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>501, 'notnull'=>1) + + ); + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + + $this->statuts_short = array(0 => 'NotRead', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted'); + $this->statuts = array(0 => 'NotRead', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted'); + } + + /** + * Check properties of ticket are ok (like ref, track_id, ...). + * All properties must be already loaded on object (this->ref, this->track_id, ...). + * + * @return int 0 if OK, <0 if KO + */ + private function verify() + { + $this->errors = array(); + + $result = 0; + + // Clean parameters + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + + if (isset($this->track_id)) { + $this->track_id = trim($this->track_id); + } + + if (isset($this->fk_soc)) { + $this->fk_soc = trim($this->fk_soc); + } + + if (isset($this->fk_project)) { + $this->fk_project = trim($this->fk_project); + } + + if (isset($this->origin_email)) { + $this->origin_email = trim($this->origin_email); + } + + if (isset($this->fk_user_create)) { + $this->fk_user_create = trim($this->fk_user_create); + } + + if (isset($this->fk_user_assign)) { + $this->fk_user_assign = trim($this->fk_user_assign); + } + + if (isset($this->subject)) { + $this->subject = trim($this->subject); + } + + if (isset($this->message)) { + $this->message = trim($this->message); + } + + if (isset($this->fk_statut)) { + $this->fk_statut = trim($this->fk_statut); + } + + if (isset($this->resolution)) { + $this->resolution = trim($this->resolution); + } + + if (isset($this->progress)) { + $this->progress = trim($this->progress); + } + + if (isset($this->timing)) { + $this->timing = trim($this->timing); + } + + if (isset($this->type_code)) { + $this->type_code = trim($this->type_code); + } + + if (isset($this->category_code)) { + $this->category_code = trim($this->category_code); + } + + if (isset($this->severity_code)) { + $this->severity_code = trim($this->severity_code); + } + + if (empty($this->ref)) { + $this->errors[] = 'ErrorBadRef'; + dol_syslog(get_class($this) . "::create error -1 ref null", LOG_ERR); + $result = -1; + } + + return $result; + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + $this->datec = dol_now(); + + // Check more parameters + // If error, this->errors[] is filled + $result = $this->verify(); + if ($result >= 0) { + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "ticketsup("; + $sql .= "ref,"; + $sql .= "track_id,"; + $sql .= "fk_soc,"; + $sql .= "fk_project,"; + $sql .= "origin_email,"; + $sql .= "fk_user_create,"; + $sql .= "fk_user_assign,"; + $sql .= "subject,"; + $sql .= "message,"; + $sql .= "fk_statut,"; + $sql .= "resolution,"; + $sql .= "progress,"; + $sql .= "timing,"; + $sql .= "type_code,"; + $sql .= "category_code,"; + $sql .= "severity_code,"; + $sql .= "datec,"; + $sql .= "date_read,"; + $sql .= "date_close"; + $sql .= ", entity"; + $sql .= ", notify_tiers_at_create"; + $sql .= ") VALUES ("; + $sql .= " " . (!isset($this->ref) ? '' : "'" . $this->db->escape($this->ref) . "'") . ","; + $sql .= " " . (!isset($this->track_id) ? 'NULL' : "'" . $this->db->escape($this->track_id) . "'") . ","; + $sql .= " " . (!isset($this->fk_soc) ? '0' : "'" . $this->db->escape($this->fk_soc) . "'") . ","; + $sql .= " " . (!isset($this->fk_project) ? '0' : "'" . $this->db->escape($this->fk_project) . "'") . ","; + $sql .= " " . (!isset($this->origin_email) ? 'NULL' : "'" . $this->db->escape($this->origin_email) . "'") . ","; + $sql .= " " . (!isset($this->fk_user_create) ? ($user->id ? $user->id : 'NULL') : "'" . $this->fk_user_create . "'") . ","; + $sql .= " " . (!isset($this->fk_user_assign) ? 'NULL' : "'" . $this->fk_user_assign . "'") . ","; + $sql .= " " . (!isset($this->subject) ? 'NULL' : "'" . $this->db->escape($this->subject) . "'") . ","; + $sql .= " " . (!isset($this->message) ? 'NULL' : "'" . $this->db->escape($this->message) . "'") . ","; + $sql .= " " . (!isset($this->fk_statut) ? '0' : "'" . $this->fk_statut . "'") . ","; + $sql .= " " . (!isset($this->resolution) ? 'NULL' : "'" . $this->resolution . "'") . ","; + $sql .= " " . (!isset($this->progress) ? '0' : "'" . $this->db->escape($this->progress) . "'") . ","; + $sql .= " " . (!isset($this->timing) ? 'NULL' : "'" . $this->db->escape($this->timing) . "'") . ","; + $sql .= " " . (!isset($this->type_code) ? 'NULL' : "'" . $this->db->escape($this->type_code) . "'") . ","; + $sql .= " " . (!isset($this->category_code) ? 'NULL' : "'" . $this->db->escape($this->category_code) . "'") . ","; + $sql .= " " . (!isset($this->severity_code) ? 'NULL' : "'" . $this->db->escape($this->severity_code) . "'") . ","; + $sql .= " " . (!isset($this->datec) || dol_strlen($this->datec) == 0 ? 'NULL' : "'" . $this->db->idate($this->datec) . "'") . ","; + $sql .= " " . (!isset($this->date_read) || dol_strlen($this->date_read) == 0 ? 'NULL' : "'" . $this->db->idate($this->date_read) . "'") . ","; + $sql .= " " . (!isset($this->date_close) || dol_strlen($this->date_close) == 0 ? 'NULL' : "'" . $this->db->idate($this->date_close) . "'") . ""; + $sql .= ", " . $conf->entity; + $sql .= ", " . (!isset($this->notify_tiers_at_create) ? '1' : "'" . $this->db->escape($this->notify_tiers_at_create) . "'"); + $sql .= ")"; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "ticketsup"); + + if (!$notrigger) { + // Call trigger + $result=$this->call_trigger('TICKET_CREATE', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + } + + //Update extrafield + if (!$error) { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) { // For avoid conflicts if trigger used + $result = $this->insertExtraFields(); + if ($result < 0) { + $error++; + } + } + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return $this->id; + } + } else { + $this->db->rollback(); + dol_syslog(get_class($this) . "::Create fails verify " . join(',', $this->errors), LOG_WARNING); + return -3; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @return int <0 if KO, >0 if OK + */ + + // possible to change the order of value, standard welcome is = id, ref, track_id ??? + public function fetch($id = '', $track_id = '', $ref = '') + { + global $langs; + + // Check parameters + if (!$id && !$track_id && !$ref) { + $this->error = 'ErrorWrongParameters'; + dol_print_error(get_class($this) . "::fetch " . $this->error); + return -1; + } + + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.ref,"; + $sql .= " t.track_id,"; + $sql .= " t.fk_soc,"; + $sql .= " t.fk_project,"; + $sql .= " t.origin_email,"; + $sql .= " t.fk_user_create,"; + $sql .= " t.fk_user_assign,"; + $sql .= " t.subject,"; + $sql .= " t.message,"; + $sql .= " t.fk_statut,"; + $sql .= " t.resolution,"; + $sql .= " t.progress,"; + $sql .= " t.timing,"; + $sql .= " t.type_code,"; + $sql .= " t.category_code,"; + $sql .= " t.severity_code,"; + $sql .= " t.datec,"; + $sql .= " t.date_read,"; + $sql .= " t.date_close,"; + $sql .= " t.tms"; + $sql .= ", type.code as type_code, type.label as type_label, category.code as category_code, category.label as category_label, severity.code as severity_code, severity.label as severity_label"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup as t"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_type as type ON type.code=t.type_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_category as category ON category.code=t.category_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_severity as severity ON severity.code=t.severity_code"; + + if ($id) { + $sql .= " WHERE t.rowid = " . $this->db->escape($id); + } else { + $sql .= " WHERE t.entity IN (" . getEntity($this->element, 1) . ")"; + if ($track_id) { + $sql .= " AND t.track_id = '" . $this->db->escape($track_id) . "'"; + } elseif ($ref) { + $sql .= " AND t.ref = '" . $this->db->escape($ref) . "'"; + } + } + + dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->ref = $obj->ref; + $this->track_id = $obj->track_id; + $this->fk_soc = $obj->fk_soc; + $this->socid = $obj->fk_soc; // for fetch_thirdparty() method + $this->fk_project = $obj->fk_project; + $this->origin_email = $obj->origin_email; + $this->fk_user_create = $obj->fk_user_create; + $this->fk_user_assign = $obj->fk_user_assign; + $this->subject = $obj->subject; + $this->message = $obj->message; + $this->fk_statut = $obj->fk_statut; + $this->resolution = $obj->resolution; + $this->progress = $obj->progress; + $this->timing = $obj->timing; + + $this->type_code = $obj->type_code; + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label_type = ($langs->trans("TicketTypeShort" . $obj->type_code) != ("TicketTypeShort" . $obj->type_code) ? $langs->trans("TicketTypeShort" . $obj->type_code) : ($obj->type_label != '-' ? $obj->type_label : '')); + $this->type_label = $label_type; + + $this->category_code = $obj->category_code; + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label_category = ($langs->trans("TicketCategoryShort" . $obj->category_code) != ("TicketCategoryShort" . $obj->category_code) ? $langs->trans("TicketCategoryShort" . $obj->category_code) : ($obj->category_label != '-' ? $obj->category_label : '')); + $this->category_label = $label_category; + + $this->severity_code = $obj->severity_code; + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label_severity = ($langs->trans("TicketSeverityShort" . $obj->severity_code) != ("TicketSeverityShort" . $obj->severity_code) ? $langs->trans("TicketSeverityShort" . $obj->severity_code) : ($obj->severity_label != '-' ? $obj->severity_label : '')); + $this->severity_label = $label_severity; + + $this->datec = $this->db->jdate($obj->datec); + $this->date_read = $this->db->jdate($obj->date_read); + $this->date_close = $this->db->jdate($obj->date_close); + $this->tms = $this->db->jdate($obj->tms); + + if (!class_exists('ExtraFields')) { + include_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; + } + + $extrafields = new ExtraFields($this->db); + $extralabels = $extrafields->fetch_name_optionals_label($this->table_element, true); + if (count($extralabels) > 0) { + $this->fetch_optionals($this->id, $extralabels); + } + } + $this->db->free($resql); + + return 1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Load all objects in memory from database + * + * @param string $sortorder Sort order + * @param string $sortfield Sort field + * @param int $limit page number + * @param int $offset + * @param int $arch archive or not (not used) + * @param array $filter + * output + * @return int <0 if KO, >0 if OK + */ + public function fetchAll($user, $sortorder = 'ASC', $sortfield = 't.datec', $limit = '', $offset = 0, $arch = '', $filter = '') + { + global $langs; + + $extrafields = new ExtraFields($this->db); + + // fetch optionals attributes and labels + $extralabels = $extrafields->fetch_name_optionals_label($this->element); + + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.ref,"; + $sql .= " t.track_id,"; + $sql .= " t.fk_soc,"; + $sql .= " t.fk_project,"; + $sql .= " t.origin_email,"; + $sql .= " t.fk_user_create, uc.lastname as user_create_lastname, uc.firstname as user_create_firstname,"; + $sql .= " t.fk_user_assign, ua.lastname as user_assign_lastname, ua.firstname as user_assign_firstname,"; + $sql .= " t.subject,"; + $sql .= " t.message,"; + $sql .= " t.fk_statut,"; + $sql .= " t.resolution,"; + $sql .= " t.progress,"; + $sql .= " t.timing,"; + $sql .= " t.type_code,"; + $sql .= " t.category_code,"; + $sql .= " t.severity_code,"; + $sql .= " t.datec,"; + $sql .= " t.date_read,"; + $sql .= " t.date_close,"; + $sql .= " t.tms"; + $sql .= ", type.label as type_label, category.label as category_label, severity.label as severity_label"; + // Add fields for extrafields + foreach ($extrafields->attribute_list as $key => $val) { + $sql .= ($extrafields->attribute_type[$key] != 'separate' ? ",ef." . $key . ' as options_' . $key : ''); + } + $sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup as t"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_type as type ON type.code=t.type_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_category as category ON category.code=t.category_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_severity as severity ON severity.code=t.severity_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid=t.fk_soc"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user as uc ON uc.rowid=t.fk_user_create"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user as ua ON ua.rowid=t.fk_user_assign"; + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "ticketsup_extrafields as ef on (t.rowid = ef.fk_object)"; + } + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc"; + } + + $sql .= " WHERE t.entity IN (" . getEntity('ticketsup') . ")"; + + // Manage filter + if (!empty($filter)) { + foreach ($filter as $key => $value) { + if (strpos($key, 'date')) { // To allow $filter['YEAR(s.dated)']=>$year + $sql .= ' AND ' . $key . ' = \'' . $value . '\''; + } elseif (($key == 't.fk_user_assign') || ($key == 't.type_code') || ($key == 't.category_code') || ($key == 't.severity_code') || ($key == 't.fk_soc')) { + $sql .= " AND " . $key . " = '" . $this->db->escape($value) ."'"; + } elseif ($key == 't.fk_statut') { + if (is_array($value) && count($value) > 0) { + $sql .= 'AND ' . $key . ' IN (' . implode(',', $value) . ')'; + } else { + $sql .= ' AND ' . $key . ' = ' . $this->db->escape($value); + } + } else { + $sql .= ' AND ' . $key . ' LIKE \'%' . $value . '%\''; + } + } + } + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= " AND t.fk_soc = sc.fk_soc AND sc.fk_user = " . $user->id; + } elseif ($user->socid) { + $sql .= " AND t.fk_soc = " . $user->socid; + } + + $sql .= " ORDER BY " . $sortfield . ' ' . $sortorder; + if (!empty($limit)) { + $sql .= ' ' . $this->db->plimit($limit + 1, $offset); + } + + dol_syslog(get_class($this) . "::fetch_all sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $this->lines = array(); + + $num = $this->db->num_rows($resql); + $i = 0; + + if ($num) { + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + + $line = new TicketsLine(); + + $line->rowid = $obj->rowid; + $line->ref = $obj->ref; + $line->track_id = $obj->track_id; + $line->fk_soc = $obj->fk_soc; + $line->fk_project = $obj->fk_project; + $line->origin_email = $obj->origin_email; + + $line->fk_user_create = $obj->fk_user_create; + $line->user_create_lastname = $obj->user_create_lastname; + $line->user_create_firstname = $obj->user_create_firstname; + + $line->fk_user_assign = $obj->fk_user_assign; + $line->user_assign_lastname = $obj->user_assign_lastname; + $line->user_assign_firstname = $obj->user_assign_firstname; + + $line->subject = $obj->subject; + $line->message = $obj->message; + $line->fk_statut = $obj->fk_statut; + $line->resolution = $obj->resolution; + $line->progress = $obj->progress; + $line->timing = $obj->timing; + + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label_type = ($langs->trans("TicketTypeShort" . $obj->type_code) != ("TicketTypeShort" . $obj->type_code) ? $langs->trans("TicketTypeShort" . $obj->type_code) : ($obj->type_label != '-' ? $obj->type_label : '')); + $line->type_label = $label_type; + + $this->category_code = $obj->category_code; + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label_category = ($langs->trans("TicketCategoryShort" . $obj->category_code) != ("TicketCategoryShort" . $obj->category_code) ? $langs->trans("TicketCategoryShort" . $obj->category_code) : ($obj->category_label != '-' ? $obj->category_label : '')); + $line->category_label = $label_category; + + $this->severity_code = $obj->severity_code; + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label_severity = ($langs->trans("TicketSeverityShort" . $obj->severity_code) != ("TicketSeverityShort" . $obj->severity_code) ? $langs->trans("TicketSeverityShort" . $obj->severity_code) : ($obj->severity_label != '-' ? $obj->severity_label : '')); + $line->severity_label = $label_severity; + + $line->datec = $this->db->jdate($obj->datec); + $line->date_read = $this->db->jdate($obj->date_read); + $line->date_close = $this->db->jdate($obj->date_close); + + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { + foreach ($extrafields->attribute_label as $key => $val) { + $tmpkey = 'options_' . $key; + $line->{$tmpkey} = $obj->$tmpkey; + } + } + + $this->lines[$i] = $line; + $i++; + } + } + $this->db->free($resql); + return $num; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch_all " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = 0, $notrigger = 0) + { + global $conf, $langs, $hookmanager; + $error = 0; + + // Clean parameters + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + + if (isset($this->track_id)) { + $this->track_id = trim($this->track_id); + } + + if (isset($this->fk_soc)) { + $this->fk_soc = trim($this->fk_soc); + } + + if (isset($this->fk_project)) { + $this->fk_project = trim($this->fk_project); + } + + if (isset($this->origin_email)) { + $this->origin_email = trim($this->origin_email); + } + + if (isset($this->fk_user_create)) { + $this->fk_user_create = trim($this->fk_user_create); + } + + if (isset($this->fk_user_assign)) { + $this->fk_user_assign = trim($this->fk_user_assign); + } + + if (isset($this->subject)) { + $this->subject = trim($this->subject); + } + + if (isset($this->message)) { + $this->message = trim($this->message); + } + + if (isset($this->fk_statut)) { + $this->fk_statut = trim($this->fk_statut); + } + + if (isset($this->resolution)) { + $this->resolution = trim($this->resolution); + } + + if (isset($this->progress)) { + $this->progress = trim($this->progress); + } + + if (isset($this->timing)) { + $this->timing = trim($this->timing); + } + + if (isset($this->type_code)) { + $this->timing = trim($this->type_code); + } + + if (isset($this->category_code)) { + $this->timing = trim($this->category_code); + } + + if (isset($this->severity_code)) { + $this->timing = trim($this->severity_code); + } + + // Check parameters + // Put here code to add a control on parameters values + // Update request + $sql = "UPDATE " . MAIN_DB_PREFIX . "ticketsup SET"; + $sql .= " ref=" . (isset($this->ref) ? "'" . $this->db->escape($this->ref) . "'" : "") . ","; + $sql .= " track_id=" . (isset($this->track_id) ? "'" . $this->db->escape($this->track_id) . "'" : "null") . ","; + $sql .= " fk_soc=" . (isset($this->fk_soc) ? "'" . $this->db->escape($this->fk_soc) . "'" : "null") . ","; + $sql .= " fk_project=" . (isset($this->fk_project) ? "'" . $this->db->escape($this->fk_project) . "'" : "null") . ","; + $sql .= " origin_email=" . (isset($this->origin_email) ? "'" . $this->db->escape($this->origin_email) . "'" : "null") . ","; + $sql .= " fk_user_create=" . (isset($this->fk_user_create) ? $this->fk_user_create : "null") . ","; + $sql .= " fk_user_assign=" . (isset($this->fk_user_assign) ? $this->fk_user_assign : "null") . ","; + $sql .= " subject=" . (isset($this->subject) ? "'" . $this->db->escape($this->subject) . "'" : "null") . ","; + $sql .= " message=" . (isset($this->message) ? "'" . $this->db->escape($this->message) . "'" : "null") . ","; + $sql .= " fk_statut=" . (isset($this->fk_statut) ? $this->fk_statut : "null") . ","; + $sql .= " resolution=" . (isset($this->resolution) ? $this->resolution : "null") . ","; + $sql .= " progress=" . (isset($this->progress) ? "'" . $this->db->escape($this->progress) . "'" : "null") . ","; + $sql .= " timing=" . (isset($this->timing) ? "'" . $this->db->escape($this->timing) . "'" : "null") . ","; + $sql .= " type_code=" . (isset($this->type_code) ? "'" . $this->db->escape($this->type_code) . "'" : "null") . ","; + $sql .= " category_code=" . (isset($this->category_code) ? "'" . $this->db->escape($this->category_code) . "'" : "null") . ","; + $sql .= " severity_code=" . (isset($this->severity_code) ? "'" . $this->db->escape($this->severity_code) . "'" : "null") . ","; + $sql .= " datec=" . (dol_strlen($this->datec) != 0 ? "'" . $this->db->idate($this->datec) . "'" : 'null') . ","; + $sql .= " date_read=" . (dol_strlen($this->date_read) != 0 ? "'" . $this->db->idate($this->date_read) . "'" : 'null') . ","; + $sql .= " date_close=" . (dol_strlen($this->date_close) != 0 ? "'" . $this->db->idate($this->date_close) . "'" : 'null') . ""; + + $sql .= " WHERE rowid=" . $this->id; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + // FIXME le hook fait double emploi avec le trigger !! + $hookmanager->initHooks(array('TicketSupDao')); + $parameters = array('ticketsupid' => $this->id); + $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if (empty($reshook)) { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) { // For avoid conflicts if trigger used + $result = $this->insertExtraFields(); + if ($result < 0) { + $error++; + } + } + } elseif ($reshook < 0) { + $error++; + } + + if (!$notrigger) { + // Call trigger + $result=$this->call_trigger('TICKET_MODIFY', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + $this->db->begin(); + + if (!$error) { + if (!$notrigger) { + // Call trigger + $result = $this->call_trigger('TICKET_DELETE', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + } + + if (!$error) { + // Delete linked contacts + $res = $this->delete_linked_contact(); + if ($res < 0) { + dol_syslog(get_class($this) . "::delete error", LOG_ERR); + $error++; + } + } + + if (!$error) { + // Delete linked object + $res = $this->deleteObjectLinked(); + if ($res < 0) $error++; + } + + if (!$error) { + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ticketsup"; + $sql .= " WHERE rowid=" . $this->id; + + dol_syslog(get_class($this) . "::delete sql=" . $sql); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + } + + // Removed extrafields + if (!$error) { + $result = $this->deleteExtraFields(); + if ($result < 0) { + $error++; + dol_syslog(get_class($this) . "::delete error -3 " . $this->error, LOG_ERR); + } + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * Load an object from its id and create a new one in database + * + * @param int $fromid Id of object to clone + * @return int New id of clone + */ + public function createFromClone($fromid) + { + global $user, $langs; + + $error = 0; + + $object = new Ticketsup($this->db); + + $this->db->begin(); + + // Load source object + $object->fetch($fromid); + $object->id = 0; + $object->statut = 0; + + // Clear fields + // ... + // Create clone + $result = $object->create($user); + + // Other options + if ($result < 0) { + $this->error = $object->error; + $error++; + } + + if (!$error) { + } + + // End + if (!$error) { + $this->db->commit(); + return $object->id; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->id = 0; + + $this->ref = 'TI0501-001'; + $this->track_id = 'XXXXaaaa'; + $this->origin_email = 'email@email.com'; + $this->fk_project = '1'; + $this->fk_user_create = '1'; + $this->fk_user_assign = '1'; + $this->subject = 'Subject of ticket'; + $this->message = 'Message of ticket'; + $this->fk_statut = '0'; + $this->resolution = '1'; + $this->progress = '10'; + $this->timing = '30'; + $this->type_code = 'TYPECODE'; + $this->category_code = 'CATEGORYCODE'; + $this->severity_code = 'SEVERITYCODE'; + $this->datec = ''; + $this->date_read = ''; + $this->date_close = ''; + $this->tms = ''; + } + + + public function printSelectStatus($selected = "") + { + print Form::selectarray('search_fk_statut', $this->statuts_short, $selected, $show_empty = 1, $key_in_label = 0, $value_as_key = 0, $option = '', $translate = 1, $maxlen = 0, $disabled = 0, $sort = '', $morecss = ''); + } + /** + * Charge dans cache la liste des types de tickets (paramétrable dans dictionnaire) + * + * @return int Nb lignes chargees, 0 si deja chargees, <0 si ko + */ + public function load_cache_types_tickets() + { + global $langs; + + if (count($this->cache_types_tickets)) { + return 0; + } + // Cache deja charge + + $sql = "SELECT rowid, code, label, use_default, pos, description"; + $sql .= " FROM " . MAIN_DB_PREFIX . "c_ticketsup_type"; + $sql .= " WHERE active > 0"; + $sql .= " ORDER BY pos"; + dol_syslog(get_class($this) . "::load_cache_type_tickets sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label = ($langs->trans("TicketTypeShort" . $obj->code) != ("TicketTypeShort" . $obj->code) ? $langs->trans("TicketTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : '')); + $this->cache_types_tickets[$obj->rowid]['code'] = $obj->code; + $this->cache_types_tickets[$obj->rowid]['label'] = $label; + $this->cache_types_tickets[$obj->rowid]['use_default'] = $obj->use_default; + $this->cache_types_tickets[$obj->rowid]['pos'] = $obj->pos; + $i++; + } + return $num; + } else { + dol_print_error($this->db); + return -1; + } + } + + /** + * Charge dans cache la liste des catégories de tickets (paramétrable dans dictionnaire) + * + * @return int Nb lignes chargees, 0 si deja chargees, <0 si ko + */ + public function load_cache_categories_tickets() + { + global $langs; + + if (count($this->cache_category_tickets)) { + return 0; + } + // Cache deja charge + + $sql = "SELECT rowid, code, label, use_default, pos, description"; + $sql .= " FROM " . MAIN_DB_PREFIX . "c_ticketsup_category"; + $sql .= " WHERE active > 0"; + $sql .= " ORDER BY pos"; + dol_syslog(get_class($this) . "::load_cache_categories_tickets sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + $this->cache_category_tickets[$obj->rowid]['code'] = $obj->code; + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label = ($langs->trans("TicketCategoryShort" . $obj->code) != ("TicketCategoryShort" . $obj->code) ? $langs->trans("TicketCategoryShort" . $obj->code) : ($obj->label != '-' ? $obj->label : '')); + $this->cache_category_tickets[$obj->rowid]['label'] = $label; + $this->cache_category_tickets[$obj->rowid]['use_default'] = $obj->use_default; + $this->cache_category_tickets[$obj->rowid]['pos'] = $obj->pos; + $i++; + } + return $num; + } else { + dol_print_error($this->db); + return -1; + } + } + + /** + * Charge dans cache la liste des sévérité de tickets (paramétrable dans dictionnaire) + * + * @return int Nb lignes chargees, 0 si deja chargees, <0 si ko + */ + public function load_cache_severities_tickets() + { + global $langs; + + if (count($this->cache_severity_tickets)) { + return 0; + } + // Cache deja charge + + $sql = "SELECT rowid, code, label, use_default, pos, description"; + $sql .= " FROM " . MAIN_DB_PREFIX . "c_ticketsup_severity"; + $sql .= " WHERE active > 0"; + $sql .= " ORDER BY pos"; + dol_syslog(get_class($this) . "::load_cache_severities_tickets sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + + $this->cache_severity_tickets[$obj->rowid]['code'] = $obj->code; + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label = ($langs->trans("TicketSeverityShort" . $obj->code) != ("TicketSeverityShort" . $obj->code) ? $langs->trans("TicketSeverityShort" . $obj->code) : ($obj->label != '-' ? $obj->label : '')); + $this->cache_severity_tickets[$obj->rowid]['label'] = $label; + $this->cache_severity_tickets[$obj->rowid]['use_default'] = $obj->use_default; + $this->cache_severity_tickets[$obj->rowid]['pos'] = $obj->pos; + $i++; + } + return $num; + } else { + dol_print_error($this->db); + return -1; + } + } + + /** + * \brief Return status label of object + * \param mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * \return string Label + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->fk_statut, $mode); + } + + /** + * \brief Return status label of object + * \param statut id statut + * \param mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * \return string Label + */ + public function LibStatut($statut, $mode = 0) + { + global $langs; + + if ($mode == 0) { + return $langs->trans($this->statuts[$statut]); + } + if ($mode == 1) { + return $langs->trans($this->statuts_short[$statut]); + } + if ($mode == 2) { + if ($statut == 0) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut0.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 1) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut1.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 3) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut3.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 4) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut4.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 5) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut5.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 6) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut6.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 8) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut8.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 9) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut9.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + } + if ($mode == 3) { + if ($statut == 0) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut0.png@ticketsup'); + } + + if ($statut == 1) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut1.png@ticketsup'); + } + + if ($statut == 3) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut3.png@ticketsup'); + } + + if ($statut == 4) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut4.png@ticketsup'); + } + + if ($statut == 5) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut5.png@ticketsup'); + } + + if ($statut == 6) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut6.png@ticketsup'); + } + + if ($statut == 8) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut8.png@ticketsup'); + } + + if ($statut == 9) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut9.png@ticketsup'); + } + } + if ($mode == 4) { + if ($statut == 0) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut0.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 1) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut1.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 3) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut3.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 4) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut4.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 5) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut5.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 6) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut6.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 8) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut8.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + + if ($statut == 9) { + return img_picto($langs->trans($this->statuts_short[$statut]), 'statut9.png@ticketsup') . ' ' . $langs->trans($this->statuts_short[$statut]); + } + } + if ($mode == 5) { + if ($statut == 0) { + return $langs->trans($this->statuts_short[$statut]) . ' ' . img_picto($langs->trans($this->statuts_short[$statut]), 'statut0.png@ticketsup'); + } + + if ($statut == 1) { + return $langs->trans($this->statuts_short[$statut]) . ' ' . img_picto($langs->trans($this->statuts_short[$statut]), 'statut1.png@ticketsup'); + } + + if ($statut == 3) { + return $langs->trans($this->statuts_short[$statut]) . ' ' . img_picto($langs->trans($this->statuts_short[$statut]), 'statut3.png@ticketsup'); + } + + if ($statut == 4) { + return $langs->trans($this->statuts_short[$statut]) . ' ' . img_picto($langs->trans($this->statuts_short[$statut]), 'statut4.png@ticketsup'); + } + + if ($statut == 5) { + return $langs->trans($this->statuts_short[$statut]) . ' ' . img_picto($langs->trans($this->statuts_short[$statut]), 'statut5.png@ticketsup'); + } + + if ($statut == 6) { + return $langs->trans($this->statuts_short[$statut]) . ' ' . img_picto($langs->trans($this->statuts_short[$statut]), 'statut6.png@ticketsup'); + } + + if ($statut == 8) { + return $langs->trans($this->statuts_short[$statut]) . ' ' . img_picto($langs->trans($this->statuts_short[$statut]), 'statut8.png@ticketsup'); + } + + if ($statut == 9) { + return $langs->trans($this->statuts_short[$statut]) . ' ' . img_picto($langs->trans($this->statuts_short[$statut]), 'statut9.png@ticketsup'); + } + } + } + + /** + * \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 + */ + public function getNomUrl($withpicto = 0, $option = '') + { + global $langs; + + $result = ''; + + $lien = ''; + $lienfin = ''; + + $picto = 'ticketsup@ticketsup'; + if (!$this->public) { + $picto = 'ticketsup@ticketsup'; + } + + $label = $langs->trans("ShowTicket") . ': ' . $this->ref . ' - ' . $this->subject; + if ($withpicto) { + $result .= ($lien . img_object($label, $picto) . $lienfin); + } + + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + + if ($withpicto != 2) { + $result .= $lien . $this->ref . ' - ' . dol_trunc($this->subject) . $lienfin; + } + + return $result; + } + + /** + * \brief Mark a message as read + * \param User + * \return boolean + */ + public function markAsRead($user, $notrigger = 0) + { + global $conf, $langs; + + if ($this->statut != 9) { // no closed + $this->db->begin(); + + $sql = "UPDATE " . MAIN_DB_PREFIX . "ticketsup"; + $sql .= " SET fk_statut = 1, date_read='" . $this->db->idate(dol_now()) . "'"; + $sql .= " WHERE rowid = " . $this->id; + + dol_syslog(get_class($this) . "::markAsRead sql=" . $sql); + $resql = $this->db->query($sql); + if ($resql) { + if (!$error && !$notrigger) { + // Call trigger + $result=$this->call_trigger('TICKET_MARK_READ', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + $this->error = join(',', $this->errors); + dol_syslog(get_class($this) . "::markAsRead " . $this->error, LOG_ERR); + return -1; + } + } else { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this) . "::markAsRead " . $this->error, LOG_ERR); + return -1; + } + } + } + + /** + * \brief Mark a message as read + * \param User + * \param int $id_assign_user ID of user assigned + * \param int $notrigger Disable trigger + * \return boolean + */ + public function assignUser($user, $id_assign_user, $notrigger = 0) + { + global $conf, $langs; + + if ($id_assign_user > 0) { // no closed + $this->db->begin(); + + $sql = "UPDATE " . MAIN_DB_PREFIX . "ticketsup"; + $sql .= " SET fk_user_assign=" . $id_assign_user; + $sql .= " , fk_statut=4"; + $sql .= " WHERE rowid = " . $this->id; + + dol_syslog(get_class($this) . "::assignUser sql=" . $sql); + $resql = $this->db->query($sql); + if ($resql) { + if (!$notrigger) { + // Call trigger + $result=$this->call_trigger('TICKET_ASSIGNED', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + $this->error = join(',', $this->errors); + dol_syslog(get_class($this) . "::assignUser " . $this->error, LOG_ERR); + return -1; + } + } else { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this) . "::assignUser " . $this->error, LOG_ERR); + return -1; + } + } + } + + /** + * Create log for the ticket + * 1- create entry into database for message storage + * 2- if trigger, send an email to ticket contacts + * + * @param User $user User that create + * @param string $message Log message + * @param int $noemail 0=send email after, 1=disable emails + * @return int <0 if KO, >0 if OK + */ + public function createTicketLog($user, $message, $noemail = 0) + { + global $conf, $langs; + + $this->db->begin(); + + // Clean parameters + $this->message = trim($this->message); + + // Check parameters + if (!$message) { + $this->error = 'ErrorBadValueForParameter'; + return -1; + } + + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "ticketsup_logs("; + $sql .= "entity,"; + $sql .= "datec,"; + $sql .= "fk_track_id,"; + $sql .= "fk_user_create,"; + $sql .= "message"; + $sql .= ") VALUES ("; + $sql .= " " . $conf->entity . ","; + $sql .= " '" . $this->db->idate(dol_now()) . "',"; + $sql .= " '" . $this->track_id . "',"; + $sql .= " " . ($user->id ? "'" . $user->id . "'" : 'NULL') . ","; + $sql .= " '" . $this->db->escape($message) . "'"; + $sql .= ")"; + + dol_syslog(get_class($this) . "::create_ticket_log sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($conf->global->TICKETS_ACTIVATE_LOG_BY_EMAIL && !$noemail) { + $this->sendLogByEmail($user, $message); + } + + if (!$error) { + $this->db->commit(); + return 1; + } + } else { + $this->db->rollback(); + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::create_ticket_log " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Send notification of changes by email + * + * @param User $user User that create + * @param string $message Log message + * @return int <0 if KO, >0 if OK (number of emails sent) + */ + private function sendLogByEmail($user, $log_message) + { + global $conf, $langs; + + $nb_sent = 0; + + $langs->load('ticketsup@ticketsup'); + + // Retrieve email of all contacts (internal and external) + $contacts = $this->liste_contact(-1, 'internal'); + $contacts = array_merge($contacts, $this->liste_contact(-1, 'external')); + + /* If origin_email and no socid, we add email to the list * */ + if (!empty($this->origin_email) && empty($this->fk_soc)) { + $array_ext = array(array('firstname' => '', 'lastname' => '', 'email' => $this->origin_email, 'libelle' => $langs->transnoentities('TicketEmailOriginIssuer'), 'socid' => "-1")); + $contacts = array_merge($contacts, $array_ext); + } + + if (!empty($this->fk_soc)) { + $this->fetch_thirdparty($this->fk_soc); + $array_company = array(array('firstname' => '', 'lastname' => $this->client->name, 'email' => $this->client->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $this->client->id)); + $contacts = array_merge($contacts, $array_company); + } + + // foreach contact send email with notification message + if (count($contacts) > 0) { + foreach ($contacts as $key => $info_sendto) { + $message = ''; + $subject = '[' . $conf->global->MAIN_INFO_SOCIETE_NOM . '] ' . $langs->transnoentities('TicketNotificationEmailSubject', $this->track_id); + $message .= $langs->transnoentities('TicketNotificationEmailBody', $this->track_id) . "\n\n"; + $message .= $langs->transnoentities('Title') . ' : ' . $this->subject . "\n"; + + $recipient_name = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1'); + $recipient = (!empty($recipient_name) ? $recipient_name : $info_sendto['email']) . ' (' . strtolower($info_sendto['libelle']) . ')'; + $message .= $langs->transnoentities('TicketNotificationRecipient') . ' : ' . $recipient . "\n"; + $message .= "\n"; + $message .= '* ' . $langs->transnoentities('TicketNotificationLogMessage') . ' *' . "\n"; + $message .= dol_html_entity_decode($log_message, ENT_QUOTES) . "\n"; + + if ($info_sendto['source'] == 'internal') { + $url_internal_ticket = dol_buildpath('/ticketsup/card.php', 2) . '?track_id=' . $this->track_id; + $message .= "\n" . $langs->transnoentities('TicketNotificationEmailBodyInfosTrackUrlinternal') . ' : ' . '' . $this->track_id . '' . "\n"; + } else { + $url_public_ticket = ($conf->global->TICKETS_URL_PUBLIC_INTERFACE ? $conf->global->TICKETS_URL_PUBLIC_INTERFACE . '/' : dol_buildpath('/ticketsup/public/view.php', 2)) . '?track_id=' . $this->track_id; + $message .= "\n" . $langs->transnoentities('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : ' . '' . $this->track_id . '' . "\n"; + } + + $message .= "\n"; + $message .= $langs->transnoentities('TicketEmailPleaseDoNotReplyToThisEmail') . "\n"; + + $from = $conf->global->MAIN_INFO_SOCIETE_NOM . '<' . $conf->global->TICKETS_NOTIFICATION_EMAIL_FROM . '>'; + $replyto = $from; + + // Init to avoid errors + $filepath = array(); + $filename = array(); + $mimetype = array(); + + $message = dol_nl2br($message); + + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO; + $conf->global->MAIN_MAIL_AUTOCOPY_TO = ''; + } + include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php'; + $mailfile = new CMailFile($subject, $info_sendto['email'], $from, $message, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, 0); + if ($mailfile->error) { + setEventMessage($mailfile->error, 'errors'); + } else { + $result = $mailfile->sendfile(); + if ($result > 0) { + $nb_sent++; + } + } + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO; + } + } + + setEventMessage($langs->trans('TicketNotificationNumberEmailSent', $nb_sent)); + } + + return $nb_sent; + } + + /** + * Charge la liste des actions sur le ticket + * + * @return int Nb lignes chargees, 0 si deja chargees, <0 si ko + */ + public function loadCacheLogsTicket() + { + global $langs; + + if (count($this->cache_logs_ticket)) { + return 0; + } + // Cache deja charge + + $sql = "SELECT rowid, fk_user_create, datec, message"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup_logs"; + $sql .= " WHERE fk_track_id ='" . $this->track_id . "'"; + $sql .= " ORDER BY datec DESC"; + dol_syslog(get_class($this) . "::load_cache_actions_ticket sql=" . $sql, LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + $this->cache_logs_ticket[$i]['id'] = $obj->rowid; + $this->cache_logs_ticket[$i]['fk_user_create'] = $obj->fk_user_create; + $this->cache_logs_ticket[$i]['datec'] = $this->db->jdate($obj->datec); + $this->cache_logs_ticket[$i]['message'] = $obj->message; + $i++; + } + return $num; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::load_cache_actions_ticket " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Add message into database + * + * @param User $user User that creates + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function createTicketMessage($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + // Clean parameters + if (isset($this->fk_track_id)) { + $this->fk_track_id = trim($this->fk_track_id); + } + + if (isset($this->message)) { + $this->message = trim($this->message); + } + + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "ticketsup_msg("; + + $sql .= "fk_track_id,"; + $sql .= "fk_user_action,"; + $sql .= "datec,"; + $sql .= "message,"; + $sql .= "private"; + $sql .= ") VALUES ("; + $sql .= " " . (!isset($this->fk_track_id) ? "'" . $this->db->escape($this->track_id) . "'" : "'" . $this->db->escape($this->fk_track_id) . "'") . ","; + $sql .= " " . (!isset($this->fk_user_action) ? $user->id : "'" . $this->fk_user_action . "'") . ","; + $sql .= " '" . $this->db->idate(dol_now()) . "',"; + $sql .= " " . (!isset($this->message) ? 'NULL' : "'" . $this->db->escape($this->message) . "'") . ","; + $sql .= " " . (empty($this->private) ? '0' : "'" . $this->db->escape($this->private) . "'") . ""; + $sql .= ")"; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::create_ticket_message sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. + //// Call triggers + //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::create_ticket_message " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * Charge la liste des messages sur le ticket + * + * @return int Nb lignes chargees, 0 si deja chargees, <0 si ko + */ + public function loadCacheMsgsTicket() + { + global $langs; + + if (count($this->cache_msgs_ticket)) { + return 0; + } + // Cache deja charge + + $sql = "SELECT rowid, fk_user_action, datec, message, private"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup_msg"; + $sql .= " WHERE fk_track_id ='" . $this->track_id . "'"; + $sql .= " ORDER BY datec DESC"; + dol_syslog(get_class($this) . "::load_cache_actions_ticket sql=" . $sql, LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + $this->cache_msgs_ticket[$i]['id'] = $obj->rowid; + $this->cache_msgs_ticket[$i]['fk_user_action'] = $obj->fk_user_action; + $this->cache_msgs_ticket[$i]['datec'] = $this->db->jdate($obj->datec); + $this->cache_msgs_ticket[$i]['message'] = $obj->message; + $this->cache_msgs_ticket[$i]['private'] = $obj->private; + $i++; + } + return $num; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::load_cache_actions_ticket " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * \brief Close a ticket + * \return boolean + */ + public function close() + { + global $conf, $user, $langs; + + if ($this->fk_statut != 9) { // not closed + $this->db->begin(); + + $sql = "UPDATE " . MAIN_DB_PREFIX . "ticketsup"; + $sql .= " SET fk_statut=8, progress=100,date_close='" . $this->db->idate(dol_now()) . "'"; + $sql .= " WHERE rowid = " . $this->id; + + dol_syslog(get_class($this) . "::close sql=" . $sql); + $resql = $this->db->query($sql); + if ($resql) { + $error = 0; + + // Valid and close fichinter linked + $this->fetchObjectLinked($this->id, $this->element, null, 'fichinter'); + foreach ($this->linkedObjectsIds['fichinter'] as $fichinter_id) { + $fichinter = new Fichinter($this->db); + $fichinter->fetch($fichinter_id); + if($fichinter->statut == 0) { + $result = $fichinter->setValid($user); + if (!$result) { + $this->errors[] = $fichinter->error; + $error++; + } + } + if ($fichinter->statut < 3) { + $result = $fichinter->setStatut(3); + if (!$result) { + $this->errors[] = $fichinter->error; + $error++; + } + } + } + + // Call trigger + $result=$this->call_trigger('TICKET_CLOSED', $user); + if ($result < 0) { + $error++; + } + // End call triggers + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + $this->error = join(',', $this->errors); + dol_syslog(get_class($this) . "::close " . $this->error, LOG_ERR); + return -1; + } + } else { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this) . "::close " . $this->error, LOG_ERR); + return -1; + } + } + } + + /** + * Search and fetch thirparties by email + * + * @param string $email Email + * @param int $type Type of thirdparties (0=any, 1=customer, 2=prospect, 3=supplier) + * @param array $filters Array of couple field name/value to filter the companies with the same name + * @param string $clause Clause for filters + * @return array Array of thirdparties object + */ + public function searchSocidByEmail($email, $type = '0', $filters = array(), $clause = 'AND') + { + $thirdparties = array(); + + // Generation requete recherche + $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "societe"; + $sql .= " WHERE entity IN (" . getEntity('ticketsup', 1) . ")"; + if (!empty($type)) { + if ($type == 1 || $type == 2) { + $sql .= " AND client = " . $type; + } elseif ($type == 3) { + $sql .= " AND fournisseur = 1"; + } + } + if (!empty($email)) { + if (!$exact) { + if (preg_match('/^([\*])?[^*]+([\*])?$/', $email, $regs) && count($regs) > 1) { + $email = str_replace('*', '%', $email); + } else { + $email = '%' . $email . '%'; + } + } + $sql .= " AND "; + if (is_array($filters) && !empty($filters)) { + $sql .= "("; + } + + if (!$case) { + $sql .= "email LIKE '" . $this->db->escape($email) . "'"; + } else { + $sql .= "email LIKE BINARY '" . $this->db->escape($email) . "'"; + } + } + if (is_array($filters) && !empty($filters)) { + foreach ($filters as $field => $value) { + $sql .= " " . $clause . " " . $field . " LIKE BINARY '" . $this->db->escape($value) . "'"; + } + if (!empty($email)) { + $sql .= ")"; + } + } + + $res = $this->db->query($sql); + if ($res) { + while ($rec = $this->db->fetch_array($res)) { + $soc = new Societe($this->db); + $soc->fetch($rec['rowid']); + $thirdparties[] = $soc; + } + + return $thirdparties; + } else { + $this->error = $this->db->error() . ' sql=' . $sql; + dol_syslog(get_class($this) . "::searchSocidByEmail " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Search and fetch contacts by email + * + * @param string $email Email + * @param array $socid Limit to a thirdparty + * @param string $case Respect case + * @return array Array of contacts object + */ + public function searchContactByEmail($email, $socid = '', $case = '') + { + $contacts = array(); + + // Generation requete recherche + $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "socpeople"; + $sql .= " WHERE entity IN (" . getEntity('ticketsup', 1) . ")"; + if (!empty($socid)) { + $sql .= " AND fk_soc='" . $this->db->escape($socid) . "'"; + } + + if (!empty($email)) { + $sql .= " AND "; + + if (!$case) { + $sql .= "email LIKE '" . $this->db->escape($email) . "'"; + } else { + $sql .= "email LIKE BINARY '" . $this->db->escape($email) . "'"; + } + } + + $res = $this->db->query($sql); + if ($res) { + while ($rec = $this->db->fetch_array($res)) { + include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; + $contactstatic = new Contact($this->db); + $contactstatic->fetch($rec['rowid']); + $contacts[] = $contactstatic; + } + + return $contacts; + } else { + $this->error = $this->db->error() . ' sql=' . $sql; + dol_syslog(get_class($this) . "::searchContactByEmail " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Define parent commany of current ticket + * + * @param int $id Id of thirdparty to set or '' to remove + * @return int <0 if KO, >0 if OK + */ + public function set_customer($id) + { + if ($this->id) { + $sql = "UPDATE " . MAIN_DB_PREFIX . "ticketsup"; + $sql .= " SET fk_soc = " . ($id > 0 ? $id : "null"); + $sql .= " WHERE rowid = " . $this->id; + dol_syslog(get_class($this) . '::set_customer sql=' . $sql); + $resql = $this->db->query($sql); + if ($resql) { + return 1; + } else { + return -1; + } + } else { + return -1; + } + } + + /** + * Define progression of current ticket + * + * @param int $percent Progression percent + * @return int <0 if KO, >0 if OK + */ + public function setProgression($percent) + { + if ($this->id) { + $sql = "UPDATE " . MAIN_DB_PREFIX . "ticketsup"; + $sql .= " SET progress = " . ($percent > 0 ? $percent : "null"); + $sql .= " WHERE rowid = " . $this->id; + dol_syslog(get_class($this) . '::set_progression sql=' . $sql); + $resql = $this->db->query($sql); + if ($resql) { + return 1; + } else { + return -1; + } + } else { + return -1; + } + } + + /** + * Link element with a project + * Override core function because of key name 'fk_project' used for this module + * + * @param int $projectid Project id to link element to + * @return int <0 if KO, >0 if OK + */ + public function setProject($projectid) + { + if (!$this->table_element) { + dol_syslog(get_class($this) . "::setProject was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + + $sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element; + if ($projectid) { + $sql .= ' SET fk_project = ' . $projectid; + } else { + $sql .= ' SET fk_project = NULL'; + } + + $sql .= ' WHERE rowid = ' . $this->id; + + dol_syslog(get_class($this) . "::setProject sql=" . $sql); + if ($this->db->query($sql)) { + $this->fk_project = $projectid; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } + + /** + * Link element with a contract + * + * @param int $contractid Contract id to link element to + * @return int <0 if KO, >0 if OK + */ + public function setContract($contractid) + { + if (!$this->table_element) { + dol_syslog(get_class($this) . "::setContract was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + + $result = $this->add_object_linked('contrat', $contractid); + if ($result) { + $this->fk_contract = $contractid; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } + + /* gestion des contacts d'un ticket */ + + /** + * Return id des contacts interne de suivi + * + * @return array Liste des id contacts suivi ticket + */ + public function getIdTicketInternalContact() + { + return $this->getIdContact('internal', 'SUPPORTTEC'); + } + + /** + * Retrieve informations about internal contacts + * + * @return array Array with datas : firstname, lastname, socid (-1 for internal users), email, code, libelle, status + */ + public function getInfosTicketInternalContact() + { + return $this->liste_contact(-1, 'internal'); + } + + /** + * Return id des contacts clients pour le suivi ticket + * + * @return array Liste des id contacts suivi ticket + */ + public function getIdTicketCustomerContact() + { + return $this->getIdContact('external', 'SUPPORTCLI'); + } + + /** + * Retrieve informations about external contacts + * + * @return array Array with datas : firstname, lastname, socid (-1 for internal users), email, code, libelle, status + */ + public function getInfosTicketExternalContact() + { + return $this->liste_contact(-1, 'external'); + } + + /** + * Return id des contacts clients des intervenants + * + * @return array Liste des id contacts intervenants + */ + public function getIdTicketInternalInvolvedContact() + { + return $this->getIdContact('internal', 'CONTRIBUTOR'); + } + + /** + * Return id des contacts clients des intervenants + * + * @return array Liste des id contacts intervenants + */ + public function getIdTicketCustomerInvolvedContact() + { + return $this->getIdContact('external', 'CONTRIBUTOR'); + } + + /** + * Return id of all contacts for ticket + * + * @param int $exclude_self exclude_self Exclude current user form list + */ + public function getTicketAllContacts() + { + $array_contact = array(); + + $array_contact = $this->getIdTicketInternalContact($exclude_self); + + $array_contact = array_merge($array_contact, $this->getIdTicketCustomerContact($exclude_self)); + + $array_contact = array_merge($array_contact, $this->getIdTicketInternalInvolvedContact($exclude_self)); + $array_contact = array_merge($array_contact, $this->getIdTicketCustomerInvolvedContact($exclude_self)); + + return $array_contact; + } + + /** + * Return id of all contacts for ticket + * + * @param int $exclude_self exclude_self Exclude current user form list + */ + public function getTicketAllCustomerContacts() + { + $array_contact = array(); + + $array_contact = array_merge($array_contact, $this->getIdTicketCustomerContact($exclude_self)); + $array_contact = array_merge($array_contact, $this->getIdTicketCustomerInvolvedContact($exclude_self)); + + return $array_contact; + } + + /** + * Check if contact are linked to the ticket + * If yes, send mail and save trace into llx_notify. + * + * @param string $action Code of action in llx_c_action_trigger (new usage) or Id of action in llx_c_action_trigger (old usage) + * @param int $socid Id of third party + * @param string $texte Message to send + * @param string $objet_type Type of object the notification deals on (facture, order, propal, order_supplier...). Just for log in llx_notify. + * @param int $objet_id Id of object the notification deals on + * @param string $file Attach a file + * @return int <0 if KO, or number of changes if OK + */ + public function messageSend($subject, $texte) + { + global $conf, $langs, $mysoc, $dolibarr_main_url_root; + + $langs->load("other"); + + dol_syslog(get_class($this) . "::message_send action=$action, socid=$socid, texte=$texte, objet_type=$objet_type, objet_id=$objet_id, file=$file"); + + $internal_contacts = $this->getIdContact('internal', 'SUPPORTTEC'); + $external_contacts = $this->getIdContact('external', 'SUPPORTTEC'); + + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) { // For each notification couple defined (third party/actioncode) + $obj = $this->db->fetch_object($result); + + $sendto = $obj->firstname . " " . $obj->lastname . " <" . $obj->email . ">"; + $actiondefid = $obj->adid; + + if (dol_strlen($sendto)) { + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + $application = ($conf->global->MAIN_APPLICATION_TITLE ? $conf->global->MAIN_APPLICATION_TITLE : 'Dolibarr ERP/CRM'); + + $subject = '[' . $application . '] ' . $langs->transnoentitiesnoconv("DolibarrNotification"); + + $message = $langs->transnoentities("YouReceiveMailBecauseOfNotification", $application, $mysoc->name) . "\n"; + $message .= $langs->transnoentities("YouReceiveMailBecauseOfNotification2", $application, $mysoc->name) . "\n"; + $message .= "\n"; + $message .= $texte; + // Add link + $link = ''; + switch ($objet_type) { + case 'ficheinter': + $link = '/fichinter/card.php?id=' . $objet_id; + break; + case 'propal': + $link = '/comm/propal.php?id=' . $objet_id; + break; + case 'facture': + if (DOL_VERSION < '6.0.0') { + $link = '/compta/facture.php?facid=' . $objet_id; + } else { + $link = '/compta/facture/card.php?facid=' . $objet_id; + } + + break; + case 'order': + $link = '/commande/card.php?facid=' . $objet_id; + break; + case 'order_supplier': + $link = '/fourn/commande/card.php?facid=' . $objet_id; + break; + } + // Define $urlwithroot + $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT; // This is to use external domain name found into config file + //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + if ($link) { + $message .= "\n" . $urlwithroot . $link; + } + + $filename = basename($file); + + $mimefile = dol_mimetype($file); + + $msgishtml = 0; + + $replyto = $conf->notification->email_from; + + $message = dol_nl2br($message); + + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $old_MAIN_MAIL_AUTOCOPY_TO = $conf->global->MAIN_MAIL_AUTOCOPY_TO; + $conf->global->MAIN_MAIL_AUTOCOPY_TO = ''; + } + $mailfile = new CMailFile( + $subject, + $sendto, + $replyto, + $message, + array($file), + array($mimefile), + array($filename[count($filename) - 1]), + '', + '', + 0, + $msgishtml + ); + + if ($mailfile->sendfile()) { + $now = dol_now(); + $sendto = htmlentities($sendto); + + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "notify (daten, fk_action, fk_contact, objet_type, objet_id, email)"; + $sql .= " VALUES ('" . $this->db->idate($now) . "', " . $actiondefid . ", " . $obj->cid . ", '" . $objet_type . "', " . $objet_id . ", '" . $this->db->escape($obj->email) . "')"; + dol_syslog("Notify::send sql=" . $sql); + if (!$this->db->query($sql)) { + dol_print_error($this->db); + } + } else { + $this->error = $mailfile->error; + //dol_syslog("Notify::send ".$this->error, LOG_ERR); + } + if (!empty($conf->global->TICKETS_DISABLE_MAIL_AUTOCOPY_TO)) { + $conf->global->MAIN_MAIL_AUTOCOPY_TO = $old_MAIN_MAIL_AUTOCOPY_TO; + } + } + $i++; + } + return $i; + } else { + $this->error = $this->db->error(); + return -1; + } + } + + /** + * Get array of all contacts for a ticket + * Override method of file commonobject.class.php to add phone number + * + * @param int $statut Status of lines to get (-1=all) + * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user) + * @param int $list 0:Return array contains all properties, 1:Return array contains just id + * @return array Array of contacts + */ + public function liste_contact($statut = -1, $source = 'external', $list = 0, $code = '') + { + global $langs; + + $tab = array(); + + $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user + if ($source == 'internal') { + $sql .= ", '-1' as socid, t.statut as statuscontact"; + } + + if ($source == 'external' || $source == 'thirdparty') { + $sql .= ", t.fk_soc as socid, t.statut as statuscontact"; + } + + $sql .= ", t.civility, t.lastname as lastname, t.firstname, t.email"; + if ($source == 'internal') { + $sql .= ", t.office_phone as phone, t.user_mobile as phone_mobile"; + } + + if ($source == 'external') { + $sql .= ", t.phone as phone, t.phone_mobile as phone_mobile, t.phone_perso as phone_perso"; + } + + $sql .= ", tc.source, tc.element, tc.code, tc.libelle"; + $sql .= " FROM " . MAIN_DB_PREFIX . "c_type_contact tc"; + $sql .= ", " . MAIN_DB_PREFIX . "element_contact ec"; + if ($source == 'internal') { + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user t on ec.fk_socpeople = t.rowid"; + } + + if ($source == 'external' || $source == 'thirdparty') { + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "socpeople t on ec.fk_socpeople = t.rowid"; + } + + $sql .= " WHERE ec.element_id =" . $this->id; + $sql .= " AND ec.fk_c_type_contact=tc.rowid"; + $sql .= " AND tc.element='" . $this->element . "'"; + if ($source == 'internal') { + $sql .= " AND tc.source = 'internal'"; + } + + if ($source == 'external' || $source == 'thirdparty') { + $sql .= " AND tc.source = 'external'"; + } + + $sql .= " AND tc.active=1"; + if ($statut >= 0) { + $sql .= " AND ec.statut = '" . $statut . "'"; + } + + $sql .= " ORDER BY t.lastname ASC"; + //echo $sql; exit; + dol_syslog(get_class($this) . "::liste_contact sql=" . $sql); + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + + if (!$list) { + $transkey = "TypeContact_" . $obj->element . "_" . $obj->source . "_" . $obj->code; + $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle); + $tab[$i] = array( + 'source' => $obj->source, + 'socid' => $obj->socid, + 'id' => $obj->id, + 'nom' => $obj->lastname, // For backward compatibility + 'civility' => $obj->civility, + 'lastname' => $obj->lastname, + 'firstname' => $obj->firstname, + 'email' => $obj->email, + 'rowid' => $obj->rowid, + 'code' => $obj->code, + 'libelle' => $libelle_type, + 'status' => $obj->statuslink, + 'statuscontact'=>$obj->statuscontact, + 'fk_c_type_contact' => $obj->fk_c_type_contact, + 'phone' => $obj->phone, + 'phone_mobile' => $obj->phone_mobile); + } else { + $tab[$i] = $obj->id; + } + + $i++; + } + + return $tab; + } else { + $this->error = $this->db->error(); + dol_print_error($this->db); + return -1; + } + } + + /** + * Get a default reference + * + * @global type $conf + * @return string Reference + */ + public function getDefaultRef($thirdparty = '') + { + global $conf; + + $defaultref = ''; + $modele = empty($conf->global->TICKETSUP_ADDON) ? 'mod_ticketsup_simple' : $conf->global->TICKETSUP_ADDON; + + // Search template files + $file = ''; + $classname = ''; + $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $file = dol_buildpath($reldir . "core/modules/ticketsup/" . $modele . '.php', 0); + if (file_exists($file)) { + $filefound = 1; + $classname = $modele; + break; + } + } + + if ($filefound) { + $result = dol_include_once($reldir . "core/modules/ticketsup/" . $modele . '.php'); + $modTicketsup = new $classname; + + $defaultref = $modTicketsup->getNextValue($thirdparty, $this); + } + + if (is_numeric($defaultref) && $defaultref <= 0) { + $defaultref = ''; + } + + return $defaultref; + } + + /** + * Show tab footer of a card + * + * @param string $paramid Name of parameter to use to name the id into the URL next/previous link + * @param string $morehtml More html content to output just before the nav bar + * @param int $shownav Show Condition (navigation is shown if value is 1) + * @param string $fieldid Nom du champ en base a utiliser pour select next et previous (we make the select max and min on this field) + * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous + * @param string $morehtmlref More html to show after ref + * @param string $moreparam More param to add in nav link url. + * @param int $nodbprefix Do not include DB prefix to forge table name + * @param string $morehtmlleft More html code to show before ref + * @param string $morehtmlright More html code to show before navigation arrows + * @return void + */ + public function ticketsup_banner_tab($paramid, $morehtml = '', $shownav = 1, $fieldid = 'id', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlright = '') + { + global $conf, $form, $user, $langs; + + $maxvisiblephotos = 1; + $showimage = 1; + $showbarcode = empty($conf->barcode->enabled) ? 0 : ($this->barcode ? 1 : 0); + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) { + $showbarcode = 0; + } + + $modulepart = 'ticketsup'; + print '
    '; + + $width = 80; + $height = 70; + $cssclass = 'photoref'; + //$showimage=$this->is_photo_available($conf->ticketsup->multidir_output[$this->entity]); + $showimage = $this->is_photo_available($conf->ticketsup->dir_output . '/' . $this->track_id); + $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : $maxvisiblephotos); + if ($conf->browser->phone) { + $maxvisiblephotos = 1; + } + + if ($showimage) { + $morehtmlleft .= '
    ' + . $this->show_photos($conf->ticketsup->dir_output, 'small', $maxvisiblephotos, 0, 0, 0, $height, $width, 0) + . '
    '; + } else { + $nophoto = '/public/theme/common/nophoto.png'; + $morehtmlleft .= '
    No photo
    '; + } + $morehtmlright .= $this->getLibStatut(2); + + if (!empty($this->name_alias)) { + $morehtmlref .= '
    ' . $this->name_alias . '
    '; + } + // For thirdparty + if (!empty($this->label)) { + $morehtmlref .= '
    ' . $this->label . '
    '; + } + // For product + if ($this->element != 'product') { + $morehtmlref .= '
    '; + $morehtmlref .= $this->getBannerAddress('refaddress', $this); + $morehtmlref .= '
    '; + } + if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { + $morehtmlref .= '
    '; + $morehtmlref .= $langs->trans("TechnicalID") . ': ' . $this->id; + $morehtmlref .= '
    '; + } + print $form->showrefnav($this, 'ref', $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlright); + print '
    '; + print '
    '; + } + + /** + * Affiche la premiere photo du ticket + * + * @param string $sdir Repertoire a scanner + * @return boolean true si photo dispo, false sinon + */ + public function is_photo_available($sdir) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + + global $conf; + + $dir = $sdir . '/'; + $nbphoto = 0; + + $dir_osencoded = dol_osencode($dir); + if (file_exists($dir_osencoded)) { + $handle = opendir($dir_osencoded); + if (is_resource($handle)) { + while (($file = readdir($handle)) != false) { + if (!utf8_check($file)) { + $file = utf8_encode($file); + } + // To be sure data is stored in UTF8 in memory + if (dol_is_file($dir . $file)) { + return true; + } + } + } + } + return false; + } + + /** + * Show photos of a product (nbmax maximum), into several columns + * TODO Move this into html.formproduct.class.php + * + * @param string $sdir Directory to scan + * @param int $size 0=original size, 1='small' use thumbnail if possible + * @param int $nbmax Nombre maximum de photos (0=pas de max) + * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1. + * @param int $showfilename 1=Show filename + * @param int $showaction 1=Show icon with action links (resize, delete) + * @param int $maxHeight Max height of original image when size='small' (so we can use original even if small requested). If 0, always use 'small' thumb image. + * @param int $maxWidth Max width of original image when size='small' + + * @param int $nolink Do not add a href link to view enlarged imaged into a new tab + * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto + */ + public function show_photos($sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0) + { + global $conf, $user, $langs; + + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php'; + + $dir = $sdir . '/'; + $pdir = '/'; + $dir .= get_exdir(0, 0, 0, 0, $this, 'ticketsup') . $this->track_id . '/'; + $pdir .= get_exdir(0, 0, 0, 0, $this, 'ticketsup') . $this->track_id . '/'; + + $dirthumb = $dir . 'thumbs/'; + $pdirthumb = $pdir . 'thumbs/'; + + $return = '' . "\n"; + $nbphoto = 0; + + $dir_osencoded = dol_osencode($dir); + if (file_exists($dir_osencoded)) { + $handle = opendir($dir_osencoded); + if (is_resource($handle)) { + while (($file = readdir($handle)) != false) { + $photo = ''; + + if (!utf8_check($file)) { + $file = utf8_encode($file); + } + // To be sure file is stored in UTF8 in memory + if (dol_is_file($dir . $file) && preg_match('/(' . $this->regeximgext . ')$/i', $dir . $file)) { + $nbphoto++; + $photo = $file; + $viewfilename = $file; + + if ($size == 1 || $size == 'small') { // Format vignette + // Find name of thumb file + $photo_vignette = basename(getImageFileNameForSize($dir . $file, '_small', '.png')); + if (!dol_is_file($dirthumb . $photo_vignette)) { + $photo_vignette = ''; + } + + // Get filesize of original file + $imgarray = dol_getImageSize($dir . $photo); + + if ($nbbyrow > 0) { + if ($nbphoto == 1) { + $return .= ''; + } + + if ($nbphoto % $nbbyrow == 1) { + $return .= ''; + } + + $return .= ''; + if (($nbphoto % $nbbyrow) == 0) { + $return .= ''; + } + } elseif ($nbbyrow < 0) { + $return .= ''; + } + } + + if (empty($size)) { // Format origine + $return .= ''; + + if ($showfilename) { + $return .= '
    ' . $viewfilename; + } + + if ($showaction) { + if ($user->rights->produit->creer || $user->rights->service->creer) { + // Link to resize + $return .= '' . img_picto($langs->trans("Resize"), DOL_URL_ROOT . '/theme/common/transform-crop-and-resize', '', 1) . '   '; + + // Link to delete + $return .= ''; + $return .= img_delete() . ''; + } + } + } + + // On continue ou on arrete de boucler ? + if ($nbmax && $nbphoto >= $nbmax) { + break; + } + } + } + } + + if ($size == 1 || $size == 'small') { + if ($nbbyrow > 0) { + // Ferme tableau + while ($nbphoto % $nbbyrow) { + $return .= ''; + $nbphoto++; + } + + if ($nbphoto) { + $return .= '
    '; + } elseif ($nbbyrow < 0) { + $return .= '
    '; + } + + $return .= "\n"; + if (empty($nolink)) { + $return .= ''; + } + + // Show image (width height=$maxHeight) + // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine + $alt = $langs->transnoentitiesnoconv('File') . ': ' . $pdir . $photo; + $alt .= ' - ' . $langs->transnoentitiesnoconv('Size') . ': ' . $imgarray['width'] . 'x' . $imgarray['height']; + + if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) { + $return .= ''; + $return .= 'dol_use_jmobile ? 'max-height' : 'height') . '="' . $maxHeight . '" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=ticketsup&entity=' . $this->entity . '&file=' . urlencode($pdirthumb . $photo_vignette) . '" title="' . dol_escape_htmltag($alt) . '">'; + } else { + $return .= ''; + $return .= 'dol_use_jmobile ? 'max-height' : 'height') . '="' . $maxHeight . '" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=ticketsup&entity=' . $this->entity . '&file=' . urlencode($pdir . $photo) . '" title="' . dol_escape_htmltag($alt) . '">'; + } + + if (empty($nolink)) { + $return .= ''; + } + + $return .= "\n"; + + if ($showfilename) { + $return .= '
    ' . $viewfilename; + } + + if ($showaction) { + $return .= '
    '; + // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites + if ($photo_vignette && preg_match('/(' . $this->regeximgext . ')$/i', $photo) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) { + $return .= '' . img_picto($langs->trans('GenerateThumb'), 'refresh') . '  '; + } + if ($user->rights->produit->creer || $user->rights->service->creer) { + // Link to resize + $return .= '' . img_picto($langs->trans("Resize"), DOL_URL_ROOT . '/theme/common/transform-crop-and-resize', '', 1) . '   '; + + // Link to delete + $return .= ''; + $return .= img_delete() . ''; + } + } + $return .= "\n"; + + if ($nbbyrow > 0) { + $return .= '
     
    '; + } + } + } + + closedir($handle); + } + + $this->nbphoto = $nbphoto; + + return $return; + } +} + +/** + * Session line Class + */ +class TicketsLine +{ + + public $id; + + /** + * @var string $ref Ticket reference + */ + public $ref; + + /** + * Hash to identify ticket +*/ + public $track_id; + + /** + * Thirdparty ID +*/ + public $fk_soc; + + /** + * Project ID +*/ + public $fk_project; + + /** + * Person email who have create ticket +*/ + public $origin_email; + + /** + * User id who have create ticket +*/ + public $fk_user_create; + + /** + * User id who have ticket assigned +*/ + public $fk_user_assign; + + /** + * Ticket subject +*/ + public $subject; + + /** + * Ticket message +*/ + public $message; + + /** + * Ticket statut +*/ + public $fk_statut; + + /** + * State resolution +*/ + public $resolution; + + /** + * Progress in percent +*/ + public $progress; + + /** + * Duration for ticket +*/ + public $timing; + + /** + * Type code +*/ + public $type_code; + + /** + * Category code +*/ + public $category_code; + + /** + * Severity code +*/ + public $severity_code; + + /** + * Type label +*/ + public $type_label; + + /** + * Category label +*/ + public $category_label; + + /** + * Severity label +*/ + public $severity_label; + + /** + * Création date +*/ + public $datec = ''; + + /** + * Read date +*/ + public $date_read = ''; + + /** + * Close ticket date +*/ + public $date_close = ''; + + public function __construct() + { + return 1; + } +} diff --git a/htdocs/ticketsup/class/ticketsuplogs.class.php b/htdocs/ticketsup/class/ticketsuplogs.class.php new file mode 100644 index 00000000000..30d1f49f21c --- /dev/null +++ b/htdocs/ticketsup/class/ticketsuplogs.class.php @@ -0,0 +1,332 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file ticketsup/class/ticketsuplogs.class.php + * \ingroup ticketsup + * \brief This file CRUD class file (Create/Read/Update/Delete) for ticket logs + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT . "/core/class/commonobject.class.php"; +//require_once(DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); +//require_once(DOL_DOCUMENT_ROOT."/product/class/product.class.php"); + +/** + * Put here description of your class + */ +class Ticketsuplogs// extends CommonObject +{ + public $db; //!< To store db handler + public $error; //!< To return error code (or message) + public $errors = array(); //!< To return several error codes (or messages) + public $element = 'ticketsuplogs'; //!< Id that identify managed objects + public $table_element = 'ticketsuplogs'; //!< Name of table without prefix where object is stored + + public $id; + + public $fk_track_id; + public $fk_user_create; + public $datec = ''; + public $message; + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + return 1; + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + // Clean parameters + + if (isset($this->fk_track_id)) { + $this->fk_track_id = trim($this->fk_track_id); + } + + if (isset($this->fk_user_create)) { + $this->fk_user_create = trim($this->fk_user_create); + } + + if (isset($this->message)) { + $this->message = trim($this->message); + } + + // Check parameters + // Put here code to add control on parameters values + + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "ticketsup_logs("; + + $sql .= "fk_track_id,"; + $sql .= "fk_user_create,"; + $sql .= "datec,"; + $sql .= "message"; + + $sql .= ") VALUES ("; + + $sql .= " " . (!isset($this->fk_track_id) ? 'NULL' : "'" . $this->db->escape($this->fk_track_id) . "'") . ","; + $sql .= " " . (!isset($this->fk_user_create) ? 'NULL' : "'" . $this->fk_user_create . "'") . ","; + $sql .= " " . (!isset($this->datec) || dol_strlen($this->datec) == 0 ? 'NULL' : "'" . $this->db->idate($this->datec). "'") . ","; + $sql .= " " . (!isset($this->message) ? 'NULL' : "'" . $this->db->escape($this->message) . "'") . ""; + + $sql .= ")"; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "ticketsup_logs"); + + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. + + //// Call triggers + //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return $this->id; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id) + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + + $sql .= " t.fk_track_id,"; + $sql .= " t.fk_user_create,"; + $sql .= " t.datec,"; + $sql .= " t.message"; + + $sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup_logs as t"; + $sql .= " WHERE t.rowid = " . $id; + + dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + + $this->fk_track_id = $obj->fk_track_id; + $this->fk_user_create = $obj->fk_user_create; + $this->datec = $this->db->jdate($obj->datec); + $this->message = $obj->message; + } + $this->db->free($resql); + + return 1; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); + return -1; + } + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = 0, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + // Clean parameters + + if (isset($this->fk_track_id)) { + $this->fk_track_id = trim($this->fk_track_id); + } + + if (isset($this->fk_user_create)) { + $this->fk_user_create = trim($this->fk_user_create); + } + + if (isset($this->message)) { + $this->message = trim($this->message); + } + + // Check parameters + // Put here code to add a control on parameters values + + // Update request + $sql = "UPDATE " . MAIN_DB_PREFIX . "ticketsup_logs SET"; + + $sql .= " fk_track_id=" . (isset($this->fk_track_id) ? "'" . $this->db->escape($this->fk_track_id) . "'" : "null") . ","; + $sql .= " fk_user_create=" . (isset($this->fk_user_create) ? $this->fk_user_create : "null") . ","; + $sql .= " datec=" . (dol_strlen($this->datec) != 0 ? "'" . $this->db->idate($this->datec) . "'" : 'null') . ","; + $sql .= " message=" . (isset($this->message) ? "'" . $this->db->escape($this->message) . "'" : "null") . ""; + + $sql .= " WHERE rowid=" . $this->id; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (!$error) { + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. + + //// Call triggers + //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + $this->db->begin(); + + if (!$error) { + if (!$notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. + + //// Call triggers + //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } + } + + if (!$error) { + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ticketsup_logs"; + $sql .= " WHERE rowid=" . $this->id; + + dol_syslog(get_class($this) . "::delete sql=" . $sql); + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->id = 0; + + $this->fk_track_id = ''; + $this->fk_user_create = ''; + $this->datec = ''; + $this->message = ''; + } +} diff --git a/htdocs/ticketsup/class/ticketsupstats.class.php b/htdocs/ticketsup/class/ticketsupstats.class.php new file mode 100644 index 00000000000..8af852eeb01 --- /dev/null +++ b/htdocs/ticketsup/class/ticketsupstats.class.php @@ -0,0 +1,161 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file /ticketsup/class/ticketsupstats.class.php + * \ingroup ticketsup + * \brief Fichier de la classe de gestion des stats des tickets + */ +require_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php'; +require_once 'ticketsup.class.php'; + +/** + * \class DeplacementStats + * \brief Classe permettant la gestion des stats des deplacements et notes de frais + */ +class TicketsupStats extends Stats +{ + public $table_element; + + public $socid; + public $userid; + + public $from; + public $field; + public $where; + + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param int $socid Id third party + * @param mixed $userid Id user for filter or array of user ids + * @return void + */ + public function __construct($db, $socid = 0, $userid = 0) + { + global $conf; + + $this->db = $db; + $this->socid = $socid; + $this->userid = $userid; + + $object = new Ticketsup($this->db); + $this->from = MAIN_DB_PREFIX . $object->table_element; + $this->field = 'km'; + + $this->where = " fk_statut > 0"; + $this->where .= " AND entity = " . $conf->entity; + if ($this->socid) { + $this->where .= " AND fk_soc = " . $this->socid; + } + if (is_array($this->userid) && count($this->userid) > 0) { + $this->where .= ' AND fk_user IN (' . join(',', $this->userid) . ')'; + } elseif ($this->userid > 0) { + $this->where .= ' AND fk_user = ' . $this->userid; + } + } + + /** + * Renvoie le nombre de tickets par annee + * + * @return array Array of values + */ + public function getNbByYear() + { + $sql = "SELECT YEAR(datec) as dm, count(*)"; + $sql .= " FROM " . $this->from; + $sql .= " GROUP BY dm DESC"; + $sql .= " WHERE " . $this->where; + + return $this->_getNbByYear($sql); + } + + /** + * Renvoie le nombre de facture par mois pour une annee donnee + * + * @param string $year Year to scan + * @return array Array of values + */ + public function getNbByMonth($year) + { + $sql = "SELECT MONTH(datec) as dm, count(*)"; + $sql .= " FROM " . $this->from; + $sql .= " WHERE YEAR(datec) = " . $year; + $sql .= " AND " . $this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); + + $res = $this->_getNbByMonth($year, $sql); + //var_dump($res);print '
    '; + return $res; + } + + /** + * Renvoie le montant de facture par mois pour une annee donnee + * + * @param int $year Year to scan + * @return array Array of values + */ + public function getAmountByMonth($year) + { + $sql = "SELECT date_format(datec,'%m') as dm, sum(" . $this->field . ")"; + $sql .= " FROM " . $this->from; + $sql .= " WHERE date_format(datec,'%Y') = '" . $year . "'"; + $sql .= " AND " . $this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); + + $res = $this->_getAmountByMonth($year, $sql); + //var_dump($res);print '
    '; + return $res; + } + + /** + * Return average amount + * + * @param int $year Year to scan + * @return array Array of values + */ + public function getAverageByMonth($year) + { + $sql = "SELECT date_format(datec,'%m') as dm, avg(" . $this->field . ")"; + $sql .= " FROM " . $this->from; + $sql .= " WHERE date_format(datec,'%Y') = '" . $year . "'"; + $sql .= " AND " . $this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); + + return $this->_getAverageByMonth($year, $sql); + } + + /** + * Return nb, total and average + * + * @return array Array of values + */ + public function getAllByYear() + { + $sql = "SELECT date_format(datec,'%Y') as year, count(*) as nb, sum(" . $this->field . ") as total, avg(" . $this->field . ") as avg"; + $sql .= " FROM " . $this->from; + $sql .= " WHERE " . $this->where; + $sql .= " GROUP BY year"; + $sql .= $this->db->order('year', 'DESC'); + + return $this->_getAllByYear($sql); + } +} diff --git a/htdocs/ticketsup/class/utils_diff.class.php b/htdocs/ticketsup/class/utils_diff.class.php new file mode 100644 index 00000000000..f09be232148 --- /dev/null +++ b/htdocs/ticketsup/class/utils_diff.class.php @@ -0,0 +1,417 @@ += $start && $end2 >= $start + && $sequence1[$end1] == $sequence2[$end2]) { + $end1--; + $end2--; + } + + // compute the table of longest common subsequence lengths + $table = self::computeTable($sequence1, $sequence2, $start, $end1, $end2); + + // generate the partial diff + $partialDiff = + self::generatePartialDiff($table, $sequence1, $sequence2, $start); + + // generate the full diff + $diff = array(); + for ($index = 0; $index < $start; $index++) { + $diff[] = array($sequence1[$index], self::UNMODIFIED); + } + while (count($partialDiff) > 0) { + $diff[] = array_pop($partialDiff); + } + + for ($index = $end1 + 1; + $index < ($compareCharacters ? strlen($sequence1) : count($sequence1)); + $index++) { + $diff[] = array($sequence1[$index], self::UNMODIFIED); + } + + // return the diff + return $diff; + } + + /* Returns the diff for two files. The parameters are: + * + * $file1 - the path to the first file + * $file2 - the path to the second file + * $compareCharacters - true to compare characters, and false to compare + * lines; this optional parameter defaults to false + */ + public static function compareFiles( + $file1, + $file2, + $compareCharacters = false + ) { + + // return the diff of the files + return self::compare( + file_get_contents($file1), + file_get_contents($file2), + $compareCharacters + ); + } + + /* Returns the table of longest common subsequence lengths for the specified + * sequences. The parameters are: + * + * $sequence1 - the first sequence + * $sequence2 - the second sequence + * $start - the starting index + * $end1 - the ending index for the first sequence + * $end2 - the ending index for the second sequence + */ + private static function computeTable( + $sequence1, + $sequence2, + $start, + $end1, + $end2 + ) { + + // determine the lengths to be compared + $length1 = $end1 - $start + 1; + $length2 = $end2 - $start + 1; + + // initialise the table + $table = array(array_fill(0, $length2 + 1, 0)); + + // loop over the rows + for ($index1 = 1; $index1 <= $length1; $index1++) { + // create the new row + $table[$index1] = array(0); + + // loop over the columns + for ($index2 = 1; $index2 <= $length2; $index2++) { + // store the longest common subsequence length + if ($sequence1[$index1 + $start - 1]== $sequence2[$index2 + $start - 1] + ) { + $table[$index1][$index2] = $table[$index1 - 1][$index2 - 1] + 1; + } else { + $table[$index1][$index2] = + max($table[$index1 - 1][$index2], $table[$index1][$index2 - 1]); + } + } + } + + // return the table + return $table; + } + + /* Returns the partial diff for the specificed sequences, in reverse order. + * The parameters are: + * + * $table - the table returned by the computeTable function + * $sequence1 - the first sequence + * $sequence2 - the second sequence + * $start - the starting index + */ + private static function generatePartialDiff( + $table, + $sequence1, + $sequence2, + $start + ) { + + // initialise the diff + $diff = array(); + + // initialise the indices + $index1 = count($table) - 1; + $index2 = count($table[0]) - 1; + + // loop until there are no items remaining in either sequence + while ($index1 > 0 || $index2 > 0) { + // check what has happened to the items at these indices + if ($index1 > 0 && $index2 > 0 + && $sequence1[$index1 + $start - 1]== $sequence2[$index2 + $start - 1] + ) { + // update the diff and the indices + $diff[] = array($sequence1[$index1 + $start - 1], self::UNMODIFIED); + $index1--; + $index2--; + } elseif ($index2 > 0 + && $table[$index1][$index2] == $table[$index1][$index2 - 1] + ) { + // update the diff and the indices + $diff[] = array($sequence2[$index2 + $start - 1], self::INSERTED); + $index2--; + } else { + // update the diff and the indices + $diff[] = array($sequence1[$index1 + $start - 1], self::DELETED); + $index1--; + } + } + + // return the diff + return $diff; + } + + /* Returns a diff as a string, where unmodified lines are prefixed by ' ', + * deletions are prefixed by '- ', and insertions are prefixed by '+ '. The + * parameters are: + * + * $diff - the diff array + * $separator - the separator between lines; this optional parameter defaults + * to "\n" + */ + public static function toString($diff, $separator = "\n") + { + + // initialise the string + $string = ''; + + // loop over the lines in the diff + foreach ($diff as $line) { + // extend the string with the line + switch ($line[1]) { + case self::UNMODIFIED: + $string .= ' ' . $line[0]; + break; + case self::DELETED: + $string .= '- ' . $line[0]; + break; + case self::INSERTED: + $string .= '+ ' . $line[0]; + break; + } + + // extend the string with the separator + $string .= $separator; + } + + // return the string + return $string; + } + + /* Returns a diff as an HTML string, where unmodified lines are contained + * within 'span' elements, deletions are contained within 'del' elements, and + * insertions are contained within 'ins' elements. The parameters are: + * + * $diff - the diff array + * $separator - the separator between lines; this optional parameter defaults + * to '
    ' + */ + public static function toHTML($diff, $separator = '
    ') + { + + // initialise the HTML + $html = ''; + + // loop over the lines in the diff + foreach ($diff as $line) { + // extend the HTML with the line + switch ($line[1]) { + case self::UNMODIFIED: + $element = 'span'; + break; + case self::DELETED: + $element = 'del'; + break; + case self::INSERTED: + $element = 'ins'; + break; + } + $html .= + '<' . $element . '>' + . htmlspecialchars($line[0]) + . ''; + + // extend the HTML with the separator + $html .= $separator; + } + + // return the HTML + return $html; + } + + /* Returns a diff as an HTML table. The parameters are: + * + * $diff - the diff array + * $indentation - indentation to add to every line of the generated HTML; this + * optional parameter defaults to '' + * $separator - the separator between lines; this optional parameter + * defaults to '
    ' + */ + public static function toTable($diff, $indentation = '', $separator = '
    ') + { + + // initialise the HTML + $html = $indentation . "\n"; + + // loop over the lines in the diff + $index = 0; + while ($index < count($diff)) { + // determine the line type + switch ($diff[$index][1]) { + // display the content on the left and right + case self::UNMODIFIED: + $leftCell = + self::getCellContent( + $diff, + $indentation, + $separator, + $index, + self::UNMODIFIED + ); + $rightCell = $leftCell; + break; + + // display the deleted on the left and inserted content on the right + case self::DELETED: + $leftCell = + self::getCellContent( + $diff, + $indentation, + $separator, + $index, + self::DELETED + ); + $rightCell = + self::getCellContent( + $diff, + $indentation, + $separator, + $index, + self::INSERTED + ); + break; + + // display the inserted content on the right + case self::INSERTED: + $leftCell = ''; + $rightCell = + self::getCellContent( + $diff, + $indentation, + $separator, + $index, + self::INSERTED + ); + break; + } + + // extend the HTML with the new row + $html .= + $indentation + . " \n" + . $indentation + . ' \n" + . $indentation + . ' \n" + . $indentation + . " \n"; + } + + // return the HTML + return $html . $indentation . "
    ' + . $leftCell + . "' + . $rightCell + . "
    \n"; + } + + /* Returns the content of the cell, for use in the toTable function. The + * parameters are: + * + * $diff - the diff array + * $indentation - indentation to add to every line of the generated HTML + * $separator - the separator between lines + * $index - the current index, passes by reference + * $type - the type of line + */ + private static function getCellContent( + $diff, + $indentation, + $separator, + &$index, + $type + ) { + + // initialise the HTML + $html = ''; + + // loop over the matching lines, adding them to the HTML + while ($index < count($diff) && $diff[$index][1] == $type) { + $html .= + '' + . htmlspecialchars($diff[$index][0]) + . '' + . $separator; + $index++; + } + + // return the HTML + return $html; + } +} diff --git a/htdocs/ticketsup/contacts.php b/htdocs/ticketsup/contacts.php new file mode 100644 index 00000000000..8879b01d237 --- /dev/null +++ b/htdocs/ticketsup/contacts.php @@ -0,0 +1,186 @@ + + * Copyright (C) 2011 Regis Houssin + * 2016 Christophe Battarel + * + * 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. + */ + +/** + * \file ticketsup/contacts.php + * \ingroup ticketsup + * \brief Contacts des tickets + */ +$res = 0; +if (file_exists("../main.inc.php")) { + $res = include "../main.inc.php"; // From htdocs directory +} elseif (!$res && file_exists("../../main.inc.php")) { + $res = include "../../main.inc.php"; // From "custom" directory +} else { + die("Include of main fails"); +} + +require_once 'class/ticketsup.class.php'; +dol_include_once('/ticketsup/lib/ticketsup.lib.php'); + +require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php"; +require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php'; + +// Load traductions files requiredby by page +$langs->load("companies"); +$langs->load("ticketsup@ticketsup"); + +// Get parameters +$socid = GETPOST("socid", 'int'); +$action = GETPOST("action", 'alpha'); +$track_id = GETPOST("track_id", 'alpha'); +$id = GETPOST("id", 'int'); +$ref = GETPOST('ref', 'alpha'); + +$type = GETPOST('type', 'alpha'); +$source = GETPOST('source', 'alpha'); + +$ligne = GETPOST('ligne', 'int'); +$lineid = GETPOST('lineid', 'int'); + + + + +// Protection if external user +if ($user->societe_id > 0) { + $socid = $user->societe_id; + accessforbidden(); +} + +// Store current page url +$url_page_current = dol_buildpath('/ticketsup/contacts.php', 1); + +$object = new Ticketsup($db); + +/* + * Ajout d'un nouveau contact + */ + +if ($action == 'addcontact' && $user->rights->ticketsup->write) { + $result = $object->fetch($id, $track_id); + + if ($result > 0 && ($id > 0 || (!empty($track_id)))) { + $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); + $result = $object->add_contact($contactid, $type, $source); + } + + if ($result >= 0) { + Header("Location: " . $url_page_current . "?id=" . $object->id); + exit; + } else { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } +} + +// bascule du statut d'un contact +if ($action == 'swapstatut' && $user->rights->ticketsup->write) { + if ($object->fetch($id, $track_id)) { + $result = $object->swapContactStatus($ligne); + } else { + dol_print_error($db, $object->error); + } +} + +// Efface un contact +if ($action == 'deletecontact' && $user->rights->ticketsup->write) { + if ($object->fetch($id, $track_id)) { + $result = $object->delete_contact($lineid); + + if ($result >= 0) { + Header("Location: " . $url_page_current . "?id=" . $object->id); + exit; + } + } +} + +/* + * View + */ +$help_url = 'FR:DocumentationModuleTicket'; +llxHeader('', $langs->trans("TicketContacts"), $help_url); + +$form = new Form($db); +$formcompany = new FormCompany($db); +$contactstatic = new Contact($db); +$userstatic = new User($db); + +/* *************************************************************************** */ +/* */ +/* Mode vue et edition */ +/* */ +/* *************************************************************************** */ + +if ($id > 0 || !empty($track_id) || !empty($ref)) { + if ($object->fetch($id, $track_id, $ref) > 0) { + if ($object->fk_soc > 0) { + $object->fetch_thirdparty(); + $head = societe_prepare_head($object->thirdparty); + dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); + dol_banner_tab($object->thirdparty, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); + dol_fiche_end(); + } + + if (!$user->societe_id && $conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY) { + $object->next_prev_filter = "te.fk_user_assign = '" . $user->id . "'"; + } elseif ($user->societe_id > 0) { + $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; + } + $head = ticketsup_prepare_head($object); + dol_fiche_head($head, 'tabTicketContacts', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + $object->label = $object->ref; + // Author + if ($object->fk_user_create > 0) { + $object->label .= ' - ' . $langs->trans("CreatedBy") . ' '; + $langs->load("users"); + $fuser = new User($db); + $fuser->fetch($object->fk_user_create); + $object->label .= $fuser->getNomUrl(0); + } + $linkback = '' . $langs->trans("BackToList") . ' '; + $object->ticketsup_banner_tab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + + dol_fiche_end(); + print '
    '; + + $permission = $user->rights->ticketsup->write; + + // Contacts lines (modules that overwrite templates must declare this into descriptor) + $dirtpls=array_merge($conf->modules_parts['tpl'], array('/core/tpl')); + foreach ($dirtpls as $reldir) { + $res=@include dol_buildpath($reldir.'/contacts.tpl.php'); + if ($res) { + break; + } + } + } else { + print "ErrorRecordNotFound"; + } +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/ticketsup/css/bg.css.php b/htdocs/ticketsup/css/bg.css.php new file mode 100755 index 00000000000..d54233860f7 --- /dev/null +++ b/htdocs/ticketsup/css/bg.css.php @@ -0,0 +1,57 @@ +conf loaded (not done into main because of NOLOGIN constant defined) +if (empty($user->id) && ! empty($_SESSION['dol_login'])) { + $user->fetch('', $_SESSION['dol_login']); +} + + +// Define css type +header('Content-type: text/css'); +// Important: Following code is to avoid page request by browser and PHP CPU at +// each Dolibarr page access. +if (empty($dolibarr_nocache)) { + header('Cache-Control: max-age=3600, public, must-revalidate'); +} else { + header('Cache-Control: no-cache'); +} + +// On the fly GZIP compression for all pages (if browser support it). Must set the bit 3 of constant to 1. +if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x04)) { + ob_start("ob_gzhandler"); +} + + +print 'html {'; +if (! empty($conf->global->TICKETS_SHOW_MODULE_LOGO)) { + print 'background: url("../public/img/bg_ticket.png") no-repeat 95% 90%;'; +} +print '}'; diff --git a/htdocs/ticketsup/css/styles.css b/htdocs/ticketsup/css/styles.css new file mode 100644 index 00000000000..694e1c27816 --- /dev/null +++ b/htdocs/ticketsup/css/styles.css @@ -0,0 +1,115 @@ +html { + min-height: 100%; height: 100%; +} + +body { + font-size: 0.88em; + background: none; + min-height: 600px; + /*padding-bottom:150px;*/ +} + +div.corps { + font-family: arial; + position: static; + padding: 2em 1em; + overflow-x: auto; + border: 2px solid rgb(153, 153, 153); + background-color: rgb(255, 255, 255); + box-shadow: 2px 2px 2px rgb(245, 245, 245); + border-radius: 10px 10px 10px 10px; + margin: 1.5em; + background : #ffffff; + + +} + +.index_create, .index_display { + float: left; + width: 33%; + text-align: center; +} + +.orange { + color: #fef4e9; + border: solid 1px #da7c0c; + background: #f78d1d; + background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20)); + background: -moz-linear-gradient(top, #faa51a, #f47a20); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#faa51a', endColorstr='#f47a20'); +} +.orange:active { + color: #fcd3a5; + background: -webkit-gradient(linear, left top, left bottom, from(#f47a20), to(#faa51a)); + background: -moz-linear-gradient(top, #f47a20, #faa51a); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f47a20', endColorstr='#faa51a'); +} + +.orange:hover { + background: #f47c20; + background: -webkit-gradient(linear, left top, left bottom, from(#f88e11), to(#f06015)); + background: -moz-linear-gradient(top, #f88e11, #f06015); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f88e11', endColorstr='#f06015'); +} + + +.blue { + color: #d9eef7; + border: solid 1px #0076a3; + background: #0095cd; + background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5)); + background: -moz-linear-gradient(top, #00adee, #0078a5); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00adee', endColorstr='#0078a5'); +} +.blue:active { + color: #80bed6; + background: -webkit-gradient(linear, left top, left bottom, from(#0078a5), to(#00adee)); + background: -moz-linear-gradient(top, #0078a5, #00adee); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0078a5', endColorstr='#00adee'); +} +.blue:hover { + background: #007ead; + background: -webkit-gradient(linear, left top, left bottom, from(#0095cc), to(#00678e)); + background: -moz-linear-gradient(top, #0095cc, #00678e); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0095cc', endColorstr='#00678e'); +} + +#form_create_ticket, +#form_view_ticket { + + margin-left: 10px; + margin-right: 10px; + padding-left:1em; + padding-right:1em; + padding-top:1.5em; + padding-bottom:12px; + + border: 1px solid #C0C0C0; + background-color: #E0E0E0; + + -moz-box-shadow: 4px 4px 4px #DDD; + -webkit-box-shadow: 4px 4px 4px #DDD; + box-shadow: 4px 4px 4px #DDD; + + border-radius: 8px; + border:solid 1px rgba(168,168,168,.4); + border-top:solid 1px f8f8f8; + background-color: #f8f8f8; + background-image: -o-linear-gradient(top, rgba(250,250,250,.6) 0%, rgba(192,192,192,.3) 100%); + background-image: -moz-linear-gradient(top, rgba(250,250,250,.6) 0%, rgba(192,192,192,.3) 100%); + background-image: -webkit-linear-gradient(top, rgba(250,250,250,.6) 0%, rgba(192,192,192,.3) 100%); + background-image: -ms-linear-gradient(top, rgba(250,250,250,.6) 0%, rgba(192,192,192,.3) 100%); + background-image: linear-gradient(top, rgba(250,250,250,.6) 0%, rgba(192,192,192,.3) 100%); +} +#form_create_ticket input.text, +#form_create_ticket textarea { width:450px;} + div.info { + background: none repeat scroll 0% 0% rgb(252, 245, 184); + padding: 2px 4px 2px 6px; + margin: 1.5em 1em; + border: 1px solid rgb(188, 169, 54); + font-weight: normal; + +} + +div.warning { color: #333333;} diff --git a/htdocs/ticketsup/css/ticketsup.css b/htdocs/ticketsup/css/ticketsup.css new file mode 100644 index 00000000000..b94e7a6d582 --- /dev/null +++ b/htdocs/ticketsup/css/ticketsup.css @@ -0,0 +1,265 @@ +#cd-timeline { + position: relative; + padding: 2em 0; + margin-bottom: 2em; +} +#cd-timeline::before { + /* this is the vertical line */ + content: ''; + position: absolute; + top: 0; + left: 18px; + height: 100%; + width: 4px; + background: #d7e4ed; +} +@media only screen and (min-width: 1170px) { + #cd-timeline { + margin-bottom: 3em; + } + #cd-timeline::before { + left: 50%; + margin-left: -2px; + } +} + +.cd-timeline-block { + position: relative; + margin: 2em 0; +} +.cd-timeline-block:after { + content: ""; + display: table; + clear: both; +} +.cd-timeline-block:first-child { + margin-top: 0; +} +.cd-timeline-block:last-child { + margin-bottom: 0; +} +@media only screen and (min-width: 1170px) { + .cd-timeline-block { + margin: 4em 0; + } + .cd-timeline-block:first-child { + margin-top: 0; + } + .cd-timeline-block:last-child { + margin-bottom: 0; + } +} + +.cd-timeline-img { + position: absolute; + top: 0; + left: 0; + width: 40px; + height: 40px; + border-radius: 50%; + box-shadow: 0 0 0 4px white, inset 0 2px 0 rgba(0, 0, 0, 0.08), 0 3px 0 4px rgba(0, 0, 0, 0.05); + background: #d7e4ed; +} +.cd-timeline-img img { + display: block; + width: 24px; + height: 24px; + position: relative; + left: 50%; + top: 50%; + margin-left: -12px; + margin-top: -12px; +} +.cd-timeline-img.cd-picture { + background: #75ce66; +} +.cd-timeline-img.cd-movie { + background: #c03b44; +} +.cd-timeline-img.cd-location { + background: #f0ca45; +} +@media only screen and (min-width: 1170px) { + .cd-timeline-img { + width: 60px; + height: 60px; + left: 50%; + margin-left: -30px; + /* Force Hardware Acceleration in WebKit */ + -webkit-transform: translateZ(0); + -webkit-backface-visibility: hidden; + } + .cssanimations .cd-timeline-img.is-hidden { + visibility: hidden; + } + .cssanimations .cd-timeline-img.bounce-in { + visibility: visible; + -webkit-animation: cd-bounce-1 0.6s; + -moz-animation: cd-bounce-1 0.6s; + animation: cd-bounce-1 0.6s; + } +} + +@-webkit-keyframes cd-bounce-1 { + 0% { + opacity: 0; + -webkit-transform: scale(0.5); + } + + 60% { + opacity: 1; + -webkit-transform: scale(1.2); + } + + 100% { + -webkit-transform: scale(1); + } +} +@-moz-keyframes cd-bounce-1 { + 0% { + opacity: 0; + -moz-transform: scale(0.5); + } + + 60% { + opacity: 1; + -moz-transform: scale(1.2); + } + + 100% { + -moz-transform: scale(1); + } +} +@keyframes cd-bounce-1 { + 0% { + opacity: 0; + -webkit-transform: scale(0.5); + -moz-transform: scale(0.5); + -ms-transform: scale(0.5); + -o-transform: scale(0.5); + transform: scale(0.5); + } + + 60% { + opacity: 1; + -webkit-transform: scale(1.2); + -moz-transform: scale(1.2); + -ms-transform: scale(1.2); + -o-transform: scale(1.2); + transform: scale(1.2); + } + + 100% { + -webkit-transform: scale(1); + -moz-transform: scale(1); + -ms-transform: scale(1); + -o-transform: scale(1); + transform: scale(1); + } +} +.cd-timeline-content { + position: relative; + margin-left: 60px; + background: white; + border-radius: 0.25em; + padding: 1em; + background-image: -o-linear-gradient(bottom, rgba(0,0,0,0.1) 0%, rgba(230,230,230,0.4) 100%); + background-image: -moz-linear-gradient(bottom, rgba(0,0,0,0.1) 0%, rgba(230,230,230,0.4) 100%); + background-image: -webkit-linear-gradient(bottom, rgba(0,0,0,0.1) 0%, rgba(230,230,230,0.4) 100%); + background-image: -ms-linear-gradient(bottom, rgba(0,0,0,0.1) 0%, rgba(230,230,230,0.4) 100%); + background-image: linear-gradient(bottom, rgba(0,0,0,0.1) 0%, rgba(230,230,230,0.4) 100%); +} +.cd-timeline-content:after { + content: ""; + display: table; + clear: both; +} +.cd-timeline-content h2 { + color: #303e49; +} +.cd-timeline-content .cd-date { + font-size: 13px; + font-size: 0.8125rem; +} +.cd-timeline-content .cd-date { + display: inline-block; +} +.cd-timeline-content p { + margin: 1em 0; + line-height: 1.6; +} + +.cd-timeline-content .cd-date { + float: left; + padding: .2em 0; + opacity: .7; +} +.cd-timeline-content::before { + content: ''; + position: absolute; + top: 16px; + right: 100%; + height: 0; + width: 0; + border: 7px solid transparent; + border-right: 7px solid white; +} +@media only screen and (min-width: 768px) { + .cd-timeline-content h2 { + font-size: 20px; + font-size: 1.25rem; + } + .cd-timeline-content { + font-size: 16px; + font-size: 1rem; + } + .cd-timeline-content .cd-read-more, .cd-timeline-content .cd-date { + font-size: 14px; + font-size: 0.875rem; + } +} +@media only screen and (min-width: 1170px) { + .cd-timeline-content { + margin-left: 0; + padding: 1.6em; + width: 43%; + } + .cd-timeline-content::before { + top: 24px; + left: 100%; + border-color: transparent; + border-left-color: white; + } + .cd-timeline-content .cd-read-more { + float: left; + } + .cd-timeline-content .cd-date { + position: absolute; + width: 55%; + left: 115%; + top: 6px; + font-size: 16px; + font-size: 1rem; + } + .cd-timeline-block:nth-child(even) .cd-timeline-content { + float: right; + } + .cd-timeline-block:nth-child(even) .cd-timeline-content::before { + top: 24px; + left: auto; + right: 100%; + border-color: transparent; + border-right-color: white; + } + .cd-timeline-block:nth-child(even) .cd-timeline-content .cd-read-more { + float: right; + } + .cd-timeline-block:nth-child(even) .cd-timeline-content .cd-date { + left: auto; + right: 115%; + text-align: right; + } + +} + + diff --git a/htdocs/ticketsup/document.php b/htdocs/ticketsup/document.php new file mode 100644 index 00000000000..4139a98e17e --- /dev/null +++ b/htdocs/ticketsup/document.php @@ -0,0 +1,168 @@ + + * Copyright (C) 2004-2010 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2010 Juanjo Menent + * Copyright (C) 2013-2016 Jean-François Ferry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file /ticketsup/document.php + * \ingroup ticketsup + * \brief files linked to a ticket + */ + +$res = 0; +if (file_exists("../main.inc.php")) { + $res = include "../main.inc.php"; // From htdocs directory +} elseif (!$res && file_exists("../../main.inc.php")) { + $res = include "../../main.inc.php"; // From "custom" directory +} else { + die("Include of main fails"); +} + +dol_include_once('/ticketsup/lib/ticketsup.lib.php'); +dol_include_once('/ticketsup/class/ticketsup.class.php'); +require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php'; +require_once DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php"; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; + +$langs->load("companies"); +$langs->load('other'); + +$action = GETPOST('action'); +$confirm = GETPOST('confirm'); +$id = GETPOST('id', 'int'); +$track_id = GETPOST('track_id', 'alpha'); +$ref = GETPOST('ref', 'alpha'); + +// Security check +if (!$user->rights->ticketsup->read) { + accessforbidden(); +} + +// Get parameters +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOST("page", 'int'); +if ($page == -1) { + $page = 0; +} +$offset = $conf->liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (!$sortorder) { + $sortorder = "ASC"; +} + +if (!$sortfield) { + $sortfield = "name"; +} + +$object = new Ticketsup($db); +$result = $object->fetch($id, $track_id, $ref); + +// to match document rules and compatibility +$old_ref = $object->ref; +$object->ref = $object->track_id; + + +if ($result < 0) { + setEventMessage($object->error, 'errors'); +} else { + $upload_dir = $conf->ticketsup->dir_output . "/" . dol_sanitizeFileName($object->track_id); +} + +/* + * Actions + */ +// Included file moved into Dolibarr 4, keep it for compatibility +$res=@include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +if (! $res) { + include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_pre_headers.tpl.php'; +} + +$object->ref = $old_ref; + +/* + * View + */ + +$form = new Form($db); + +$help_url = ''; +llxHeader('', $langs->trans("TicketDocumentsLinked") . ' - ' . $langs->trans("Files"), $help_url); + +if ($object->id) { + /* + * Affichage onglets + */ + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } + + $form = new Form($db); + if ($object->fk_soc > 0) { + $object->fetch_thirdparty(); + $head = societe_prepare_head($object->thirdparty); + dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); + dol_banner_tab($object->thirdparty, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); + dol_fiche_end(); + } + + if (!$user->societe_id && $conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY) { + $object->next_prev_filter = "te.fk_user_assign = '" . $user->id . "'"; + } elseif ($user->societe_id > 0) { + $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; + } + $head = ticketsup_prepare_head($object); + dol_fiche_head($head, 'tabTicketDocument', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + $object->label = $object->ref; + // Author + if ($object->fk_user_create > 0) { + $object->label .= ' - ' . $langs->trans("CreatedBy") . ' '; + $langs->load("users"); + $fuser = new User($db); + $fuser->fetch($object->fk_user_create); + $object->label .= $fuser->getNomUrl(0); + } + $linkback = '' . $langs->trans("BackToList") . ' '; + $object->ticketsup_banner_tab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + + dol_fiche_end(); + + // Construit liste des fichiers + $filearray = dol_dir_list($upload_dir, "files", 0, '', '\.meta$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1); + $totalsize = 0; + foreach ($filearray as $key => $file) { + $totalsize += $file['size']; + } + // For compatibility we use track ID for directory + $object->ref = $object->track_id; + $modulepart = 'ticketsup'; + $permission = $user->rights->ticketsup->write; + include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + + + print "

    "; +} else { + accessforbidden('', 0, 0); +} + +llxFooter(); +$db->close(); diff --git a/htdocs/ticketsup/history.php b/htdocs/ticketsup/history.php new file mode 100644 index 00000000000..089f31b942c --- /dev/null +++ b/htdocs/ticketsup/history.php @@ -0,0 +1,139 @@ + + * + * 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, see . + */ + +/** + * History of ticket + * + * @package ticketsup + */ + +$res = 0; +if (file_exists("../main.inc.php")) { + $res = include "../main.inc.php"; // From htdocs directory +} elseif (!$res && file_exists("../../main.inc.php")) { + $res = include "../../main.inc.php"; // From "custom" directory +} else { + die("Include of main fails"); +} +require_once 'class/actions_ticketsup.class.php'; +require_once 'class/html.formticketsup.class.php'; +require_once 'lib/ticketsup.lib.php'; +require_once DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php"; +require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; + +if (!class_exists('Contact')) { + include DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; +} + +// Load traductions files requiredby by page +$langs->load("companies"); +$langs->load("other"); +$langs->load("ticketsup@ticketsup"); + +// Get parameters +$id = GETPOST('id', 'int'); +$track_id = GETPOST('track_id', 'alpha', 3); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha', 3); + +// Security check +if (!$user->rights->ticketsup->read) { + accessforbidden(); +} + +$object = new ActionsTicketsup($db); + +$object->doActions($action); + +$extrafields = new ExtraFields($db); +$extralabels = $extrafields->fetch_name_optionals_label($object->dao->table_element); + +if (!$action) { + $action = 'view'; +} + +/*************************************************** + * PAGE + * + * Put here all code to build page + ****************************************************/ + +$help_url = 'FR:DocumentationModuleTicket'; +$page_title = $object->getTitle($action); +llxHeader('', $page_title, $help_url); + +$userstat = new User($db); +$form = new Form($db); +$formticket = new FormTicketsup($db); + +if ($action == 'view') { + $res = $object->fetch($id, $track_id, $ref); + + if ($res > 0) { + // restrict access for externals users + if ($user->societe_id > 0 && ($object->dao->fk_soc != $user->societe_id) + ) { + accessforbidden('', 0); + } + // or for unauthorized internals users + if (!$user->societe_id && ($conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY && $object->dao->fk_user_assign != $user->id) && !$user->rights->ticketsup->manage) { + accessforbidden('', 0); + } + + if ($object->dao->fk_soc > 0) { + $object->dao->fetch_thirdparty(); + $head = societe_prepare_head($object->dao->thirdparty); + dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); + dol_banner_tab($object->dao->thirdparty, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); + dol_fiche_end(); + } + + if (!$user->societe_id && $conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY) { + $object->next_prev_filter = "te.fk_user_assign = '" . $user->id . "'"; + } elseif ($user->societe_id > 0) { + $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; + } + $head = ticketsup_prepare_head($object->dao); + dol_fiche_head($head, 'tabTicketLogs', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + $object->dao->label = $object->dao->ref; + // Author + if ($object->dao->fk_user_create > 0) { + $object->dao->label .= ' - ' . $langs->trans("CreatedBy") . ' '; + $langs->load("users"); + $fuser = new User($db); + $fuser->fetch($object->dao->fk_user_create); + $object->dao->label .= $fuser->getNomUrl(0); + } + $linkback = '' . $langs->trans("BackToList") . ' '; + $object->dao->ticketsup_banner_tab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + + dol_fiche_end(); + + print '
    '; + // Logs list + print load_fiche_titre($langs->trans('TicketHistory'), '', 'history@ticketsup'); + $object->viewTimelineTicketLogs(); + print '
    '; + print '
    '; + } +} // End action view + +// End of page +llxFooter(''); +$db->close(); diff --git a/htdocs/ticketsup/img/gplv3.png b/htdocs/ticketsup/img/gplv3.png new file mode 100644 index 0000000000000000000000000000000000000000..ba78d4c4941dabf2fcac5409a92ac4c57920c69f GIT binary patch literal 2666 zcmV-w3YGPVP)Px#32;bRa{vGVivR!tivi)#(!2lw00(qQO+^RT0uvMpF24YJ`L;(K) z{{a7>y{D4^014_zL_t(&-tC%skW|$b#(x5`77PlZ01Xf|tXfvU1+9P)Nl;9MMIeIW zf~A;|yxWx-F&@d<9Z!mSGK`{-NXD*+V< z1U?qnFHjo71r>243NtglEQV7Q5|M$wwPW#3mU1Xa75(4)}+D^1dj!r-wg;N!7wPTlz6cv~* zaG8PJ%ocdxi%_r(8VF2J2gJd((|x~-stE3f0*?zktgtfz_z{7D0<}|XS^^CmbayaJ zV6ea`S+E+%|4L05^x|!{8+(dT?jEM~Js`$27+y6h2%>GgYF0wJYE0l-O z)7o925Tv&W;2eAZgu;B5;j^dJ8-bz3oKpjkZt1g)zX^66mI| z)j_Xp5wNzxdh2k6HU6=}>lr5fjzC|47oe%aZiQ_MKeNs1Wz;5au`^ddqYxT8_`O0| z2+eKGVG3K)+k_Uu1%|7S@cDv!RA5U0Jp{%pe3tfppM%?rytQ5}8P;njwoMwi^#raG z_|!q~0P19O58V`YC~Ow^rGefh%fweYXuAOFEA&%1pirdH-T=NSi#0u9by^9`QxJv5 zHjl?NEpVEPINjb~s%aLOrIZQ$Er2cpYhwES(!o;>ZWd4fj>h!yt-vP^&Rzf~rSJ-% zg@aKFTLZW-2{m&$=#dIvD=Zf1XvcR*1&`sq0ThV$zmI09^NGMv1M6&ojS7EJsBiOF z8n;M=9{?nvrNFcK_*#Yg1^TDhK}Ke?#C57YX(PO#~hmZ&YIfXpm0?Of77b zcz4lUy){(?;9j;d=Zg=NarIQ8n^{2*frBCRE`gImI7i`?I3Q90+X5fTF_*Oh*9+WO z1x|lZpeTTXIJ}Zj$9dYg#Asf_jNm>ECo6nxzAm326$kDY0%zN14N};eq2A;GS}N34 z_?^POB%Ep+b3>f}wIrZv1mNKjYL#A=I=IZiomF5OUkN;%%t28n`n7hnwKmOUxi!^C z?!7sJ)RYjqCgH3A+6T}!^hf+gd!G=mbKa5;2^2Z#5Q*l| zfdhdl0@EDyF+dtC++#s#w6j4H&?112wh__NE(zy`FhF3r<@t|C0A7{B|L)KTzz$ld zr)$xAGn~&v$ExqQqQD+9qd48hXc$805H1yOr8Q%W^E8V!qcoEr7HA|sO)M9(j7va) zLPO)u<>K8*eH(mXo|E4b6{n4!WlMoas%ZhvALqY1(?UYejX$qum2H*6CFz(2o?R^x zDEv(hmVvj&jg=p^uDHvkZKlwQXnG#Q_KXL#Ubbsr9Nn7x7-IFOx}g0W@Fj z20>x8!ootY1Jtn~{dF~g`?~m)`Q!|iyHa6%kmfQnQM3*U9~p3ePDSc@Q2%*2Wf?S% zmJ%okp_W5IHRG)GOwilcdW(Gu*4g{T~>dyLTd*<7nqH5>P4bO#m15lF^bQk0@fXG4I;>Zi8G4~)h=aS0UnUjaR`^J~?z=+$ zHTWKdViR&!n`TiY-;I@$Nas4sHq*3$R%RqSBP!U};>Y>BK#9N@@vNzKHf)UY&9JQQ zCMxp?bTg|ev(NnmCWO%6!B~MAp&w|lz>EMc4xx`RjCHn%FPzVQekwkb8YeK{!Gi*~ zsNb|P0)6c!`IJklP`iK9vb6vc-7RoHJ0Nq5dRwk5m+UDA)gAo?O?LN0*eFN#QW*D#LIwjzkygL(4{)S zRcNGevoWb@0%ujrt~sxh79Qi@G*o92@TaP*zZ6=F7pc}Mlq8{3Nv<1-3c80vD-#)#iR!fAg3`3i=|n0Ep+VCB*yVN$x?2_YiZ5k$@3&Tcz#W!=Gm9%=?NxpL Y19h*OP%`Tk_W%F@07*qoM6N<$g8#_jNdN!< literal 0 HcmV?d00001 diff --git a/htdocs/ticketsup/img/history.png b/htdocs/ticketsup/img/history.png new file mode 100644 index 0000000000000000000000000000000000000000..59f9ac7d94c62bf7a39172db3adb591e742ad5a1 GIT binary patch literal 2191 zcmV;A2ypj_P)z@;j(q!3lK=n!AY({UO#lFTB>(_`g8%^e{{R4h=>PzA zFaQARU;qF*m;eA5Z<1fdMgRZ^1xZ9fRCwC7R(VuZ*B$<5-n{qby;*>n0Rd4GcM&AG z0HG31ZIjrz5ZsQ|J=LT3M32=|v@JcRX%bHsEv+^791}~TmPl2kF2qJOBnFilR2Gqu z9R`@02h9FvdGGcQqcI*eV)Xm#p1Yj;-S2+C1$ap0&(G(Y-{Oj`NuP(ylMrvy699fo0XQ$PE z=ulBXZEa&yO>GOQH(N+UgGDSWD?fegSjlNwmPu*pS7rdZM^!*|uZ7xLbEn193(+qd zWu8^ zPR__N>9a0WRAF#jG@_%8U>F*J0D$3I!22Fd8O< zo;0=E6z1z@+tS4^B?IW}w+YXl{cl5IVNsvW=2TQvRAczicu*=Dp{u+IEv1m`7C=t?C`}Jtp+sBK$Z!- z9ud8L9@N!U2YLh{kdiV%8y2C5(GUiOLJ3h6aizKeLDA_e|N8UI0D2#ZfYE5wC8wk( z+64zVj)N4EK`ANNdptN*a>QI%uyZSb_NRv?u2{7ucc~H-A`ChRb_WE(f!LTxZhUHH z+WB*(*8oTlOF#+0IDf(N-26{Ywu~H|lH&9EKq)8y3WP!uSeC}QvSV)oH~^rmsiAtK zwbN`?DrvYJ9uS#;Q?qb;MXXtqyXVbqdustiKQsZFreoCV@JU3ei*UL9AVdL)5D)+q zrNV&72$)O}{yWZi1`Ub}saXap6$Oo!gPLO?NfJ6bt!Qj)9z@f$u|Hv`p(rXXI(pD6 z%U9+s95OV~prQzLS{^zr2bN_a2(35HoIbuXEp2>#Wo7k-x${*vr)0-k3Prq_Vy)dg>lm&fMi<*^SPhF_E( z|Fo^8(PXz-ny0=ne-2G&$38o86nKt@D25OWhHgrxq`+}BA|iO)XzIXcpP$3N{OyJQ zfLDkJHxK|_0FaT9dAzNytp~t70MzQ$tBt#N@3!7efcoxLQe%(MbyyTV$1EL9;^6q? zmpi(8q0y)j8L3BD7zbWML(NfedAumUcn#$jYw<(E$14IQM^VMj>^hQ z;>i<7yrUA54Y9E?pj9fk-Ck5xRf^r69nQ2#FGR6wEdxLl#em)v855B;d->m7E-$W` zTcP1Oe*K2u?T9pmqr0n%I2<18LDld(Stw>&V)9SkX}VEW=ycjk0Od1dQ>OfC+N@<0 zt18cRpE&xDwE%2!aS6Fu*;zwaTH2SEG5IA~=F?(hBQavwAaE=L0s_B31dmSyt)lR0 z!N&)+T4U?MgZs-$OH2Mk2zg+BhyrliMA|UZss+n($%s*@NAK8YdjI`h6+TfWM~csr zD_5I|%M~PjeIju>gT(0!5<&2hc8i1DXy_(w?JiP!ww`2VFWz_0Jn#dE0+iDM`5OS2 zZ%sx=51jkq-lBslhDK7t5cqrnT(57%)tV|vr_m`!j~cFwi8dl6%diV>d{tH^Iv@!DVt2Q7#Q3!52iSUCPGfE=bj37T_I*rIRLqQ-ucQS0B0O#n#6SohuNNQfdGA8yrLQaR8wLG=(HOPxt#|kD zS16Q_r4ZB%jWG$spx3DE62NqJ_37)bH$e0Up<-B=>uY*dtN(y1RPNBlJNc07I)VFxCjIPKTmHhlSRT=787hj(T7s>L=m> zP(z1}%~`wdja6e3oKyG9lnO4qY|}E}Z`cfB#F)TA$B(5`Y(g^>KUw0JH!A zrBd0NT3S$WV0T^oQ$tLNNfV4L$1A=(Q)02&tiHst&kmJksUAQxo)FU1ymkwK5dg+d zNPoFv+3L3lK+OPrV^}!_C#|P458EKByyllAr)EKh%=_e*nlGt|G-z R4J!Zu002ovPDHLkV1fg>*qi_W literal 0 HcmV?d00001 diff --git a/htdocs/ticketsup/img/mark-read.png b/htdocs/ticketsup/img/mark-read.png new file mode 100644 index 0000000000000000000000000000000000000000..450a80cb3fa55d29ae6bb78a7dd36ef125d39753 GIT binary patch literal 1014 zcmVblv`+ARTPH5ede6z%q>Z$ zA(J#S>1dmpRBW0it)(S30j=8DAqYW;(gZ2m7oqqfeG@Mg6fd9%T1nCriv}X?I0{xm z)iegFC0ImBFAq&7ZOr64lgymCo$Z62I89Adq8k=#Zx;Wzf7m}8{--5YBW~(-KWK?+ zUjs-uRGM&ifB5Xh6o9fC@PZ@eFdXq&fYxo#e>7V#|MUJ%U&*S$rj|*@3u1F~`T{$> z5AjCRnay^adbXtp%c{WHWf13uFI$nOq`BsBrD2q{{wH97E7O$u?@ zs{e%NMT@5O*Vp*Vb7$5$yF-uIG+SE7=PILab0gA}OeJp4uIRYA%e&DWk)IW>^K81m z@?q;*TQTPeF3!~%Eu?5-YMryR^ofQeVw5XPL_#FZ#Ne`Ee|Onof#uCDzFNK9U7>sz zK8@dd2!I18Jzs&`?sB;GtyR12HDwLrZ2T0p)<*g-2a-yP5AFc_kKg5%TIv&LUg3`F zyX$RHIm7289VA2?Q=07A-h`^=?Q`dQaOj2nnz+E*6VFj;-vJ32zJ75c(0(JR-tN-# zxX7eCd_`4uPf>;X%k&S78dpJ;pg|yX9EZM^lr-oMPcX+Mre<=FqlQPUPtn=;vMH0a zAdri%>+kdo*w;AgcKIG%Gnu%_(B!um#E_Z7|@y|6_l*w@zl{r$zZCCHH!F*=93gDqPj{4!%#IEuUk^vBYqyK*Y}+gk&}!FV#BkftfKc2X8 klq<-VnH2+>B|TgG4*q;*G(^2q9smFU07*qoM6N<$f~?~28vpnG>mGLA(Zhz1~gJpjr)04$Kg833{b0L)4O*r5f$Grc^qBLV>QAA7^ zi0Mj@l!QqEM~ut^>g-pS)X8^J^To##z23!Iw(OFwv@a>gLJf$zKwP;BaFvar(h1kX zq|;N1=#xK!ow*U{I$4BT1Tl;R=X}DNlb*01F6@J+YX@;;=2O)G!hM-Ajvq0E+3Btvv5a)ko*C`YHX>@0T zoh#H@mdsWd18z*fjkN{)TfzeFEX_bT=tDx$E4Hei{;agc4&itgMXo1ddJM#OZGS>{ z;0T9K5uZCgSvs~LGBHLI?D!2PO9gJnrDYe6 z3qovni3RJkPUQO#>ficb^krZEqzm^*vJ{STdLW?fKV*c1fu>_dyp>FydGZ>~Wf(`+gy zTK`%|NTLaz(*3PaOhbi{-PWg}L**vhYkpCI2ue&1c-`En_!p5lk|ZAKpx9Ddr+Op` zS?&-Hbtg(!$VFP1k*SJb!&Sy%EkczGJ>E9yS~)3>wA+|6-=mr|O9#KpON;pk-(OJ3 zV%AKhYO78CFZ+$dcAQkCgc!e2kG-}&ce+)5@A^W|wSFdc*xuD$4`}V(jnh|Kla4-F zWUtn+O7U8YjoZjuKq@5+1Oys zHT~Ra=5&!&Ed0Ab0nJ#z^3+qF`poE5&^>!rrQ`~~L=rnu*#08+_J{8oWm-nlT52TN zD^2%j^qE)gfSv0j82{Rf+au!08FMTev>;@CGw$({o4fc2Hc;*_W#YCo>>mRY6p^RG#U4ixLi~sha4gQvhI>}|>GQ=?YtW@C8djfI6+fB=6c{5+u61ie?8F(sc zWngNYcRevjhioaGu;HC0)C{P~H!5!qN26->Wf}AY>zYQNS4(IW&NVbEc?^GecjALJ@6e{#PP!{~VK#7$10dcz5hoqd53YZp5$Bet#ZRIH4;p? zaO6C+K=?e{^82SpI!sm=SvR?#VEp;cfC=a9&HZk?W;)H!>58ts86>-iLD1^I9m}^n zJ-&d76_OEgeQoe;=1%`VHcAyRtT;7IULrvPMVZ8yp?FYpwzkcgtHgT#8IEPi`%2~3 zuejZ%FLo#Q4y=<;?l2UFMS4lrk2#jbQ*!P*hg2KM|15myI}!QbNtEfvL(h#i<~w!> zmigZYtjzl&h905D=|R=8C5I!qNQwvblmkN=<}vrOi^voKlU!aV>%h#aku3;xa zcTMV)JD#wxl42HX;k9&}@GR#5v1?D^>9@cP|S G)&Bv~urI;@ literal 0 HcmV?d00001 diff --git a/htdocs/ticketsup/img/object_ticketsup.png b/htdocs/ticketsup/img/object_ticketsup.png new file mode 100644 index 0000000000000000000000000000000000000000..8ece94fbefc95424eb6674b4051851bfe358c424 GIT binary patch literal 520 zcmV+j0{8uiP)?wsqma!+klNd+x(OM&KOUu?4F0A*D=2Mj~m5 zXqYOce5QyW8Md*HKIJE8Fd$+{N~@Ap5la}zYkhg|c9yg38k*R2bWnG=R~NBCj1r?F zHXQEN9UasSO>AQKkKoE&o7!U4@a#9m-rLAp*2xqv-ZDJ-FhhE5s{H-$L8#81Ca$7}%X#)Ao=NG0=^H=&Z~OxI>4-$CiC}F20000< KMNUMnLSTaX59zl6 literal 0 HcmV?d00001 diff --git a/htdocs/ticketsup/img/statut0.png b/htdocs/ticketsup/img/statut0.png new file mode 100644 index 0000000000000000000000000000000000000000..6e631dc0086a9fae78a8486c3a55b4b0096b1488 GIT binary patch literal 329 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`EX7WqAsj$Z!;#Vf4nJ z@Rfov&TwPN&sq(7jb6y4sh9`4U-=%OobPPSe zH}1i?RrLjpy$e>YiZ+gpe~@?gFY|%k-O4Qmv0jybmmRpP&VN!xi9OVmK~1S$;_=-` z$Lpom47*o;H9Tf6Xvh%FATZJNgTe~DWM4fM%;wO literal 0 HcmV?d00001 diff --git a/htdocs/ticketsup/img/statut1.png b/htdocs/ticketsup/img/statut1.png new file mode 100644 index 0000000000000000000000000000000000000000..5bff8090beba27faa75233b12e1e80934a310434 GIT binary patch literal 470 zcmV;{0V)28P)Dk}+!=K@f%C>_u`Rfl>t0 zrZBiMxKZaKLFjf@kS2wySYU&T6gF5zDz_@^DhlKe1XQF*k&xyFBJe?eLYfrmRoGyV ziwopP??NRi~Jc4pr9W`|wi0TIV>Eu3Xj*g5wOz#+*&qtO^{WMHj5H^vM~rQX^G z-uu@8Mj&7R>5%`*F@xVfB}5Zvg~c>KU!rFMbQwz zb}{)n%d%dYrhh|!c7s-{^>iNg-aiL$9C8skP1AHz)|dcSDwUtkxfh|)?RF!QA4=M* zBuPHa4>15xtyV8YvxMJtN;ev9NpL>?D=-igQ?l4l~) zENWj=_0=K+lO)L>W6VpEx5b`y0HXjG(=QjnKNFI@#6f1rGpTW{-x7!VC?a3Lld(?2Fc5}6TT!LF1rNf& zWP1Y%-hhd%9grB1+74_;pRSNHc zD}b^r9|l`c)n{vMX6tgdQ|Nowh%2`Z9D5xF}ak4e`Tok}=`JkQ@xo&WyE5W-?C aSrb31xqSEexw`290000&reI{!_NkA+F z#oA86Rv`qF+0Mq&5AZWmq_na31BA8EZbKvx(9RFANU309A(*(D-R!e43A^i#$?az5 z-Sh6786roGMq{633&0V{f~r2N>Sd);X?dPEPS!GOHpUnLHzZ5hGgZAWm&?^8WGPwT zy6!T7JCbX8$w+RGMx)PuzyC1ZlT3#y$*nwdqUJQYP66UL-uTZvNwI1Lh{*dqfT|9x z0Fu6{zRpQ-Wd-=Y{|(?wRU=FH#~=tUtbmCk03SK#v8tZ;dcD*LsefRMIR zlHx0lb#GB~Lc22nfQ7qHB_bsN_yP4sbm^h(uV(-N N002ovPDHLkV1hA$t(O1* literal 0 HcmV?d00001 diff --git a/htdocs/ticketsup/img/statut5.png b/htdocs/ticketsup/img/statut5.png new file mode 100644 index 0000000000000000000000000000000000000000..6ea7f62a9ff22ffbf63ef42b0d6469e1d8482618 GIT binary patch literal 363 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`EX7WqAsj$Z!;#Vf4nJ z@RfovW9oY-_FNK4h>*ai^kEerRZH>CY(c z9>caLg~opuX>_e$$Mmb;qVN0M;^IlxzCSciZ(6+0V8fTrb35H9&6fLmQ=F}C-Uhx0 zE-vpF8lGHRz%)tA_cFU+W!{RPtD3?hveS>vIBehAp2RrKD8MFx`;#&-v=}^H{an^L HB{Ts5t67XL literal 0 HcmV?d00001 diff --git a/htdocs/ticketsup/img/statut6.png b/htdocs/ticketsup/img/statut6.png new file mode 100644 index 0000000000000000000000000000000000000000..af7f6d433dc839f6d416e67af74dd2fd2ec9cf74 GIT binary patch literal 341 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`EX7WqAsj$Z!;#Vf4nJ z@RfovMWA))+t3ZvmM z84;%ng`Er=7#Zp{6d&3h+riSXYu$QJy)!wBS1qqR@V!N4PwBa}m&#{5=`pN1o3naV zy3!`*ZzTdw7Hl7Uiqg_vuX~-hYL!*_xvdQMLcY4V+;g|BH&*|rT-(y#J7ZCmiw k)hnOvIe5kRUvLd$`rhmx>TwUFVdQ&MBb@02u&^1poj5 literal 0 HcmV?d00001 diff --git a/htdocs/ticketsup/img/statut8.png b/htdocs/ticketsup/img/statut8.png new file mode 100644 index 0000000000000000000000000000000000000000..84f3c5e7fc505eac2b593d7005623dd6294e53cb GIT binary patch literal 272 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`EX7WqAsj$Z!;#Vf4nJ z@RfovbtYqx$@+i%8#?A8yk<&yERH^7WrTH!AT&Fc7 z^6qM_r~h7twKfSju>?%s62{PQxWtxU^X;1D+r1XCOV_wX Q0A0`E>FVdQ&MBb@052G5fdBvi literal 0 HcmV?d00001 diff --git a/htdocs/ticketsup/img/ticketsup-32.png b/htdocs/ticketsup/img/ticketsup-32.png new file mode 100644 index 0000000000000000000000000000000000000000..ce4b71ca624f73ce0f0b56b945b2ec254b21b383 GIT binary patch literal 1412 zcmV-~1$+95P)$^!`kVuT1S#0y?(pjMjr;)97O zBpRYGq)h>n#u&knmO|7Z4KYy(rd;I~C~~P3q(U#0NK@=?chC56zQUp1ZR>-+=$D-2 zd^7X?=YMAA%zW@)UmjpQkO6c6`Y-y;1p)$CfDf1nbOQ}Q_#blYGmeJ=r-87zlwKek z$OH}pxBDI6u+L9NcseixVLG-w6#&aRhjJD;!${v*HZ2Xsa6Sr{3p4>2fgS*f!7$ZC z;{wnKK-sP!wzn9S*ARk05J&)37=mfe@x)A*gtEYNSzMD|z zPJTIfBbJ+lxCEBIm(T5{HMCxy%(YWCnR)y1`ah?;`yks_w#Gd3W_2pw;31-+HC#Kn z7>(wUw=BS@%nR`d#E!uF+6mZHlHgxVTVosN4m5J_kMForzhOwVo;7zP!$&M&+M+B{ zCZ!Px)nQRe#fqzaO|6&!DkTW>iG(3NdoNubo4Hb-02B?ueGyj<`{-=nO#0+KL_#3U zN2Mf|aeo5q_dE@{9F+jVQ6k};G#>pLvlz zkw6w;1LI;iA7^w~#VgR+9}Rn%z|-ddpoIPV-?dFfRsyc}AD?&`fbK zdW$d7_=rP5B^O9U6jYk1DC%%&Bfz7;LLdP6T{^#!Ei^Wf`<14}eM;t+^> za!?szb~pQ0hiRb!;1yFNy(?s70b^tLIeXK5;0U6gocII;AA*GvMTy4xL3{snV46!l z&B%y3(tGg)3&9tkfW;-?F5tn^)IKn+z#;P<0P-h6Wo#a#z`+=g07@rO&c`PZ^fw^fGm|b8m9#!lXa=?d zr+_&w`5YtLYHZwvo#tQx!aaiihWG?Nd8P+wF(YCDwid*wgB!pJ^WSHfXPlAUh>`yS z&;~6Iun}1VtYPggpKE+afp38=z!>vvF|z3W5&!nC1Z;U3Sc0Iy0fXJ|cKYx-x;H{W z;Z0x)Do&U!kC%egzjCbl4$x*UuC3++dQ)=I=t7izHHN6X0lbPzGNSbeA5y;R`p|Dg zrL`pp?}MbFgg|#<$u^QR8`zZpXUsDn92-tYa}Kt>4%L@Hh9TO5vXROa+y35-NP2dl z-eh1M!ehYe*gQ!`Qw49;o}l`C2XgB}`z2jhASwly0hAJsfpH#~*NNzk9M?BkRd{?7kvi0d!jdBXY@ SHh8K40000$^!`kVuT1S#0y?(pjMjr;)97O zBpRYGq)h>n#u&knmO|7Z4KYy(rd;I~C~~P3q(U#0NK@=?chC56zQUp1ZR>-+=$D-2 zd^7X?=YMAA%zW@)UmjpQkO6c6`Y-y;1p)$CfDf1nbOQ}Q_#blYGmeJ=r-87zlwKek z$OH}pxBDI6u+L9NcseixVLG-w6#&aRhjJD;!${v*HZ2Xsa6Sr{3p4>2fgS*f!7$ZC z;{wnKK-sP!wzn9S*ARk05J&)37=mfe@x)A*gtEYNSzMD|z zPJTIfBbJ+lxCEBIm(T5{HMCxy%(YWCnR)y1`ah?;`yks_w#Gd3W_2pw;31-+HC#Kn z7>(wUw=BS@%nR`d#E!uF+6mZHlHgxVTVosN4m5J_kMForzhOwVo;7zP!$&M&+M+B{ zCZ!Px)nQRe#fqzaO|6&!DkTW>iG(3NdoNubo4Hb-02B?ueGyj<`{-=nO#0+KL_#3U zN2Mf|aeo5q_dE@{9F+jVQ6k};G#>pLvlz zkw6w;1LI;iA7^w~#VgR+9}Rn%z|-ddpoIPV-?dFfRsyc}AD?&`fbK zdW$d7_=rP5B^O9U6jYk1DC%%&Bfz7;LLdP6T{^#!Ei^Wf`<14}eM;t+^> za!?szb~pQ0hiRb!;1yFNy(?s70b^tLIeXK5;0U6gocII;AA*GvMTy4xL3{snV46!l z&B%y3(tGg)3&9tkfW;-?F5tn^)IKn+z#;P<0P-h6Wo#a#z`+=g07@rO&c`PZ^fw^fGm|b8m9#!lXa=?d zr+_&w`5YtLYHZwvo#tQx!aaiihWG?Nd8P+wF(YCDwid*wgB!pJ^WSHfXPlAUh>`yS z&;~6Iun}1VtYPggpKE+afp38=z!>vvF|z3W5&!nC1Z;U3Sc0Iy0fXJ|cKYx-x;H{W z;Z0x)Do&U!kC%egzjCbl4$x*UuC3++dQ)=I=t7izHHN6X0lbPzGNSbeA5y;R`p|Dg zrL`pp?}MbFgg|#<$u^QR8`zZpXUsDn92-tYa}Kt>4%L@Hh9TO5vXROa+y35-NP2dl z-eh1M!ehYe*gQ!`Qw49;o}l`C2XgB}`z2jhASwly0hAJsfpH#~*NNzk9M?BkRd{?7kvi0d!jdBXY@ SHh8K40000 + * + * 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, see . + */ + +/** + * Index page for ticket module + * + * @package ticketsup + */ + +$res = 0; +if (file_exists("../main.inc.php")) { + $res = include "../main.inc.php"; // From htdocs directory +} elseif (!$res && file_exists("../../main.inc.php")) { + $res = include "../../main.inc.php"; // From "custom" directory +} else { + die("Include of main fails"); +} + +require_once 'class/actions_ticketsup.class.php'; +require_once 'class/ticketsupstats.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/dolgraph.class.php'; + +// Load traductions files requiredby by page +$langs->load("companies"); +$langs->load("other"); +$langs->load("ticketsup@ticketsup"); + +$WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); +$HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); + +// Get parameters +$id = GETPOST('id', 'int'); +$msg_id = GETPOST('msg_id', 'int'); + +$action = GETPOST('action', 'alpha', 3); + +if ($user->societe_id) { + $socid = $user->societe_id; +} + +// Security check +$result = restrictedArea($user, 'ticketsup', 0, '', '', '', ''); + +$nowyear = strftime("%Y", dol_now()); +$year = GETPOST('year') > 0 ? GETPOST('year') : $nowyear; +//$startyear=$year-2; +$startyear = $year - 1; +$endyear = $year; + +$object = new ActionsTicketsup($db); + +/******************************************************************* + * ACTIONS + * + * Put here all code to do according to value of "action" parameter + ********************************************************************/ + +/*************************************************** + * PAGE + * + * Put here all code to build page + ****************************************************/ + +llxHeader('', $langs->trans('TicketsIndex'), ''); + +$form = new Form($db); + +$dir = ''; +$filenamenb = $dir . "/" . $prefix . "ticketsupinyear-" . $endyear . ".png"; +$fileurlnb = DOL_URL_ROOT . '/viewimage.php?modulepart=ticketsup&file=ticketsupinyear-' . $endyear . '.png'; + +$stats = new TicketsupStats($db, $socid, $userid); +$param_year = 'DOLUSERCOOKIE_ticketsup_by_status_year'; +$param_shownb = 'DOLUSERCOOKIE_ticketsup_by_status_shownb'; +$param_showtot = 'DOLUSERCOOKIE_ticketsup_by_status_showtot'; +$autosetarray = preg_split("/[,;:]+/", GETPOST('DOL_AUTOSET_COOKIE')); +if (in_array('DOLUSERCOOKIE_ticketsup_by_status', $autosetarray)) { + $endyear = GETPOST($param_year, 'int'); + $shownb = GETPOST($param_shownb, 'alpha'); + $showtot = GETPOST($param_showtot, 'alpha'); +} else { + $tmparray = json_decode($_COOKIE['DOLUSERCOOKIE_ticketsup_by_status'], true); + $endyear = $tmparray['year']; + $shownb = $tmparray['shownb']; + $showtot = $tmparray['showtot']; +} +if (empty($shownb) && empty($showtot)) { + $showtot = 1; +} + +$nowarray = dol_getdate(dol_now(), true); +if (empty($endyear)) { + $endyear = $nowarray['year']; +} + +$startyear = $endyear - 1; +$WIDTH = (($shownb && $showtot) || !empty($conf->dol_optimize_smallscreen)) ? '256' : '320'; +$HEIGHT = '192'; + +print '
    '; + +/* + * Statistics area + */ +$tick = array( + 'unread' => 0, + 'read' => 0, + 'answered' => 0, + 'assigned' => 0, + 'inprogress' => 0, + 'waiting' => 0, + 'closed' => 0, + 'deleted' => 0, +); +$total = 0; +$sql = "SELECT t.fk_statut, COUNT(t.fk_statut) as nb"; +$sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup as t"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc"; +} + +$sql .= ' WHERE t.entity IN (' . getEntity('ticketsup', 1) . ')'; +$sql .= " AND t.fk_statut IS NOT NULL"; +$sql .= " AND date_format(datec,'%Y') = '" . $endyear . "'"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND t.fk_soc = sc.fk_soc AND sc.fk_user = " . $user->id; +} + +// External users restriction +if ($user->societe_id > 0) { + $sql .= " AND t.fk_soc='" . $user->societe_id . "'"; +} else { + // For internals users, + if (!empty($conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY) && !$user->rights->ticketsup->manage) { + $sql .= " AND t.fk_user_assign=" . $user->id; + } +} +$sql .= " GROUP BY t.fk_statut"; + +$result = $db->query($sql); +if ($result) { + while ($objp = $db->fetch_object($result)) { + $found = 0; + if ($objp->fk_statut == 0) { + $tick['unread'] = $objp->nb; + } + if ($objp->fk_statut == 1) { + $tick['read'] = $objp->nb; + } + if ($objp->fk_statut == 3) { + $tick['answered'] = $objp->nb; + } + if ($objp->fk_statut == 4) { + $tick['assigned'] = $objp->nb; + } + if ($objp->fk_statut == 5) { + $tick['inprogress'] = $objp->nb; + } + if ($objp->fk_statut == 6) { + $tick['waiting'] = $objp->nb; + } + if ($objp->fk_statut == 8) { + $tick['closed'] = $objp->nb; + } + if ($objp->fk_statut == 9) { + $tick['deleted'] = $objp->nb; + } + } + + if ((round($tick['unread']) ? 1 : 0) +(round($tick['read']) ? 1 : 0) +(round($tick['answered']) ? 1 : 0) +(round($tick['assigned']) ? 1 : 0) +(round($tick['inprogress']) ? 1 : 0) +(round($tick['waiting']) ? 1 : 0) +(round($tick['closed']) ? 1 : 0) +(round($tick['deleted']) ? 1 : 0) >= 2 + ) { + $dataseries = array(); + $dataseries[] = array('label' => $langs->trans("NotRead"), 'data' => round($tick['unread'])); + $dataseries[] = array('label' => $langs->trans("Read"), 'data' => round($tick['read'])); + $dataseries[] = array('label' => $langs->trans("Answered"), 'data' => round($tick['answered'])); + $dataseries[] = array('label' => $langs->trans("Assigned"), 'data' => round($tick['assigned'])); + $dataseries[] = array('label' => $langs->trans("InProgress"), 'data' => round($tick['inprogress'])); + $dataseries[] = array('label' => $langs->trans("Waiting"), 'data' => round($tick['waiting'])); + $dataseries[] = array('label' => $langs->trans("Closed"), 'data' => round($tick['Closed'])); + $dataseries[] = array('label' => $langs->trans("Deleted"), 'data' => round($tick['Deleted'])); + } +} else { + dol_print_error($db); +} + +$stringtoshow = ''; +$stringtoshow .= ''; +$stringtoshow .= '
    '; // hideobject is to start hidden +$stringtoshow .= '
    '; +$stringtoshow .= ''; +$stringtoshow .= ''; +$stringtoshow .= $langs->trans("Year") . ' '; +$stringtoshow .= ''; +$stringtoshow .= '
    '; +$stringtoshow .= '
    '; + +print ''; +print ''; + +print ''; + +print '
    ' . $langs->trans("Statistics") . ' ' . img_picto('', 'filter.png', 'id="idsubimgDOLUSERCOOKIE_ticketsup_by_status" class="linkobject"') . '
    '; + +// don't display graph if no series +if (count($dataseries) >1) { + $data = array(); + foreach ($dataseries as $key => $value) { + $data[] = array($value['label'], $value['data']); + } + $px1 = new DolGraph(); + $mesg = $px1->isGraphKo(); + if (!$mesg) { + $px1->SetData($data); + unset($data1); + $px1->SetPrecisionY(0); + $i = $startyear; + $legend = array(); + while ($i <= $endyear) { + $legend[] = $i; + $i++; + } + $px1->SetType(array('pie')); + $px1->SetLegend($legend); + $px1->SetMaxValue($px1->GetCeilMaxValue()); + $px1->SetWidth($WIDTH); + $px1->SetHeight($HEIGHT); + $px1->SetYLabel($langs->trans("TicketStatByStatus")); + $px1->SetShading(3); + $px1->SetHorizTickIncrement(1); + $px1->SetPrecisionY(0); + $px1->SetCssPrefix("cssboxes"); + $px1->mode = 'depth'; + //$px1->SetTitle($langs->trans("TicketStatByStatus")); + + $px1->draw($filenamenb, $fileurlnb); + print $px1->show(); + + print $stringtoshow; + } +} +print '
    '; + +// Build graphic number of object +$data = $stats->getNbByMonth($endyear, $startyear); + +print '
    '; + +/* + * Last tickets + */ +$max = 15; +$sql = "SELECT t.rowid, t.ref, t.track_id, t.datec, t.subject, t.type_code, t.category_code, t.severity_code"; +$sql .= ", type.label as type_label, category.label as category_label, severity.label as severity_label"; +$sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup as t"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_type as type ON type.code=t.type_code"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_category as category ON category.code=t.category_code"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticketsup_severity as severity ON severity.code=t.severity_code"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc"; +} + +$sql .= ' WHERE t.entity IN (' . getEntity('ticketsup', 1) . ')'; +$sql .= " AND t.fk_statut=0"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND t.fk_soc = sc.fk_soc AND sc.fk_user = " . $user->id; +} + +if ($user->societe_id > 0) { + $sql .= " AND t.fk_soc='" . $user->societe_id . "'"; +} else { + // Restricted to assigned user only + if ($conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY && !$user->rights->ticketsup->manage) { + $sql .= " AND t.fk_user_assign=" . $user->id; + } +} +$sql .= $db->order("t.datec", "DESC"); +$sql .= $db->plimit($max, 0); + +//print $sql; +$result = $db->query($sql); +if ($result) { + $num = $db->num_rows($result); + + $i = 0; + + $transRecordedType = $langs->trans("LastNewTickets", $max); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if ($num > 0) { + $var = true; + + while ($i < $num) { + $objp = $db->fetch_object($result); + + $var = !$var; + print ""; + // Creation date + print '"; + + // Ref + print '\n"; + + // Subject + print '\n"; + + // Type + print ''; + + // Category + print '"; + + // Severity + print '"; + print "\n"; + $i++; + } + + $db->free(); + } else { + print ''; + } + + print "
    ' . $transRecordedType . '' . $langs->trans('Ref') . '' . $langs->trans('Subject') . '' . $langs->trans('Type') . '' . $langs->trans('Category') . '' . $langs->trans('Severity') . '
    '; + print dol_print_date($db->jdate($objp->datec), 'dayhour'); + print "'; + print '' . $objp->ref . ''; + print "'; + print '' . dol_trunc($objp->subject, 30) . ''; + print "'; + print $objp->type_label; + print ''; + print $objp->category_label; + print "'; + print $objp->severity_label; + print "
    ' . $langs->trans('NoTicketsFound') . '
    "; +} else { + dol_print_error($db); +} + +print '
    '; +print '
    '; + +print ''; + +// End of page +llxFooter(''); +$db->close(); diff --git a/htdocs/ticketsup/list.php b/htdocs/ticketsup/list.php new file mode 100644 index 00000000000..9ac484df26f --- /dev/null +++ b/htdocs/ticketsup/list.php @@ -0,0 +1,728 @@ + + * 2016 Christophe Battarel + * + * 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, see . + */ + +/** + * Tickets List + * + * @package ticketsup + */ + + +// Load Dolibarr environment +$res=0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"); +// Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME +$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; +while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } +if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=include(substr($tmp, 0, ($i+1))."/main.inc.php"); +if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"); +// Try main.inc.php using relative path +if (! $res && file_exists("../main.inc.php")) $res=include("../main.inc.php"); +if (! $res && file_exists("../../main.inc.php")) $res=include("../../main.inc.php"); +if (! $res && file_exists("../../../main.inc.php")) $res=include("../../../main.inc.php"); +if (! $res) die("Include of main fails"); + + +require_once 'class/actions_ticketsup.class.php'; +require_once 'class/html.formticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php'; +if (!empty($conf->projet->enabled)) { + include DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; + include_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php'; +} + +// Load traductions files requiredby by page +// Load traductions files requiredby by page +$langs->loadLangs( + array( + "ticketsup@ticketsup", + "companies", + "other") + ); + + +// Get parameters +$action = GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction','alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files','int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm','alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list +$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'ticketsuplist'; // To manage different context of search +$backtopage = GETPOST('backtopage','alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss','aZ'); // Option for the css output (always '' except when 'print') + +$id = GETPOST('id','int'); + +$msg_id = GETPOST('msg_id', 'int'); +$socid = GETPOST('socid', 'int'); +$projectid = GETPOST('projectid', 'int'); + +$mode = GETPOST('mode', 'alpha'); + +// Load variable for pagination +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST('sortfield','alpha'); +$sortorder = GETPOST('sortorder','alpha'); +$page = GETPOST('page','int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects +$object=new Ticketsup($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->ticketsup->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('ticketsuplist')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('ticketsup'); +$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (! $sortfield) $sortfield="t.".key($object->fields); // Set here default search field. By default 1st field in definition. +if (! $sortorder) $sortorder="ASC"; + +// Initialize array of search criterias +$search_all=trim(GETPOST("search_all",'alpha')); +$search=array(); +foreach($object->fields as $key => $val) +{ + if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha'); +} + + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +foreach($object->fields as $key => $val) +{ + if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; +} + +// Definition of fields for list +$arrayfields=array(); +foreach($object->fields as $key => $val) +{ + // If $val['visible']==0, then we never show the field + if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } +} +$object->fields = dol_sort_array($object->fields, 'position'); +$arrayfields = dol_sort_array($arrayfields, 'position'); + + +// Filters +// $search_soc = GETPOST("search_soc"); +// $search_fk_status = GETPOST("search_fk_status", 'alpha'); +// $search_subject = GETPOST("search_subject"); +// $search_type = GETPOST("search_type", 'alpha'); +// $search_category = GETPOST("search_category", 'alpha'); +// $search_severity = GETPOST("search_severity", 'alpha'); +// $search_project = GETPOST("search_project", 'int'); +// $search_fk_user_create = GETPOST("search_fk_user_create", 'int'); +// $search_fk_user_assign = GETPOST("search_fk_user_assign", 'int'); + +// Security check +if (!$user->rights->ticketsup->read) { + accessforbidden(); +} + +// Store current page url +$url_page_current = dol_buildpath('/ticketsup/list.php', 1); + + + +/* + * Actions + * + * Put here all code to do according to value of "$action" parameter + */ + +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +$parameters=array(); +$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) +{ + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + foreach($object->fields as $key => $val) + { + $search[$key]=''; + } + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass='Ticketsup'; + $objectlabel='Ticketsup'; + $permtoread = $user->rights->ticketsup->read; + $permtodelete = $user->rights->ticketsup->delete; + $uploaddir = $conf->ticketsup->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; +} + + +/*************************************************** + * PAGE + * + * Put here all code to build page + ****************************************************/ +$help_url = 'FR:DocumentationModuleTicket'; +llxHeader('', $langs->trans('TicketList'), $help_url); + +$form = new Form($db); + +$formTicket = new FormTicketsup($db); + +$user_assign = new User($db); +$user_create = new User($db); +$socstatic = new Societe($db); + + +$search_fk_status = GETPOST('search_fk_status', 'alpha'); + + +// Build and execute select +// -------------------------------------------------------------------- +$sql = 'SELECT '; +foreach($object->fields as $key => $val) +{ + $sql.='t.'.$key.', '; +} +// Add fields from extrafields +foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); +// Add fields from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +$sql=preg_replace('/, $/','', $sql); +$sql.= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."ticketsup_extrafields as ef on (t.rowid = ef.fk_object)"; +if ($object->ismultientitymanaged == 1) $sql.= " WHERE t.entity IN (".getEntity('ticketsup').")"; +else $sql.=" WHERE 1 = 1"; +foreach($search as $key => $val) +{ + $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); + if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); +} +if ($search_all) $sql.= natural_search(array_keys($fieldstosearchall), $search_all); + +if (!$user->societe_id && ($mode == "my_assign" || (!$user->admin && $conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY))) { + $sql.= " AND t.fk_user_assign=".$user->id; +} + +if (isset($search_fk_status) && $search_fk_status == 'non_closed') { + //$search['fk_statut'] = '0,1'; // + $sql.= " AND t.fk_statut IN (0, 1, 3, 4, 5, 6)"; +} + +// Add where from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; + +/* If a group by is required + $sql.= " GROUP BY " + foreach($object->fields as $key => $val) + { + $sql.='t.'.$key.', '; + } + // Add fields from extrafields + foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); + // Add where from hooks + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters); // Note that $action and $object may have been modified by hook + $sql.=$hookmanager->resPrint; + */ + +$sql.=$db->order($sortfield,$sortorder); + +// Count total nb of records +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} +// if total resultset is smaller then paging size (filtering), goto and load page 0 +if (($page * $limit) > $nbtotalofrecords) +{ + $page = 0; + $offset = 0; +} +// if total resultset is smaller the limit, no need to do paging. +if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) +{ + $resql = $result; + $num = $nbtotalofrecords; +} +else +{ + $sql.= $db->plimit($limit+1, $offset); + + $resql=$db->query($sql); + if (! $resql) + { + dol_print_error($db); + exit; + } + + $num = $db->num_rows($resql); +} + +// Direct jump if only one record found +if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +{ + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/ticketsup/card.php?id='.$id); + exit; +} + + +// Output page +// -------------------------------------------------------------------- + +if ($socid && !$projectid && $user->rights->societe->lire) { + $socstat = new Societe($db); + $res = $socstat->fetch($socid); + if ($res > 0) { + $head = societe_prepare_head($socstat); + dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); + + dol_banner_tab($socstat, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); + + print '
    '; + + print '
    '; + print ''; + + // Customer code + if ($socstat->client && !empty($socstat->code_client)) { + print ''; + print $htmllogobar; + $htmllogobar = ''; + print ''; + } + print '
    '; + print $langs->trans('CustomerCode') . ''; + print $socstat->code_client; + if ($socstat->check_codeclient() != 0) { + print ' (' . $langs->trans("WrongCustomerCode") . ')'; + } + + print '
    '; + print '
    '; + dol_fiche_end(); + } +} + +if ($projectid) { + $projectstat = new Project($db); + if ($projectstat->fetch($projectid) > 0) { + $projectstat->fetch_thirdparty(); + + // To verify role of users + //$userAccess = $object->restrictedProjectArea($user,'read'); + $userWrite = $projectstat->restrictedProjectArea($user, 'write'); + //$userDelete = $object->restrictedProjectArea($user,'delete'); + //print "userAccess=".$userAccess." userWrite=".$userWrite." userDelete=".$userDelete; + + $head = project_prepare_head($projectstat); + dol_fiche_head($head, 'ticketsup', $langs->trans("Project"), 0, ($projectstat->public ? 'projectpub' : 'project')); + + /* + * Projet synthese pour rappel + */ + print ''; + + $linkback = '' . $langs->trans("BackToList") . ''; + + // Ref + print ''; + + // Label + print ''; + + // Customer + print ""; + print ''; + + // Visibility + print ''; + + // Statut + print ''; + + print "
    ' . $langs->trans('Ref') . ''; + // Define a complementary filter for search of next/prev ref. + if (!$user->rights->projet->all->lire) { + $objectsListId = $projectstat->getProjectsAuthorizedForUser($user, $mine, 0); + $projectstat->next_prev_filter = " rowid in (" . (count($objectsListId) ? join(',', array_keys($objectsListId)) : '0') . ")"; + } + print $form->showrefnav($projectstat, 'ref', $linkback, 1, 'ref', 'ref', ''); + print '
    ' . $langs->trans("Label") . '' . $projectstat->title . '
    " . $langs->trans("ThirdParty") . "'; + if ($projectstat->thirdparty->id > 0) { + print $projectstat->thirdparty->getNomUrl(1); + } else { + print ' '; + } + + print '
    ' . $langs->trans("Visibility") . ''; + if ($projectstat->public) { + print $langs->trans('SharedProject'); + } else { + print $langs->trans('PrivateProject'); + } + + print '
    ' . $langs->trans("Status") . '' . $projectstat->getLibStatut(4) . '
    "; + + print '
    '; + } else { + print "ErrorRecordNotFound"; + } +} + +$arrayofselected=is_array($toselect)?$toselect:array(); + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); +foreach($search as $key => $val) +{ + $param.= '&search_'.$key.'='.urlencode($search[$key]); +} +if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + +// List of mass actions available +$arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), +); +if ($user->rights->ticketsup->delete) $arrayofmassactions['predelete']=$langs->trans("Delete"); +if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); +$massactionbutton=$form->selectMassAction('', $arrayofmassactions); + + +print '
    '; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + + +print_barre_liste($langs->trans('TicketList'), $page, 'list.php', $param, $sortfield, $sortorder, '', $num, $num_total, 'img/ticketsup-32.png', 1); + +if ($mode == 'my_assign') { + print '
    ' . $langs->trans('TicketAssignedToMeInfos') . '
    '; +} +// Add code for pre mass action (confirmation or email presend form) +$topicmail="SendTicketsupRef"; +$modelmail="ticketsup"; +$objecttmp=new Ticketsup($db); +$trackid='xxxx'.$object->id; +include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + +if ($sall) +{ + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); +} + + +if ($search_fk_status == 'non_closed') { + print ''; + $param .= '&search_fk_status=non_closed'; +} else { + print ''; + $param .= '&search_fk_status=-1'; +} + + + +$moreforfilter = ''; +/*$moreforfilter.='
    '; + $moreforfilter.= $langs->trans('MyFilter') . ': '; + $moreforfilter.= '
    ';*/ + +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; +else $moreforfilter = $hookmanager->resPrint; + +if (! empty($moreforfilter)) +{ + print '
    '; + print $moreforfilter; + print '
    '; +} + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print ''."\n"; + + +// Fields title search +// -------------------------------------------------------------------- +print ''; + +foreach($object->fields as $key => $val) +{ + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; + if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) { + if ($key == 'fk_statut') { + print ''; + + } elseif ($key == 'type_code') { + print ''; + } elseif ($key == 'category_code') { + print ''; + } elseif ($key == 'severity_code') { + print ''; + } else { + + print ''; + } + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Action column +print ''; + +print ''."\n"; + + +// Fields title label +// -------------------------------------------------------------------- +print ''; +foreach($object->fields as $key => $val) +{ + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; + if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; +// Hook fields +$parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); +$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],'','','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n"; +print ''."\n"; + + +// Detect if we need a fetch on each output line +$needToFetchEachLine=0; +foreach ($extrafields->attribute_computed as $key => $val) +{ + if (preg_match('/\$object/',$val)) $needToFetchEachLine++; // There is at least one compute field that use $object +} + + + +// Loop on record +// -------------------------------------------------------------------- +$i=0; +$totalarray=array(); +while ($i < min($num, $limit)) +{ + $obj = $db->fetch_object($resql); + if (empty($obj)) break; // Should not happen + + // Store properties in $object + $object->id = $obj->rowid; + foreach($object->fields as $key => $val) + { + if (isset($obj->$key)) $object->$key = $obj->$key; + } + + // Show here line of result + print ''; + foreach($object->fields as $key => $val) + { + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; + if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) + { + print ''; + print $object->showOutputField($val, $key, $obj->$key, ''); + print ''; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + $totalarray['val']['t.'.$key] += $obj->$key; + } + } + } + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + + print ''; + + $i++; +} + +// Show total line +if (isset($totalarray['pos'])) +{ + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if (! empty($totalarray['pos'][$i])) print ''; + else + { + if ($i == 1) + { + if ($num < $limit) print ''; + else print ''; + } + else print ''; + } + } + print ''; +} + +// If no record found +if ($num == 0) +{ + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print ''; +} + + +$db->free($resql); + +$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print '
    '; + $object->printSelectStatus(dol_escape_htmltag($search[$key])); + print ''; + $formTicket->selectTypesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1); + print ''; + $formTicket->selectCategoriesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1); + print ''; + $formTicket->selectSeveritiesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1); + print ''; +$searchpicto=$form->showFilterButtons(); +print $searchpicto; +print '
    '; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
    '.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''.$langs->trans("Totalforthispage").'
    '.$langs->trans("NoRecordFound").'
    '."\n"; +print '
    '."\n"; + +print '
    '."\n"; + + +print ''; + + +if (in_array('builddoc',$arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) +{ + $hidegeneratedfilelistifempty=1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + + require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); + + $filedir=$diroutputmassaction; + $genallowed=$user->rights->ticketsup->read; + $delallowed=$user->rights->ticketsup->create; + + print $formfile->showdocuments('massfilesarea_ticketsup','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'','','',null,$hidegeneratedfilelistifempty); +} + +// End of page +llxFooter(''); +$db->close(); diff --git a/htdocs/ticketsup/new.php b/htdocs/ticketsup/new.php new file mode 100644 index 00000000000..4728004e14f --- /dev/null +++ b/htdocs/ticketsup/new.php @@ -0,0 +1,106 @@ + + * 2016 Christophe Battarel + * + * 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, see . + */ + +/** + * Display form to add new ticket + * + * @package ticketsup + */ + +$res = 0; +if (file_exists("../main.inc.php")) { + $res = include "../main.inc.php"; // From htdocs directory +} elseif (!$res && file_exists("../../main.inc.php")) { + $res = include "../../main.inc.php"; // From "custom" directory +} else { + die("Include of main fails"); +} + +require_once 'class/actions_ticketsup.class.php'; +require_once 'class/html.formticketsup.class.php'; +require_once 'lib/ticketsup.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; + +// Load traductions files requiredby by page +$langs->load("companies"); +$langs->load("other"); +$langs->load("ticketsup@ticketsup"); + +// Get parameters +$id = GETPOST('id', 'int'); +$socid = GETPOST('socid', 'int'); +$contactid = GETPOST('contactid', 'int'); +$msg_id = GETPOST('msg_id', 'int'); +$notNotifyTiers = GETPOST("not_notify_tiers_at_create", 'alpha'); +$notnotifytiersatcreate = !empty($notNotifyTiers); + +$action = GETPOST('action', 'alpha', 3); + +// Protection if external user +if (!$user->rights->ticketsup->read || !$user->rights->ticketsup->create) { + accessforbidden(); +} + +$object = new ActionsTicketsup($db); + +$object->doActions($action); + +/*************************************************** + * PAGE + * + * Put here all code to build page + ****************************************************/ +$help_url = 'FR:DocumentationModuleTicket'; +$page_title = $object->getTitle($action); +llxHeader('', $page_title, $help_url); + +$form = new Form($db); + +if ($action == 'create_ticket') { + $formticket = new FormTicketsup($db); + + print load_fiche_titre($langs->trans('NewTicket'), '', 'img/ticketsup-32.png', 1); + + $formticket->withfromsocid = $socid ? $socid : $user->societe_id; + $formticket->withfromcontactid = $contactid ? $contactid : ''; + $formticket->withtitletopic = 1; + $formticket->withnotnotifytiersatcreate = $notnotifytiersatcreate; + $formticket->withusercreate = 1; + $formticket->withref = 1; + $formticket->fk_user_create = $user->id; + $formticket->withfile = 2; + $formticket->withextrafields = 1; + $formticket->param = array('origin' => GETPOST('origin'), 'originid' => GETPOST('originid')); + if (empty($defaultref)) { + $defaultref = ''; + } + + $formticket->showForm(); +} + +/*************************************************** + * LINKED OBJECT BLOCK + * + * Put here code to view linked object + ****************************************************/ +//$somethingshown=$object->showLinkedObjectBlock(); + +// End of page +llxFooter(''); +$db->close(); diff --git a/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php b/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php new file mode 100644 index 00000000000..f834ff10cb4 --- /dev/null +++ b/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php @@ -0,0 +1,61 @@ + + * Copyright (C) 2013 Jean-François FERRY + * + * 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. + * + */ +?> + + + +load('ticketsup@ticketsup'); +$linkedObjectBlock = $GLOBALS['linkedObjectBlock']; +echo '
    '; +print_titre($langs->trans('RelatedTickets')); +?> + + + + + + + + +> + + + socid = $object->fk_soc; + $object->fetch_thirdparty(); + ?> + + + + +
    trans("Subject"); ?>trans("DateCreation"); ?>trans("Customer"); ?>trans("Status"); ?>
    + subject) ? ' '.$object->subject : ''); ?> + + datec, 'day'); ?>thirdparty->getNomUrl(1); ?>getLibstatut(2); ?>
    + + \ No newline at end of file diff --git a/test/phpunit/TicketsupTest.php b/test/phpunit/TicketsupTest.php new file mode 100644 index 00000000000..d45c72b14d5 --- /dev/null +++ b/test/phpunit/TicketsupTest.php @@ -0,0 +1,423 @@ + + * +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +* or see http://www.gnu.org/ +*/ + +/** + * \file test/unit/TicketsupTest.php +* \ingroup test +* \brief PHPUnit test +* \remarks To run this script as CLI: phpunit filename.php +*/ +namespace test\unit; + +global $conf,$user,$langs,$db; +//define('TEST_DB_FORCE_TYPE','mysql'); // This is to force using mysql driver +//require_once 'PHPUnit/Autoload.php'; +$res = false; +if (file_exists(dirname(__FILE__).'/../../../../htdocs/master.inc.php')) { + $res = require_once dirname(__FILE__).'/../../../../htdocs/master.inc.php'; +} elseif (file_exists(dirname(__FILE__).'/../../../../../htdocs/master.inc.php')) { + $res = require_once dirname(__FILE__).'/../../../../../htdocs/master.inc.php'; +} else { + die('Include of mains fails'); +} + + +require_once dirname(__FILE__).'/../../class/ticketsup.class.php'; + + +if (empty($user->id)) { + print "Load permissions for admin user nb 1\n"; + $user->fetch(1); + $user->getrights(); +} + +$conf->global->MAIN_DISABLE_ALL_MAILS=1; + + +/** + * Class for PHPUnit tests + * + * @backupGlobals disabled + * @backupStaticAttributes enabled + * @remarks backupGlobals must be disabled to have db,conf,user and lang not erased. + */ +class TicketsupTest extends \PHPUnit_Framework_TestCase +{ + protected $savconf; + protected $savuser; + protected $savlangs; + protected $savdb; + + /** + * Constructor + * We save global variables into local variables + * + * @return ContratTest + */ + public function __construct() + { + //$this->sharedFixture + global $conf,$user,$langs,$db; + $this->savconf=$conf; + $this->savuser=$user; + $this->savlangs=$langs; + $this->savdb=$db; + + print __METHOD__." db->type=".$db->type." user->id=".$user->id; + //print " - db ".$db->db; + print "\n"; + } + + // Static methods + public static function setUpBeforeClass() + { + global $conf,$user,$langs,$db; + $db->begin(); // This is to have all actions inside a transaction even if test launched without suite. + + print __METHOD__."\n"; + } + + // tear down after class + public static function tearDownAfterClass() + { + global $conf,$user,$langs,$db; + $db->rollback(); + + print __METHOD__."\n"; + } + + /** + * Init phpunit tests + * + * @return void + */ + protected function setUp() + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + print __METHOD__."\n"; + } + /** + * End phpunit tests + * + * @return void + */ + protected function tearDown() + { + print __METHOD__."\n"; + } + + /** + * testTicketsupCreate + * + * @return int + */ + public function testTicketsupCreate() + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + // Try to create one with bad values + $localobject=new \Ticketsup($this->savdb); + $localobject->initAsSpecimen(); + $localobject->fk_statut = '\'1=1'; + $result=$localobject->create($user); + + print __METHOD__." result=".$result."\n"; + $this->assertEquals($result, -1); + + // Try to create one with correct values + $localobject=new \Ticketsup($this->savdb); + $localobject->initAsSpecimen(); + $result=$localobject->create($user); + + print __METHOD__." result=".$result."\n"; + $this->assertLessThan($result, 0); + + + return $result; + } + + /** + * testTicketsupFetch + * + * @param int $id Id of ticket + * @return int + * + * @depends testTicketsupCreate + * The depends says test is run only if previous is ok + */ + public function testTicketsupFetch($id) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $localobject=new \Ticketsup($this->savdb); + $result=$localobject->fetch($id); + + print __METHOD__." id=".$id." result=".$result."\n"; + $this->assertLessThan($result, 0); + + return $localobject; + } + + /** + * testTicketsupmarkAsRead + * + * @param Ticketsup $localobject Ticket + * @return int + * + * @depends testTicketsupFetch + * The depends says test is run only if previous is ok + */ + public function testTicketsupmarkAsRead($localobject) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $result=$localobject->markAsRead($user); + print __METHOD__." id=".$localobject->id." result=".$result."\n"; + + $this->assertLessThan($result, 0); + return $localobject; + } + + /** + * testTicketsupsetProject + * + * @param Ticketsup $localobject Ticket + * @return int + * + * @depends testTicketsupFetch + * The depends says test is run only if previous is ok + */ + public function testTicketsupsetProject($localobject) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $project_id = 1; + + $result=$localobject->setProject($project_id); + print __METHOD__." id=".$localobject->id." result=".$result."\n"; + + $this->assertLessThan($result, 0); + return $localobject; + } + + /** + * testTicketsupsetContract + * + * @param Ticketsup $localobject Ticket + * @return int + * + * @depends testTicketsupFetch + * The depends says test is run only if previous is ok + */ + public function testTicketsupsetContract($localobject) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $contract_id = 1; + + $result=$localobject->setContract($contract_id); + print __METHOD__." id=".$localobject->id." result=".$result."\n"; + + $this->assertLessThan($result, 0); + return $localobject; + } + + /** + * testTicketsupsetProgression + * + * @param Ticketsup $localobject Ticket + * @return int + * + * @depends testTicketsupFetch + * The depends says test is run only if previous is ok + */ + public function testTicketsupsetProgression($localobject) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $percent = 80; + + $result=$localobject->setProgression($percent); + print __METHOD__." id=".$localobject->id." result=".$result."\n"; + + $this->assertLessThan($result, 0); + return $localobject; + } + + /** + * testTicketsupassignUser + * + * @param Ticketsup $localobject Ticket + * @return int + * + * @depends testTicketsupFetch + * The depends says test is run only if previous is ok + */ + public function testTicketsupassignUser($localobject) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $user_id_to_assign = 1; + + $result=$localobject->assignUser($user, $user_id_to_assign); + ; + print __METHOD__." id=".$localobject->id." result=".$result."\n"; + + $this->assertLessThan($result, 0); + return $localobject; + } + + /** + * testTicketsupassignUserOther + * + * @param Ticketsup $localobject Ticket + * @return int + * + * @depends testTicketsupFetch + * The depends says test is run only if previous is ok + */ + public function testTicketsupassignUserOther($localobject) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $user_id_to_assign = 2; + + $result=$localobject->assignUser($user, $user_id_to_assign); + ; + print __METHOD__." id=".$localobject->id." result=".$result."\n"; + + $this->assertLessThan($result, 0); + return $localobject; + } + + /** + * testTicketsupcreateTicketLog + * + * @param Ticketsup $localobject Ticket + * @return int + * + * @depends testTicketsupFetch + * The depends says test is run only if previous is ok + */ + public function testTicketsupcreateTicketLog($localobject) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + + $message = 'Test ticket log'; + $noemail = 1; + $result=$localobject->createTicketLog($user, $message, $noemail); + print __METHOD__." id=".$localobject->id." result=".$result."\n"; + + $this->assertLessThan($result, 0); + return $localobject; + } + + /** + * testTicketsupclose + * + * @param Ticketsup $localobject Ticket + * @return int + * + * @depends testTicketsupFetch + * The depends says test is run only if previous is ok + */ + public function testTicketsupclose($localobject) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $result=$localobject->close(); + print __METHOD__." id=".$localobject->id." result=".$result."\n"; + + $this->assertLessThan($result, 0); + return $localobject->id; + } + + + /** + * testTicketsupDelete + * + * @param int $id Id of ticket + * @return int + * + * @depends testTicketsupclose + * The depends says test is run only if previous is ok + */ + public function testTicketsupDelete($id) + { + + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + + $localobject=new \Ticketsup($this->savdb); + $result=$localobject->fetch($id); + $result=$localobject->delete($user); + + print __METHOD__." id=".$id." result=".$result."\n"; + $this->assertLessThan($result, 0); + return $result; + } +} From 138c842959b979aed67d19d9933ae9d5ca6248af Mon Sep 17 00:00:00 2001 From: jfefe Date: Sat, 10 Mar 2018 23:10:55 +0100 Subject: [PATCH 182/413] Correct bad paths --- htdocs/ticketsup/card.php | 4 ++-- htdocs/ticketsup/class/api_ticketsups.class.php | 2 +- htdocs/ticketsup/contacts.php | 2 +- htdocs/ticketsup/document.php | 4 ++-- htdocs/ticketsup/history.php | 4 ++-- htdocs/ticketsup/list.php | 4 ++-- htdocs/ticketsup/new.php | 4 ++-- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/htdocs/ticketsup/card.php b/htdocs/ticketsup/card.php index cd638fb3eff..79cc87a52d8 100644 --- a/htdocs/ticketsup/card.php +++ b/htdocs/ticketsup/card.php @@ -34,8 +34,8 @@ if (file_exists("../main.inc.php")) { } require_once 'class/actions_ticketsup.class.php'; -require_once 'class/html.formticketsup.class.php'; -require_once 'lib/ticketsup.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; diff --git a/htdocs/ticketsup/class/api_ticketsups.class.php b/htdocs/ticketsup/class/api_ticketsups.class.php index 019ecc05934..7f69d3b27a4 100644 --- a/htdocs/ticketsup/class/api_ticketsups.class.php +++ b/htdocs/ticketsup/class/api_ticketsups.class.php @@ -18,7 +18,7 @@ use Luracast\Restler\RestException; require 'ticketsup.class.php'; -dol_include_once('/ticketsup/lib/ticketsup.lib.php'); +require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; /** * API class for ticketsup object diff --git a/htdocs/ticketsup/contacts.php b/htdocs/ticketsup/contacts.php index 8879b01d237..39f6976e795 100644 --- a/htdocs/ticketsup/contacts.php +++ b/htdocs/ticketsup/contacts.php @@ -33,7 +33,7 @@ if (file_exists("../main.inc.php")) { } require_once 'class/ticketsup.class.php'; -dol_include_once('/ticketsup/lib/ticketsup.lib.php'); +require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php"; diff --git a/htdocs/ticketsup/document.php b/htdocs/ticketsup/document.php index 4139a98e17e..9ffdcd35048 100644 --- a/htdocs/ticketsup/document.php +++ b/htdocs/ticketsup/document.php @@ -35,8 +35,8 @@ if (file_exists("../main.inc.php")) { die("Include of main fails"); } -dol_include_once('/ticketsup/lib/ticketsup.lib.php'); -dol_include_once('/ticketsup/class/ticketsup.class.php'); +require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; +require_once 'class/ticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php"; diff --git a/htdocs/ticketsup/history.php b/htdocs/ticketsup/history.php index 089f31b942c..43e35244e0c 100644 --- a/htdocs/ticketsup/history.php +++ b/htdocs/ticketsup/history.php @@ -31,8 +31,8 @@ if (file_exists("../main.inc.php")) { die("Include of main fails"); } require_once 'class/actions_ticketsup.class.php'; -require_once 'class/html.formticketsup.class.php'; -require_once 'lib/ticketsup.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; require_once DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php"; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; diff --git a/htdocs/ticketsup/list.php b/htdocs/ticketsup/list.php index 9ac484df26f..bb4aa27b0f2 100644 --- a/htdocs/ticketsup/list.php +++ b/htdocs/ticketsup/list.php @@ -41,7 +41,7 @@ if (! $res) die("Include of main fails"); require_once 'class/actions_ticketsup.class.php'; -require_once 'class/html.formticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php'; @@ -55,7 +55,7 @@ if (!empty($conf->projet->enabled)) { // Load traductions files requiredby by page $langs->loadLangs( array( - "ticketsup@ticketsup", + "ticketsup", "companies", "other") ); diff --git a/htdocs/ticketsup/new.php b/htdocs/ticketsup/new.php index 4728004e14f..590c4b5db46 100644 --- a/htdocs/ticketsup/new.php +++ b/htdocs/ticketsup/new.php @@ -33,8 +33,8 @@ if (file_exists("../main.inc.php")) { } require_once 'class/actions_ticketsup.class.php'; -require_once 'class/html.formticketsup.class.php'; -require_once 'lib/ticketsup.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; // Load traductions files requiredby by page From 8217587b5e53eddd4098224436d7457527c2ce25 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 10:34:21 +0100 Subject: [PATCH 183/413] Dolibarize new module --- htdocs/ticketsup/card.php | 15 +++-------- .../class/actions_ticketsup.class.php | 5 ++-- htdocs/ticketsup/class/ticketsup.class.php | 6 ++--- .../ticketsup/class/ticketsuplogs.class.php | 6 ++--- .../ticketsup/class/ticketsupstats.class.php | 4 +-- htdocs/ticketsup/class/utils_diff.class.php | 26 +++++++++---------- htdocs/ticketsup/contacts.php | 18 +++++-------- htdocs/ticketsup/document.php | 15 +++-------- htdocs/ticketsup/history.php | 16 +++--------- htdocs/ticketsup/index.php | 17 +++--------- htdocs/ticketsup/list.php | 25 +++--------------- htdocs/ticketsup/new.php | 19 ++++---------- .../ticketsup/tpl/linkedobjectblock.tpl.php | 4 +-- 13 files changed, 52 insertions(+), 124 deletions(-) diff --git a/htdocs/ticketsup/card.php b/htdocs/ticketsup/card.php index 79cc87a52d8..5d005063b8b 100644 --- a/htdocs/ticketsup/card.php +++ b/htdocs/ticketsup/card.php @@ -1,7 +1,6 @@ - * 2016 Christophe Battarel +/* Copyright (C) - 2013-2016 Jean-François FERRY + * Copyright (C) 2016 Christophe Battarel * * 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 @@ -23,15 +22,7 @@ * @package ticketsup */ -// Change this following line to use the correct relative path (../, ../../, etc) -$res = 0; -if (file_exists("../main.inc.php")) { - $res = include "../main.inc.php"; // From htdocs directory -} elseif (!$res && file_exists("../../main.inc.php")) { - $res = include "../../main.inc.php"; // From "custom" directory -} else { - die("Include of main fails"); -} +require '../main.inc.php'; require_once 'class/actions_ticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticketsup.class.php'; diff --git a/htdocs/ticketsup/class/actions_ticketsup.class.php b/htdocs/ticketsup/class/actions_ticketsup.class.php index d72e8388905..3c1c2febdae 100644 --- a/htdocs/ticketsup/class/actions_ticketsup.class.php +++ b/htdocs/ticketsup/class/actions_ticketsup.class.php @@ -1,6 +1,6 @@ - * 2016 Christophe Battarel +/* Copyright (C) 2013-2015 Jean-François FERRY + * Copyright (C) 2016 Christophe Battarel * * 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 @@ -24,7 +24,6 @@ */ require_once "ticketsup.class.php"; - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php'; diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index 289a865b4e8..03179cc36d9 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -1,7 +1,6 @@ - * 2016 Christophe Battarel +/* Copyright (C) 2013-2018 Jean-François Ferry + * Copyright (C) 2016 Christophe Battarel * * 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 @@ -29,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT . '/fichinter/class/fichinter.class.php'; //require_once(DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); //require_once(DOL_DOCUMENT_ROOT."/product/class/product.class.php"); + /** * Put here description of your class */ diff --git a/htdocs/ticketsup/class/ticketsuplogs.class.php b/htdocs/ticketsup/class/ticketsuplogs.class.php index 30d1f49f21c..e8f30d5db9f 100644 --- a/htdocs/ticketsup/class/ticketsuplogs.class.php +++ b/htdocs/ticketsup/class/ticketsuplogs.class.php @@ -1,6 +1,5 @@ +/* Copyright (C) - 2013-2016 Jean-François FERRY * * 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 @@ -27,8 +26,9 @@ require_once DOL_DOCUMENT_ROOT . "/core/class/commonobject.class.php"; //require_once(DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); //require_once(DOL_DOCUMENT_ROOT."/product/class/product.class.php"); + /** - * Put here description of your class + * Class of log for ticketsup */ class Ticketsuplogs// extends CommonObject { diff --git a/htdocs/ticketsup/class/ticketsupstats.class.php b/htdocs/ticketsup/class/ticketsupstats.class.php index 8af852eeb01..3c299b911af 100644 --- a/htdocs/ticketsup/class/ticketsupstats.class.php +++ b/htdocs/ticketsup/class/ticketsupstats.class.php @@ -23,9 +23,9 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php'; require_once 'ticketsup.class.php'; + /** - * \class DeplacementStats - * \brief Classe permettant la gestion des stats des deplacements et notes de frais + * Classe permettant la gestion des stats des deplacements et notes de frais */ class TicketsupStats extends Stats { diff --git a/htdocs/ticketsup/class/utils_diff.class.php b/htdocs/ticketsup/class/utils_diff.class.php index f09be232148..4f0d276b192 100644 --- a/htdocs/ticketsup/class/utils_diff.class.php +++ b/htdocs/ticketsup/class/utils_diff.class.php @@ -1,22 +1,20 @@ + * + * A class containing a diff implementation + * + * Created by Stephen Morley - http://stephenmorley.org/ - and released under the + * terms of the CC0 1.0 Universal legal code: + * + * http://creativecommons.org/publicdomain/zero/1.0/legalcode */ -// A class containing functions for computing diffs and formatting the output. + +/** + * A class containing functions for computing diffs and formatting the output. + */ class Diff { - // define the constants const UNMODIFIED = 0; const DELETED = 1; diff --git a/htdocs/ticketsup/contacts.php b/htdocs/ticketsup/contacts.php index 39f6976e795..0a04c8ce509 100644 --- a/htdocs/ticketsup/contacts.php +++ b/htdocs/ticketsup/contacts.php @@ -1,7 +1,7 @@ - * Copyright (C) 2011 Regis Houssin - * 2016 Christophe Battarel +/* Copyright (C) 2011-2016 Jean-François Ferry + * Copyright (C) 2011 Regis Houssin + * Copyright (C) 2016 Christophe Battarel * * 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 @@ -23,16 +23,10 @@ * \ingroup ticketsup * \brief Contacts des tickets */ -$res = 0; -if (file_exists("../main.inc.php")) { - $res = include "../main.inc.php"; // From htdocs directory -} elseif (!$res && file_exists("../../main.inc.php")) { - $res = include "../../main.inc.php"; // From "custom" directory -} else { - die("Include of main fails"); -} -require_once 'class/ticketsup.class.php'; +require '../main.inc.php'; + +require_once DOL_DOCUMENT_ROOT . '/ticketsup/class/ticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; diff --git a/htdocs/ticketsup/document.php b/htdocs/ticketsup/document.php index 9ffdcd35048..ee1fc47f5d3 100644 --- a/htdocs/ticketsup/document.php +++ b/htdocs/ticketsup/document.php @@ -1,6 +1,5 @@ +/* Copyright (C) 2002-2007 Rodolphe Quiedeville * Copyright (C) 2004-2010 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2010 Juanjo Menent @@ -26,17 +25,9 @@ * \brief files linked to a ticket */ -$res = 0; -if (file_exists("../main.inc.php")) { - $res = include "../main.inc.php"; // From htdocs directory -} elseif (!$res && file_exists("../../main.inc.php")) { - $res = include "../../main.inc.php"; // From "custom" directory -} else { - die("Include of main fails"); -} - +require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; -require_once 'class/ticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT . '/ticketsup/class/ticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php"; diff --git a/htdocs/ticketsup/history.php b/htdocs/ticketsup/history.php index 43e35244e0c..fe0194e759c 100644 --- a/htdocs/ticketsup/history.php +++ b/htdocs/ticketsup/history.php @@ -1,6 +1,5 @@ +/* Copyright (C) - 2013-2016 Jean-François FERRY * * 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 @@ -17,20 +16,13 @@ */ /** - * History of ticket + * History of ticket * * @package ticketsup */ -$res = 0; -if (file_exists("../main.inc.php")) { - $res = include "../main.inc.php"; // From htdocs directory -} elseif (!$res && file_exists("../../main.inc.php")) { - $res = include "../../main.inc.php"; // From "custom" directory -} else { - die("Include of main fails"); -} -require_once 'class/actions_ticketsup.class.php'; +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT . '/ticketsup/class/actions_ticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; require_once DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php"; diff --git a/htdocs/ticketsup/index.php b/htdocs/ticketsup/index.php index 6b44d930e07..74a6000c2ee 100644 --- a/htdocs/ticketsup/index.php +++ b/htdocs/ticketsup/index.php @@ -1,6 +1,5 @@ +/* Copyright (C) - 2013-2016 Jean-François FERRY * * 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 @@ -22,17 +21,9 @@ * @package ticketsup */ -$res = 0; -if (file_exists("../main.inc.php")) { - $res = include "../main.inc.php"; // From htdocs directory -} elseif (!$res && file_exists("../../main.inc.php")) { - $res = include "../../main.inc.php"; // From "custom" directory -} else { - die("Include of main fails"); -} - -require_once 'class/actions_ticketsup.class.php'; -require_once 'class/ticketsupstats.class.php'; +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT . '/ticketsup/class/actions_ticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT . '/ticketsup/class/ticketsupstats.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/dolgraph.class.php'; // Load traductions files requiredby by page diff --git a/htdocs/ticketsup/list.php b/htdocs/ticketsup/list.php index bb4aa27b0f2..5661a78de71 100644 --- a/htdocs/ticketsup/list.php +++ b/htdocs/ticketsup/list.php @@ -1,6 +1,5 @@ +/* Copyright (C) - 2013-2018 Jean-François FERRY * 2016 Christophe Battarel * * This program is free software; you can redistribute it and/or modify @@ -23,30 +22,14 @@ * @package ticketsup */ - -// Load Dolibarr environment -$res=0; -// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"); -// Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=include(substr($tmp, 0, ($i+1))."/main.inc.php"); -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"); -// Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=include("../main.inc.php"); -if (! $res && file_exists("../../main.inc.php")) $res=include("../../main.inc.php"); -if (! $res && file_exists("../../../main.inc.php")) $res=include("../../../main.inc.php"); -if (! $res) die("Include of main fails"); - - -require_once 'class/actions_ticketsup.class.php'; +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT . '/ticketsup/class/actions_ticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php'; if (!empty($conf->projet->enabled)) { - include DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; include_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; include_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php'; } diff --git a/htdocs/ticketsup/new.php b/htdocs/ticketsup/new.php index 590c4b5db46..3fb4294f150 100644 --- a/htdocs/ticketsup/new.php +++ b/htdocs/ticketsup/new.php @@ -1,6 +1,5 @@ +/* Copyright (C) - 2013-2016 Jean-François FERRY * 2016 Christophe Battarel * * This program is free software; you can redistribute it and/or modify @@ -18,21 +17,13 @@ */ /** - * Display form to add new ticket + * Display form to add new ticket * - * @package ticketsup + * @package ticketsup */ -$res = 0; -if (file_exists("../main.inc.php")) { - $res = include "../main.inc.php"; // From htdocs directory -} elseif (!$res && file_exists("../../main.inc.php")) { - $res = include "../../main.inc.php"; // From "custom" directory -} else { - die("Include of main fails"); -} - -require_once 'class/actions_ticketsup.class.php'; +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT . 'class/actions_ticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; diff --git a/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php b/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php index f834ff10cb4..e071881b506 100644 --- a/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php +++ b/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php @@ -37,11 +37,9 @@ print_titre($langs->trans('RelatedTickets')); trans("Status"); ?> -> + subject) ? ' '.$object->subject : ''); ?> From bfaffe6692edb2a80e07bc333462c76be9ba0c41 Mon Sep 17 00:00:00 2001 From: BENKE Charlene Date: Sun, 11 Mar 2018 10:51:05 +0100 Subject: [PATCH 184/413] Changes Done --- htdocs/core/modules/DolibarrModules.class.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/core/modules/DolibarrModules.class.php b/htdocs/core/modules/DolibarrModules.class.php index 5eb049f8323..c1c570e8269 100644 --- a/htdocs/core/modules/DolibarrModules.class.php +++ b/htdocs/core/modules/DolibarrModules.class.php @@ -1049,7 +1049,7 @@ class DolibarrModules // Can not be abstract, because we need to insta { if (preg_match('/\.sql$/i',$file) && ! preg_match('/\.key\.sql$/i',$file) && substr($file,0,4) == 'llx_' && substr($file,0,4) != 'data') { - $result=run_sql($dir.$file, $conf->global->INSTALL_DISPLAY_SQL_LOG, '', 1); + $result=run_sql($dir.$file, empty($conf->global->INSTALL_DISPLAY_SQL_LOG)?0:1, '', 1); if ($result <= 0) $error++; } } @@ -1067,7 +1067,7 @@ class DolibarrModules // Can not be abstract, because we need to insta { if (preg_match('/\.key\.sql$/i',$file) && substr($file,0,4) == 'llx_' && substr($file,0,4) != 'data') { - $result=run_sql($dir.$file, $conf->global->INSTALL_DISPLAY_SQL_LOG, '', 1); + $result=run_sql($dir.$file, empty($conf->global->INSTALL_DISPLAY_SQL_LOG)?0:1, '', 1); if ($result <= 0) $error++; } } @@ -1085,7 +1085,7 @@ class DolibarrModules // Can not be abstract, because we need to insta { if (preg_match('/\.sql$/i',$file) && ! preg_match('/\.key\.sql$/i',$file) && substr($file,0,4) == 'data') { - $result=run_sql($dir.$file, $conf->global->INSTALL_DISPLAY_SQL_LOG, '', 1); + $result=run_sql($dir.$file, empty($conf->global->INSTALL_DISPLAY_SQL_LOG)?0:1, '', 1); if ($result <= 0) $error++; } } @@ -1103,7 +1103,7 @@ class DolibarrModules // Can not be abstract, because we need to insta { if (preg_match('/\.sql$/i',$file) && ! preg_match('/\.key\.sql$/i',$file) && substr($file,0,6) == 'update') { - $result=run_sql($dir.$file, $conf->global->INSTALL_DISPLAY_SQL_LOG, '', 1); + $result=run_sql($dir.$file, empty($conf->global->INSTALL_DISPLAY_SQL_LOG)?0:1, '', 1); if ($result <= 0) $error++; } } From e14d2f08b82d8e2f0048b967b617a2a7ac06c5b0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 11:12:38 +0100 Subject: [PATCH 185/413] Dolibarize --- .../core/class/html.formticketsup.class.php | 15 ++-- htdocs/core/lib/ticketsup.lib.php | 17 ++-- .../ticketsup/mod_ticketsup_simple.php | 11 --- .../ticketsup/mod_ticketsup_universal.php | 11 --- .../class/actions_ticketsup.class.php | 88 ++++++++++++------- .../ticketsup/class/api_ticketsups.class.php | 2 +- htdocs/ticketsup/class/ticketsup.class.php | 9 +- .../ticketsup/class/ticketsuplogs.class.php | 18 ++-- htdocs/ticketsup/class/utils_diff.class.php | 30 ++----- .../ticketsup/tpl/linkedobjectblock.tpl.php | 1 - 10 files changed, 93 insertions(+), 109 deletions(-) diff --git a/htdocs/core/class/html.formticketsup.class.php b/htdocs/core/class/html.formticketsup.class.php index 6beae7438e2..b7834923b26 100644 --- a/htdocs/core/class/html.formticketsup.class.php +++ b/htdocs/core/class/html.formticketsup.class.php @@ -1,6 +1,6 @@ - * 2016 Christophe Battarel +/* Copyright (C) - 2013-2015 Jean-François FERRY + * Copyright (C) 2016 Christophe Battarel * * 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 @@ -31,8 +31,8 @@ if (!class_exists('FormCompany')) { /** * Classe permettant la generation du formulaire d'un nouveau ticket * - * @package ticketsup - + * \ingroup ticketsup + * * \remarks Utilisation: $formticketsup = new FormTicketsup($db) * \remarks $formticketsup->proprietes=1 ou chaine ou tableau de valeurs * \remarks $formticketsup->show_form() affiche le formulaire @@ -74,7 +74,6 @@ class FormTicketsup public $withcancel; /** - * * @var array $substit Substitutions */ public $substit = array(); @@ -414,9 +413,9 @@ class FormTicketsup * @param string $filtertype To filter on field type in llx_c_ticketsup_type (array('code'=>xx,'label'=>zz)) * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code * @param int $empty 1=peut etre vide, 0 sinon - * @param int $noadmininfo 0=Add admin info, 1=Disable admin info + * @param int $noadmininfo 0=Add admin info, 1=Disable admin info * @param int $maxlength Max length of label - * @return void + * @return void */ public function selectTypesTickets($selected = '', $htmlname = 'tickettype', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0) { @@ -432,7 +431,7 @@ class FormTicketsup $filterarray = explode(',', $filtertype); } - $ticketstat->load_cache_types_tickets(); + $ticketstat->loadCacheTypesTickets(); print ''; if ($empty) { @@ -624,7 +627,7 @@ class FormTicketsup $filterarray = explode(',', $filtertype); } - $ticketstat->load_cache_severities_tickets(); + $ticketstat->loadCacheSeveritiesTickets(); print ''; //$placeholder=' placeholder="00:00"'; - $placeholder=''; //$tableCell.='+'; } $tableCell.='\n"; + $total_plannedworkload=0; + $total_declaredprogressworkload=0; while ($i < $num) { $objp = $db->fetch_object($resql); From df185de6aea7f485a3e641652ce4cc1c5597a98c Mon Sep 17 00:00:00 2001 From: Maxime Kohlhaas Date: Sun, 11 Mar 2018 15:09:25 +0100 Subject: [PATCH 190/413] Fix mail send --- htdocs/core/class/html.formmail.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index 8ea76bb4fcb..55345d68cc7 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -859,7 +859,7 @@ class FormMail extends Form if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1') { if ($arraydefaultmessage && $arraydefaultmessage->content) { - $defaultmessage = $arraydefaultmessage['content']; + $defaultmessage = $arraydefaultmessage->content; } elseif (! is_numeric($this->withbody)) { $defaultmessage = $this->withbody; } From e393621f2f861c8a5468b0dd4efcd3eeb3e1b6e1 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 16:00:18 +0100 Subject: [PATCH 191/413] Dolibarrize --- htdocs/ticketsup/card.php | 2 +- .../class/actions_ticketsup.class.php | 4 +- htdocs/ticketsup/class/ticketsup.class.php | 43 ++++++++++--------- htdocs/ticketsup/contacts.php | 2 +- htdocs/ticketsup/document.php | 2 +- htdocs/ticketsup/history.php | 2 +- 6 files changed, 29 insertions(+), 26 deletions(-) diff --git a/htdocs/ticketsup/card.php b/htdocs/ticketsup/card.php index 5d005063b8b..cdf026a9a0a 100644 --- a/htdocs/ticketsup/card.php +++ b/htdocs/ticketsup/card.php @@ -224,7 +224,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti $object->dao->label .= $object->dao->origin_email . ' (' . $langs->trans("TicketEmailOriginIssuer") . ')'; } $linkback = '' . $langs->trans("BackToList") . ' '; - $object->dao->ticketsup_banner_tab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + $object->dao->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); print '
    '; print '
    '; diff --git a/htdocs/ticketsup/class/actions_ticketsup.class.php b/htdocs/ticketsup/class/actions_ticketsup.class.php index bc532619ce5..c5ddadf6a54 100644 --- a/htdocs/ticketsup/class/actions_ticketsup.class.php +++ b/htdocs/ticketsup/class/actions_ticketsup.class.php @@ -475,7 +475,7 @@ class ActionsTicketsup // Set parent company if ($action == 'set_thirdparty' && $user->rights->societe->creer) { if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { - $result = $this->dao->set_customer(GETPOST('editcustomer', 'int')); + $result = $this->dao->setCustomer(GETPOST('editcustomer', 'int')); $url = 'card.php?action=view&track_id=' . GETPOST('track_id', 'alpha'); header("Location: " . $url); exit(); @@ -1329,7 +1329,7 @@ class ActionsTicketsup * @param int $fieldid Id * @return int 0 */ - public function load_previous_next_ref($filter, $fieldid) + function load_previous_next_ref($filter, $fieldid) { $this->getInstanceDao(); return $this->dao->load_previous_next_ref($filter, $fieldid); diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index 531ebec308a..ae3a6c67fc1 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -1052,7 +1052,7 @@ class Ticketsup extends CommonObject * * @return int Nb lignes chargees, 0 si deja chargees, <0 si ko */ - public function load_cache_categories_tickets() + function load_cache_categories_tickets() { global $langs; @@ -1129,9 +1129,10 @@ class Ticketsup extends CommonObject } /** - * \brief Return status label of object - * \param mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto - * \return string Label + * Return status label of object + * + * @param mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string Label */ public function getLibStatut($mode = 0) { @@ -1139,10 +1140,11 @@ class Ticketsup extends CommonObject } /** - * \brief Return status label of object - * \param statut id statut - * \param mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto - * \return string Label + * Return status label of object + * + * @param string $statut id statut + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string Label */ public function LibStatut($statut, $mode = 0) { @@ -1324,12 +1326,13 @@ class Ticketsup extends CommonObject return $result; } - + /** * Mark a message as read * - * @param User $user Object user - * @return int <0 if KO, >0 if OK + * @param User $user Object user + * @param int $notrigger No trigger + * @return int <0 if KO, >0 if OK */ public function markAsRead($user, $notrigger = 0) { @@ -1337,7 +1340,7 @@ class Ticketsup extends CommonObject if ($this->statut != 9) { // no closed $this->db->begin(); - + $sql = "UPDATE " . MAIN_DB_PREFIX . "ticketsup"; $sql .= " SET fk_statut = 1, date_read='" . $this->db->idate(dol_now()) . "'"; $sql .= " WHERE rowid = " . $this->id; @@ -1914,13 +1917,13 @@ class Ticketsup extends CommonObject * @param int $id Id of thirdparty to set or '' to remove * @return int <0 if KO, >0 if OK */ - public function set_customer($id) + public function setCustomer($id) { if ($this->id) { $sql = "UPDATE " . MAIN_DB_PREFIX . "ticketsup"; $sql .= " SET fk_soc = " . ($id > 0 ? $id : "null"); $sql .= " WHERE rowid = " . $this->id; - dol_syslog(get_class($this) . '::set_customer sql=' . $sql); + dol_syslog(get_class($this) . '::setCustomer sql=' . $sql); $resql = $this->db->query($sql); if ($resql) { return 1; @@ -2077,7 +2080,7 @@ class Ticketsup extends CommonObject /** * Return id of all contacts for ticket * - * @param int $exclude_self exclude_self Exclude current user form list + * @return array Array of contacts for tickets */ public function getTicketAllContacts() { @@ -2236,10 +2239,10 @@ class Ticketsup extends CommonObject * Get array of all contacts for a ticket * Override method of file commonobject.class.php to add phone number * - * @param int $statut Status of lines to get (-1=all) - * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user) - * @param int $list 0:Return array contains all properties, 1:Return array contains just id - * @return array Array of contacts + * @param int $statut Status of lines to get (-1=all) + * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user) + * @param int $list 0:Return array contains all properties, 1:Return array contains just id + * @return array Array of contacts */ public function liste_contact($statut = -1, $source = 'external', $list = 0, $code = '') { @@ -2393,7 +2396,7 @@ class Ticketsup extends CommonObject * @param string $morehtmlright More html code to show before navigation arrows * @return void */ - public function ticketsup_banner_tab($paramid, $morehtml = '', $shownav = 1, $fieldid = 'id', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlright = '') + public function ticketsupBannerTab($paramid, $morehtml = '', $shownav = 1, $fieldid = 'id', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlright = '') { global $conf, $form, $user, $langs; diff --git a/htdocs/ticketsup/contacts.php b/htdocs/ticketsup/contacts.php index 0a04c8ce509..72b72ac0e57 100644 --- a/htdocs/ticketsup/contacts.php +++ b/htdocs/ticketsup/contacts.php @@ -155,7 +155,7 @@ if ($id > 0 || !empty($track_id) || !empty($ref)) { $object->label .= $fuser->getNomUrl(0); } $linkback = '' . $langs->trans("BackToList") . ' '; - $object->ticketsup_banner_tab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + $object->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); dol_fiche_end(); print '
    '; diff --git a/htdocs/ticketsup/document.php b/htdocs/ticketsup/document.php index ee1fc47f5d3..f9d96beaf1f 100644 --- a/htdocs/ticketsup/document.php +++ b/htdocs/ticketsup/document.php @@ -133,7 +133,7 @@ if ($object->id) { $object->label .= $fuser->getNomUrl(0); } $linkback = '' . $langs->trans("BackToList") . ' '; - $object->ticketsup_banner_tab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + $object->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); dol_fiche_end(); diff --git a/htdocs/ticketsup/history.php b/htdocs/ticketsup/history.php index fe0194e759c..48ba39a2b02 100644 --- a/htdocs/ticketsup/history.php +++ b/htdocs/ticketsup/history.php @@ -113,7 +113,7 @@ if ($action == 'view') { $object->dao->label .= $fuser->getNomUrl(0); } $linkback = '' . $langs->trans("BackToList") . ' '; - $object->dao->ticketsup_banner_tab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + $object->dao->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); dol_fiche_end(); From 5656e17570f961bc94e852bb32cdc16c267e6d52 Mon Sep 17 00:00:00 2001 From: jfefe Date: Sun, 11 Mar 2018 16:06:11 +0100 Subject: [PATCH 192/413] Fix PHPCS errors (ticketsup module) --- .../class/actions_ticketsup.class.php | 16 ++++++------- htdocs/ticketsup/class/ticketsup.class.php | 24 +++++++++++-------- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/htdocs/ticketsup/class/actions_ticketsup.class.php b/htdocs/ticketsup/class/actions_ticketsup.class.php index 94ef7db5849..c7668418980 100644 --- a/htdocs/ticketsup/class/actions_ticketsup.class.php +++ b/htdocs/ticketsup/class/actions_ticketsup.class.php @@ -609,8 +609,8 @@ class ActionsTicketsup /** * Add new message on a ticket (private area) * - * @param User $user - * @param string $action + * @param User $user User for action + * @param string $action Action string */ private function newMessage($user, &$action) { @@ -820,8 +820,8 @@ class ActionsTicketsup /** * Add new message on a ticket (public area) * - * @param User $user - * @param string $action + * @param User $user User for action + * @param string $action Action string */ private function newMessagePublic($user, &$action) { @@ -964,9 +964,9 @@ class ActionsTicketsup /** * Fetch object * - * @param string $id - * @param string $track_id - * @param string $ref + * @param int $id ID of ticket + * @param string $track_id Track ID of ticket (for public area) + * @param string $ref Reference of ticket * @return void */ public function fetch($id = 0, $track_id = 0, $ref = '') @@ -1321,7 +1321,7 @@ class ActionsTicketsup * @param int $fieldid Id * @return int 0 */ - public function load_previous_next_ref($filter, $fieldid) + function load_previous_next_ref($filter, $fieldid) { $this->getInstanceDao(); return $this->dao->load_previous_next_ref($filter, $fieldid); diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index 0dfe7907f71..a224b7d39f4 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -1129,21 +1129,25 @@ class Ticketsup extends CommonObject } } + /** - * \brief Return status label of object - * \param mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto - * \return string Label + * Return status label of object + * + * @param number $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string */ public function getLibStatut($mode = 0) { return $this->libStatut($this->fk_statut, $mode); } + /** - * \brief Return status label of object - * \param statut id statut - * \param mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto - * \return string Label + * Return status label of object + * + * @param int $statut id statut + * @param number $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string */ public function libStatut($statut, $mode = 0) { @@ -2390,7 +2394,7 @@ class Ticketsup extends CommonObject * @param string $morehtmlright More html code to show before navigation arrows * @return void */ - public function ticketsup_banner_tab($paramid, $morehtml = '', $shownav = 1, $fieldid = 'id', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlright = '') + function ticketsup_banner_tab($paramid, $morehtml = '', $shownav = 1, $fieldid = 'id', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlright = '') { global $conf, $form, $user, $langs; @@ -2453,7 +2457,7 @@ class Ticketsup extends CommonObject * @param string $sdir Repertoire a scanner * @return boolean true si photo dispo, false sinon */ - public function is_photo_available($sdir) + function is_photo_available($sdir) { include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; @@ -2495,7 +2499,7 @@ class Ticketsup extends CommonObject * @param int $nolink Do not add a href link to view enlarged imaged into a new tab * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto */ - public function show_photos($sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0) + function show_photos($sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0) { global $conf, $user, $langs; From cfdaa7c88dacbdef7a21c90b3808dc46d00c0162 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sun, 11 Mar 2018 16:07:13 +0100 Subject: [PATCH 193/413] ticket sup make it work --- htdocs/admin/ticketsup.php | 6 +- htdocs/admin/ticketsup_extrafields.php | 3 +- htdocs/core/lib/ticketsup.lib.php | 26 ++--- .../ticketsup/mod_ticketsup_simple.php | 2 +- .../ticketsup/mod_ticketsup_universal.php | 2 +- .../install/mysql/migration/7.0.0-8.0.0.sql | 102 ++++++++++++++++++ .../mysql/tables/llx_ticketsup.key.sql | 3 +- .../mysql/tables/llx_ticketsup_logs.key.sql | 2 +- 8 files changed, 123 insertions(+), 23 deletions(-) diff --git a/htdocs/admin/ticketsup.php b/htdocs/admin/ticketsup.php index ced25a1cd2d..529d64abf9c 100644 --- a/htdocs/admin/ticketsup.php +++ b/htdocs/admin/ticketsup.php @@ -34,10 +34,10 @@ if (file_exists("../../main.inc.php")) { // Libraries require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php"; -require_once "../class/ticketsup.class.php"; -require_once "../lib/ticketsup.lib.php"; +require_once DOL_DOCUMENT_ROOT."/ticketsup/class/ticketsup.class.php"; +require_once DOL_DOCUMENT_ROOT."/core/lib/ticketsup.lib.php"; // Translations -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Access control if (!$user->admin) { diff --git a/htdocs/admin/ticketsup_extrafields.php b/htdocs/admin/ticketsup_extrafields.php index 8a7ae788921..9084cac2ac1 100644 --- a/htdocs/admin/ticketsup_extrafields.php +++ b/htdocs/admin/ticketsup_extrafields.php @@ -29,7 +29,8 @@ if (file_exists("../../main.inc.php")) { } else { die("Include of main fails"); } -require_once '../lib/ticketsup.lib.php'; +// Libraries +require_once DOL_DOCUMENT_ROOT."/core/lib/ticketsup.lib.php"; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; diff --git a/htdocs/core/lib/ticketsup.lib.php b/htdocs/core/lib/ticketsup.lib.php index c3063783a6f..2d96a6faae5 100644 --- a/htdocs/core/lib/ticketsup.lib.php +++ b/htdocs/core/lib/ticketsup.lib.php @@ -31,18 +31,14 @@ function ticketsupAdminPrepareHead() $h = 0; $head = array(); - $head[$h][0] = dol_buildpath("/ticketsup/admin/admin_ticketsup.php", 1); + $head[$h][0] = DOL_URL_ROOT.'/admin/admin_ticketsup.php'; $head[$h][1] = $langs->trans("TicketSupSettings"); $head[$h][2] = 'settings'; $h++; - $head[$h][0] = dol_buildpath("/ticketsup/admin/ticketsup_extrafields.php", 1); + $head[$h][0] = DOL_URL_ROOT.'/admin/ticketsup_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFieldsTicketSup"); $head[$h][2] = 'attributes'; $h++; - $head[$h][0] = dol_buildpath("/ticketsup/admin/about.php", 1); - $head[$h][1] = $langs->trans("About"); - $head[$h][2] = 'about'; - $h++; // Show more tabs from modules // Entries must be declared in modules descriptor with line @@ -59,9 +55,9 @@ function ticketsupAdminPrepareHead() /** * Prepare head for ticket card - * + * * @param Object $object Object Ticket - * @return array Array of tabs + * @return array Array of tabs */ function ticketsup_prepare_head($object) { @@ -69,21 +65,21 @@ function ticketsup_prepare_head($object) $h = 0; $head = array(); - $head[$h][0] = dol_buildpath('/ticketsup/card.php', 1) . '?action=view&track_id=' . $object->track_id; + $head[$h][0] = DOL_URL_ROOT.'/ticketsup/card.php?action=view&track_id=' . $object->track_id; $head[$h][1] = $langs->trans("Card"); $head[$h][2] = 'tabTicketsup'; $h++; if (empty($user->socid)) { - $head[$h][0] = dol_buildpath('/ticketsup/contacts.php', 1) . '?track_id=' . $object->track_id; + $head[$h][0] = DOL_URL_ROOT.'/ticketsup/contacts.php?track_id=' . $object->track_id; $head[$h][1] = $langs->trans('Contacts'); $head[$h][2] = 'tabTicketContacts'; $h++; } complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticketsup'); - - + + // Attached files include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; $upload_dir = $conf->ticketsup->dir_output . "/" . $object->track_id; @@ -99,15 +95,15 @@ function ticketsup_prepare_head($object) // History - $head[$h][0] = dol_buildpath('/ticketsup/history.php', 1) . '?track_id=' . $object->track_id; + $head[$h][0] = DOL_URL_ROOT.'/ticketsup/history.php?track_id=' . $object->track_id; $head[$h][1] = $langs->trans('TicketHistory'); $head[$h][2] = 'tabTicketLogs'; $h++; - + complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticketsup','remove'); - + return $head; } diff --git a/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php b/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php index 25fabb12377..06c4863fc94 100644 --- a/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php +++ b/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php @@ -23,7 +23,7 @@ * \brief File with class to manage the numbering module Simple for ticketsup references */ -dol_include_once('/ticketsup/core/modules/modules_ticketsup.php'); +require_once DOL_DOCUMENT_ROOT.'/core/modules/modules_ticketsup.php'; /** * Class to manage the numbering module Simple for ticketsup references diff --git a/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php b/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php index cc8b88d7e8d..8c0c8c8fe0c 100644 --- a/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php +++ b/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php @@ -22,7 +22,7 @@ * \brief Fichier contenant la classe du modele de numerotation de reference de projet Universal */ -dol_include_once('/ticketsup/core/modules/modules_ticketsup.php'); +require_once DOL_DOCUMENT_ROOT.'/core/modules/modules_ticketsup.php'; /** * Classe du modele de numerotation de reference de projet Universal diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 7c82c54fb94..e9543583b03 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -120,4 +120,106 @@ ALTER TABLE llx_societe_rib ADD COLUMN total_amount_of_all_payments double(24,8) ALTER TABLE llx_societe_rib ADD COLUMN stripe_card_ref varchar(128); ALTER TABLE llx_societe_rib ADD COLUMN status integer NOT NULL DEFAULT 1; +CREATE TABLE llx_ticketsup +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, + ref varchar(128) NOT NULL, + track_id varchar(128) NOT NULL, + fk_soc integer DEFAULT 0, + fk_project integer DEFAULT 0, + origin_email varchar(128), + fk_user_create integer, + fk_user_assign integer, + subject varchar(255), + message text, + fk_statut integer, + resolution integer, + progress varchar(100), + timing varchar(20), + type_code varchar(32), + category_code varchar(32), + severity_code varchar(32), + datec datetime, + date_read datetime, + date_close datetime, + tms timestamp +)ENGINE=innodb; + +ALTER TABLE llx_ticketsup ADD UNIQUE uk_ticketsup_rowid_track_id (rowid, track_id); +ALTER TABLE llx_ticketsup ADD INDEX id_ticketsup_track_id (track_id); + +CREATE TABLE llx_ticketsup_msg +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, + fk_track_id varchar(128), + fk_user_action integer, + datec datetime, + message text, + private integer DEFAULT 0 +)ENGINE=innodb; + + +ALTER TABLE llx_ticketsup_msg ADD CONSTRAINT fk_ticketsup_msg_fk_track_id FOREIGN KEY (fk_track_id) REFERENCES llx_ticketsup (track_id); + +CREATE TABLE llx_ticketsup_logs +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, + fk_track_id varchar(128), + fk_user_create integer, + datec datetime, + message text +)ENGINE=innodb; + +ALTER TABLE llx_ticketsup_logs ADD CONSTRAINT fk_ticketsup_logs_fk_track_id FOREIGN KEY (fk_track_id) REFERENCES llx_ticketsup (track_id); + +CREATE TABLE llx_ticketsup_extrafields +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp, + fk_object integer NOT NULL, + import_key varchar(14) +)ENGINE=innodb; + +ALTER TABLE llx_c_ticketsup_category ADD INDEX idx_code (code); + +CREATE TABLE llx_c_ticketsup_category +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + code varchar(32) NOT NULL, + pos varchar(32) NOT NULL, + label varchar(128) NOT NULL, + active integer DEFAULT 1, + use_default integer DEFAULT 1, + description varchar(255) +)ENGINE=innodb; + +ALTER TABLE llx_c_ticketsup_severity ADD INDEX idx_code (code); + +CREATE TABLE llx_c_ticketsup_severity +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + code varchar(32) NOT NULL, + pos varchar(32) NOT NULL, + label varchar(128) NOT NULL, + color varchar(10) NOT NULL, + active integer DEFAULT 1, + use_default integer DEFAULT 1, + description varchar(255) +)ENGINE=innodb; + +ALTER TABLE llx_c_ticketsup_type ADD INDEX idx_code (code); + +CREATE TABLE llx_c_ticketsup_type +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + code varchar(32) NOT NULL, + pos varchar(32) NOT NULL, + label varchar(128) NOT NULL, + active integer DEFAULT 1, + use_default integer DEFAULT 1, + description varchar(255) +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_ticketsup.key.sql b/htdocs/install/mysql/tables/llx_ticketsup.key.sql index 4e06a1d8f44..abf853e718c 100755 --- a/htdocs/install/mysql/tables/llx_ticketsup.key.sql +++ b/htdocs/install/mysql/tables/llx_ticketsup.key.sql @@ -14,4 +14,5 @@ -- You should have received a copy of the GNU General Public License -- along with this program. If not, see . -ALTER TABLE llx_ticketsup ADD UNIQUE uk_matable_field(rowid, track_id); +ALTER TABLE llx_ticketsup ADD UNIQUE uk_ticketsup_rowid_track_id (rowid, track_id); +ALTER TABLE llx_ticketsup ADD INDEX id_ticketsup_track_id (track_id); diff --git a/htdocs/install/mysql/tables/llx_ticketsup_logs.key.sql b/htdocs/install/mysql/tables/llx_ticketsup_logs.key.sql index 764a6dc313a..180febe01bf 100755 --- a/htdocs/install/mysql/tables/llx_ticketsup_logs.key.sql +++ b/htdocs/install/mysql/tables/llx_ticketsup_logs.key.sql @@ -14,4 +14,4 @@ -- You should have received a copy of the GNU General Public License -- along with this program. If not, see . -ALTER TABLE llx_ticketsup_logs ADD CONSTRAINT fk_ticketsup_logs_fk_track_id FOREIGN KEY (fk_track_id) REFERENCES llx_ticketsup (fk_track_id); +ALTER TABLE llx_ticketsup_logs ADD CONSTRAINT fk_ticketsup_logs_fk_track_id FOREIGN KEY (fk_track_id) REFERENCES llx_ticketsup (track_id); From c3fab4c54cb0e6044b177ab7c80d797153c77d63 Mon Sep 17 00:00:00 2001 From: jfefe Date: Sun, 11 Mar 2018 16:48:26 +0100 Subject: [PATCH 194/413] Fix Phpunit issue --- htdocs/core/modules/ticketsup/mod_ticketsup_simple.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php b/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php index 25fabb12377..f0293f78d1f 100644 --- a/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php +++ b/htdocs/core/modules/ticketsup/mod_ticketsup_simple.php @@ -73,7 +73,8 @@ class mod_ticketsup_simple extends ModeleNumRefTicketsup $posindice = 8; $sql = "SELECT MAX(CAST(SUBSTRING(ref FROM " . $posindice . ") AS SIGNED)) as max"; $sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup"; - $sql .= " WHERE ref LIKE '" . $this->prefix . "____-%'"; + $search = $this->prefix . "____-%"; + $sql .= " WHERE ref LIKE '" . $search ."'"; $sql .= " AND entity = " . $conf->entity; $resql = $db->query($sql); if ($resql) { @@ -107,7 +108,8 @@ class mod_ticketsup_simple extends ModeleNumRefTicketsup $posindice = 8; $sql = "SELECT MAX(CAST(SUBSTRING(ref FROM " . $posindice . ") AS SIGNED)) as max"; $sql .= " FROM " . MAIN_DB_PREFIX . "ticketsup"; - $sql .= " WHERE ref like '" . $this->prefix . "____-%'"; + $search = $this->prefix . "____-%"; + $sql .= " WHERE ref LIKE '" . $search ."'"; $sql .= " AND entity = " . $conf->entity; $resql = $db->query($sql); From 7ffce2a28f99df117c269e3389c2128d7803061d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 16:48:44 +0100 Subject: [PATCH 195/413] Dolibarize --- htdocs/core/class/html.formticketsup.class.php | 2 +- htdocs/ticketsup/class/ticketsup.class.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/core/class/html.formticketsup.class.php b/htdocs/core/class/html.formticketsup.class.php index 0c10c256e83..329d23a7c51 100644 --- a/htdocs/core/class/html.formticketsup.class.php +++ b/htdocs/core/class/html.formticketsup.class.php @@ -624,7 +624,7 @@ class FormTicketsup $filterarray = explode(',', $filtertype); } - $ticketstat->load_cache_severities_tickets(); + $ticketstat->loadCacheSeveritiesTickets(); print ''; print ''; print ''; } - + // Initial message print ''; print ''; - + print ''; - + print ''; @@ -1209,7 +1209,7 @@ class ActionsTicketsup $action = GETPOST('action'); $this->viewTicketOriginalMessage($user, $action); - + if (is_array($this->dao->cache_msgs_ticket) && count($this->dao->cache_msgs_ticket) > 0) { print_titre($langs->trans('TicketMailExchanges')); @@ -1264,7 +1264,7 @@ class ActionsTicketsup print '
    ' . $langs->trans('NoMsgForThisTicket') . '
    '; } } - + /** * View list of message for ticket with timeline display * @@ -1275,11 +1275,11 @@ class ActionsTicketsup public function viewTicketTimelineMessages($show_private, $show_user = true) { global $conf, $langs, $user, $bc; - + // Load logs in cache $ret = $this->dao->loadCacheMsgsTicket(); $action = GETPOST('action'); - + if (is_array($this->dao->cache_msgs_ticket) && count($this->dao->cache_msgs_ticket) > 0) { print '
    '; @@ -1291,13 +1291,13 @@ class ActionsTicketsup print '
    '; print ''; print '
    '; - + print '
    '; print $arraymsgs['message']; - + print ''; print dol_print_date($arraymsgs['datec'], 'dayhour'); - + if ($show_user) { if ($arraymsgs['fk_user_action'] > 0) { $userstat = new User($this->db); @@ -1324,7 +1324,7 @@ class ActionsTicketsup /** * load_previous_next_ref - * + * * @param string $filter Filter * @param int $fieldid Id * @return int 0 @@ -1420,7 +1420,7 @@ class ActionsTicketsup /** * Copy files into ticket directory * Used for files linked into messages - * + * * @return void */ public function copyFilesForTicket() @@ -1467,7 +1467,7 @@ class ActionsTicketsup /** * Print html navbar with link to set ticket status * $selected : 0=>'NotRead', 1=>'Read', 3=>'Answered', 4=>'Assigned', 5 => 'InProgress', 6=> 'Waiting', 8=>'Closed', 9=>'Deleted' - * + * * @return void */ public function viewStatusActions() @@ -1506,17 +1506,17 @@ class ActionsTicketsup print '

    '; } - + /** * deleteObjectLinked - * + * * @return number - */ + */ public function deleteObjectLinked() { return $this->dao->deleteObjectLinked(); } - + /** * Hook to add email element template * @@ -1529,13 +1529,13 @@ class ActionsTicketsup public function emailElementlist($parameters, &$object, &$action, $hookmanager) { global $langs; - + $error = 0; - + if (in_array('admin', explode(':', $parameters['context']))) { $this->results = array('ticketsup_send' => $langs->trans('MailToSendTicketsupMessage')); } - + if (! $error) { return 0; // or return 1 to replace standard code } else { diff --git a/htdocs/ticketsup/class/api_ticketsups.class.php b/htdocs/ticketsup/class/api_ticketsups.class.php index fdfe4adae6c..bda05dd589c 100644 --- a/htdocs/ticketsup/class/api_ticketsups.class.php +++ b/htdocs/ticketsup/class/api_ticketsups.class.php @@ -303,7 +303,7 @@ class Ticketsups extends DolibarrApi public function post($request_data = null) { $ticketstatic = new Ticketsup($this->db); - if (! DolibarrApiAccess::$user->rights->ticketsup->create) { + if (! DolibarrApiAccess::$user->rights->ticketsup->write) { throw new RestException(401); } // Check mandatory fields @@ -334,7 +334,7 @@ class Ticketsups extends DolibarrApi public function postNewMessage($request_data = null) { $ticketstatic = new Ticketsup($this->db); - if (! DolibarrApiAccess::$user->rights->ticketsup->create) { + if (! DolibarrApiAccess::$user->rights->ticketsup->write) { throw new RestException(401); } // Check mandatory fields @@ -365,7 +365,7 @@ class Ticketsups extends DolibarrApi */ public function put($id, $request_data = null) { - if (! DolibarrApiAccess::$user->rights->ticketsup->create) { + if (! DolibarrApiAccess::$user->rights->ticketsup->write) { throw new RestException(401); } @@ -398,7 +398,7 @@ class Ticketsups extends DolibarrApi */ public function delete($id) { - if (! DolibarrApiAccess::$user->rights->ticketsup->supprimer) { + if (! DolibarrApiAccess::$user->rights->ticketsup->delete) { throw new RestException(401); } $result = $this->ticketsup->fetch($id); diff --git a/htdocs/ticketsup/list.php b/htdocs/ticketsup/list.php index 5661a78de71..43c405c5578 100644 --- a/htdocs/ticketsup/list.php +++ b/htdocs/ticketsup/list.php @@ -159,7 +159,7 @@ if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - + // Purge search criteria if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { @@ -175,7 +175,7 @@ if (empty($reshook)) { $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation } - + // Mass actions $objectclass='Ticketsup'; $objectlabel='Ticketsup'; @@ -285,14 +285,14 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) else { $sql.= $db->plimit($limit+1, $offset); - + $resql=$db->query($sql); if (! $resql) { dol_print_error($db); exit; } - + $num = $db->num_rows($resql); } @@ -513,7 +513,7 @@ foreach($object->fields as $key => $val) print '
    '; - + } elseif ($key == 'type_code') { print ''; } else { - + print ''; } } @@ -586,14 +586,14 @@ while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); if (empty($obj)) break; // Should not happen - + // Store properties in $object $object->id = $obj->rowid; foreach($object->fields as $key => $val) { if (isset($obj->$key)) $object->$key = $obj->$key; } - + // Show here line of result print ''; foreach($object->fields as $key => $val) @@ -633,9 +633,9 @@ while ($i < min($num, $limit)) } print ''; if (! $i) $totalarray['nbfield']++; - + print ''; - + $i++; } @@ -691,18 +691,18 @@ if (in_array('builddoc',$arrayofmassactions) && ($nbtotalofrecords === '' || $nb { $hidegeneratedfilelistifempty=1; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; - + require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); $formfile = new FormFile($db); - + // Show list of available documents $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; $urlsource.=str_replace('&','&',$param); - + $filedir=$diroutputmassaction; $genallowed=$user->rights->ticketsup->read; - $delallowed=$user->rights->ticketsup->create; - + $delallowed=$user->rights->ticketsup->write; + print $formfile->showdocuments('massfilesarea_ticketsup','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'','','',null,$hidegeneratedfilelistifempty); } diff --git a/htdocs/ticketsup/new.php b/htdocs/ticketsup/new.php index 3fb4294f150..4cf1ec3d749 100644 --- a/htdocs/ticketsup/new.php +++ b/htdocs/ticketsup/new.php @@ -44,7 +44,7 @@ $notnotifytiersatcreate = !empty($notNotifyTiers); $action = GETPOST('action', 'alpha', 3); // Protection if external user -if (!$user->rights->ticketsup->read || !$user->rights->ticketsup->create) { +if (!$user->rights->ticketsup->read || !$user->rights->ticketsup->write) { accessforbidden(); } From d28680e3ed5f6767d18109788ec28d27a01e926c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 18:34:47 +0100 Subject: [PATCH 206/413] Fix phpcs --- htdocs/ticketsup/class/ticketsup.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index 33bd82c38e6..5aaa3867b86 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -1141,7 +1141,7 @@ class Ticketsup extends CommonObject return $this->libStatut($this->fk_statut, $mode); } - + /** * Return status label of object * @@ -1492,7 +1492,7 @@ class Ticketsup extends CommonObject * Send notification of changes by email * * @param User $user User that create - * @param string $log_message Log message + * @param string $message Log message * @return int <0 if KO, >0 if OK (number of emails sent) */ private function sendLogByEmail($user, $message) From 7c3984c9dbf70cfe42ca073f93aa5af47f20857e Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Sun, 11 Mar 2018 18:54:38 +0100 Subject: [PATCH 207/413] Fix: dolibarrizzzz --- htdocs/admin/ticketsup_extrafields.php | 14 +++----------- htdocs/core/lib/ticketsup.lib.php | 9 ++++----- 2 files changed, 7 insertions(+), 16 deletions(-) diff --git a/htdocs/admin/ticketsup_extrafields.php b/htdocs/admin/ticketsup_extrafields.php index 9084cac2ac1..6a6a36a3bf8 100644 --- a/htdocs/admin/ticketsup_extrafields.php +++ b/htdocs/admin/ticketsup_extrafields.php @@ -1,6 +1,5 @@ +/* Copyright (C) 2013-2016 Jean-François FERRY * * 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 @@ -21,15 +20,8 @@ * \ingroup ticketsup * \brief Page to setup extra fields of ticket */ -$res = ''; -if (file_exists("../../main.inc.php")) { - $res = include "../../main.inc.php"; // From htdocs directory -} elseif (!$res && file_exists("../../../main.inc.php")) { - $res = include "../../../main.inc.php"; // From "custom" directory -} else { - die("Include of main fails"); -} -// Libraries + +require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT."/core/lib/ticketsup.lib.php"; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; diff --git a/htdocs/core/lib/ticketsup.lib.php b/htdocs/core/lib/ticketsup.lib.php index d44ca92f68d..7394ddeba24 100644 --- a/htdocs/core/lib/ticketsup.lib.php +++ b/htdocs/core/lib/ticketsup.lib.php @@ -1,7 +1,6 @@ - * 2016 Christophe Battarel +/* Copyright (C) 2013-2016 Jean-François FERRY + * Copyright (C) 2016 Christophe Battarel * * 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 @@ -25,7 +24,7 @@ /** * Build tabs for admin page - * + * * @return array */ function ticketsupAdminPrepareHead() @@ -37,7 +36,7 @@ function ticketsupAdminPrepareHead() $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/admin/admin_ticketsup.php'; + $head[$h][0] = DOL_URL_ROOT.'/admin/ticketsup.php'; $head[$h][1] = $langs->trans("TicketSupSettings"); $head[$h][2] = 'settings'; $h++; From da48dc6eabcd8632fccc29910432e4299c61424d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Sun, 11 Mar 2018 18:56:04 +0100 Subject: [PATCH 208/413] Update new.php --- htdocs/ticketsup/new.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/ticketsup/new.php b/htdocs/ticketsup/new.php index 4cf1ec3d749..18e8fbf5a17 100644 --- a/htdocs/ticketsup/new.php +++ b/htdocs/ticketsup/new.php @@ -23,7 +23,7 @@ */ require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . 'class/actions_ticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT . '/ticketsup/class/actions_ticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticketsup.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/ticketsup.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; @@ -31,7 +31,7 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $id = GETPOST('id', 'int'); From ecb44e2f531279cc8d47dc910932286b3fd15f07 Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Sun, 11 Mar 2018 18:57:36 +0100 Subject: [PATCH 209/413] Fix: wrong copy/paste --- htdocs/admin/ticketsup.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/admin/ticketsup.php b/htdocs/admin/ticketsup.php index 9c587ea8264..be1a3d2f8bf 100644 --- a/htdocs/admin/ticketsup.php +++ b/htdocs/admin/ticketsup.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2013-2018 Jean-François FERRY * Copyright (C) 2016 Christophe Battarel * * This program is free software: you can redistribute it and/or modify From a09bad6d6917526251ffb65cc0560329f405d3bb Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Sun, 11 Mar 2018 18:59:45 +0100 Subject: [PATCH 210/413] Fix: wrong year --- htdocs/core/lib/ticketsup.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/ticketsup.lib.php b/htdocs/core/lib/ticketsup.lib.php index 7394ddeba24..b25f3d1a4cd 100644 --- a/htdocs/core/lib/ticketsup.lib.php +++ b/htdocs/core/lib/ticketsup.lib.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2013-2018 Jean-François FERRY * Copyright (C) 2016 Christophe Battarel * * This program is free software: you can redistribute it and/or modify From a3d25b24d31b43c21dc6276af1f45d08ac1e8e55 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 19:27:03 +0100 Subject: [PATCH 211/413] FIX #8285 Extrafields now reported by /api/index.php/agendaevents/{id} --- htdocs/comm/action/class/api_agendaevents.class.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/comm/action/class/api_agendaevents.class.php b/htdocs/comm/action/class/api_agendaevents.class.php index 58deec46f5e..7fd76b5d1a9 100644 --- a/htdocs/comm/action/class/api_agendaevents.class.php +++ b/htdocs/comm/action/class/api_agendaevents.class.php @@ -80,6 +80,8 @@ class AgendaEvents extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } + $result = $this->actioncomm->fetch_optionals(); + $this->actioncomm->fetchObjectLinked(); return $this->_cleanObjectDatas($this->actioncomm); } @@ -319,7 +321,6 @@ class AgendaEvents extends DolibarrApi unset($object->usermod); unset($object->libelle); - unset($object->array_options); unset($object->context); unset($object->canvas); unset($object->contact); From 43ac1adbc4a3bad08fcab81280b8afb13aa840a2 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 19:32:28 +0100 Subject: [PATCH 212/413] Fix phpcs --- htdocs/ticketsup/class/actions_ticketsup.class.php | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/htdocs/ticketsup/class/actions_ticketsup.class.php b/htdocs/ticketsup/class/actions_ticketsup.class.php index a98f3ecf15d..c87264098ef 100644 --- a/htdocs/ticketsup/class/actions_ticketsup.class.php +++ b/htdocs/ticketsup/class/actions_ticketsup.class.php @@ -976,14 +976,10 @@ class ActionsTicketsup } /** - * print statut -<<<<<<< HEAD + * Print statut * - * @param int $mode Mode -======= - * @param int $mode Display mode ->>>>>>> branch 'develop' of git@github.com:Dolibarr/dolibarr.git - * @return void + * @param int $mode Display mode + * @return void */ public function getLibStatut($mode = 0) { From b084ca4a505babba6d55b18bae5fde8368ff6e2d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 19:44:19 +0100 Subject: [PATCH 213/413] Fix --- htdocs/core/class/CMailFile.class.php | 53 --------------------------- 1 file changed, 53 deletions(-) diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 74ed258928e..b7af324adb7 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -340,59 +340,6 @@ class CMailFile $this->smtps=$smtps; } - // TODO not stable, in progress - else if ($this->sendmode == 'phpmailer') - { - // Use PHPMailer library - // ------------------------------------------ - - require_once DOL_DOCUMENT_ROOT.'/includes/phpmailer/class.phpmailer.php'; - $this->phpmailer = new PHPMailer(); - $this->phpmailer->CharSet = $conf->file->character_set_client; - - $this->phpmailer->Subject($this->encodetorfc2822($subject)); - $this->phpmailer->setTO($this->getValidAddress($to,0,1)); - $this->phpmailer->SetFrom($this->getValidAddress($from,0,1)); - $this->phpmailer->SetReplyTo($this->getValidAddress($replyto,0,1)); - // TODO Add trackid into smtp header - // TODO if (! empty($moreinheader)) ... - - if (! empty($this->html)) - { - if (!empty($css)) - { - $this->css = $css; - $this->buildCSS(); - } - $msg = $this->html; - $msg = $this->checkIfHTML($msg); - } - - if ($this->msgishtml) $smtps->setBodyContent($msg,'html'); - else $smtps->setBodyContent($msg,'plain'); - - if ($this->atleastoneimage) - { - foreach ($this->images_encoded as $img) - { - $smtps->setImageInline($img['image_encoded'],$img['name'],$img['content_type'],$img['cid']); - } - } - - if ($this->atleastonefile) - { - foreach ($filename_list as $i => $val) - { - $content=file_get_contents($filename_list[$i]); - $smtps->setAttachment($content,$mimefilename_list[$i],$mimetype_list[$i]); - } - } - - $this->phpmailer->setCC($addr_cc); - $this->phpmailer->setBCC($addr_bcc); - $this->phpmailer->setErrorsTo($errors_to); - $this->phpmailer->setDeliveryReceipt($deliveryreceipt); - } else if ($this->sendmode == 'swiftmailer') { // Use Swift Mailer library From b04d38e7602d1aea839bd2655531c8030936228e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Sun, 11 Mar 2018 20:16:06 +0100 Subject: [PATCH 214/413] Update ticketsup.lang --- htdocs/langs/en_US/ticketsup.lang | 40 +++++++++++++++---------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/htdocs/langs/en_US/ticketsup.lang b/htdocs/langs/en_US/ticketsup.lang index ebf1f89309a..b50116c4997 100644 --- a/htdocs/langs/en_US/ticketsup.lang +++ b/htdocs/langs/en_US/ticketsup.lang @@ -18,14 +18,14 @@ # Generic # -Module110120Name = Tickets -Module110120Desc = Ticket system for incident management +Module56000Name=Tickets +Module56000Desc=Ticket system for incident management -Permission110121=See tickets -Permission110122=Modify tickets -Permission110123=Delete tickets -Permission110124=Manage tickets -Permission110125=See tickets of all thirdparties (not effective for external users, always be limited to the thirdparty they depend on) +Permission56001=See tickets +Permission56002=Modify tickets +Permission56003=Delete tickets +Permission56004=Manage tickets +Permission56005=See tickets of all thirdparties (not effective for external users, always be limited to the thirdparty they depend on) TicketsupDictType=Tickets type TicketsupDictCategory=Tickets categories @@ -70,22 +70,22 @@ Category=Category Severity=Severity # Email templates -MailToSendTicketsupMessage = To send email from ticket message +MailToSendTicketsupMessage=To send email from ticket message # # Admin page # -TicketsupSetup = Ticket module setup -TicketSupSettings = Settings -TicketsupSetupPage = -TicketsupPublicAccess = A public interface requiring no identification is available at the following url -TicketsupSetupDictionaries = The type of application categories and severity level are configurable from dictionaries +TicketsupSetup=Ticket module setup +TicketSupSettings=Settings +TicketsupSetupPage= +TicketsupPublicAccess=A public interface requiring no identification is available at the following url +TicketsupSetupDictionaries=The type of application categories and severity level are configurable from dictionaries TicketParamModule=Module variable setup TicketParamMail=Email setup -TicketEmailNotificationFrom = Notification email from -TicketEmailNotificationFromHelp = Used into ticket message answer by example -TicketEmailNotificationTo = Notifications email to -TicketEmailNotificationToHelp = Send email notifications to this address. +TicketEmailNotificationFrom=Notification email from +TicketEmailNotificationFromHelp=Used into ticket message answer by example +TicketEmailNotificationTo=Notifications email to +TicketEmailNotificationToHelp=Send email notifications to this address. TicketNewEmailBodyLabel=Text message sent after creating a ticket (public interface) TicketNewEmailBodyHelp=The text specified here will be inserted into the email confirming the creation of a new ticket from the public interface. Information on the consultation of the ticket are automatically added. TicketParamPublicInterface=Public interface setup @@ -128,9 +128,9 @@ TicketNotNotifyTiersAtCreate=Do not notify the company to the creation # # About page # -About = About -TicketSupAbout = About ticket module -TicketSupAboutModule = The development of this module has been initiated by the company Libr&thic. +About=About +TicketSupAbout=About ticket module +TicketSupAboutModule=The development of this module has been initiated by the company Libr&thic. TicketSupAboutModuleHelp=You can get help by using the contact form on the website librethic.io TicketSupAboutModuleImprove=Feel free to suggest improvements! Please visit the project page on Doliforge website to report bugs and add tasks. TicketSupAboutModuleThanks=Thanks to nwa who creates icons for this module./ From 111bbd98cebc740da39ac07e1036377ad840295d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Sun, 11 Mar 2018 20:36:52 +0100 Subject: [PATCH 215/413] Update ticketsup.php --- htdocs/admin/ticketsup.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/admin/ticketsup.php b/htdocs/admin/ticketsup.php index be1a3d2f8bf..f0dfb8c690a 100644 --- a/htdocs/admin/ticketsup.php +++ b/htdocs/admin/ticketsup.php @@ -235,9 +235,9 @@ $head = ticketsupAdminPrepareHead(); dol_fiche_head( $head, 'settings', - $langs->trans("Module110120Name"), + $langs->trans("Module56000Name"), 0, - "ticketsup@ticketsup" + "ticketsup" ); print '

    ' . $langs->trans("TicketsupSetupDictionaries") . ' : ' . dol_buildpath('/admin/dict.php', 2) . '

    '; @@ -546,7 +546,7 @@ if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) { // Email d'envoi des notifications print '
    '; print ''; +print ''; print ''; From ad05ddfe5c1fd0987c40df2ccd5cabc501d76bd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Sun, 11 Mar 2018 20:42:39 +0100 Subject: [PATCH 216/413] Update ticketsup_extrafields.php --- htdocs/admin/ticketsup_extrafields.php | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/htdocs/admin/ticketsup_extrafields.php b/htdocs/admin/ticketsup_extrafields.php index 6a6a36a3bf8..09fe827ca7c 100644 --- a/htdocs/admin/ticketsup_extrafields.php +++ b/htdocs/admin/ticketsup_extrafields.php @@ -26,7 +26,7 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/ticketsup.lib.php"; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); $langs->load("admin"); $extrafields = new ExtraFields($db); @@ -50,11 +50,7 @@ if (!$user->admin) { /* * Actions */ -if (versioncompare(versiondolibarrarray(), array(3, 5, 0)) > 0) { - include DOL_DOCUMENT_ROOT . '/core/actions_extrafields.inc.php'; -} elseif (versioncompare(versiondolibarrarray(), array(3, 4, 0)) > 0) { - include DOL_DOCUMENT_ROOT . '/core/admin_extrafields.inc.php'; -} +include DOL_DOCUMENT_ROOT . '/core/actions_extrafields.inc.php'; /* * View @@ -74,9 +70,9 @@ $head = ticketsupAdminPrepareHead(); dol_fiche_head( $head, 'attributes', - $langs->trans("Module110120Name"), + $langs->trans("Module56000Name"), 0, - "ticketsup@ticketsup" + "ticketsup" ); require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; From 683486eaf1a6d2b811fbbab8544d2cd1bad8ecfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Sun, 11 Mar 2018 21:00:39 +0100 Subject: [PATCH 217/413] Update html.formticketsup.class.php --- htdocs/core/class/html.formticketsup.class.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/core/class/html.formticketsup.class.php b/htdocs/core/class/html.formticketsup.class.php index 52b470c0929..08dbc4e0fe6 100644 --- a/htdocs/core/class/html.formticketsup.class.php +++ b/htdocs/core/class/html.formticketsup.class.php @@ -499,7 +499,7 @@ class FormTicketsup } print ''; if ($user->admin && !$noadmininfo) { - print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } } @@ -597,7 +597,7 @@ class FormTicketsup } print ''; if ($user->admin && !$noadmininfo) { - print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } } @@ -694,7 +694,7 @@ class FormTicketsup } print ''; if ($user->admin && !$noadmininfo) { - print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"), 1); + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } } From e1654f4215b3613940887a51499759e11651aa6c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 21:18:18 +0100 Subject: [PATCH 218/413] Fix division by zero --- htdocs/compta/tva/quadri_detail.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/compta/tva/quadri_detail.php b/htdocs/compta/tva/quadri_detail.php index c622881d273..d4ccbf98804 100644 --- a/htdocs/compta/tva/quadri_detail.php +++ b/htdocs/compta/tva/quadri_detail.php @@ -447,7 +447,7 @@ else $ratiopaymentinvoice=1; if ($modetax == 0) { - if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); print ' From ae82d045f8f23ad77b17551c1e4123b17c6bb5a3 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 23:40:25 +0100 Subject: [PATCH 227/413] Dolibarrize module ticket --- htdocs/admin/ticketsup.php | 28 ++++++++--------- htdocs/admin/ticketsup_extrafields.php | 14 ++++----- .../boxes/box_last_modified_ticketsup.php | 2 +- htdocs/core/boxes/box_last_ticketsup.php | 2 +- .../core/class/html.formticketsup.class.php | 6 ++-- htdocs/core/class/translate.class.php | 4 +-- htdocs/core/lib/ticketsup.lib.php | 2 +- htdocs/core/modules/modTicketsup.class.php | 22 +++++++------- htdocs/core/modules/modules_ticketsup.php | 4 +-- .../ticketsup/mod_ticketsup_universal.php | 2 +- ...face_50_modTicketsup_TicketEmail.class.php | 4 +-- .../install/mysql/migration/7.0.0-8.0.0.sql | 1 + htdocs/install/mysql/tables/llx_ticketsup.sql | 3 +- htdocs/langs/en_US/ticketsup.lang | 2 +- htdocs/public/ticketsup/create_ticket.php | 2 +- htdocs/public/ticketsup/index.php | 2 +- htdocs/public/ticketsup/list.php | 2 +- htdocs/public/ticketsup/view.php | 2 +- htdocs/ticketsup/card.php | 4 +-- htdocs/ticketsup/class/ticketsup.class.php | 8 ++--- htdocs/ticketsup/contacts.php | 4 +-- htdocs/ticketsup/document.php | 3 +- htdocs/ticketsup/history.php | 4 +-- htdocs/ticketsup/index.php | 30 +++++++++---------- htdocs/ticketsup/list.php | 19 +++++------- htdocs/ticketsup/new.php | 25 ++++++++-------- .../ticketsup/tpl/linkedobjectblock.tpl.php | 4 +-- 27 files changed, 101 insertions(+), 104 deletions(-) diff --git a/htdocs/admin/ticketsup.php b/htdocs/admin/ticketsup.php index f0dfb8c690a..4f6839d1e59 100644 --- a/htdocs/admin/ticketsup.php +++ b/htdocs/admin/ticketsup.php @@ -18,14 +18,15 @@ /** * \file admin/ticketsup.php - * \ingroup ticketsup - * \brief This file is a module setup page + * \ingroup ticketsup + * \brief This file is a module setup page */ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php"; require_once DOL_DOCUMENT_ROOT."/ticketsup/class/ticketsup.class.php"; require_once DOL_DOCUMENT_ROOT."/core/lib/ticketsup.lib.php"; + // Translations $langs->load("ticketsup"); @@ -214,9 +215,12 @@ if ($action == 'setvarother') { } } + + /* * View */ + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); $form = new Form($db); @@ -226,28 +230,22 @@ $page_name = "TicketsupSetup"; llxHeader('', $langs->trans($page_name), $help_url); // Subheader -$linkback = '' -. $langs->trans("BackToModuleList") . ''; -print load_fiche_titre($langs->trans($page_name), $linkback); +$linkback = '' . $langs->trans("BackToModuleList") . ''; + +print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); // Configuration header $head = ticketsupAdminPrepareHead(); -dol_fiche_head( - $head, - 'settings', - $langs->trans("Module56000Name"), - 0, - "ticketsup" -); -print '

    ' . $langs->trans("TicketsupSetupDictionaries") . ' : ' . dol_buildpath('/admin/dict.php', 2) . '

    '; +dol_fiche_head($head, 'settings', $langs->trans("Module56000Name"), -1, "ticketsup"); -print '

    ' . $langs->trans("TicketsupPublicAccess") . ' : ' . dol_buildpath('/ticketsup/public/index.php', 2) . '

    '; +print $langs->trans("TicketsupSetupDictionaries") . ' : ' . dol_buildpath('/admin/dict.php', 2) . '
    '; -//print '

    '. $langs->trans("TicketsupSetupPage").'

    '; +print $langs->trans("TicketsupPublicAccess") . ' : ' . dol_buildpath('/ticketsup/public/index.php', 2) . ''; dol_fiche_end(); + /* * Projects Numbering model */ diff --git a/htdocs/admin/ticketsup_extrafields.php b/htdocs/admin/ticketsup_extrafields.php index 09fe827ca7c..5709472e858 100644 --- a/htdocs/admin/ticketsup_extrafields.php +++ b/htdocs/admin/ticketsup_extrafields.php @@ -47,11 +47,15 @@ if (!$user->admin) { accessforbidden(); } + /* * Actions */ + include DOL_DOCUMENT_ROOT . '/core/actions_extrafields.inc.php'; + + /* * View */ @@ -63,17 +67,11 @@ $page_name = "TicketsupSetup"; llxHeader('', $langs->trans($page_name), $help_url); $linkback = '' . $langs->trans("BackToModuleList") . ''; -print load_fiche_titre($langs->trans("TicketsupSetup"), $linkback, 'setup'); +print load_fiche_titre($langs->trans("TicketsupSetup"), $linkback, 'title_setup'); $head = ticketsupAdminPrepareHead(); -dol_fiche_head( - $head, - 'attributes', - $langs->trans("Module56000Name"), - 0, - "ticketsup" -); +dol_fiche_head($head, 'attributes', $langs->trans("Module56000Name"), -1, "ticketsup"); require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; diff --git a/htdocs/core/boxes/box_last_modified_ticketsup.php b/htdocs/core/boxes/box_last_modified_ticketsup.php index 08bf47ad46c..fd49653eced 100644 --- a/htdocs/core/boxes/box_last_modified_ticketsup.php +++ b/htdocs/core/boxes/box_last_modified_ticketsup.php @@ -31,7 +31,7 @@ class box_last_modified_ticketsup extends ModeleBoxes { public $boxcode = "box_last_modified_ticketsup"; - public $boximg = "ticketsup@ticketsup"; + public $boximg = "ticketsup"; public $boxlabel; public $depends = array("ticketsup"); public $db; diff --git a/htdocs/core/boxes/box_last_ticketsup.php b/htdocs/core/boxes/box_last_ticketsup.php index 3eecceb74ae..6044bb179f5 100644 --- a/htdocs/core/boxes/box_last_ticketsup.php +++ b/htdocs/core/boxes/box_last_ticketsup.php @@ -31,7 +31,7 @@ class box_last_ticketsup extends ModeleBoxes { public $boxcode = "box_last_ticketsup"; - public $boximg = "ticketsup@ticketsup"; + public $boximg = "ticketsup"; public $boxlabel; public $depends = array("ticketsup"); public $db; diff --git a/htdocs/core/class/html.formticketsup.class.php b/htdocs/core/class/html.formticketsup.class.php index 08dbc4e0fe6..2bf41921793 100644 --- a/htdocs/core/class/html.formticketsup.class.php +++ b/htdocs/core/class/html.formticketsup.class.php @@ -122,7 +122,7 @@ class FormTicketsup $langs->load("other"); $langs->load("mails"); - $langs->load("ticketsup@ticketsup"); + $langs->load("ticketsup"); $form = new Form($this->db); $formcompany = new FormCompany($this->db); @@ -148,6 +148,7 @@ class FormTicketsup } print ''; + print '
    '; print '
    '; @@ -1163,9 +1163,9 @@ class ActionsTicketsup print '' . img_edit($langs->trans('Modify')) . ' ' . $langs->trans('Modify') . ''; } print '
    '; if (!empty($user->rights->ticketsup->manage) && $action == 'edit_message_init') { // MESSAGE @@ -1181,7 +1181,7 @@ class ActionsTicketsup } else { print dol_nl2br($this->dao->message); } - + //print '
    ' . $this->dao->message . '
    '; } print '
    '; $object->printSelectStatus(dol_escape_htmltag($search[$key])); print ''; $formTicket->selectTypesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1); @@ -527,7 +527,7 @@ foreach($object->fields as $key => $val) $formTicket->selectSeveritiesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1); print '
    ' . $langs->trans("TicketEmailNotificationFrom") . ''; -print ''; print $form->textwithpicto('', $langs->trans("TicketEmailNotificationFromHelp"), 1, 'help'); print ''; //print $fields['totalht']."-".$fields['payment_amount']."-".$fields['ftotal_ttc']; if ($fields['payment_amount'] && $fields['ftotal_ttc']) From 51c94fadfa8f1405f7164af90c1a81cbbaadc66b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 21:31:34 +0100 Subject: [PATCH 219/413] Look and feel v7 --- htdocs/admin/taxes.php | 18 +++++++++++++----- htdocs/langs/en_US/compta.lang | 2 +- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/htdocs/admin/taxes.php b/htdocs/admin/taxes.php index a4aa1afbd8c..391f3c38cc7 100644 --- a/htdocs/admin/taxes.php +++ b/htdocs/admin/taxes.php @@ -113,13 +113,14 @@ if ($action == 'update') { */ llxHeader(); + $form=new Form($db); if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); $linkback=''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans('TaxSetup'),$linkback,'title_setup'); -dol_fiche_head(); +dol_fiche_head(null, '0', '', -1); if (empty($mysoc->tva_assuj)) { @@ -127,6 +128,8 @@ if (empty($mysoc->tva_assuj)) } else { + print '
    '; + print ''; // Cas des parametres TAX_MODE_SELL/BUY_SERVICE/PRODUCT @@ -146,7 +149,7 @@ else print "
    \n"; print '
    '; - print load_fiche_titre($langs->trans("SummaryOfVatExigibilityUsedByDefault"),'',''); + print ' -> '.$langs->trans("SummaryOfVatExigibilityUsedByDefault"); //print ' ('.$langs->trans("CanBeChangedWhenMakingInvoice").')'; print ''; @@ -195,22 +198,27 @@ else print "
    \n"; + + /* * Others params */ + +print load_fiche_titre($langs->trans("OtherOptions"),'',''); + print '
    '; print ''; -print ''; +print ''; print "\n"; foreach ($list as $key) { - + print ''; // Param - $label = $langs->trans($key); + $label = $langs->trans($key); print ''; // Value diff --git a/htdocs/langs/en_US/compta.lang b/htdocs/langs/en_US/compta.lang index d1413fb0454..e476c951123 100644 --- a/htdocs/langs/en_US/compta.lang +++ b/htdocs/langs/en_US/compta.lang @@ -31,7 +31,7 @@ Credit=Credit Piece=Accounting Doc. AmountHTVATRealReceived=Net collected AmountHTVATRealPaid=Net paid -VATToPay=VAT sells +VATToPay=Tax sales VATReceived=Tax received VATToCollect=Tax purchases VATSummary=Tax Balance From 93f4d6fdcd6c38ed39e0425b9775381d3b0abf2a Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 21:34:38 +0100 Subject: [PATCH 220/413] Translation --- htdocs/adherents/card.php | 2 +- htdocs/comm/propal/card.php | 4 ++-- htdocs/commande/card.php | 4 ++-- htdocs/compta/facture/card.php | 6 +++--- htdocs/contrat/card.php | 4 ++-- htdocs/expedition/card.php | 4 ++-- htdocs/expensereport/card.php | 4 ++-- htdocs/fichinter/card.php | 4 ++-- htdocs/fourn/commande/card.php | 2 +- htdocs/fourn/facture/card.php | 4 ++-- htdocs/supplier_proposal/card.php | 4 ++-- 11 files changed, 21 insertions(+), 21 deletions(-) diff --git a/htdocs/adherents/card.php b/htdocs/adherents/card.php index 250c8e18b4e..de4c0100c48 100644 --- a/htdocs/adherents/card.php +++ b/htdocs/adherents/card.php @@ -1627,7 +1627,7 @@ else { // Send if ($object->statut == 1) { - print ''; + print ''; } // Send card by email diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index c33cc9b31ed..086cd1128dd 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -2339,9 +2339,9 @@ if ($action == 'create') // Send if ($object->statut == Propal::STATUS_VALIDATED || $object->statut == Propal::STATUS_SIGNED) { if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->propal->propal_advance->send) { - print ''; + print ''; } else - print ''; + print ''; } // Create an order diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index f11c4778b0b..a35f89f9038 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -2490,9 +2490,9 @@ if ($action == 'create' && $user->rights->commande->creer) // Send if ($object->statut > Commande::STATUS_DRAFT) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) { - print ''; + print ''; } else - print ''; + print ''; } // Valid diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index c39c918cd71..90bc80a6a19 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -4244,12 +4244,12 @@ else if ($id > 0 || ! empty($ref)) // Send by mail if (($object->statut == Facture::STATUS_VALIDATED || $object->statut == Facture::STATUS_CLOSED) || ! empty($conf->global->FACTURE_SENDBYEMAIL_FOR_ALL_STATUS)) { if ($objectidnext) { - print '
    ' . $langs->trans('SendByMail') . '
    '; + print '
    ' . $langs->trans('SendMail') . '
    '; } else { if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send) { - print ''; + print ''; } else - print ''; + print ''; } } diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index a2d189c9790..8034b8594d5 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -2108,9 +2108,9 @@ else // Send if ($object->statut == 1) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) { - print ''; + print ''; } else - print ''; + print ''; } if ($object->statut == 0 && $nbofservices) diff --git a/htdocs/expedition/card.php b/htdocs/expedition/card.php index 5ff1b133d20..719f738d081 100644 --- a/htdocs/expedition/card.php +++ b/htdocs/expedition/card.php @@ -2526,9 +2526,9 @@ else if ($id || $ref) { if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->expedition->shipping_advance->send) { - print ''.$langs->trans('SendByMail').''; + print ''.$langs->trans('SendMail').''; } - else print ''.$langs->trans('SendByMail').''; + else print ''.$langs->trans('SendMail').''; } // Create bill diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index 68ee395793f..1e5b8d183e4 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -2244,9 +2244,9 @@ if ($action != 'create' && $action != 'edit') // Send if ($object->fk_statut > ExpenseReport::STATUS_DRAFT) { //if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->expensereport->expensereport_advance->send)) { - print ''; + print ''; //} else - // print ''; + // print ''; } diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index b2533ba553c..b4a2b58a18e 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -1648,9 +1648,9 @@ else if ($id > 0 || ! empty($ref)) { if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->ficheinter->ficheinter_advance->send) { - print ''; + print ''; } - else print ''; + else print ''; } // Proposal diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index a9b207a9ee9..31574a4b3c0 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -2308,7 +2308,7 @@ elseif (! empty($object->id)) { if ($user->rights->fournisseur->commande->commander) { - print ''.$langs->trans('SendByMail').''; + print ''.$langs->trans('SendMail').''; } } diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index d69e1be6c3a..d0d3b505245 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -3004,9 +3004,9 @@ else { if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->fournisseur->supplier_invoice_advance->send) { - print ''; + print ''; } - else print '
    '.$langs->trans('SendByMail').'
    '; + else print '
    '.$langs->trans('SendMail').'
    '; } // Make payments diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index e12e1e34505..ade114f11b3 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1763,9 +1763,9 @@ if ($action == 'create') // Send if ($object->statut == SupplierProposal::STATUS_VALIDATED || $object->statut == SupplierProposal::STATUS_SIGNED) { if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->supplier_proposal->send_advance) { - print ''; + print ''; } else - print ''; + print ''; } // Create an order From c0d4ca3682c282d0c1cbb42cb28776ab8884861b Mon Sep 17 00:00:00 2001 From: Alexandre SPANGARO Date: Sun, 11 Mar 2018 22:28:27 +0100 Subject: [PATCH 221/413] Fix : Remove two langs->load("sendings") and use loadLangs instead --- htdocs/commande/card.php | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index a35f89f9038..44375df6dc8 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -56,15 +56,7 @@ if (!empty($conf->variants->enabled)) { require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; } -$langs->load('orders'); -$langs->load('sendings'); -$langs->load('companies'); -$langs->load('bills'); -$langs->load('propal'); -$langs->load('deliveries'); -$langs->load('sendings'); -$langs->load('products'); -$langs->load('other'); +$langs->loadLangs(array('orders','sendings','companies','bills','propal','deliveries','products','other')); if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); if (! empty($conf->margin->enabled)) $langs->load('margins'); if (! empty($conf->productbatch->enabled)) $langs->load("productbatch"); From d1fbf2a80eda51f06e63d37210c0c65580d66a84 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 23:07:57 +0100 Subject: [PATCH 222/413] Dolibarrize --- htdocs/public/ticketsup/create_ticket.php | 30 ++++---------------- htdocs/public/ticketsup/index.php | 29 ++++--------------- htdocs/public/ticketsup/view.php | 34 ++++++----------------- 3 files changed, 19 insertions(+), 74 deletions(-) diff --git a/htdocs/public/ticketsup/create_ticket.php b/htdocs/public/ticketsup/create_ticket.php index 867658b48ac..bc5fc584219 100644 --- a/htdocs/public/ticketsup/create_ticket.php +++ b/htdocs/public/ticketsup/create_ticket.php @@ -45,30 +45,12 @@ if (!defined('NOREQUIREHTML')) { define("NOLOGIN", 1); // This means this output page does not require to be logged. define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -// Change this following line to use the correct relative path (../, ../../, etc) -$res = 0; -if (!$res && file_exists("../main.inc.php")) { - $res = @include "../main.inc.php"; -} - -if (!$res && file_exists("../../main.inc.php")) { - $res = @include "../../main.inc.php"; -} - -if (!$res && file_exists("../../../main.inc.php")) { - $res = @include "../../../main.inc.php"; -} - -if (!$res) { - die("Include of main fails"); -} - -dol_include_once('/ticketsup/class/ticketsup.class.php'); -dol_include_once('/ticketsup/class/html.formticketsup.class.php'); -dol_include_once('/ticketsup/lib/ticketsup.lib.php'); - -require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; -require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php'; +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/ticketsup/class/actions_ticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT.'/ticketsup/class/html.formticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT.'/ticketsup/lib/ticketsup.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; // Load traductions files requiredby by page $langs->load("companies"); diff --git a/htdocs/public/ticketsup/index.php b/htdocs/public/ticketsup/index.php index ed141b32922..f913ce9c70d 100644 --- a/htdocs/public/ticketsup/index.php +++ b/htdocs/public/ticketsup/index.php @@ -42,30 +42,11 @@ if (!defined("NOLOGIN")) { } // If this page is public (can be called outside logged session) -// Change this following line to use the correct relative path (../, ../../, etc) -$res = 0; -if (!$res && file_exists("../main.inc.php")) { - $res = @include '../main.inc.php'; -} - -if (!$res && file_exists("../../main.inc.php")) { - $res = @include '../../main.inc.php'; -} - -if (!$res && file_exists("../../../main.inc.php")) { - $res = @include '../../../main.inc.php'; -} - -if (!$res) { - die("Include of main fails"); -} - -require_once DOL_DOCUMENT_ROOT . '/core/lib/security.lib.php'; - -// Change this following line to use the correct relative path from htdocs -dol_include_once('/ticketsup/class/ticketsup.class.php'); -dol_include_once('/ticketsup/class/html.formticketsup.class.php'); -dol_include_once('/ticketsup/lib/ticketsup.lib.php'); +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/ticketsup/class/actions_ticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT.'/ticketsup/class/html.formticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT.'/ticketsup/lib/ticketsup.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php'; // Load traductions files requiredby by page $langs->load("companies"); diff --git a/htdocs/public/ticketsup/view.php b/htdocs/public/ticketsup/view.php index 036d1d17b86..68e18e67d14 100644 --- a/htdocs/public/ticketsup/view.php +++ b/htdocs/public/ticketsup/view.php @@ -17,8 +17,8 @@ /** * \file ticketsup/public/index.php - * \ingroup ticketsup - * \brief Public file to add and manage ticket + * \ingroup ticketsup + * \brief Public file to add and manage ticket */ if (!defined('NOCSRFCHECK')) { @@ -34,28 +34,10 @@ if (!defined("NOLOGIN")) { } // If this page is public (can be called outside logged session) -// Change this following line to use the correct relative path (../, ../../, etc) -$res = 0; -if (!$res && file_exists("../main.inc.php")) { - $res = @include '../main.inc.php'; -} - -if (!$res && file_exists("../../main.inc.php")) { - $res = @include '../../main.inc.php'; -} - -if (!$res && file_exists("../../../main.inc.php")) { - $res = @include '../../../main.inc.php'; -} - -if (!$res) { - die("Include of main fails"); -} - -// Change this following line to use the correct relative path from htdocs -dol_include_once('/ticketsup/class/actions_ticketsup.class.php'); -dol_include_once('/ticketsup/class/html.formticketsup.class.php'); -dol_include_once('/ticketsup/lib/ticketsup.lib.php'); +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/ticketsup/class/actions_ticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT.'/ticketsup/class/html.formticketsup.class.php'; +require_once DOL_DOCUMENT_ROOT.'/ticketsup/lib/ticketsup.lib.php'; // Load traductions files requiredby by page $langs->load("companies"); @@ -300,13 +282,13 @@ if ($action == "view_ticket" || $action == "add_message" || $action == "close" | print load_fiche_titre($langs->trans('TicketMessagesList'), '', 'messages@ticketsup'); $object->viewTicketMessages(false); - print '
    '; + print '
    '; // Logs list print load_fiche_titre($langs->trans('TicketHistory'), '', 'history@ticketsup'); $object->viewTicketLogs(false); } else { - print ''; + print ''; } } else { print '

    ' . $langs->trans("TicketPublicMsgViewLogIn") . '

    '; From b5ca4ca3915614150edf78a78253d967e38fdf71 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 23:19:43 +0100 Subject: [PATCH 223/413] PHPunit --- test/phpunit/TicketsupTest.php | 82 +++++++++++++++++----------------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/test/phpunit/TicketsupTest.php b/test/phpunit/TicketsupTest.php index d45c72b14d5..9e807b855db 100644 --- a/test/phpunit/TicketsupTest.php +++ b/test/phpunit/TicketsupTest.php @@ -25,20 +25,20 @@ namespace test\unit; global $conf,$user,$langs,$db; -//define('TEST_DB_FORCE_TYPE','mysql'); // This is to force using mysql driver +//define('TEST_DB_FORCE_TYPE','mysql'); // This is to force using mysql driver //require_once 'PHPUnit/Autoload.php'; -$res = false; -if (file_exists(dirname(__FILE__).'/../../../../htdocs/master.inc.php')) { - $res = require_once dirname(__FILE__).'/../../../../htdocs/master.inc.php'; -} elseif (file_exists(dirname(__FILE__).'/../../../../../htdocs/master.inc.php')) { - $res = require_once dirname(__FILE__).'/../../../../../htdocs/master.inc.php'; -} else { - die('Include of mains fails'); +require_once dirname(__FILE__).'/../../htdocs/master.inc.php'; +require_once dirname(__FILE__).'/../../htdocs/user/class/usergroup.class.php'; +require_once dirname(__FILE__).'/../../htdocs/ticketsup/class/ticketsup.class.php'; + +if (empty($user->id)) { + print "Load permissions for admin user nb 1\n"; + $user->fetch(1); + $user->getrights(); } +$conf->global->MAIN_DISABLE_ALL_MAILS=1; -require_once dirname(__FILE__).'/../../class/ticketsup.class.php'; - if (empty($user->id)) { print "Load permissions for admin user nb 1\n"; @@ -144,10 +144,10 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase $localobject->initAsSpecimen(); $localobject->fk_statut = '\'1=1'; $result=$localobject->create($user); - + print __METHOD__." result=".$result."\n"; $this->assertEquals($result, -1); - + // Try to create one with correct values $localobject=new \Ticketsup($this->savdb); $localobject->initAsSpecimen(); @@ -155,7 +155,7 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase print __METHOD__." result=".$result."\n"; $this->assertLessThan($result, 0); - + return $result; } @@ -209,7 +209,7 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase $this->assertLessThan($result, 0); return $localobject; } - + /** * testTicketsupsetProject * @@ -226,16 +226,16 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase $user=$this->savuser; $langs=$this->savlangs; $db=$this->savdb; - + $project_id = 1; - + $result=$localobject->setProject($project_id); print __METHOD__." id=".$localobject->id." result=".$result."\n"; - + $this->assertLessThan($result, 0); return $localobject; } - + /** * testTicketsupsetContract * @@ -252,16 +252,16 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase $user=$this->savuser; $langs=$this->savlangs; $db=$this->savdb; - + $contract_id = 1; - + $result=$localobject->setContract($contract_id); print __METHOD__." id=".$localobject->id." result=".$result."\n"; - + $this->assertLessThan($result, 0); return $localobject; } - + /** * testTicketsupsetProgression * @@ -278,16 +278,16 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase $user=$this->savuser; $langs=$this->savlangs; $db=$this->savdb; - + $percent = 80; $result=$localobject->setProgression($percent); print __METHOD__." id=".$localobject->id." result=".$result."\n"; - + $this->assertLessThan($result, 0); return $localobject; } - + /** * testTicketsupassignUser * @@ -304,17 +304,17 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase $user=$this->savuser; $langs=$this->savlangs; $db=$this->savdb; - + $user_id_to_assign = 1; - + $result=$localobject->assignUser($user, $user_id_to_assign); ; print __METHOD__." id=".$localobject->id." result=".$result."\n"; - + $this->assertLessThan($result, 0); return $localobject; } - + /** * testTicketsupassignUserOther * @@ -331,17 +331,17 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase $user=$this->savuser; $langs=$this->savlangs; $db=$this->savdb; - + $user_id_to_assign = 2; - + $result=$localobject->assignUser($user, $user_id_to_assign); ; print __METHOD__." id=".$localobject->id." result=".$result."\n"; - + $this->assertLessThan($result, 0); return $localobject; } - + /** * testTicketsupcreateTicketLog * @@ -358,13 +358,13 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase $user=$this->savuser; $langs=$this->savlangs; $db=$this->savdb; - - + + $message = 'Test ticket log'; $noemail = 1; $result=$localobject->createTicketLog($user, $message, $noemail); print __METHOD__." id=".$localobject->id." result=".$result."\n"; - + $this->assertLessThan($result, 0); return $localobject; } @@ -385,15 +385,15 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase $user=$this->savuser; $langs=$this->savlangs; $db=$this->savdb; - + $result=$localobject->close(); print __METHOD__." id=".$localobject->id." result=".$result."\n"; - + $this->assertLessThan($result, 0); return $localobject->id; } - - + + /** * testTicketsupDelete * @@ -405,7 +405,7 @@ class TicketsupTest extends \PHPUnit_Framework_TestCase */ public function testTicketsupDelete($id) { - + global $conf,$user,$langs,$db; $conf=$this->savconf; $user=$this->savuser; From 6da3fbe3c9898d28b0c4f3107463c5bc11f28a18 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 23:21:14 +0100 Subject: [PATCH 224/413] Translation --- htdocs/langs/en_US/ticketsup.lang | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/langs/en_US/ticketsup.lang b/htdocs/langs/en_US/ticketsup.lang index b50116c4997..986a1882936 100644 --- a/htdocs/langs/en_US/ticketsup.lang +++ b/htdocs/langs/en_US/ticketsup.lang @@ -19,7 +19,7 @@ # Module56000Name=Tickets -Module56000Desc=Ticket system for incident management +Module56000Desc=Ticket system for issue or request management Permission56001=See tickets Permission56002=Modify tickets From 6ac070823f3476b3a62a2727887328f08cbb900c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 23:22:55 +0100 Subject: [PATCH 225/413] Fix phpcs --- htdocs/ticketsup/class/actions_ticketsup.class.php | 12 ++++++------ htdocs/ticketsup/tpl/linkedobjectblock.tpl.php | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/htdocs/ticketsup/class/actions_ticketsup.class.php b/htdocs/ticketsup/class/actions_ticketsup.class.php index c87264098ef..5ab3fabaffd 100644 --- a/htdocs/ticketsup/class/actions_ticketsup.class.php +++ b/htdocs/ticketsup/class/actions_ticketsup.class.php @@ -774,7 +774,7 @@ class ActionsTicketsup $message = $message_intro . $message; // Add signature - $message .= '
    ' . $message_signature; + $message .= '
    ' . $message_signature; if (!empty($this->dao->origin_email)) { $sendto[] = $this->dao->origin_email; @@ -1118,7 +1118,7 @@ class ActionsTicketsup $userstat = new User($this->db); $res = $userstat->fetch($arraylogs['fk_user_create']); if ($res) { - print '
    '.$userstat->getNomUrl(1).''; + print '
    '.$userstat->getNomUrl(1).''; } } } @@ -1296,11 +1296,11 @@ class ActionsTicketsup $userstat = new User($this->db); $res = $userstat->fetch($arraymsgs['fk_user_action']); if ($res) { - print '
    '; + print '
    '; print $userstat->getNomUrl(1); } } else { - print '
    '; + print '
    '; print $langs->trans('Customer'); } } @@ -1496,7 +1496,7 @@ class ActionsTicketsup // Sort results to be similar to status object list sort($exclude_status); - //print '
    '; + //print '
    '; foreach ($this->dao->statuts_short as $status => $statut_label) { if (!in_array($status, $exclude_status)) { print '
    '; @@ -1506,7 +1506,7 @@ class ActionsTicketsup print '
    '; } } - print '

    '; + print '
    '; } diff --git a/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php b/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php index 4c1a00c3d82..dc03dd32c3c 100644 --- a/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php +++ b/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php @@ -31,7 +31,7 @@ if (empty($conf) || ! is_object($conf)) $langs = $GLOBALS['langs']; $langs->load('ticketsup@ticketsup'); $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; -echo '
    '; +echo '
    '; print_titre($langs->trans('RelatedTickets')); ?>
    ' . $langs->trans('OtherOptions') . '' . $langs->trans('Parameters') . '
    From 1ede43971d813a8849323a9222f9172bd4ec030b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 11 Mar 2018 23:40:25 +0100 Subject: [PATCH 226/413] Dolibarrize module ticket --- .../boxes/box_last_modified_ticketsup.php | 2 +- htdocs/core/boxes/box_last_ticketsup.php | 2 +- .../core/class/html.formticketsup.class.php | 2 +- htdocs/core/class/translate.class.php | 4 +-- htdocs/core/lib/ticketsup.lib.php | 2 +- htdocs/core/modules/modTicketsup.class.php | 22 +++++++------- htdocs/core/modules/modules_ticketsup.php | 4 +-- .../ticketsup/mod_ticketsup_universal.php | 2 +- ...face_50_modTicketsup_TicketEmail.class.php | 4 +-- htdocs/langs/en_US/ticketsup.lang | 2 +- htdocs/public/ticketsup/create_ticket.php | 2 +- htdocs/public/ticketsup/index.php | 2 +- htdocs/public/ticketsup/list.php | 2 +- htdocs/public/ticketsup/view.php | 2 +- htdocs/ticketsup/card.php | 4 +-- htdocs/ticketsup/class/ticketsup.class.php | 8 ++--- htdocs/ticketsup/contacts.php | 4 +-- htdocs/ticketsup/document.php | 3 +- htdocs/ticketsup/history.php | 4 +-- htdocs/ticketsup/index.php | 30 +++++++++---------- .../ticketsup/tpl/linkedobjectblock.tpl.php | 4 +-- 21 files changed, 56 insertions(+), 55 deletions(-) diff --git a/htdocs/core/boxes/box_last_modified_ticketsup.php b/htdocs/core/boxes/box_last_modified_ticketsup.php index 08bf47ad46c..fd49653eced 100644 --- a/htdocs/core/boxes/box_last_modified_ticketsup.php +++ b/htdocs/core/boxes/box_last_modified_ticketsup.php @@ -31,7 +31,7 @@ class box_last_modified_ticketsup extends ModeleBoxes { public $boxcode = "box_last_modified_ticketsup"; - public $boximg = "ticketsup@ticketsup"; + public $boximg = "ticketsup"; public $boxlabel; public $depends = array("ticketsup"); public $db; diff --git a/htdocs/core/boxes/box_last_ticketsup.php b/htdocs/core/boxes/box_last_ticketsup.php index 3eecceb74ae..6044bb179f5 100644 --- a/htdocs/core/boxes/box_last_ticketsup.php +++ b/htdocs/core/boxes/box_last_ticketsup.php @@ -31,7 +31,7 @@ class box_last_ticketsup extends ModeleBoxes { public $boxcode = "box_last_ticketsup"; - public $boximg = "ticketsup@ticketsup"; + public $boximg = "ticketsup"; public $boxlabel; public $depends = array("ticketsup"); public $db; diff --git a/htdocs/core/class/html.formticketsup.class.php b/htdocs/core/class/html.formticketsup.class.php index 08dbc4e0fe6..d504a846507 100644 --- a/htdocs/core/class/html.formticketsup.class.php +++ b/htdocs/core/class/html.formticketsup.class.php @@ -122,7 +122,7 @@ class FormTicketsup $langs->load("other"); $langs->load("mails"); - $langs->load("ticketsup@ticketsup"); + $langs->load("ticketsup"); $form = new Form($this->db); $formcompany = new FormCompany($this->db); diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php index 69fe031459d..62abbbbcc18 100644 --- a/htdocs/core/class/translate.class.php +++ b/htdocs/core/class/translate.class.php @@ -205,7 +205,7 @@ class Translate // Check cache if (! empty($this->_tab_loaded[$newdomain])) // File already loaded for this domain { - //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain); + dol_syslog("Translate::Load already loaded for newdomain=".$newdomain); return 0; } @@ -231,7 +231,7 @@ class Translate $filelangexists=is_file($file_lang_osencoded); - //dol_syslog(get_class($this).'::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' newdomain='.$domain.' modulename='.$modulename.' file_lang='.$file_lang." => filelangexists=".$filelangexists); + dol_syslog(get_class($this).'::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' newdomain='.$domain.' modulename='.$modulename.' file_lang='.$file_lang." => filelangexists=".$filelangexists); if ($filelangexists) { diff --git a/htdocs/core/lib/ticketsup.lib.php b/htdocs/core/lib/ticketsup.lib.php index b25f3d1a4cd..ca27e9e8024 100644 --- a/htdocs/core/lib/ticketsup.lib.php +++ b/htdocs/core/lib/ticketsup.lib.php @@ -31,7 +31,7 @@ function ticketsupAdminPrepareHead() { global $langs, $conf; - $langs->load("ticketsup@ticketsup"); + $langs->load("ticketsup"); $h = 0; $head = array(); diff --git a/htdocs/core/modules/modTicketsup.class.php b/htdocs/core/modules/modTicketsup.class.php index 38299617788..7e824cdf47b 100644 --- a/htdocs/core/modules/modTicketsup.class.php +++ b/htdocs/core/modules/modTicketsup.class.php @@ -74,7 +74,7 @@ class modTicketsup extends DolibarrModules // use this->picto='pictovalue' // If file is in module/img directory under name object_pictovalue.png // use this->picto='pictovalue@module' - $this->picto = 'ticketsup@ticketsup'; // mypicto@ticketsup + $this->picto = 'ticketsup'; // mypicto@ticketsup // Defined all module parts (triggers, login, substitutions, menus, css, etc...) // for default path (eg: /ticketsup/core/xxxxx) (0=disable, 1=enable) // for specific path of parts (eg: /ticketsup/core/modules/barcode) @@ -135,7 +135,7 @@ class modTicketsup extends DolibarrModules $conf->ticketsup->enabled=0; } $this->dictionaries = array( - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'tabname' => array(MAIN_DB_PREFIX . "c_ticketsup_type", MAIN_DB_PREFIX . "c_ticketsup_category", MAIN_DB_PREFIX . "c_ticketsup_severity"), 'tablib' => array("TicketsupDictType", "TicketsupDictCategory", "TicketsupDictSeverity"), 'tabsql' => array('SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticketsup_type as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticketsup_category as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticketsup_severity as f'), @@ -153,10 +153,10 @@ class modTicketsup extends DolibarrModules $r = 0; // Example: - $this->boxes[$r][1] = "box_last_ticketsup@ticketsup"; + $this->boxes[$r][1] = "box_last_ticketsup"; $r++; - $this->boxes[$r][1] = "box_last_modified_ticketsup@ticketsup"; + $this->boxes[$r][1] = "box_last_modified_ticketsup"; $r++; // Permissions @@ -209,7 +209,7 @@ class modTicketsup extends DolibarrModules 'mainmenu' => 'ticketsup', 'leftmenu' => '1', // Use 1 if you also want to add left menu entries using this descriptor. 'url' => '/ticketsup/index.php', - 'langs' => 'ticketsup@ticketsup', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'langs' => 'ticketsup', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. 'position' => 100, 'enabled' => '1', // Define condition to show or hide menu entry. Use '$conf->ticketsup->enabled' if entry must be visible if module is enabled. 'perms' => '$user->rights->ticketsup->read', // Use 'perms'=>'$user->rights->ticketsup->level1->level2' if you want your menu with a permission rules @@ -223,7 +223,7 @@ class modTicketsup extends DolibarrModules 'mainmenu' => 'ticketsup', 'leftmenu' => 'ticketsup', 'url' => '/ticketsup/index.php', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 101, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->read', @@ -236,7 +236,7 @@ class modTicketsup extends DolibarrModules 'titre' => 'NewTicket', 'mainmenu' => 'ticketsup', 'url' => '/ticketsup/new.php?action=create_ticket', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 102, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->write', @@ -250,7 +250,7 @@ class modTicketsup extends DolibarrModules 'mainmenu' => 'ticketsup', 'leftmenu' => 'ticketsuplist', 'url' => '/ticketsup/list.php', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 103, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->read', @@ -264,7 +264,7 @@ class modTicketsup extends DolibarrModules 'mainmenu' => 'ticketsup', 'leftmenu' => 'ticketsuplist', 'url' => '/ticketsup/list.php?search_fk_status=non_closed', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 104, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->read', @@ -278,7 +278,7 @@ class modTicketsup extends DolibarrModules 'mainmenu' => 'ticketsup', 'leftmenu' => 'ticketsupmy', 'url' => '/ticketsup/list.php?mode=my_assign', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 105, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->read', @@ -291,7 +291,7 @@ class modTicketsup extends DolibarrModules 'titre' => 'MenuTicketsupMyAssignNonClosed', 'mainmenu' => 'ticketsup', 'url' => '/ticketsup/list.php?mode=my_assign&search_fk_status=non_closed', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 106, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->read', diff --git a/htdocs/core/modules/modules_ticketsup.php b/htdocs/core/modules/modules_ticketsup.php index 9eb652c31f4..e6e47adaa9f 100644 --- a/htdocs/core/modules/modules_ticketsup.php +++ b/htdocs/core/modules/modules_ticketsup.php @@ -49,7 +49,7 @@ abstract class ModeleNumRefTicketsup public function info() { global $langs; - $langs->load("ticketsup@ticketsup"); + $langs->load("ticketsup"); return $langs->trans("NoDescription"); } @@ -61,7 +61,7 @@ abstract class ModeleNumRefTicketsup public function getExample() { global $langs; - $langs->load("ticketsup@ticketsup"); + $langs->load("ticketsup"); return $langs->trans("NoExample"); } diff --git a/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php b/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php index 8c0c8c8fe0c..881ba5a7f15 100644 --- a/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php +++ b/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php @@ -43,7 +43,7 @@ class mod_ticketsup_universal extends ModeleNumRefTicketsup { global $conf, $langs; - $langs->load("ticketsup@ticketsup"); + $langs->load("ticketsup"); $langs->load("admin"); $form = new Form($this->db); diff --git a/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php b/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php index 1990f184f84..16b317cc108 100644 --- a/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php +++ b/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php @@ -50,7 +50,7 @@ class InterfaceTicketEmail extends DolibarrTriggers $this->family = "ticketsup"; $this->description = "Triggers of the module ticketsup"; $this->version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' or version - $this->picto = 'ticketsup@ticketsup'; + $this->picto = 'ticketsup'; } /** @@ -176,7 +176,7 @@ class InterfaceTicketEmail extends DolibarrTriggers $filename = array(); $mimetype = array(); - $langs->load('ticketsup@ticketsup'); + $langs->load('ticketsup'); $object->fetch('', $object->track_id); diff --git a/htdocs/langs/en_US/ticketsup.lang b/htdocs/langs/en_US/ticketsup.lang index 986a1882936..8187e8220d9 100644 --- a/htdocs/langs/en_US/ticketsup.lang +++ b/htdocs/langs/en_US/ticketsup.lang @@ -180,7 +180,7 @@ TicketMessageSuccessfullyAdded=Message successfully added TicketMessagesList=Message list NoMsgForThisTicket=No message for this ticket Properties=Classification -LastNewTickets=Last %s tickets newest (not read) +LatestNewTickets=Last %s tickets newest (not read) TicketSeverity=Severity ShowTicket=See ticket RelatedTickets=Related tickets diff --git a/htdocs/public/ticketsup/create_ticket.php b/htdocs/public/ticketsup/create_ticket.php index bc5fc584219..a0cb6f787ac 100644 --- a/htdocs/public/ticketsup/create_ticket.php +++ b/htdocs/public/ticketsup/create_ticket.php @@ -56,7 +56,7 @@ require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $langs->load("companies"); $langs->load("other"); $langs->load("mails"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $id = GETPOST('id', 'int'); diff --git a/htdocs/public/ticketsup/index.php b/htdocs/public/ticketsup/index.php index f913ce9c70d..8352282c4af 100644 --- a/htdocs/public/ticketsup/index.php +++ b/htdocs/public/ticketsup/index.php @@ -51,7 +51,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php'; // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); $langs->load("errors"); // Get parameters diff --git a/htdocs/public/ticketsup/list.php b/htdocs/public/ticketsup/list.php index adea8def5ea..34413168bc0 100644 --- a/htdocs/public/ticketsup/list.php +++ b/htdocs/public/ticketsup/list.php @@ -42,7 +42,7 @@ require_once DOL_DOCUMENT_ROOT.'/ticketsup/lib/ticketsup.lib.php'; // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $track_id = GETPOST('track_id', 'alpha'); diff --git a/htdocs/public/ticketsup/view.php b/htdocs/public/ticketsup/view.php index 68e18e67d14..c0069d9f6ee 100644 --- a/htdocs/public/ticketsup/view.php +++ b/htdocs/public/ticketsup/view.php @@ -42,7 +42,7 @@ require_once DOL_DOCUMENT_ROOT.'/ticketsup/lib/ticketsup.lib.php'; // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $track_id = GETPOST('track_id', 'alpha'); diff --git a/htdocs/ticketsup/card.php b/htdocs/ticketsup/card.php index b5ffa4b63d8..5bf64d34cc8 100644 --- a/htdocs/ticketsup/card.php +++ b/htdocs/ticketsup/card.php @@ -48,7 +48,7 @@ if (!class_exists('Contact')) { // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $id = GETPOST('id', 'int'); @@ -208,7 +208,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti } $head = ticketsup_prepare_head($object->dao); - dol_fiche_head($head, 'tabTicketsup', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + dol_fiche_head($head, 'tabTicketsup', $langs->trans("Ticket"), 0, 'ticketsup'); $object->dao->label = $object->dao->ref; // Author if ($object->dao->fk_user_create > 0) { diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index e507e2e89a7..902bb6943ef 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -53,7 +53,7 @@ class Ticketsup extends CommonObject /** * @var string String with name of icon for ticketsupcore. Must be the part after the 'object_' into object_ticketsupcore.png */ - public $picto = 'ticketsup@ticketsup'; + public $picto = 'ticketsup'; /** @@ -1309,9 +1309,9 @@ class Ticketsup extends CommonObject $lien = ''; $lienfin = ''; - $picto = 'ticketsup@ticketsup'; + $picto = 'ticketsup'; if (!$this->public) { - $picto = 'ticketsup@ticketsup'; + $picto = 'ticketsup'; } $label = $langs->trans("ShowTicket") . ': ' . $this->ref . ' - ' . $this->subject; @@ -1501,7 +1501,7 @@ class Ticketsup extends CommonObject $nb_sent = 0; - $langs->load('ticketsup@ticketsup'); + $langs->load('ticketsup'); // Retrieve email of all contacts (internal and external) $contacts = $this->listeContact(-1, 'internal'); diff --git a/htdocs/ticketsup/contacts.php b/htdocs/ticketsup/contacts.php index 72b72ac0e57..9ef592b22a7 100644 --- a/htdocs/ticketsup/contacts.php +++ b/htdocs/ticketsup/contacts.php @@ -36,7 +36,7 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php'; // Load traductions files requiredby by page $langs->load("companies"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $socid = GETPOST("socid", 'int'); @@ -144,7 +144,7 @@ if ($id > 0 || !empty($track_id) || !empty($ref)) { $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } $head = ticketsup_prepare_head($object); - dol_fiche_head($head, 'tabTicketContacts', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + dol_fiche_head($head, 'tabTicketContacts', $langs->trans("Ticket"), 0, 'ticketsup'); $object->label = $object->ref; // Author if ($object->fk_user_create > 0) { diff --git a/htdocs/ticketsup/document.php b/htdocs/ticketsup/document.php index f9d96beaf1f..f221dce73c2 100644 --- a/htdocs/ticketsup/document.php +++ b/htdocs/ticketsup/document.php @@ -35,6 +35,7 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; $langs->load("companies"); $langs->load('other'); +$langs->load("ticketsup"); $action = GETPOST('action'); $confirm = GETPOST('confirm'); @@ -122,7 +123,7 @@ if ($object->id) { $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } $head = ticketsup_prepare_head($object); - dol_fiche_head($head, 'tabTicketDocument', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + dol_fiche_head($head, 'tabTicketDocument', $langs->trans("Ticket"), 0, 'ticketsup'); $object->label = $object->ref; // Author if ($object->fk_user_create > 0) { diff --git a/htdocs/ticketsup/history.php b/htdocs/ticketsup/history.php index 48ba39a2b02..9bd69ade897 100644 --- a/htdocs/ticketsup/history.php +++ b/htdocs/ticketsup/history.php @@ -36,7 +36,7 @@ if (!class_exists('Contact')) { // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $id = GETPOST('id', 'int'); @@ -102,7 +102,7 @@ if ($action == 'view') { $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } $head = ticketsup_prepare_head($object->dao); - dol_fiche_head($head, 'tabTicketLogs', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + dol_fiche_head($head, 'tabTicketLogs', $langs->trans("Ticket"), 0, 'ticketsup'); $object->dao->label = $object->dao->ref; // Author if ($object->dao->fk_user_create > 0) { diff --git a/htdocs/ticketsup/index.php b/htdocs/ticketsup/index.php index 505812f84c6..e596d9149c1 100644 --- a/htdocs/ticketsup/index.php +++ b/htdocs/ticketsup/index.php @@ -29,7 +29,7 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/dolgraph.class.php'; // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); @@ -55,17 +55,17 @@ $endyear = $year; $object = new ActionsTicketsup($db); -/******************************************************************* - * ACTIONS - * - * Put here all code to do according to value of "action" parameter - ********************************************************************/ -/*************************************************** - * PAGE - * - * Put here all code to build page - ****************************************************/ +/* + * Actions + */ + +// None + + +/* + * View + */ llxHeader('', $langs->trans('TicketsIndex'), ''); @@ -241,10 +241,10 @@ if (count($dataseries) >1) { $px1->SetCssPrefix("cssboxes"); $px1->mode = 'depth'; //$px1->SetTitle($langs->trans("TicketStatByStatus")); - + $px1->draw($filenamenb, $fileurlnb); print $px1->show(); - + print $stringtoshow; } } @@ -295,7 +295,7 @@ if ($result) { $i = 0; - $transRecordedType = $langs->trans("LastNewTickets", $max); + $transRecordedType = $langs->trans("LatestNewTickets", $max); print '
    '; print ''; print ''; @@ -347,7 +347,7 @@ if ($result) { $db->free(); } else { - print ''; + print ''; } print "
    ' . $transRecordedType . '' . $langs->trans('Ref') . '
    ' . $langs->trans('NoTicketsFound') . '
    ' . $langs->trans('NoTicketsFound') . '
    "; diff --git a/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php b/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php index dc03dd32c3c..824f392d638 100644 --- a/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php +++ b/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php @@ -29,7 +29,7 @@ if (empty($conf) || ! is_object($conf)) load('ticketsup@ticketsup'); +$langs->load('ticketsup'); $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; echo '
    '; print_titre($langs->trans('RelatedTickets')); @@ -47,7 +47,7 @@ foreach ($linkedObjectBlock as $object) {
    subject) ? ' '.$object->subject : ''); ?> + trans("ShowTicket"), "ticketsup") . ' ' . (! empty($object->subject) ? ' '.$object->subject : ''); ?> datec, 'day'); ?>
    '; @@ -194,7 +195,7 @@ class FormTicketsup } }); }); - + function runJsCodeForEvent'.$htmlname.'(obj) { console.log("Run runJsCodeForEvent'.$htmlname.'"); var id = $("#'.$htmlname.'").val(); @@ -392,6 +393,7 @@ class FormTicketsup } print '
    '; + print '
    '; print '
    '; print ''; diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php index 69fe031459d..62abbbbcc18 100644 --- a/htdocs/core/class/translate.class.php +++ b/htdocs/core/class/translate.class.php @@ -205,7 +205,7 @@ class Translate // Check cache if (! empty($this->_tab_loaded[$newdomain])) // File already loaded for this domain { - //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain); + dol_syslog("Translate::Load already loaded for newdomain=".$newdomain); return 0; } @@ -231,7 +231,7 @@ class Translate $filelangexists=is_file($file_lang_osencoded); - //dol_syslog(get_class($this).'::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' newdomain='.$domain.' modulename='.$modulename.' file_lang='.$file_lang." => filelangexists=".$filelangexists); + dol_syslog(get_class($this).'::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' newdomain='.$domain.' modulename='.$modulename.' file_lang='.$file_lang." => filelangexists=".$filelangexists); if ($filelangexists) { diff --git a/htdocs/core/lib/ticketsup.lib.php b/htdocs/core/lib/ticketsup.lib.php index b25f3d1a4cd..ca27e9e8024 100644 --- a/htdocs/core/lib/ticketsup.lib.php +++ b/htdocs/core/lib/ticketsup.lib.php @@ -31,7 +31,7 @@ function ticketsupAdminPrepareHead() { global $langs, $conf; - $langs->load("ticketsup@ticketsup"); + $langs->load("ticketsup"); $h = 0; $head = array(); diff --git a/htdocs/core/modules/modTicketsup.class.php b/htdocs/core/modules/modTicketsup.class.php index 38299617788..7e824cdf47b 100644 --- a/htdocs/core/modules/modTicketsup.class.php +++ b/htdocs/core/modules/modTicketsup.class.php @@ -74,7 +74,7 @@ class modTicketsup extends DolibarrModules // use this->picto='pictovalue' // If file is in module/img directory under name object_pictovalue.png // use this->picto='pictovalue@module' - $this->picto = 'ticketsup@ticketsup'; // mypicto@ticketsup + $this->picto = 'ticketsup'; // mypicto@ticketsup // Defined all module parts (triggers, login, substitutions, menus, css, etc...) // for default path (eg: /ticketsup/core/xxxxx) (0=disable, 1=enable) // for specific path of parts (eg: /ticketsup/core/modules/barcode) @@ -135,7 +135,7 @@ class modTicketsup extends DolibarrModules $conf->ticketsup->enabled=0; } $this->dictionaries = array( - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'tabname' => array(MAIN_DB_PREFIX . "c_ticketsup_type", MAIN_DB_PREFIX . "c_ticketsup_category", MAIN_DB_PREFIX . "c_ticketsup_severity"), 'tablib' => array("TicketsupDictType", "TicketsupDictCategory", "TicketsupDictSeverity"), 'tabsql' => array('SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticketsup_type as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticketsup_category as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticketsup_severity as f'), @@ -153,10 +153,10 @@ class modTicketsup extends DolibarrModules $r = 0; // Example: - $this->boxes[$r][1] = "box_last_ticketsup@ticketsup"; + $this->boxes[$r][1] = "box_last_ticketsup"; $r++; - $this->boxes[$r][1] = "box_last_modified_ticketsup@ticketsup"; + $this->boxes[$r][1] = "box_last_modified_ticketsup"; $r++; // Permissions @@ -209,7 +209,7 @@ class modTicketsup extends DolibarrModules 'mainmenu' => 'ticketsup', 'leftmenu' => '1', // Use 1 if you also want to add left menu entries using this descriptor. 'url' => '/ticketsup/index.php', - 'langs' => 'ticketsup@ticketsup', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'langs' => 'ticketsup', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. 'position' => 100, 'enabled' => '1', // Define condition to show or hide menu entry. Use '$conf->ticketsup->enabled' if entry must be visible if module is enabled. 'perms' => '$user->rights->ticketsup->read', // Use 'perms'=>'$user->rights->ticketsup->level1->level2' if you want your menu with a permission rules @@ -223,7 +223,7 @@ class modTicketsup extends DolibarrModules 'mainmenu' => 'ticketsup', 'leftmenu' => 'ticketsup', 'url' => '/ticketsup/index.php', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 101, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->read', @@ -236,7 +236,7 @@ class modTicketsup extends DolibarrModules 'titre' => 'NewTicket', 'mainmenu' => 'ticketsup', 'url' => '/ticketsup/new.php?action=create_ticket', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 102, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->write', @@ -250,7 +250,7 @@ class modTicketsup extends DolibarrModules 'mainmenu' => 'ticketsup', 'leftmenu' => 'ticketsuplist', 'url' => '/ticketsup/list.php', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 103, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->read', @@ -264,7 +264,7 @@ class modTicketsup extends DolibarrModules 'mainmenu' => 'ticketsup', 'leftmenu' => 'ticketsuplist', 'url' => '/ticketsup/list.php?search_fk_status=non_closed', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 104, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->read', @@ -278,7 +278,7 @@ class modTicketsup extends DolibarrModules 'mainmenu' => 'ticketsup', 'leftmenu' => 'ticketsupmy', 'url' => '/ticketsup/list.php?mode=my_assign', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 105, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->read', @@ -291,7 +291,7 @@ class modTicketsup extends DolibarrModules 'titre' => 'MenuTicketsupMyAssignNonClosed', 'mainmenu' => 'ticketsup', 'url' => '/ticketsup/list.php?mode=my_assign&search_fk_status=non_closed', - 'langs' => 'ticketsup@ticketsup', + 'langs' => 'ticketsup', 'position' => 106, 'enabled' => 1, 'perms' => '$user->rights->ticketsup->read', diff --git a/htdocs/core/modules/modules_ticketsup.php b/htdocs/core/modules/modules_ticketsup.php index 9eb652c31f4..e6e47adaa9f 100644 --- a/htdocs/core/modules/modules_ticketsup.php +++ b/htdocs/core/modules/modules_ticketsup.php @@ -49,7 +49,7 @@ abstract class ModeleNumRefTicketsup public function info() { global $langs; - $langs->load("ticketsup@ticketsup"); + $langs->load("ticketsup"); return $langs->trans("NoDescription"); } @@ -61,7 +61,7 @@ abstract class ModeleNumRefTicketsup public function getExample() { global $langs; - $langs->load("ticketsup@ticketsup"); + $langs->load("ticketsup"); return $langs->trans("NoExample"); } diff --git a/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php b/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php index 8c0c8c8fe0c..881ba5a7f15 100644 --- a/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php +++ b/htdocs/core/modules/ticketsup/mod_ticketsup_universal.php @@ -43,7 +43,7 @@ class mod_ticketsup_universal extends ModeleNumRefTicketsup { global $conf, $langs; - $langs->load("ticketsup@ticketsup"); + $langs->load("ticketsup"); $langs->load("admin"); $form = new Form($this->db); diff --git a/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php b/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php index 1990f184f84..16b317cc108 100644 --- a/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php +++ b/htdocs/core/triggers/interface_50_modTicketsup_TicketEmail.class.php @@ -50,7 +50,7 @@ class InterfaceTicketEmail extends DolibarrTriggers $this->family = "ticketsup"; $this->description = "Triggers of the module ticketsup"; $this->version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' or version - $this->picto = 'ticketsup@ticketsup'; + $this->picto = 'ticketsup'; } /** @@ -176,7 +176,7 @@ class InterfaceTicketEmail extends DolibarrTriggers $filename = array(); $mimetype = array(); - $langs->load('ticketsup@ticketsup'); + $langs->load('ticketsup'); $object->fetch('', $object->track_id); diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index e9543583b03..37e22e182a7 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -146,6 +146,7 @@ CREATE TABLE llx_ticketsup tms timestamp )ENGINE=innodb; +ALTER TABLE llx_ticketsup ADD COLUMN notify_tiers_at_create integer; ALTER TABLE llx_ticketsup ADD UNIQUE uk_ticketsup_rowid_track_id (rowid, track_id); ALTER TABLE llx_ticketsup ADD INDEX id_ticketsup_track_id (track_id); diff --git a/htdocs/install/mysql/tables/llx_ticketsup.sql b/htdocs/install/mysql/tables/llx_ticketsup.sql index 5449cf4825d..f79cda97712 100644 --- a/htdocs/install/mysql/tables/llx_ticketsup.sql +++ b/htdocs/install/mysql/tables/llx_ticketsup.sql @@ -18,7 +18,7 @@ CREATE TABLE llx_ticketsup ( rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1, - ref varchar(128) NOT NULL, + ref varchar(128) NOT NULL, track_id varchar(128) NOT NULL, fk_soc integer DEFAULT 0, fk_project integer DEFAULT 0, @@ -37,5 +37,6 @@ CREATE TABLE llx_ticketsup datec datetime, date_read datetime, date_close datetime, + notify_tiers_at_create, tms timestamp )ENGINE=innodb; diff --git a/htdocs/langs/en_US/ticketsup.lang b/htdocs/langs/en_US/ticketsup.lang index 986a1882936..8187e8220d9 100644 --- a/htdocs/langs/en_US/ticketsup.lang +++ b/htdocs/langs/en_US/ticketsup.lang @@ -180,7 +180,7 @@ TicketMessageSuccessfullyAdded=Message successfully added TicketMessagesList=Message list NoMsgForThisTicket=No message for this ticket Properties=Classification -LastNewTickets=Last %s tickets newest (not read) +LatestNewTickets=Last %s tickets newest (not read) TicketSeverity=Severity ShowTicket=See ticket RelatedTickets=Related tickets diff --git a/htdocs/public/ticketsup/create_ticket.php b/htdocs/public/ticketsup/create_ticket.php index bc5fc584219..a0cb6f787ac 100644 --- a/htdocs/public/ticketsup/create_ticket.php +++ b/htdocs/public/ticketsup/create_ticket.php @@ -56,7 +56,7 @@ require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $langs->load("companies"); $langs->load("other"); $langs->load("mails"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $id = GETPOST('id', 'int'); diff --git a/htdocs/public/ticketsup/index.php b/htdocs/public/ticketsup/index.php index f913ce9c70d..8352282c4af 100644 --- a/htdocs/public/ticketsup/index.php +++ b/htdocs/public/ticketsup/index.php @@ -51,7 +51,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php'; // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); $langs->load("errors"); // Get parameters diff --git a/htdocs/public/ticketsup/list.php b/htdocs/public/ticketsup/list.php index adea8def5ea..34413168bc0 100644 --- a/htdocs/public/ticketsup/list.php +++ b/htdocs/public/ticketsup/list.php @@ -42,7 +42,7 @@ require_once DOL_DOCUMENT_ROOT.'/ticketsup/lib/ticketsup.lib.php'; // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $track_id = GETPOST('track_id', 'alpha'); diff --git a/htdocs/public/ticketsup/view.php b/htdocs/public/ticketsup/view.php index 68e18e67d14..c0069d9f6ee 100644 --- a/htdocs/public/ticketsup/view.php +++ b/htdocs/public/ticketsup/view.php @@ -42,7 +42,7 @@ require_once DOL_DOCUMENT_ROOT.'/ticketsup/lib/ticketsup.lib.php'; // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $track_id = GETPOST('track_id', 'alpha'); diff --git a/htdocs/ticketsup/card.php b/htdocs/ticketsup/card.php index b5ffa4b63d8..5bf64d34cc8 100644 --- a/htdocs/ticketsup/card.php +++ b/htdocs/ticketsup/card.php @@ -48,7 +48,7 @@ if (!class_exists('Contact')) { // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $id = GETPOST('id', 'int'); @@ -208,7 +208,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti } $head = ticketsup_prepare_head($object->dao); - dol_fiche_head($head, 'tabTicketsup', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + dol_fiche_head($head, 'tabTicketsup', $langs->trans("Ticket"), 0, 'ticketsup'); $object->dao->label = $object->dao->ref; // Author if ($object->dao->fk_user_create > 0) { diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index e507e2e89a7..902bb6943ef 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -53,7 +53,7 @@ class Ticketsup extends CommonObject /** * @var string String with name of icon for ticketsupcore. Must be the part after the 'object_' into object_ticketsupcore.png */ - public $picto = 'ticketsup@ticketsup'; + public $picto = 'ticketsup'; /** @@ -1309,9 +1309,9 @@ class Ticketsup extends CommonObject $lien = ''; $lienfin = ''; - $picto = 'ticketsup@ticketsup'; + $picto = 'ticketsup'; if (!$this->public) { - $picto = 'ticketsup@ticketsup'; + $picto = 'ticketsup'; } $label = $langs->trans("ShowTicket") . ': ' . $this->ref . ' - ' . $this->subject; @@ -1501,7 +1501,7 @@ class Ticketsup extends CommonObject $nb_sent = 0; - $langs->load('ticketsup@ticketsup'); + $langs->load('ticketsup'); // Retrieve email of all contacts (internal and external) $contacts = $this->listeContact(-1, 'internal'); diff --git a/htdocs/ticketsup/contacts.php b/htdocs/ticketsup/contacts.php index 72b72ac0e57..9ef592b22a7 100644 --- a/htdocs/ticketsup/contacts.php +++ b/htdocs/ticketsup/contacts.php @@ -36,7 +36,7 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php'; // Load traductions files requiredby by page $langs->load("companies"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $socid = GETPOST("socid", 'int'); @@ -144,7 +144,7 @@ if ($id > 0 || !empty($track_id) || !empty($ref)) { $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } $head = ticketsup_prepare_head($object); - dol_fiche_head($head, 'tabTicketContacts', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + dol_fiche_head($head, 'tabTicketContacts', $langs->trans("Ticket"), 0, 'ticketsup'); $object->label = $object->ref; // Author if ($object->fk_user_create > 0) { diff --git a/htdocs/ticketsup/document.php b/htdocs/ticketsup/document.php index f9d96beaf1f..f221dce73c2 100644 --- a/htdocs/ticketsup/document.php +++ b/htdocs/ticketsup/document.php @@ -35,6 +35,7 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; $langs->load("companies"); $langs->load('other'); +$langs->load("ticketsup"); $action = GETPOST('action'); $confirm = GETPOST('confirm'); @@ -122,7 +123,7 @@ if ($object->id) { $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } $head = ticketsup_prepare_head($object); - dol_fiche_head($head, 'tabTicketDocument', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + dol_fiche_head($head, 'tabTicketDocument', $langs->trans("Ticket"), 0, 'ticketsup'); $object->label = $object->ref; // Author if ($object->fk_user_create > 0) { diff --git a/htdocs/ticketsup/history.php b/htdocs/ticketsup/history.php index 48ba39a2b02..9bd69ade897 100644 --- a/htdocs/ticketsup/history.php +++ b/htdocs/ticketsup/history.php @@ -36,7 +36,7 @@ if (!class_exists('Contact')) { // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); // Get parameters $id = GETPOST('id', 'int'); @@ -102,7 +102,7 @@ if ($action == 'view') { $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } $head = ticketsup_prepare_head($object->dao); - dol_fiche_head($head, 'tabTicketLogs', $langs->trans("Ticket"), 0, 'ticketsup@ticketsup'); + dol_fiche_head($head, 'tabTicketLogs', $langs->trans("Ticket"), 0, 'ticketsup'); $object->dao->label = $object->dao->ref; // Author if ($object->dao->fk_user_create > 0) { diff --git a/htdocs/ticketsup/index.php b/htdocs/ticketsup/index.php index 505812f84c6..e596d9149c1 100644 --- a/htdocs/ticketsup/index.php +++ b/htdocs/ticketsup/index.php @@ -29,7 +29,7 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/dolgraph.class.php'; // Load traductions files requiredby by page $langs->load("companies"); $langs->load("other"); -$langs->load("ticketsup@ticketsup"); +$langs->load("ticketsup"); $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); @@ -55,17 +55,17 @@ $endyear = $year; $object = new ActionsTicketsup($db); -/******************************************************************* - * ACTIONS - * - * Put here all code to do according to value of "action" parameter - ********************************************************************/ -/*************************************************** - * PAGE - * - * Put here all code to build page - ****************************************************/ +/* + * Actions + */ + +// None + + +/* + * View + */ llxHeader('', $langs->trans('TicketsIndex'), ''); @@ -241,10 +241,10 @@ if (count($dataseries) >1) { $px1->SetCssPrefix("cssboxes"); $px1->mode = 'depth'; //$px1->SetTitle($langs->trans("TicketStatByStatus")); - + $px1->draw($filenamenb, $fileurlnb); print $px1->show(); - + print $stringtoshow; } } @@ -295,7 +295,7 @@ if ($result) { $i = 0; - $transRecordedType = $langs->trans("LastNewTickets", $max); + $transRecordedType = $langs->trans("LatestNewTickets", $max); print ''; print ''; print ''; @@ -347,7 +347,7 @@ if ($result) { $db->free(); } else { - print ''; + print ''; } print "
    ' . $transRecordedType . '' . $langs->trans('Ref') . '
    ' . $langs->trans('NoTicketsFound') . '
    ' . $langs->trans('NoTicketsFound') . '
    "; diff --git a/htdocs/ticketsup/list.php b/htdocs/ticketsup/list.php index 43c405c5578..ea56c133b6b 100644 --- a/htdocs/ticketsup/list.php +++ b/htdocs/ticketsup/list.php @@ -34,7 +34,6 @@ if (!empty($conf->projet->enabled)) { include_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php'; } -// Load traductions files requiredby by page // Load traductions files requiredby by page $langs->loadLangs( array( @@ -60,7 +59,7 @@ $id = GETPOST('id','int'); $msg_id = GETPOST('msg_id', 'int'); $socid = GETPOST('socid', 'int'); $projectid = GETPOST('projectid', 'int'); - +$search_fk_status = GETPOST('search_fk_status', 'alpha'); $mode = GETPOST('mode', 'alpha'); // Load variable for pagination @@ -186,16 +185,15 @@ if (empty($reshook)) } -/*************************************************** - * PAGE - * - * Put here all code to build page - ****************************************************/ + +/* + * View + */ + $help_url = 'FR:DocumentationModuleTicket'; llxHeader('', $langs->trans('TicketList'), $help_url); $form = new Form($db); - $formTicket = new FormTicketsup($db); $user_assign = new User($db); @@ -203,9 +201,6 @@ $user_create = new User($db); $socstatic = new Societe($db); -$search_fk_status = GETPOST('search_fk_status', 'alpha'); - - // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; @@ -447,7 +442,7 @@ print ''; print_barre_liste($langs->trans('TicketList'), $page, 'list.php', $param, $sortfield, $sortorder, '', $num, $num_total, 'img/ticketsup-32.png', 1); if ($mode == 'my_assign') { - print '
    ' . $langs->trans('TicketAssignedToMeInfos') . '
    '; + print '
    ' . $langs->trans('TicketAssignedToMeInfos') . '

    '; } // Add code for pre mass action (confirmation or email presend form) $topicmail="SendTicketsupRef"; diff --git a/htdocs/ticketsup/new.php b/htdocs/ticketsup/new.php index 18e8fbf5a17..3d1a3c7c9f2 100644 --- a/htdocs/ticketsup/new.php +++ b/htdocs/ticketsup/new.php @@ -1,6 +1,6 @@ - * 2016 Christophe Battarel +/* Copyright (C) 2013-2016 Jean-François FERRY + * Copyright (C) 2016 Christophe Battarel * * 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 @@ -50,13 +50,19 @@ if (!$user->rights->ticketsup->read || !$user->rights->ticketsup->write) { $object = new ActionsTicketsup($db); + +/* + * Actions + */ + $object->doActions($action); -/*************************************************** - * PAGE - * - * Put here all code to build page - ****************************************************/ + + +/* + * View + */ + $help_url = 'FR:DocumentationModuleTicket'; $page_title = $object->getTitle($action); llxHeader('', $page_title, $help_url); @@ -85,11 +91,6 @@ if ($action == 'create_ticket') { $formticket->showForm(); } -/*************************************************** - * LINKED OBJECT BLOCK - * - * Put here code to view linked object - ****************************************************/ //$somethingshown=$object->showLinkedObjectBlock(); // End of page diff --git a/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php b/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php index dc03dd32c3c..824f392d638 100644 --- a/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php +++ b/htdocs/ticketsup/tpl/linkedobjectblock.tpl.php @@ -29,7 +29,7 @@ if (empty($conf) || ! is_object($conf)) load('ticketsup@ticketsup'); +$langs->load('ticketsup'); $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; echo '
    '; print_titre($langs->trans('RelatedTickets')); @@ -47,7 +47,7 @@ foreach ($linkedObjectBlock as $object) { subject) ? ' '.$object->subject : ''); ?> + trans("ShowTicket"), "ticketsup") . ' ' . (! empty($object->subject) ? ' '.$object->subject : ''); ?> datec, 'day'); ?> From 478b3dfa427ed306088d3cb81945d0725c672177 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Mon, 12 Mar 2018 08:34:47 +0100 Subject: [PATCH 228/413] Update llx_ticketsup.sql --- htdocs/install/mysql/tables/llx_ticketsup.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/install/mysql/tables/llx_ticketsup.sql b/htdocs/install/mysql/tables/llx_ticketsup.sql index f79cda97712..aeb5d41814d 100644 --- a/htdocs/install/mysql/tables/llx_ticketsup.sql +++ b/htdocs/install/mysql/tables/llx_ticketsup.sql @@ -37,6 +37,6 @@ CREATE TABLE llx_ticketsup datec datetime, date_read datetime, date_close datetime, - notify_tiers_at_create, + notify_tiers_at_create tinyint, tms timestamp )ENGINE=innodb; From 98320ffad29dc4791f7dbb522f80b72cc7f51ed0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Mon, 12 Mar 2018 08:36:18 +0100 Subject: [PATCH 229/413] Update 7.0.0-8.0.0.sql --- htdocs/install/mysql/migration/7.0.0-8.0.0.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 37e22e182a7..67f18f374f0 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -143,6 +143,7 @@ CREATE TABLE llx_ticketsup datec datetime, date_read datetime, date_close datetime, + notify_tiers_at_create tinyint, tms timestamp )ENGINE=innodb; From 98b7d4c2e29174838ec0de29ce435fa6a22692e8 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 12 Mar 2018 12:27:40 +0100 Subject: [PATCH 230/413] NEW Can set the start/end date of service line in invoice templates --- htdocs/compta/facture/card.php | 35 +++++++------ .../facture/class/facture-rec.class.php | 33 +++++++++--- htdocs/compta/facture/class/facture.class.php | 41 +++++++++++---- htdocs/compta/facture/fiche-rec.php | 52 +++++-------------- htdocs/core/tpl/objectline_create.tpl.php | 30 +++++++++-- htdocs/core/tpl/objectline_edit.tpl.php | 27 ++++++++-- htdocs/core/tpl/objectline_view.tpl.php | 30 ++++++----- .../install/mysql/migration/7.0.0-8.0.0.sql | 3 ++ .../mysql/tables/llx_facturedet_rec.sql | 2 + htdocs/langs/en_US/bills.lang | 4 ++ htdocs/theme/eldy/style.css.php | 4 +- htdocs/theme/md/style.css.php | 3 ++ 12 files changed, 171 insertions(+), 93 deletions(-) diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 90bc80a6a19..1dd7dab2de8 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -553,7 +553,7 @@ if (empty($reshook)) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) ) { - $idwarehouse = GETPOST('idwarehouse'); + $idwarehouse = GETPOST('idwarehouse','int'); $object->fetch($id); $object->fetch_thirdparty(); @@ -640,8 +640,8 @@ if (empty($reshook)) else if ($action == 'confirm_paid_partially' && $confirm == 'yes' && $user->rights->facture->paiement) { $object->fetch($id); - $close_code = $_POST["close_code"]; - $close_note = $_POST["close_note"]; + $close_code = GETPOST("close_code",'none'); + $close_note = GETPOST("close_note",'none'); if ($close_code) { $result = $object->set_paid($user, $close_code, $close_note); if ($result<0) setEventMessages($object->error, $object->errors, 'errors'); @@ -651,8 +651,8 @@ if (empty($reshook)) } // Classify "abandoned" else if ($action == 'confirm_canceled' && $confirm == 'yes') { $object->fetch($id); - $close_code = $_POST["close_code"]; - $close_note = $_POST["close_note"]; + $close_code = GETPOST("close_code",'none'); + $close_note = GETPOST("close_note",'none'); if ($close_code) { $result = $object->set_canceled($user, $close_code, $close_note); if ($result<0) setEventMessages($object->error, $object->errors, 'errors'); @@ -1419,6 +1419,7 @@ if (empty($reshook)) } } + // Situation invoices if (GETPOST('type') == Facture::TYPE_SITUATION && (!empty($_POST['situations']))) { $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); @@ -1455,16 +1456,16 @@ if (empty($reshook)) $object->fetch_thirdparty(); $object->date = $datefacture; $object->date_pointoftax = $date_pointoftax; - $object->note_public = trim($_POST['note_public']); - $object->note = trim($_POST['note']); - $object->ref_client = $_POST['ref_client']; - $object->ref_int = $_POST['ref_int']; - $object->modelpdf = $_POST['model']; - $object->fk_project = $_POST['projectid']; - $object->cond_reglement_id = $_POST['cond_reglement_id']; - $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->remise_absolue = $_POST['remise_absolue']; - $object->remise_percent = $_POST['remise_percent']; + $object->note_public = trim(GETPOST('note_public','none')); + $object->note = trim(GETPOST('note','none')); + $object->ref_client = GETPOST('ref_client','alpha'); + $object->ref_int = GETPOST('ref_int','alpha'); + $object->modelpdf = GETPOST('model','alpha'); + $object->fk_project = GETPOST('projectid','int'); + $object->cond_reglement_id = GETPOST('cond_reglement_id','int'); + $object->mode_reglement_id = GETPOST('mode_reglement_id','int'); + $object->remise_absolue = GETPOST('remise_absolue','int'); + $object->remise_percent = GETPOST('remise_percent','int'); // Proprietes particulieres a facture de remplacement @@ -1533,14 +1534,14 @@ if (empty($reshook)) // Set if we used free entry or predefined product $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + $product_desc=(GETPOST('dp_desc','none')?GETPOST('dp_desc','none'):''); $price_ht = GETPOST('price_ht'); $price_ht_devise = GETPOST('multicurrency_price_ht'); $prod_entry_mode = GETPOST('prod_entry_mode','alpha'); if ($prod_entry_mode == 'free') { $idprod=0; - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + $tva_tx = (GETPOST('tva_tx','alpha') ? GETPOST('tva_tx','alpha') : 0); } else { diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index c36e6cb09d1..630433324c4 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -439,7 +439,7 @@ class FactureRec extends CommonInvoice $sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx, '; $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; - $sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; + $sql.= ' l.info_bits, l.date_start_fill, l.date_end_fill, l.total_ht, l.total_tva, l.total_ttc,'; //$sql.= ' l.situation_percent, l.fk_prev_id,'; //$sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,'; $sql.= ' l.rang, l.special_code,'; @@ -487,6 +487,8 @@ class FactureRec extends CommonInvoice $line->remise_percent = $objp->remise_percent; $line->fk_remise_except = $objp->fk_remise_except; $line->fk_product = $objp->fk_product; + $line->date_start_fill = $objp->date_start_fill; + $line->date_end_fill = $objp->date_end_fill; $line->info_bits = $objp->info_bits; $line->total_ht = $objp->total_ht; $line->total_tva = $objp->total_tva; @@ -602,15 +604,17 @@ class FactureRec extends CommonInvoice * @param string $label Label of the line * @param string $fk_unit Unit * @param double $pu_ht_devise Unit price in currency + * @param int $date_start_fill 1=Flag to fill start date when generating invoice + * @param int $date_end_fill 1=Flag to fill end date when generating invoice * @return int <0 if KO, Id of line if OK */ - function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise=0) + function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise=0, $date_start_fill=0, $date_end_fill=0) { global $mysoc; $facid=$this->id; - dol_syslog(get_class($this)."::addline facid=$facid,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva,txlocaltax1=$txlocaltax1,txlocaltax2=$txlocaltax2,fk_product=$fk_product,remise_percent=$remise_percent,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type,fk_unit=$fk_unit,pu_ht_devise=$pu_ht_devise", LOG_DEBUG); + dol_syslog(get_class($this)."::addline facid=$facid,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva,txlocaltax1=$txlocaltax1,txlocaltax2=$txlocaltax2,fk_product=$fk_product,remise_percent=$remise_percent,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type,fk_unit=$fk_unit,pu_ht_devise=$pu_ht_devise,date_start_fill=$date_start_fill,date_end_fill=$date_end_fill", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Check parameters @@ -700,6 +704,8 @@ class FactureRec extends CommonInvoice $sql.= ", total_localtax1"; $sql.= ", total_localtax2"; $sql.= ", total_ttc"; + $sql.= ", date_start_fill"; + $sql.= ", date_end_fill"; $sql.= ", info_bits"; $sql.= ", rang"; $sql.= ", special_code"; @@ -727,6 +733,8 @@ class FactureRec extends CommonInvoice $sql.= ", ".price2num($total_localtax1); $sql.= ", ".price2num($total_localtax2); $sql.= ", ".price2num($total_ttc); + $sql.= ", ".(int) $date_start_fill; + $sql.= ", ".(int) $date_end_fill; $sql.= ", ".$info_bits; $sql.= ", ".$rang; $sql.= ", ".$special_code; @@ -778,9 +786,11 @@ class FactureRec extends CommonInvoice * @param string $fk_unit Unit * @param double $pu_ht_devise Unit price in currency * @param int $notrigger disable line update trigger + * @param int $date_start_fill 1=Flag to fill start date when generating invoice + * @param int $date_end_fill 1=Flag to fill end date when generating invoice * @return int <0 if KO, Id of line if OK */ - function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise = 0, $notrigger=0) + function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise = 0, $notrigger=0, $date_start_fill=0, $date_end_fill=0) { global $mysoc; @@ -883,6 +893,8 @@ class FactureRec extends CommonInvoice $sql.= ", total_localtax1='".price2num($total_localtax1)."'"; $sql.= ", total_localtax2='".price2num($total_localtax2)."'"; $sql.= ", total_ttc='".price2num($total_ttc)."'"; + $sql.= ", date_start_fill=".((int) $date_start_fill); + $sql.= ", date_end_fill=".((int) $date_end_fill); $sql.= ", info_bits=".$info_bits; $sql.= ", rang=".$rang; $sql.= ", special_code=".$special_code; @@ -948,7 +960,7 @@ class FactureRec extends CommonInvoice * Create all recurrents invoices (for all entities if multicompany is used). * A result may also be provided into this->output. * - * WARNING: This method change context $conf->entity to be in correct context for each recurring invoice found. + * WARNING: This method change temporarly context $conf->entity to be in correct context for each recurring invoice found. * * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK) */ @@ -1561,6 +1573,10 @@ class FactureLigneRec extends CommonInvoiceLine public $element='facturedetrec'; public $table_element='facturedet_rec'; + var $date_start_fill; + var $date_end_fill; + + /** * Delete line in database * @@ -1615,7 +1631,7 @@ class FactureLigneRec extends CommonInvoiceLine { $sql = 'SELECT l.rowid, l.fk_facture ,l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; - $sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; + $sql.= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; $sql.= ' l.rang, l.special_code,'; $sql.= ' l.fk_unit, l.fk_contract_line,'; $sql.= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc'; @@ -1655,6 +1671,8 @@ class FactureLigneRec extends CommonInvoiceLine $this->remise_percent = $objp->remise_percent; $this->fk_remise_except = $objp->fk_remise_except; $this->fk_product = $objp->fk_product; + $this->date_start_fill = $objp->date_start_fill; + $this->date_end_fill = $objp->date_end_fill; $this->info_bits = $objp->info_bits; $this->total_ht = $objp->total_ht; $this->total_tva = $objp->total_tva; @@ -1711,6 +1729,9 @@ class FactureLigneRec extends CommonInvoiceLine $sql.= ", product_type=".$this->product_type; $sql.= ", remise_percent='".price2num($this->remise_percent)."'"; $sql.= ", subprice='".price2num($this->subprice)."'"; + $sql.= ", info_bits='".price2num($this->info_bits)."'"; + $sql.= ", date_start_fill=".(int) $this->date_start_fill; + $sql.= ", date_end_fill=".(int) $this->date_end_fill; $sql.= ", total_ht='".price2num($this->total_ht)."'"; $sql.= ", total_tva='".price2num($this->total_tva)."'"; $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'"; diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 1939aa0e62f..8aca7562654 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -287,6 +287,10 @@ class Facture extends CommonInvoice $this->db->begin(); + $originaldatewhen=null; + $nextdatewhen=null; + $previousdaynextdatewhen=null; + // Create invoice from a template invoice if ($this->fac_rec > 0) { @@ -297,7 +301,10 @@ class Facture extends CommonInvoice $result=$_facrec->fetch($this->fac_rec); $result=$_facrec->fetchObjectLinked(); // This load $_facrec->linkedObjectsIds + // Define some dates $originaldatewhen = $_facrec->date_when; + $nextdatewhen=dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency); + $previousdaynextdatewhen=dol_time_plus_duree($nextdatewhen, -1, 'd'); $this->socid = $_facrec->socid; // Invoice created on same thirdparty than template $this->entity = $_facrec->entity; // Invoice created in same entity than template @@ -374,7 +381,8 @@ class Facture extends CommonInvoice $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y'); // Only for tempalte invoice $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = dol_print_date($originaldatewhen, 'dayhour'); - $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date(dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency), 'dayhour'); + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($nextdatewhen, 'dayhour'); + $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($previousdaynextdatewhen, 'dayhour'); //var_dump($substitutionarray);exit; @@ -494,6 +502,7 @@ class Facture extends CommonInvoice } } + // Propagate contacts if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id)) // Get contact from origin object { $originforcontact = $this->origin; @@ -531,11 +540,10 @@ class Facture extends CommonInvoice else dol_print_error($resqlcontact); } - /* - * Insert lines of invoices into database + * Insert lines of invoices, if not from template invoice, into database */ - if (count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode) + if (! $error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode) { $fk_parent_line = 0; @@ -545,9 +553,18 @@ class Facture extends CommonInvoice $newinvoiceline=$this->lines[$i]; $newinvoiceline->fk_facture=$this->id; - // TODO This seems not used. Here we put origin 'facture' but after, we put an id of object ! - $newinvoiceline->origin = $this->element; - $newinvoiceline->origin_id = $this->lines[$i]->id; + $newinvoiceline->origin = $this->lines[$i]->element; + $newinvoiceline->origin_id = $this->lines[$i]->id; + + // Auto set date of service ? + if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) // $originaldatewhen is defined when generating from recurring invoice only + { + $newinvoiceline->date_start = $originaldatewhen; + } + if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) // $previousdaynextdatewhen is defined when generating from recurring invoice only + { + $newinvoiceline->date_end = $previousdaynextdatewhen; + } if ($result >= 0) { @@ -581,7 +598,7 @@ class Facture extends CommonInvoice } } } - else // If this->lines is an array of invoice line arrays + elseif (! $error && empty($this->fac_rec)) // If this->lines is an array of invoice line arrays { $fk_parent_line = 0; @@ -689,7 +706,9 @@ class Facture extends CommonInvoice $localtax2_tx, $_facrec->lines[$i]->fk_product, $_facrec->lines[$i]->remise_percent, - '','',0, + ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen)?$originaldatewhen:'', + ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen)?$previousdaynextdatewhen:'', + 0, $tva_npr, '', 'HT', @@ -2522,8 +2541,8 @@ class Facture extends CommonInvoice * @param double $txlocaltax2 Local tax 2 rate (deprecated, use instead txtva with code inside) * @param int $fk_product Id of predefined product/service * @param double $remise_percent Percent of discount on line - * @param int $date_start Date start of service - * @param int $date_end Date end of service + * @param int $date_start Date start of service + * @param int $date_end Date end of service * @param int $ventil Code of dispatching into accountancy * @param int $info_bits Bits de type de lignes * @param int $fk_remise_except Id discount used diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php index 8d955f1141d..6f96e74d345 100644 --- a/htdocs/compta/facture/fiche-rec.php +++ b/htdocs/compta/facture/fiche-rec.php @@ -66,22 +66,8 @@ if ($action == "create" || $action == "add") $objecttype = ''; $result = restrictedArea($user, 'facture', $id, $objecttype); $projectid = GETPOST('projectid','int'); -$search_ref=GETPOST('search_ref'); -$search_societe=GETPOST('search_societe'); -$search_montant_ht=GETPOST('search_montant_ht'); -$search_montant_vat=GETPOST('search_montant_vat'); -$search_montant_ttc=GETPOST('search_montant_ttc'); -$search_payment_mode=GETPOST('search_payment_mode'); -$search_payment_term=GETPOST('search_payment_term'); -$day=GETPOST('day'); -$year=GETPOST('year'); -$month=GETPOST('month'); -$day_date_when=GETPOST('day_date_when'); $year_date_when=GETPOST('year_date_when'); $month_date_when=GETPOST('month_date_when'); -$search_recurring=GETPOST('search_recurring','int'); -$search_frequency=GETPOST('search_frequency','alpha'); -$search_unit_frequency=GETPOST('search_unit_frequency','alpha'); $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); @@ -144,28 +130,6 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - // Do we click on purge search criteria ? - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers - { - $search_ref=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_montant_mode=''; - $search_montant_term=''; - $day=''; - $year=''; - $month=''; - $day_date_when=''; - $year_date_when=''; - $month_date_when=''; - $search_recurring=''; - $search_frequency=''; - $search_unit_frequency=''; - $search_array_options=array(); - } - // Mass actions /*$objectclass='MyObject'; $objectlabel='MyObject'; @@ -686,6 +650,9 @@ if (empty($reshook)) $fk_unit= GETPOST('units', 'alpha'); } + $date_start_fill = GETPOST('date_start_fill','int'); + $date_end_fill = GETPOST('date_end_fill','int'); + // Margin $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value @@ -706,7 +673,7 @@ if (empty($reshook)) else { // Insert line - $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit); + $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit, 0, $date_start_fill, $date_end_fill); if ($result > 0) { @@ -762,6 +729,9 @@ if (empty($reshook)) unset($_POST['date_endmonth']); unset($_POST['date_endyear']); + unset($_POST['date_start_fill']); + unset($_POST['date_end_fill']); + unset($_POST['situations']); unset($_POST['progress']); } @@ -883,6 +853,9 @@ if (empty($reshook)) $error ++; } + $date_start_fill = GETPOST('date_start_fill','int'); + $date_end_fill = GETPOST('date_end_fill','int'); + // Update line if (! $error) { @@ -905,7 +878,10 @@ if (empty($reshook)) $special_code, $label, GETPOST('units'), - $pu_ht_devise + $pu_ht_devise, + 0, + $date_start_fill, + $date_end_fill ); if ($result >= 0) diff --git a/htdocs/core/tpl/objectline_create.tpl.php b/htdocs/core/tpl/objectline_create.tpl.php index 501e3db3d6c..e2dfed0f68b 100644 --- a/htdocs/core/tpl/objectline_create.tpl.php +++ b/htdocs/core/tpl/objectline_create.tpl.php @@ -283,6 +283,18 @@ else { if (! empty($conf->global->FCKEDITOR_ENABLE_DETAILS_FULL)) $toolbarname='dolibarr_notes'; $doleditor=new DolEditor('dp_desc',GETPOST('dp_desc'),'',100,$toolbarname,'',false,true,$enabled,$nbrows,'98%'); $doleditor->Create(); + + // Show autofill date for recuring invoices + if (! empty($conf->service->enabled) && $object->element == 'facturerec') + { + echo '

    '; + echo $langs->trans('AutoFillDateFrom').' '; + echo $form->selectyesno('date_start_fill', $line->date_start_fill, 1); + echo ' - '; + echo $langs->trans('AutoFillDateTo').' '; + echo $form->selectyesno('date_end_fill', $line->date_end_fill, 1); + echo '
    '; + } ?> @@ -594,8 +606,17 @@ jQuery(document).ready(function() { if (editor) { editor.focus(); } } } - if (jQuery('#select_type').val() == '0') jQuery('#trlinefordates').hide(); - else jQuery('#trlinefordates').show(); + console.log("Hide/show date according to product type"); + if (jQuery('#select_type').val() == '0') + { + jQuery('#trlinefordates').hide(); + jQuery('.divlinefordates').hide(); + } + else + { + jQuery('#trlinefordates').show(); + jQuery('.divlinefordates').show(); + } }); $("#prod_entry_mode_predef").on( "click", function() { @@ -799,7 +820,7 @@ function setforfree() { jQuery("#units, #title_units").show(); } function setforpredef() { - console.log("Call setforpredef. We hide some fields"); + console.log("Call setforpredef. We hide some fields and show dates"); jQuery("#select_type").val(-1); jQuery("#prod_entry_mode_free").prop('checked',false).change(); @@ -820,6 +841,9 @@ function setforpredef() { jQuery(".np_marginRate").hide(); // May no exists jQuery(".np_markRate").hide(); // May no exists jQuery("#units, #title_units").hide(); + + jQuery('#trlinefordates').show(); + jQuery('.divlinefordates').show(); } diff --git a/htdocs/core/tpl/objectline_edit.tpl.php b/htdocs/core/tpl/objectline_edit.tpl.php index 67adba3a2ae..30b4f01cfb8 100644 --- a/htdocs/core/tpl/objectline_edit.tpl.php +++ b/htdocs/core/tpl/objectline_edit.tpl.php @@ -62,7 +62,10 @@ if (!empty($conf->multicurrency->enabled)) $colspan+=2; $coldisplay=-1; // We remove first td ?> > - global->MAIN_VIEW_LINE_NUMBER) ? ' colspan="2"' : ''); ?>>global->MAIN_VIEW_LINE_NUMBER))?2:1; ?> + global->MAIN_VIEW_LINE_NUMBER)) { ?> + + +
    @@ -83,7 +86,7 @@ $coldisplay=-1; // We remove first td echo ' - '.nl2br($line->product_label); ?> -
    +

    @@ -110,6 +113,18 @@ $coldisplay=-1; // We remove first td } else { print ''; } + + // Show autofill date for recuring invoices + if (! empty($conf->service->enabled) && $line->product_type == 1 && $line->element == 'facturedetrec') + { + echo '
    '; + echo $langs->trans('AutoFillDateFrom').' '; + echo $form->selectyesno('date_start_fill', $line->date_start_fill, 1); + echo ' - '; + echo $langs->trans('AutoFillDateTo').' '; + echo $form->selectyesno('date_end_fill', $line->date_end_fill, 1); + } + ?> @@ -117,7 +132,7 @@ $coldisplay=-1; // We remove first td if ($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') // We must have same test in printObjectLines { ?> - + service->enabled) && $line->product_type == 1 && $dateSelector) { ?> > + global->MAIN_VIEW_LINE_NUMBER)) { ?> + + trans('ServiceLimitedDuration').' '.$langs->trans('From').' '; ?> global->MAIN_USE_HOURMIN_IN_DATE_RANGE)?$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE:''); @@ -264,7 +282,8 @@ $coldisplay=-1; // We remove first td ?> - + '; diff --git a/htdocs/loan/createschedule.php b/htdocs/loan/createschedule.php index 70688461ae9..4ab2499c265 100644 --- a/htdocs/loan/createschedule.php +++ b/htdocs/loan/createschedule.php @@ -22,14 +22,11 @@ */ require '../main.inc.php'; - require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/loan.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php'; -global $user; - $loanid = GETPOST('loanid', 'int'); $action = GETPOST('action','aZ09'); @@ -107,6 +104,7 @@ $(document).ready(function() { var idcap=echeance-1; idcap = '#hi_capital'+idcap; var capital=$(idcap).val(); + console.log("Change montly amount echeance="+echeance+" idcap="+idcap+" capital="+capital); $.ajax({ dataType: 'json', url: 'calcmens.php', @@ -135,50 +133,59 @@ $(document).ready(function() { print '
    '; print ''; print ''; -if(count($echeance->lines)>0){ +if(count($echeance->lines)>0) +{ print ''; }else{ print ''; } print ''; print ''; -print '"; +print ''; print ''; print ''; -Print ''; -Print ''; -Print ''; -Print ''; -Print ''; -print ''; +Print ''; +Print ''; +Print ''; +Print ''; +Print ''; +print ''."\n"; if ($object->nbterm > 0 && count($echeance->lines)==0) { $i=1; $capital = $object->capital; - while($i <$object->nbterm+1){ - $mens = round($echeance->calc_mens($capital, $object->rate/100, $object->nbterm-$i+1),2,PHP_ROUND_HALF_UP); + while($i <$object->nbterm+1) + { + $mens = price2num($echeance->calc_mens($capital, $object->rate/100, $object->nbterm-$i+1), 'MT'); $int = ($capital*($object->rate/12))/100; - $int = round($int,2,PHP_ROUND_HALF_UP); - $cap_rest = round($capital - ($mens-$int),2,PHP_ROUND_HALF_UP); + $int = price2num($int, 'MT'); + $cap_rest = price2num($capital - ($mens-$int), 'MT'); print ''; print ''; print ''; print ''; print ''; print ''; - print ''; + print ''."\n"; $i++; $capital = $cap_rest; } -}elseif(count($echeance->lines)>0){ +} +elseif(count($echeance->lines)>0) +{ $i=1; $capital = $object->capital; foreach ($echeance->lines as $line){ $mens = $line->amount_capital+$line->amount_insurance+$line->amount_interest; $int = $line->amount_interest; - $cap_rest = round($capital - ($mens-$int),2,PHP_ROUND_HALF_UP); + $cap_rest = price2num($capital - ($mens-$int), 'MT'); print ''; print ''; print ''; @@ -189,7 +196,7 @@ if ($object->nbterm > 0 && count($echeance->lines)==0) } print ''; print ''; - print ''; + print ''."\n"; $i++; $capital = $cap_rest; } From d045dca00395744468395bbebc39b25417beb05a Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 12 Mar 2018 20:03:32 +0100 Subject: [PATCH 249/413] Fix financial commitment --- htdocs/loan/card.php | 4 +-- htdocs/loan/createschedule.php | 45 ++++++++++++++++++++-------------- 2 files changed, 28 insertions(+), 21 deletions(-) diff --git a/htdocs/loan/card.php b/htdocs/loan/card.php index f44316ba45d..b6bb7ce81bf 100644 --- a/htdocs/loan/card.php +++ b/htdocs/loan/card.php @@ -422,11 +422,11 @@ if ($id > 0) print ''; diff --git a/htdocs/loan/createschedule.php b/htdocs/loan/createschedule.php index 70688461ae9..4ab2499c265 100644 --- a/htdocs/loan/createschedule.php +++ b/htdocs/loan/createschedule.php @@ -22,14 +22,11 @@ */ require '../main.inc.php'; - require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/loan.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php'; -global $user; - $loanid = GETPOST('loanid', 'int'); $action = GETPOST('action','aZ09'); @@ -107,6 +104,7 @@ $(document).ready(function() { var idcap=echeance-1; idcap = '#hi_capital'+idcap; var capital=$(idcap).val(); + console.log("Change montly amount echeance="+echeance+" idcap="+idcap+" capital="+capital); $.ajax({ dataType: 'json', url: 'calcmens.php', @@ -135,50 +133,59 @@ $(document).ready(function() { print ''; print ''; print ''; -if(count($echeance->lines)>0){ +if(count($echeance->lines)>0) +{ print ''; }else{ print ''; } print '
    ' . "Création d'échéancier'; +print $langs->trans("FinancialCommitment"); +print '
    Echéance Date Montant Intérêts Capital restant du
    '.$langs->trans("DueDate").''.$langs->trans("Date").''.$langs->trans("Amount").''.$langs->trans("InterestAmount").''.$langs->trans("Remain"); +print ' ('.price2num($object->capital).')'; +print ''; +print '
    ' . $i .'' . dol_print_date(dol_time_plus_duree($object->datestart, $i-1, 'm'),'day') . ''.price($int,0,'',1).' €'.price($cap_rest).' €
    ' . $i .'' . dol_print_date($line->datep,'day') . ''.price($int,0,'',1).' €'.price($cap_rest).' €
    '; print ''; -print '"; +print ''; print ''; print ''; -Print ''; -Print ''; -Print ''; -Print ''; -Print ''; -print ''; +Print ''; +Print ''; +Print ''; +Print ''; +Print ''; +print ''."\n"; if ($object->nbterm > 0 && count($echeance->lines)==0) { $i=1; $capital = $object->capital; - while($i <$object->nbterm+1){ - $mens = round($echeance->calc_mens($capital, $object->rate/100, $object->nbterm-$i+1),2,PHP_ROUND_HALF_UP); + while($i <$object->nbterm+1) + { + $mens = price2num($echeance->calc_mens($capital, $object->rate/100, $object->nbterm-$i+1), 'MT'); $int = ($capital*($object->rate/12))/100; - $int = round($int,2,PHP_ROUND_HALF_UP); - $cap_rest = round($capital - ($mens-$int),2,PHP_ROUND_HALF_UP); + $int = price2num($int, 'MT'); + $cap_rest = price2num($capital - ($mens-$int), 'MT'); print ''; print ''; print ''; print ''; print ''; print ''; - print ''; + print ''."\n"; $i++; $capital = $cap_rest; } -}elseif(count($echeance->lines)>0){ +} +elseif(count($echeance->lines)>0) +{ $i=1; $capital = $object->capital; foreach ($echeance->lines as $line){ $mens = $line->amount_capital+$line->amount_insurance+$line->amount_interest; $int = $line->amount_interest; - $cap_rest = round($capital - ($mens-$int),2,PHP_ROUND_HALF_UP); + $cap_rest = price2num($capital - ($mens-$int), 'MT'); print ''; print ''; print ''; @@ -189,7 +196,7 @@ if ($object->nbterm > 0 && count($echeance->lines)==0) } print ''; print ''; - print ''; + print ''."\n"; $i++; $capital = $cap_rest; } From f2bba8fb03f3c6e015cb02d8259f40f48c495f36 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 12 Mar 2018 20:11:34 +0100 Subject: [PATCH 250/413] Fix translation --- htdocs/langs/en_US/loan.lang | 4 +++- htdocs/loan/card.php | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/htdocs/langs/en_US/loan.lang b/htdocs/langs/en_US/loan.lang index d00b11738be..9aae3869cc3 100644 --- a/htdocs/langs/en_US/loan.lang +++ b/htdocs/langs/en_US/loan.lang @@ -50,4 +50,6 @@ ConfigLoan=Configuration of the module loan LOAN_ACCOUNTING_ACCOUNT_CAPITAL=Accounting account capital by default LOAN_ACCOUNTING_ACCOUNT_INTEREST=Accounting account interest by default LOAN_ACCOUNTING_ACCOUNT_INSURANCE=Accounting account insurance by default -CreateCalcSchedule=Créer / Modifier échéancier de pret +FinancialCommitment=Financial commitment +CreateCalcSchedule=Edit financial commitment +InterestAmount=Interest amount diff --git a/htdocs/loan/card.php b/htdocs/loan/card.php index faa109181da..06e0066968d 100644 --- a/htdocs/loan/card.php +++ b/htdocs/loan/card.php @@ -692,7 +692,7 @@ if ($id > 0) $total_insurance = 0; $total_interest = 0; $total_capital = 0; - print '
    ' . "Création d'échéancier'; +print $langs->trans("FinancialCommitment"); +print '
    Echéance Date Montant Intérêts Capital restant du
    '.$langs->trans("DueDate").''.$langs->trans("Date").''.$langs->trans("Amount").''.$langs->trans("InterestAmount").''.$langs->trans("Remain"); +print ' ('.price2num($object->capital).')'; +print ''; +print '
    ' . $i .'' . dol_print_date(dol_time_plus_duree($object->datestart, $i-1, 'm'),'day') . ''.price($int,0,'',1).' €'.price($cap_rest).' €
    ' . $i .'' . dol_print_date($line->datep,'day') . ''.price($int,0,'',1).' €'.price($cap_rest).' €
    '; + print '
    '; print ''; print ''; print ''; @@ -729,7 +729,9 @@ if ($id > 0) $staytopay = $object->capital - $totalpaid; print ''; - print ''; + print ''; } print "
    '.$langs->trans("RefPayment").''.$langs->trans("Date").'
    '.$langs->trans("RemainderToPay").' :'.price($staytopay, 0, $langs, 0, 0, -1, $conf->currency).'
    '; + print price($staytopay, 0, $langs, 0, 0, -1, $conf->currency); + print '
    "; $db->free($resql); From 717a1daf28ad5a9bdcf6c98a6be5d879a34d24af Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 12 Mar 2018 20:26:47 +0100 Subject: [PATCH 251/413] Fix sql injection --- htdocs/ticketsup/class/ticketsup.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index b76cb9a0861..34fc63f8366 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -894,12 +894,12 @@ class Ticketsup extends CommonObject if (!$error) { $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ticketsup_logs"; - $sql .= " WHERE fk_track_id = '" . $this->track_id . "'"; + $sql .= " WHERE fk_track_id = '" . $this->db->escape($this->track_id) . "'"; $resql = $this->db->query($sql); } if (!$error) { $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ticketsup_msg"; - $sql .= " WHERE fk_track_id = '" . $this->track_id . "'"; + $sql .= " WHERE fk_track_id = '" . $this->db->escape($this->track_id) . "'"; $resql = $this->db->query($sql); } From 56d023165ef43997461f5ea9b0ae988282c44552 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Mon, 12 Mar 2018 20:43:38 +0100 Subject: [PATCH 252/413] Update ticketsup.class.php --- htdocs/ticketsup/class/ticketsup.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index 34fc63f8366..0e8e7e71574 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -2262,7 +2262,7 @@ class Ticketsup extends CommonObject * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...) * @return array Array of contacts */ - function liste_contact($statut = -1, $source = 'external', $list = 0, $code = '') + function listeContact($statut = -1, $source = 'external', $list = 0, $code = '') { global $langs; From 08bca60ae2c03ca79e4d89ee529b051f8253e60c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Mon, 12 Mar 2018 20:52:39 +0100 Subject: [PATCH 253/413] Update ticketsup.class.php --- htdocs/ticketsup/class/ticketsup.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index 0e8e7e71574..f1f23b09dcd 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -341,8 +341,8 @@ class Ticketsup extends CommonObject $sql .= " " . (!isset($this->fk_soc) ? '0' : "'" . $this->db->escape($this->fk_soc) . "'") . ","; $sql .= " " . (!isset($this->fk_project) ? '0' : "'" . $this->db->escape($this->fk_project) . "'") . ","; $sql .= " " . (!isset($this->origin_email) ? 'NULL' : "'" . $this->db->escape($this->origin_email) . "'") . ","; - $sql .= " " . ($this->fk_user_create > 0 ? ($user->id > 0 ? $user->id : 'NULL') : $this->fk_user_create) . ","; - $sql .= " " . ($this->fk_user_assign > 0 ? 'NULL' : $this->fk_user_assign) . ","; + $sql .= " " . ($this->fk_user_create > 0 ? $this->fk_user_create : ($user->id > 0 ? $user->id : 'NULL')) . ","; + $sql .= " " . ($this->fk_user_assign > 0 ? $this->fk_user_assign : 'NULL') . ","; $sql .= " " . (!isset($this->subject) ? 'NULL' : "'" . $this->db->escape($this->subject) . "'") . ","; $sql .= " " . (!isset($this->message) ? 'NULL' : "'" . $this->db->escape($this->message) . "'") . ","; $sql .= " " . (!isset($this->fk_statut) ? '0' : "'" . $this->db->escape($this->fk_statut) . "'") . ","; From 7b864aeaec14b184dbc68330dd372b6e7a8774a7 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 12 Mar 2018 21:29:03 +0100 Subject: [PATCH 254/413] Fix regression with live box --- htdocs/public/payment/newpayment.php | 2 +- htdocs/stripe/config.php | 10 ---------- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/htdocs/public/payment/newpayment.php b/htdocs/public/payment/newpayment.php index f7ceb201da5..3ad3f2d33fd 100644 --- a/htdocs/public/payment/newpayment.php +++ b/htdocs/public/payment/newpayment.php @@ -542,7 +542,7 @@ if (! empty($conf->paypal->enabled) && (! empty($conf->global->PAYPAL_API_SANDBO { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Paypal'),'','warning'); } -if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) +if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha'))) { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); } diff --git a/htdocs/stripe/config.php b/htdocs/stripe/config.php index 0e207474a51..31959b3516f 100644 --- a/htdocs/stripe/config.php +++ b/htdocs/stripe/config.php @@ -33,15 +33,6 @@ global $conf; //use \includes\stripe as stripe; $stripe = array(); -if ((empty($conf->global->STRIPECONNECT_LIVE) && ! (empty($conf->stripeconnect->enabled))) || GETPOST('forcesandbox','alpha')) -{ - $stripe = array( - "secret_key" => $conf->global->STRIPE_TEST_SECRET_KEY, - "publishable_key" => $conf->global->STRIPE_TEST_PUBLISHABLE_KEY - ); -} -else -{ if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha')) { $stripe = array( @@ -56,7 +47,6 @@ else "publishable_key" => $conf->global->STRIPE_LIVE_PUBLISHABLE_KEY ); } -} require_once DOL_DOCUMENT_ROOT."/includes/stripe/lib/Stripe.php"; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; From 01f25b00b04ecddf61093eb821f11ca99cc23a71 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 12 Mar 2018 23:43:47 +0100 Subject: [PATCH 255/413] Test --- test/phpunit/TicketsupTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/phpunit/TicketsupTest.php b/test/phpunit/TicketsupTest.php index e709a8855ca..84490d7cae7 100644 --- a/test/phpunit/TicketsupTest.php +++ b/test/phpunit/TicketsupTest.php @@ -131,11 +131,11 @@ class TicketsupTest extends PHPUnit_Framework_TestCase // Try to create one with bad values $localobject=new Ticketsup($this->savdb); $localobject->initAsSpecimen(); - $localobject->fk_statut = '\'1=1'; + $localobject->ref = ''; $result=$localobject->create($user); print __METHOD__." result=".$result."\n"; - $this->assertEquals(-1, $result, $localobject->error); + $this->assertEquals(-3, $result, $localobject->error.join(',', $localobject->errors)); // Try to create one with correct values $localobject=new Ticketsup($this->savdb); @@ -143,7 +143,7 @@ class TicketsupTest extends PHPUnit_Framework_TestCase $result=$localobject->create($user); print __METHOD__." result=".$result."\n"; - $this->assertGreaterThan(0, $result, $localobject->error); + $this->assertGreaterThan(0, $result, $localobject->error.join(',', $localobject->errors)); return $result; } From 9408a98c52af9befdfc1828e240c5a1145a4f9ef Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Tue, 13 Mar 2018 00:26:09 +0100 Subject: [PATCH 256/413] Fix SQL and ADD support LIVE/TEST mode --- htdocs/stripe/class/stripe.class.php | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 801d0e17057..3a9c8646686 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -98,12 +98,20 @@ class Stripe extends CommonObject public function getStripeCustomerAccount($id) { global $conf; - + if (empty($conf->global->STRIPECONNECT_LIVE)) { + $mode = 0; + } else { + if (empty($conf->global->STRIPE_LIVE)) { + $mode = 0; + } else { + $mode = $conf->global->STRIPE_LIVE; + } + } $sql = "SELECT sa.key_account as key_account, sa.entity"; - $sql.= " FROM " . MAIN_DB_PREFIX . "llx_societe_accounts as sa"; + $sql.= " FROM " . MAIN_DB_PREFIX . "llx_societe_account as sa"; $sql.= " WHERE sa.fk_soc = " . $id; $sql.= " AND sa.entity IN (".getEntity('societe').")"; - $sql.= " AND site = 'stripe'"; + $sql.= " AND sa.site = 'stripe' AND sa.status = ".$mode; dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $result = $this->db->query($sql); From d6be9651a0fd69f748f44cf46c45ec56beb7ce77 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Tue, 13 Mar 2018 00:29:28 +0100 Subject: [PATCH 257/413] ADD key_account variable for stripe or other gateway --- htdocs/install/mysql/tables/llx_societe_account.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/install/mysql/tables/llx_societe_account.sql b/htdocs/install/mysql/tables/llx_societe_account.sql index 9938d47bfb5..e1a421affe4 100644 --- a/htdocs/install/mysql/tables/llx_societe_account.sql +++ b/htdocs/install/mysql/tables/llx_societe_account.sql @@ -27,6 +27,7 @@ CREATE TABLE llx_societe_account( site varchar(128), -- name of external web site fk_website integer, -- id of local web site note_private text, + key_account varchar(128), date_last_login datetime, date_previous_login datetime, date_creation datetime NOT NULL, @@ -36,4 +37,4 @@ CREATE TABLE llx_societe_account( import_key varchar(14), status integer -- END MODULEBUILDER FIELDS -) ENGINE=innodb; \ No newline at end of file +) ENGINE=innodb; From 6c7a5cebdfc37ce02c3acf0088a62793fd16c087 Mon Sep 17 00:00:00 2001 From: atm-quentin Date: Tue, 13 Mar 2018 09:34:50 +0100 Subject: [PATCH 258/413] FIX check verif exped on delete order --- htdocs/commande/class/commande.class.php | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index de3a47d36d4..b450a6ad16b 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -3126,6 +3126,7 @@ class Commande extends CommonOrder if ($result < 0) $error++; // End call triggers } + if($this->nb_expedition()!=0)$error++; //TODO: Check for error after each action. If one failed we rollback, don't waste time to do action if previous fail if (! $error) From 490acd96dc060f71bfb41e53f46c135c0985b3f6 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 09:37:59 +0100 Subject: [PATCH 259/413] It is better to let the caller decide which mode (live or not) to take --- htdocs/stripe/class/stripe.class.php | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 3a9c8646686..cfeecd2bda8 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -93,25 +93,18 @@ class Stripe extends CommonObject * getStripeCustomerAccount * * @param int $id Id of third party - * @return string Stripe customer ref 'cu_xxxxxxxxxxxxx' + * @param int $status Status + * @return string Stripe customer ref 'cu_xxxxxxxxxxxxx' */ - public function getStripeCustomerAccount($id) + public function getStripeCustomerAccount($id, $status=0) { global $conf; - if (empty($conf->global->STRIPECONNECT_LIVE)) { - $mode = 0; - } else { - if (empty($conf->global->STRIPE_LIVE)) { - $mode = 0; - } else { - $mode = $conf->global->STRIPE_LIVE; - } - } + $sql = "SELECT sa.key_account as key_account, sa.entity"; $sql.= " FROM " . MAIN_DB_PREFIX . "llx_societe_account as sa"; $sql.= " WHERE sa.fk_soc = " . $id; $sql.= " AND sa.entity IN (".getEntity('societe').")"; - $sql.= " AND sa.site = 'stripe' AND sa.status = ".$mode; + $sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status); dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $result = $this->db->query($sql); From 51229a602f136f5aa9c654af6edcf43edf8588e9 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 09:51:45 +0100 Subject: [PATCH 260/413] Update commande.class.php --- htdocs/commande/class/commande.class.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index b450a6ad16b..6c156997995 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -3126,7 +3126,8 @@ class Commande extends CommonOrder if ($result < 0) $error++; // End call triggers } - if($this->nb_expedition()!=0)$error++; + + if ($this->nb_expedition() != 0) $error++; //TODO: Check for error after each action. If one failed we rollback, don't waste time to do action if previous fail if (! $error) From dcd3387a30cd57c59ab2f94d38dd2574452c647d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 09:53:21 +0100 Subject: [PATCH 261/413] Update commande.class.php --- htdocs/commande/class/commande.class.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 6c156997995..429566e054d 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -3127,8 +3127,12 @@ class Commande extends CommonOrder // End call triggers } - if ($this->nb_expedition() != 0) $error++; - + if ($this->nb_expedition() != 0) + { + $this->errors[] = $langs->trans('SomeShipmentExists'); + $error++; + } + //TODO: Check for error after each action. If one failed we rollback, don't waste time to do action if previous fail if (! $error) { From 5d512af4b4c53921fc581e8dc7ea4c2e201560bc Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 09:53:33 +0100 Subject: [PATCH 262/413] Fix migration --- htdocs/install/mysql/migration/7.0.0-8.0.0.sql | 5 +++-- .../install/mysql/tables/llx_societe_account.sql | 14 +++++++------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 1d1261edf5f..6ff739b5f40 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -235,6 +235,7 @@ CREATE TABLE llx_societe_account( -- BEGIN MODULEBUILDER FIELDS rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, entity integer DEFAULT 1, + key_account varchar(128), login varchar(128) NOT NULL, pass_encoding varchar(24) NOT NULL, pass_crypted varchar(128), @@ -255,13 +256,13 @@ CREATE TABLE llx_societe_account( ) ENGINE=innodb; --- BEGIN MODULEBUILDER INDEXES +ALTER TABLE llx_societe_account ADD COLUMN key_account varchar(128); + ALTER TABLE llx_societe_account ADD INDEX idx_societe_account_rowid (rowid); ALTER TABLE llx_societe_account ADD INDEX idx_societe_account_login (login); ALTER TABLE llx_societe_account ADD INDEX idx_societe_account_status (status); ALTER TABLE llx_societe_account ADD INDEX idx_societe_account_fk_website (fk_website); ALTER TABLE llx_societe_account ADD INDEX idx_societe_account_fk_soc (fk_soc); --- END MODULEBUILDER INDEXES ALTER TABLE llx_societe_account ADD UNIQUE INDEX uk_societe_account_login_website_soc(entity, fk_soc, login, site, fk_website); diff --git a/htdocs/install/mysql/tables/llx_societe_account.sql b/htdocs/install/mysql/tables/llx_societe_account.sql index e1a421affe4..4dd17f441ed 100644 --- a/htdocs/install/mysql/tables/llx_societe_account.sql +++ b/htdocs/install/mysql/tables/llx_societe_account.sql @@ -19,17 +19,17 @@ CREATE TABLE llx_societe_account( -- BEGIN MODULEBUILDER FIELDS rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, entity integer DEFAULT 1, + key_account varchar(128), login varchar(128) NOT NULL, - pass_encoding varchar(24) NOT NULL, - pass_crypted varchar(128), - pass_temp varchar(128), -- temporary password when asked for forget password - fk_soc integer, + pass_encoding varchar(24) NOT NULL, + pass_crypted varchar(128), + pass_temp varchar(128), -- temporary password when asked for forget password + fk_soc integer, site varchar(128), -- name of external web site fk_website integer, -- id of local web site note_private text, - key_account varchar(128), - date_last_login datetime, - date_previous_login datetime, + date_last_login datetime, + date_previous_login datetime, date_creation datetime NOT NULL, tms timestamp NOT NULL, fk_user_creat integer NOT NULL, From 4f6f0b302ef10d90ab9bdac16e6f57d73d7168d1 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Tue, 13 Mar 2018 10:28:44 +0100 Subject: [PATCH 263/413] FIX for nondisplay of fk_element 's id in REST API response the fk_element don't display when the call is made with REST API (reason non found) --- htdocs/comm/action/class/actioncomm.class.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 9e0a0d6321d..f5209421694 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -164,6 +164,7 @@ class ActionComm extends CommonObject // Properties for links to other objects var $fk_element; // Id of record + var $elementid; // Id of record alternative for API var $elementtype; // Type of record. This if property ->element of object linked to. // Ical @@ -547,7 +548,7 @@ class ActionComm extends CommonObject $sql.= " a.fk_user_author, a.fk_user_mod,"; $sql.= " a.fk_user_action, a.fk_user_done,"; $sql.= " a.fk_contact, a.percent as percentage,"; - $sql.= " a.fk_element, a.elementtype,"; + $sql.= " a.fk_element as elementid, a.elementtype,"; $sql.= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,"; $sql.= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; $sql.= " s.nom as socname,"; @@ -621,7 +622,8 @@ class ActionComm extends CommonObject $this->societe->id = $obj->fk_soc; // deprecated $this->contact->id = $obj->fk_contact; // deprecated - $this->fk_element = $obj->fk_element; + $this->fk_element = $obj->elementid; + $this->elementid = $obj->elementid; $this->elementtype = $obj->elementtype; $this->fetchResources(); From cd71e49762145eea793ae9fb383f07eb806d06e2 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 10:42:58 +0100 Subject: [PATCH 264/413] Picto ticket module --- htdocs/core/modules/modTicketsup.class.php | 20 ++++++------------ htdocs/theme/eldy/img/menus/ticketsup.png | Bin 0 -> 936 bytes .../theme/eldy/img/menus_black/ticketsup.png | Bin 0 -> 1044 bytes htdocs/theme/eldy/img/title_ticketsup.png | Bin 0 -> 1044 bytes htdocs/theme/eldy/style.css.php | 11 +++++++--- htdocs/theme/md/img/ticketsup.png | Bin 0 -> 1034 bytes htdocs/theme/md/img/title_ticketsup.png | Bin 0 -> 1044 bytes htdocs/ticketsup/index.php | 6 +++++- 8 files changed, 20 insertions(+), 17 deletions(-) create mode 100644 htdocs/theme/eldy/img/menus/ticketsup.png create mode 100644 htdocs/theme/eldy/img/menus_black/ticketsup.png create mode 100644 htdocs/theme/eldy/img/title_ticketsup.png create mode 100644 htdocs/theme/md/img/ticketsup.png create mode 100644 htdocs/theme/md/img/title_ticketsup.png diff --git a/htdocs/core/modules/modTicketsup.class.php b/htdocs/core/modules/modTicketsup.class.php index 7e824cdf47b..4b79d472324 100644 --- a/htdocs/core/modules/modTicketsup.class.php +++ b/htdocs/core/modules/modTicketsup.class.php @@ -161,37 +161,31 @@ class modTicketsup extends DolibarrModules // Permissions $this->rights = array(); // Permission array used by this module - $r = 0; - $r++; $this->rights[$r][0] = 56001; // id de la permission $this->rights[$r][1] = "Read ticket"; // libelle de la permission $this->rights[$r][2] = 'r'; // type de la permission (deprecie a ce jour) $this->rights[$r][3] = 1; // La permission est-elle une permission par defaut $this->rights[$r][4] = 'read'; - $r++; $this->rights[$r][0] = 56002; // id de la permission $this->rights[$r][1] = "Create les tickets"; // libelle de la permission $this->rights[$r][2] = 'w'; // type de la permission (deprecie a ce jour) $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut $this->rights[$r][4] = 'write'; - $r++; $this->rights[$r][0] = 56003; // id de la permission $this->rights[$r][1] = "Delete les tickets"; // libelle de la permission $this->rights[$r][2] = 'd'; // type de la permission (deprecie a ce jour) $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut $this->rights[$r][4] = 'delete'; - $r++; $this->rights[$r][0] = 56004; // id de la permission $this->rights[$r][1] = "Manage tickets"; // libelle de la permission //$this->rights[$r][2] = 'd'; // type de la permission (deprecie a ce jour) $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut $this->rights[$r][4] = 'manage'; - $r++; $this->rights[$r][0] = 56005; // id de la permission $this->rights[$r][1] = 'See all tickets, even if not assigned to (not effective for external users, always restricted to the thirdpardy they depends on)'; // libelle de la permission $this->rights[$r][2] = 'r'; // type de la permission (deprecie a ce jour) @@ -211,7 +205,7 @@ class modTicketsup extends DolibarrModules 'url' => '/ticketsup/index.php', 'langs' => 'ticketsup', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. 'position' => 100, - 'enabled' => '1', // Define condition to show or hide menu entry. Use '$conf->ticketsup->enabled' if entry must be visible if module is enabled. + 'enabled' => '$conf->ticketsup->enabled', // Define condition to show or hide menu entry. Use '$conf->ticketsup->enabled' if entry must be visible if module is enabled. 'perms' => '$user->rights->ticketsup->read', // Use 'perms'=>'$user->rights->ticketsup->level1->level2' if you want your menu with a permission rules 'target' => '', 'user' => 2); // 0=Menu for internal users, 1=external users, 2=both @@ -225,7 +219,7 @@ class modTicketsup extends DolibarrModules 'url' => '/ticketsup/index.php', 'langs' => 'ticketsup', 'position' => 101, - 'enabled' => 1, + 'enabled' => '$conf->ticketsup->enabled', 'perms' => '$user->rights->ticketsup->read', 'target' => '', 'user' => 2); @@ -238,7 +232,7 @@ class modTicketsup extends DolibarrModules 'url' => '/ticketsup/new.php?action=create_ticket', 'langs' => 'ticketsup', 'position' => 102, - 'enabled' => 1, + 'enabled' => '$conf->ticketsup->enabled', 'perms' => '$user->rights->ticketsup->write', 'target' => '', 'user' => 2); @@ -252,7 +246,7 @@ class modTicketsup extends DolibarrModules 'url' => '/ticketsup/list.php', 'langs' => 'ticketsup', 'position' => 103, - 'enabled' => 1, + 'enabled' => '$conf->ticketsup->enabled', 'perms' => '$user->rights->ticketsup->read', 'target' => '', 'user' => 2); @@ -266,7 +260,7 @@ class modTicketsup extends DolibarrModules 'url' => '/ticketsup/list.php?search_fk_status=non_closed', 'langs' => 'ticketsup', 'position' => 104, - 'enabled' => 1, + 'enabled' => '$conf->ticketsup->enabled', 'perms' => '$user->rights->ticketsup->read', 'target' => '', 'user' => 2); @@ -280,7 +274,7 @@ class modTicketsup extends DolibarrModules 'url' => '/ticketsup/list.php?mode=my_assign', 'langs' => 'ticketsup', 'position' => 105, - 'enabled' => 1, + 'enabled' => '$conf->ticketsup->enabled', 'perms' => '$user->rights->ticketsup->read', 'target' => '', 'user' => 0); @@ -293,7 +287,7 @@ class modTicketsup extends DolibarrModules 'url' => '/ticketsup/list.php?mode=my_assign&search_fk_status=non_closed', 'langs' => 'ticketsup', 'position' => 106, - 'enabled' => 1, + 'enabled' => '$conf->ticketsup->enabled', 'perms' => '$user->rights->ticketsup->read', 'target' => '', 'user' => 0); diff --git a/htdocs/theme/eldy/img/menus/ticketsup.png b/htdocs/theme/eldy/img/menus/ticketsup.png new file mode 100644 index 0000000000000000000000000000000000000000..03354cc98e0b5d1506cf4f534c7877b51c9c567e GIT binary patch literal 936 zcmV;Z16TZsP)kdg00002VoOIv0063u zBQgL0010qNS#tmY4c7nw4c7reD4Tcy000McNliru;sXr{BPr2XW~KlD135`VK~zY` z&6V448b=g|zq1R=#ax2Z#Nc}yN0uu!X(RRjm#RKiQL9Fd-P8%eVDL>b7%yIS=bSz) z#$eosJhk&SnmOP6&TS6-*GsHHj$?6OZ)!dpgkl~UUJ%oi90Jf}{B2GFHT&(8AWsd<@Q&gh5(nG&mP)0R^h<-9liM4l`;vOr8k#8}_*wlD@; zVT~q(RI$v+s!*pNW$b5m$zy=W8OAdVfQUnW%g0nXmBBQKv!1z{y>Yu*147>Mg&`qO zq(qJHDS~(9AIR_imwTJcEFgL+J6_#Wx6dEaF5KLojFzm$5B?s{V`s-a4hSp!Xl1>~ zjxv}2;e6B!HypY(>m_+B@hUtkPF?V3ZoQ^~bMNF=FJrG468Fl>$}h>EIO@!tP65MB z{Z2*O9Qf}!V#jK8<~3e&T}O>|jiDm}X zc?DI&V(V9K0Z=kD@XVhyjYl0H1*qKGz!dDs0|34{!aL2x7&~c?iem?eC-sPi>eRRL z96&{lSak|Wh$*I-uo?wo+#LWV#+l3m`Wh*kyK6>z#29HRYd}no+sWOWqGKJ*yKqH> zlD`PjUxsu3La0vM6An2S1Go$*;E1@IE9LmwPjD;|Fb0s3eV|O5$O`BDEu+c%0R@!A zUC$|~DZgF;Gkdg00002VoOIv0RM-N z%)bBt010qNS#tmY4c7nw4c7reD4Tcy000McNliru;sXr{7YHUBg%1D#1EonsK~zY` z&6Vv>+f@|DKj+?GOI!Oe%0ttN3<`sdEyC0&NN_>-kSr`F#uvWx?=#VuMVTRPCT5Yr zP}vM5jFurAY!phN4;j$*_q)DmDJ{$w`bN*Yn{&ROdmeJ`h5y<#QQFC2{*|_yCP87* zN0FzL|AE*dj+&fVoe_65-(Z92B{Iloa0Y6 z;Jn9-FoK6BJh*@o2OM%B4|uS20K7>T2{M(89t#fnTLn{Kj%~800OBV^8}CT~lh5Sl?fd!d`exKwPxRI0 z{dnFvGpl~FlMDG{&!vD)nh$s1CloQh$ zeuhU36K#-38Rk*pp);pfRg)fk=i(`V88s1XW`9iri%fH+0dR$B7UB1&YDR2{$ml76 z6}B8}K`#RkB!)wKP2P?}j39tcSc}?N%_jgO5#<$2WmKi}1}_8D(&Qooc&q!8CoQ79 z!;uDnM3qb1YI~*tfQ^qK+_(U6;bsUQHo$B_?`XuWVvQxl#H)~8_2f{-%~eVOl(>qU zGEVifoD%VxXam5~T8kscOYPtgr3-*AqL?E&C`W89E~^2cQgWy)9jL}+Sp?kl0?>;a z!{X7ds-SYop-MHDu%QmM(&0~h)%%y2!b=>0I9{e$s^svoPqirI(5yEA{3%@&RGav# zz#S$@)-p&k$xgKce$}c(m;8+xd|xIf!iA~?AWec+T4rxDgI=|!9|E&exn;N zKa*#l9QK6eTxV3oJd~-VeFBiM`?As@t%S9!e`mQsj^|_%c35G99Hm<=e5A%yKrO2~ zchawU4-$J9EZw8Sa!&l`vmfLi+d#Tf{g+l(r`(Wh;#Yfe@4NZBN1%S?KJ{>oal*hB zQ*4ss0Pqkb!VMz8E_bq?S!@i3pUe;6?4693*MB@;G@Bl}O?TyEkyTb%`D&N{rTqo<%tv;ioLqST O0000kdg00002VoOIv0RM-N z%)bBt010qNS#tmY4c7nw4c7reD4Tcy000McNliru;sXr{7YHUBg%1D#1EonsK~zY` z&6Vv>+f@|DKj+?GOI!Oe%0ttN3<`sdEyC0&NN_>-kSr`F#uvWx?=#VuMVTRPCT5Yr zP}vM5jFurAY!phN4;j$*_q)DmDJ{$w`bN*Yn{&ROdmeJ`h5y<#QQFC2{*|_yCP87* zN0FzL|AE*dj+&fVoe_65-(Z92B{Iloa0Y6 z;Jn9-FoK6BJh*@o2OM%B4|uS20K7>T2{M(89t#fnTLn{Kj%~800OBV^8}CT~lh5Sl?fd!d`exKwPxRI0 z{dnFvGpl~FlMDG{&!vD)nh$s1CloQh$ zeuhU36K#-38Rk*pp);pfRg)fk=i(`V88s1XW`9iri%fH+0dR$B7UB1&YDR2{$ml76 z6}B8}K`#RkB!)wKP2P?}j39tcSc}?N%_jgO5#<$2WmKi}1}_8D(&Qooc&q!8CoQ79 z!;uDnM3qb1YI~*tfQ^qK+_(U6;bsUQHo$B_?`XuWVvQxl#H)~8_2f{-%~eVOl(>qU zGEVifoD%VxXam5~T8kscOYPtgr3-*AqL?E&C`W89E~^2cQgWy)9jL}+Sp?kl0?>;a z!{X7ds-SYop-MHDu%QmM(&0~h)%%y2!b=>0I9{e$s^svoPqirI(5yEA{3%@&RGav# zz#S$@)-p&k$xgKce$}c(m;8+xd|xIf!iA~?AWec+T4rxDgI=|!9|E&exn;N zKa*#l9QK6eTxV3oJd~-VeFBiM`?As@t%S9!e`mQsj^|_%c35G99Hm<=e5A%yKrO2~ zchawU4-$J9EZw8Sa!&l`vmfLi+d#Tf{g+l(r`(Wh;#Yfe@4NZBN1%S?KJ{>oal*hB zQ*4ss0Pqkb!VMz8E_bq?S!@i3pUe;6?4693*MB@;G@Bl}O?TyEkyTb%`D&N{rTqo<%tv;ioLqST O0000); } +div.mainmenu.ticketsup { + background-image: url(); +} + div.mainmenu.tools { background-image: url(); } @@ -1686,10 +1690,11 @@ div.mainmenu.website { 'name of class for div') -$moduletomainmenu=array('user'=>'','syslog'=>'','societe'=>'companies','projet'=>'project','propale'=>'commercial','commande'=>'commercial', +$moduletomainmenu=array( + 'user'=>'','syslog'=>'','societe'=>'companies','projet'=>'project','propale'=>'commercial','commande'=>'commercial', 'produit'=>'products','service'=>'products','stock'=>'products', 'don'=>'accountancy','tax'=>'accountancy','banque'=>'accountancy','facture'=>'accountancy','compta'=>'accountancy','accounting'=>'accountancy','adherent'=>'members','import'=>'tools','export'=>'tools','mailing'=>'tools', - 'contrat'=>'commercial','ficheinter'=>'commercial','deplacement'=>'commercial', + 'contrat'=>'commercial','ficheinter'=>'commercial','ticketsup'=>'ticketsup','deplacement'=>'commercial', 'fournisseur'=>'companies', 'barcode'=>'','fckeditor'=>'','categorie'=>'', ); @@ -1705,7 +1710,7 @@ $generic=1; // Put here list of menu entries when the div.mainmenu.menuentry was previously defined $divalreadydefined=array('home','companies','products','commercial','externalsite','accountancy','project','tools','members','agenda','ftp','holiday','hrm','bookmark','cashdesk','ecm','geoipmaxmind','gravatar','clicktodial','paypal','stripe','webservices','website'); // Put here list of menu entries we are sure we don't want -$divnotrequired=array('multicurrency','salaries','margin','opensurvey','paybox','expensereport','incoterm','prelevement','propal','workflow','notification','supplier_proposal','cron','product','productbatch','expedition'); +$divnotrequired=array('multicurrency','salaries','ticketsup','margin','opensurvey','paybox','expensereport','incoterm','prelevement','propal','workflow','notification','supplier_proposal','cron','product','productbatch','expedition'); foreach($mainmenuusedarray as $val) { if (empty($val) || in_array($val,$divalreadydefined)) continue; diff --git a/htdocs/theme/md/img/ticketsup.png b/htdocs/theme/md/img/ticketsup.png new file mode 100644 index 0000000000000000000000000000000000000000..3ee928e07b3524a319cab19f8ef91c012397df77 GIT binary patch literal 1034 zcmV+l1oiugP)kdg00002VoOIv0RM-N z%)bBt010qNS#tmY4c7nw4c7reD4Tcy000McNliru;sXr{7Ayk;P@ez*1Di=iK~zY` z&6VFzn`IQoKc{`$(Mnrd=t#Ti__eWt2#bm!VUxJT#Eh62O^i4GYu*`SjIv1J2Oi(Tn+_vSp`@AExB-tU3``iLe7@KnspL)FVU zUWj^dxImFbabE)L(1M>QxKjFjjRcP+cW~jMza~kNvz!GoWLVx=?k<+$5nku{zHTWq z#yHQP@(g~jk$(EA;S@FafIW8DWk*w_F71Gxp^162`-jUmI!g)(hwTThNr!E!>flF z=P1EKB6vB_60(~U_7`uuYwIxbC}h&|ZnT%kioQs5GQmttuKeA=YJ9sc8=kJLde;`y z`HN@Y|SUp{S|1_2)VE{Al&Kh;2#|Xw7Z9pBHwfmJ<0(4N8NhciyPyn`A zQ?Y?mV+DaGtj`#`+Ft;`5Tpmc`T*32pB{o3fWCrRH>lqxD^o~nz@qtsp~S_{HQ57@ zJ+9%$#g-n+ThV|dDhOP!@v2oloNFuzZ356H66gUOtW{%V6=E4phP6Dr-wF$?%< z1E38*$}FXS)rPH4ckN1L3eW7W@tD}{Ab?or7$ZOn04)Rkdg00002VoOIv0RM-N z%)bBt010qNS#tmY4c7nw4c7reD4Tcy000McNliru;sXr{7YHUBg%1D#1EonsK~zY` z&6Vv>+f@|DKj+?GOI!Oe%0ttN3<`sdEyC0&NN_>-kSr`F#uvWx?=#VuMVTRPCT5Yr zP}vM5jFurAY!phN4;j$*_q)DmDJ{$w`bN*Yn{&ROdmeJ`h5y<#QQFC2{*|_yCP87* zN0FzL|AE*dj+&fVoe_65-(Z92B{Iloa0Y6 z;Jn9-FoK6BJh*@o2OM%B4|uS20K7>T2{M(89t#fnTLn{Kj%~800OBV^8}CT~lh5Sl?fd!d`exKwPxRI0 z{dnFvGpl~FlMDG{&!vD)nh$s1CloQh$ zeuhU36K#-38Rk*pp);pfRg)fk=i(`V88s1XW`9iri%fH+0dR$B7UB1&YDR2{$ml76 z6}B8}K`#RkB!)wKP2P?}j39tcSc}?N%_jgO5#<$2WmKi}1}_8D(&Qooc&q!8CoQ79 z!;uDnM3qb1YI~*tfQ^qK+_(U6;bsUQHo$B_?`XuWVvQxl#H)~8_2f{-%~eVOl(>qU zGEVifoD%VxXam5~T8kscOYPtgr3-*AqL?E&C`W89E~^2cQgWy)9jL}+Sp?kl0?>;a z!{X7ds-SYop-MHDu%QmM(&0~h)%%y2!b=>0I9{e$s^svoPqirI(5yEA{3%@&RGav# zz#S$@)-p&k$xgKce$}c(m;8+xd|xIf!iA~?AWec+T4rxDgI=|!9|E&exn;N zKa*#l9QK6eTxV3oJd~-VeFBiM`?As@t%S9!e`mQsj^|_%c35G99Hm<=e5A%yKrO2~ zchawU4-$J9EZw8Sa!&l`vmfLi+d#Tf{g+l(r`(Wh;#Yfe@4NZBN1%S?KJ{>oal*hB zQ*4ss0Pqkb!VMz8E_bq?S!@i3pUe;6?4693*MB@;G@Bl}O?TyEkyTb%`D&N{rTqo<%tv;ioLqST O0000trans('TicketsIndex'), ''); -$form = new Form($db); +$linkback=''; +print load_fiche_titre($langs->trans('TicketsIndex'),$linkback,'title_ticketsup.png'); + $dir = ''; $filenamenb = $dir . "/" . $prefix . "ticketsupinyear-" . $endyear . ".png"; From 0f15f3c129feeefbab239e9d76124c8124ee5bb1 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Tue, 13 Mar 2018 11:27:16 +0100 Subject: [PATCH 265/413] Fix database name --- htdocs/stripe/class/stripe.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index cfeecd2bda8..d6d1601d405 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -101,7 +101,7 @@ class Stripe extends CommonObject global $conf; $sql = "SELECT sa.key_account as key_account, sa.entity"; - $sql.= " FROM " . MAIN_DB_PREFIX . "llx_societe_account as sa"; + $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa"; $sql.= " WHERE sa.fk_soc = " . $id; $sql.= " AND sa.entity IN (".getEntity('societe').")"; $sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status); From eabc5c0812b4adf6ea481debb439fcd24ec0af08 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Tue, 13 Mar 2018 11:37:40 +0100 Subject: [PATCH 266/413] FIX with new database llx_societe_account --- htdocs/stripe/class/stripe.class.php | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index d6d1601d405..c46b554388d 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -123,11 +123,11 @@ class Stripe extends CommonObject } - /** - * customerStripe +/** + * customerStripe Call customer in stripe && create/update and save it on dolibarr * - * @param int $id ??? - * @param string $key ??? + * @param int $id Id of third party + * @return string Stripe account ref 'acc_xxxxxxxxxxxxx' * @return \Stripe\StripeObject|\Stripe\ApiResource */ public function customerStripe($id,$key) @@ -142,10 +142,11 @@ class Stripe extends CommonObject $mode = $conf->global->STRIPE_LIVE; } } - $sql = "SELECT rowid,fk_soc,fk_key,mode,entity"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe"; - $sql .= " WHERE fk_soc = " . $id . " "; - $sql .= " AND mode=" . $mode . " AND entity IN (" . getEntity('stripe') . ")"; + $sql = "SELECT sa.key_account as key_account, sa.entity"; + $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa"; + $sql.= " WHERE sa.fk_soc = " . $id; + $sql.= " AND sa.entity IN (".getEntity('societe').")"; + $sql.= " AND sa.site = 'stripe' AND sa.status = 0".((int) $status); dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -155,7 +156,7 @@ class Stripe extends CommonObject $num = $this->db->num_rows($resql); if ($num) { $obj = $this->db->fetch_object($resql); - $tiers = $obj->fk_key; + $tiers = $obj->key_account; if ($conf->entity == 1) { $customer = \Stripe\Customer::retrieve("$tiers"); } else { @@ -178,8 +179,8 @@ class Stripe extends CommonObject )); } $customer_id = "" . $customer->id . ""; - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_stripe (fk_soc,fk_key,mode,entity)"; - $sql .= " VALUES ($id,'$customer_id'," . $mode . "," . $conf->entity . ")"; + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_account (fk_soc,key_account,site,status,entity)"; + $sql .= " VALUES ($id,'$customer_id','stripe'," . $mode . "," . $conf->entity . ")"; dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); } From 7feaeb1b89512416e69f20cc076cfb5cc5f265fd Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Tue, 13 Mar 2018 12:07:53 +0100 Subject: [PATCH 267/413] more FIX for unified stripe's payment class --- htdocs/stripe/class/stripe.class.php | 51 +++++++++++++--------------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index c46b554388d..7a6234575f7 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -123,8 +123,8 @@ class Stripe extends CommonObject } -/** - * customerStripe Call customer in stripe && create/update and save it on dolibarr + /** + * customerStripe * * @param int $id Id of third party * @return string Stripe account ref 'acc_xxxxxxxxxxxxx' @@ -146,7 +146,7 @@ class Stripe extends CommonObject $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa"; $sql.= " WHERE sa.fk_soc = " . $id; $sql.= " AND sa.entity IN (".getEntity('societe').")"; - $sql.= " AND sa.site = 'stripe' AND sa.status = 0".((int) $status); + $sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status); dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -189,44 +189,41 @@ class Stripe extends CommonObject } /** - * createPaymentStripe + * createPaymentStripe Create charge with public/payment/newpayment.php, stripe/card.php, cronjobs or REST API * - * @param unknown $amount ??? - * @param unknown $currency ??? - * @param unknown $origin ??? - * @param unknown $item ??? - * @param unknown $source ??? - * @param unknown $customer ??? - * @param unknown $account ??? + * @param int $amount amount to pay + * @param string $currency EUR, GPB... + * @param string $origin order, invoice, contract... + * @param int $item if of element to pay + * @param string $source src_xxxxx or card_xxxxx or ac_xxxxx + * @param string $customer Stripe account ref 'cu_xxxxxxxxxxxxx' via customerStripe() + * @param string $account Stripe account ref 'acc_xxxxxxxxxxxxx' via getStripeAccount() + * @param int $status Status * @return Stripe */ - public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) + public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account, $status=0) { global $conf; - if (empty($conf->global->STRIPECONNECT_LIVE)) { - $mode = 0; - } else { - if (empty($conf->global->STRIPE_LIVE)) { - $mode = 0; - } else { - $mode = $conf->global->STRIPE_LIVE; - } - } - $sql = "SELECT fk_soc,fk_key,mode,entity"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe"; - $sql .= " WHERE fk_key = '$customer' "; - $sql .= " AND mode=" . $mode . " "; + $sql = "SELECT sa.key_account as key_account, sa.entity"; + $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa"; + $sql.= " WHERE sa.key_account = " . $customer; + //$sql.= " AND sa.entity IN (".getEntity('societe').")"; + $sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status); dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - $entite = $obj->entity; - $fksoc = $obj->fk_soc; + $key = $obj->fk_soc; + } else { + $key = NULL; } + } else { + $key = NULL; } + $stripeamount = round($amount * 100); $societe = new Societe($this->db); $societe->fetch($fksoc); From 8048259733a5c32f63b5153df6caba2a3d94dfb0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 12:13:47 +0100 Subject: [PATCH 268/413] Work on ticket module integration --- .tx/config | 6 ++ htdocs/core/lib/admin.lib.php | 24 +++---- htdocs/core/modules/modApi.class.php | 15 ----- htdocs/core/modules/modTicketsup.class.php | 5 +- .../mysql/data/llx_c_ticketsup_category.sql | 20 ++++++ .../mysql/data/llx_c_ticketsup_severity.sql | 24 +++++-- .../mysql/data/llx_c_ticketsup_type.sql | 26 ++++++-- htdocs/install/mysql/data/llx_ticketsup.sql | 17 ----- .../install/mysql/migration/7.0.0-8.0.0.sql | 59 ++++++++++++------ .../tables/llx_c_ticketsup_category.key.sql | 2 +- .../mysql/tables/llx_c_ticketsup_category.sql | 1 + .../tables/llx_c_ticketsup_severity.key.sql | 2 +- .../mysql/tables/llx_c_ticketsup_severity.sql | 1 + .../mysql/tables/llx_c_ticketsup_type.key.sql | 2 +- .../mysql/tables/llx_c_ticketsup_type.sql | 1 + htdocs/langs/en_US/ticketsup.lang | 6 +- htdocs/theme/eldy/img/menus/README.md | 4 +- htdocs/ticketsup/img/ticketsup-32.png | Bin 1412 -> 0 bytes htdocs/ticketsup/list.php | 2 +- htdocs/ticketsup/new.php | 2 +- 20 files changed, 135 insertions(+), 84 deletions(-) create mode 100644 htdocs/install/mysql/data/llx_c_ticketsup_category.sql delete mode 100644 htdocs/install/mysql/data/llx_ticketsup.sql delete mode 100644 htdocs/ticketsup/img/ticketsup-32.png diff --git a/.tx/config b/.tx/config index 89d123b0362..14d735d8610 100644 --- a/.tx/config +++ b/.tx/config @@ -356,6 +356,12 @@ source_file = htdocs/langs/en_US/supplier_proposal.lang source_lang = en_US type = MOZILLAPROPERTIES +[dolibarr.ticketsup] +file_filter = htdocs/langs//ticketsup.lang +source_file = htdocs/langs/en_US/ticketsup.lang +source_lang = en_US +type = MOZILLAPROPERTIES + [dolibarr.trips] file_filter = htdocs/langs//trips.lang source_file = htdocs/langs/en_US/trips.lang diff --git a/htdocs/core/lib/admin.lib.php b/htdocs/core/lib/admin.lib.php index 0f219a032cc..2c94dcf65ca 100644 --- a/htdocs/core/lib/admin.lib.php +++ b/htdocs/core/lib/admin.lib.php @@ -1031,7 +1031,8 @@ function unActivateModule($value, $requiredby=1) /** - * Add external modules to list of dictionaries + * Add external modules to list of dictionaries. + * Addition is done into var $taborder, $tabname, etc... that are passed with pointers. * * @param array $taborder Taborder * @param array $tabname Tabname @@ -1097,23 +1098,20 @@ function complete_dictionary_with_modules(&$taborder,&$tabname,&$tablib,&$tabsql if ($modulequalified) { // Load languages files of module - if (isset($objMod->langfiles) && is_array($objMod->langfiles)) - { - foreach($objMod->langfiles as $langfile) - { - $langs->load($langfile); - } - } + if (isset($objMod->langfiles) && is_array($objMod->langfiles)) { + foreach ($objMod->langfiles as $langfile) { + $langs->load($langfile); + } + } - // Complete arrays - //&$tabname,&$tablib,&$tabsql,&$tabsqlsort,&$tabfield,&$tabfieldvalue,&$tabfieldinsert,&$tabrowid,&$tabcond + // Complete the arrays &$tabname,&$tablib,&$tabsql,&$tabsqlsort,&$tabfield,&$tabfieldvalue,&$tabfieldinsert,&$tabrowid,&$tabcond if (empty($objMod->dictionaries) && ! empty($objMod->dictionnaries)) $objMod->dictionaries=$objMod->dictionnaries; // For backward compatibility if (! empty($objMod->dictionaries)) { //var_dump($objMod->dictionaries['tabname']); $nbtabname=$nbtablib=$nbtabsql=$nbtabsqlsort=$nbtabfield=$nbtabfieldvalue=$nbtabfieldinsert=$nbtabrowid=$nbtabcond=$nbtabfieldcheck=$nbtabhelp=0; - foreach($objMod->dictionaries['tabname'] as $val) { $nbtabname++; $taborder[] = max($taborder)+1; $tabname[] = $val; } + foreach($objMod->dictionaries['tabname'] as $val) { $nbtabname++; $taborder[] = max($taborder)+1; $tabname[] = $val; } // Position foreach($objMod->dictionaries['tablib'] as $val) { $nbtablib++; $tablib[] = $val; } foreach($objMod->dictionaries['tabsql'] as $val) { $nbtabsql++; $tabsql[] = $val; } foreach($objMod->dictionaries['tabsqlsort'] as $val) { $nbtabsqlsort++; $tabsqlsort[] = $val; } @@ -1130,6 +1128,10 @@ function complete_dictionary_with_modules(&$taborder,&$tabname,&$tablib,&$tabsql print 'Error in descriptor of module '.$const_name.'. Array ->dictionaries has not same number of record for key "tabname", "tablib", "tabsql" and "tabsqlsort"'; //print "$const_name: $nbtabname=$nbtablib=$nbtabsql=$nbtabsqlsort=$nbtabfield=$nbtabfieldvalue=$nbtabfieldinsert=$nbtabrowid=$nbtabcond=$nbtabfieldcheck=$nbtabhelp\n"; } + else + { + $taborder[] = 0; // Add an empty line + } } $j++; diff --git a/htdocs/core/modules/modApi.class.php b/htdocs/core/modules/modApi.class.php index 24d784585d3..86588f06ed4 100644 --- a/htdocs/core/modules/modApi.class.php +++ b/htdocs/core/modules/modApi.class.php @@ -125,21 +125,6 @@ class modApi extends DolibarrModules $conf->api->enabled=0; } $this->dictionaries=array(); - /* Example: - if (! isset($conf->api->enabled)) $conf->api->enabled=0; // This is to avoid warnings - $this->dictionaries=array( - 'langs'=>'mylangfile@api', - 'tabname'=>array(MAIN_DB_PREFIX."table1",MAIN_DB_PREFIX."table2",MAIN_DB_PREFIX."table3"), // List of tables we want to see into dictonnary editor - 'tablib'=>array("Table1","Table2","Table3"), // Label of tables - 'tabsql'=>array('SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table1 as f','SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table2 as f','SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table3 as f'), // Request to select fields - 'tabsqlsort'=>array("label ASC","label ASC","label ASC"), // Sort order - 'tabfield'=>array("code,label","code,label","code,label"), // List of fields (result of select to show dictionary) - 'tabfieldvalue'=>array("code,label","code,label","code,label"), // List of fields (list of fields to edit a record) - 'tabfieldinsert'=>array("code,label","code,label","code,label"), // List of fields (list of fields for insert) - 'tabrowid'=>array("rowid","rowid","rowid"), // Name of columns with primary key (try to always name it 'rowid') - 'tabcond'=>array($conf->api->enabled,$conf->api->enabled,$conf->api->enabled) // Condition to show each dictionary - ); - */ // Boxes // Add here list of php file(s) stored in core/boxes that contains class to show a box. diff --git a/htdocs/core/modules/modTicketsup.class.php b/htdocs/core/modules/modTicketsup.class.php index 4b79d472324..c6a6ada09f9 100644 --- a/htdocs/core/modules/modTicketsup.class.php +++ b/htdocs/core/modules/modTicketsup.class.php @@ -311,8 +311,7 @@ class modTicketsup extends DolibarrModules array("sql" => "insert into llx_c_type_contact(rowid, element, source, code, libelle, active ) values (110121, 'ticketsup', 'internal', 'CONTRIBUTOR', 'Intervenant', 1);", "ignoreerror" => 1), array("sql" => "insert into llx_c_type_contact(rowid, element, source, code, libelle, active ) values (110122, 'ticketsup', 'external', 'SUPPORTCLI', 'Contact client suivi incident', 1);", "ignoreerror" => 1), array("sql" => "insert into llx_c_type_contact(rowid, element, source, code, libelle, active ) values (110123, 'ticketsup', 'external', 'CONTRIBUTOR', 'Intervenant', 1);", "ignoreerror" => 1), - array("sql" => "insert into llx_c_action_trigger (rowid,code,label,description,elementtype,rang) values ('','TICKETMESSAGE_SENTBYMAIL','Envoi message de réponse par mail','Executed when a response is made on a ticket','ticketsup','');", "ignoreerror" => 1), - + array("sql" => "insert into llx_c_action_trigger (rowid,code,label,description,elementtype,rang) values ('','TICKETMESSAGE_SENTBYMAIL','Send email for ticket','Executed when a response is made on a ticket','ticketsup','');", "ignoreerror" => 1), ); $result = $this->loadTables(); @@ -345,6 +344,6 @@ class modTicketsup extends DolibarrModules */ private function loadTables() { - return $this->_load_tables('/ticketsup/sql/'); + return $this->_load_tables(); } } diff --git a/htdocs/install/mysql/data/llx_c_ticketsup_category.sql b/htdocs/install/mysql/data/llx_c_ticketsup_category.sql new file mode 100644 index 00000000000..0f00ec77502 --- /dev/null +++ b/htdocs/install/mysql/data/llx_c_ticketsup_category.sql @@ -0,0 +1,20 @@ +-- Copyright (C) 2018 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 +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- +-- Contenu de la table llx_c_ticketsup_category +-- + +INSERT INTO llx_c_ticketsup_category (code, pos, label, active, use_default, description) VALUES('OTHER', '10', 'Other', 1, 1, NULL); diff --git a/htdocs/install/mysql/data/llx_c_ticketsup_severity.sql b/htdocs/install/mysql/data/llx_c_ticketsup_severity.sql index 9e356988256..1b9c3e42ca0 100644 --- a/htdocs/install/mysql/data/llx_c_ticketsup_severity.sql +++ b/htdocs/install/mysql/data/llx_c_ticketsup_severity.sql @@ -1,9 +1,23 @@ - +-- Copyright (C) 2018 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 +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- -- -- Contenu de la table llx_c_ticketsup_severity -- -INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(1, 'LOW', '10', 'Bas', '', 1, 0, NULL); -INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(2, 'NORMAL', '20', 'Normal', '', 1, 1, NULL); -INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(3, 'LOWHIGH', '30', 'Important', '', 1, 0, NULL); -INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(4, 'HIGH', '40', 'Critique / bloquant', '', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_severity (code, pos, label, color, active, use_default, description) VALUES('LOW', '10', 'Low', '', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_severity (code, pos, label, color, active, use_default, description) VALUES('NORMAL', '20', 'Normal', '', 1, 1, NULL); +INSERT INTO llx_c_ticketsup_severity (code, pos, label, color, active, use_default, description) VALUES('HIGH', '30', 'High', '', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_severity (code, pos, label, color, active, use_default, description) VALUES('BLOCKING', '40', 'Critical / blocking', '', 1, 0, NULL); diff --git a/htdocs/install/mysql/data/llx_c_ticketsup_type.sql b/htdocs/install/mysql/data/llx_c_ticketsup_type.sql index e5bb1869e5d..310b075a604 100644 --- a/htdocs/install/mysql/data/llx_c_ticketsup_type.sql +++ b/htdocs/install/mysql/data/llx_c_ticketsup_type.sql @@ -1,8 +1,24 @@ - +-- Copyright (C) 2018 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 +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- -- -- Contenu de la table llx_c_ticketsup_type -- -INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(1, 'COM', '10', 'Question commerciale', 1, 1, NULL); -INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(2, 'INCIDENT', '20', 'Demande d''assistance', 1, 0, NULL); -INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(3, 'PROJET', '30', 'Suivi projet', 1, 0, NULL); -INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(4, 'OTHER', '40', 'Autre', 1, 0, NULL); + +INSERT INTO llx_c_ticketsup_type (code, pos, label, active, use_default, description) VALUES('COM', '10', 'Commercial question', 1, 1, NULL); +INSERT INTO llx_c_ticketsup_type (code, pos, label, active, use_default, description) VALUES('ISSUE', '20', 'Issue or problem' , 1, 0, NULL); +INSERT INTO llx_c_ticketsup_type (code, pos, label, active, use_default, description) VALUES('REQUEST', '25', 'Change or enhancement request', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_type (code, pos, label, active, use_default, description) VALUES('PROJECT', '30', 'Project', 0, 0, NULL); +INSERT INTO llx_c_ticketsup_type (code, pos, label, active, use_default, description) VALUES('OTHER', '40', 'Other', 1, 0, NULL); diff --git a/htdocs/install/mysql/data/llx_ticketsup.sql b/htdocs/install/mysql/data/llx_ticketsup.sql deleted file mode 100644 index 41c78d32d21..00000000000 --- a/htdocs/install/mysql/data/llx_ticketsup.sql +++ /dev/null @@ -1,17 +0,0 @@ - --- --- Contenu de la table llx_c_ticketsup_type --- -INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(1, 'COM', '10', 'Question commerciale', 1, 1, NULL); -INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(2, 'INCIDENT', '20', 'Demande d''assistance', 1, 0, NULL); -INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(3, 'PROJET', '30', 'Suivi projet', 1, 0, NULL); -INSERT INTO llx_c_ticketsup_type (rowid, code, pos, label, active, use_default, description) VALUES(4, 'OTHER', '40', 'Autre', 1, 0, NULL); - --- --- Contenu de la table llx_c_ticketsup_severity --- - -INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(1, 'LOW', '10', 'Bas', '', 1, 0, NULL); -INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(2, 'NORMAL', '20', 'Normal', '', 1, 1, NULL); -INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(3, 'LOWHIGH', '30', 'Important', '', 1, 0, NULL); -INSERT INTO llx_c_ticketsup_severity (rowid, code, pos, label, color, active, use_default, description) VALUES(4, 'HIGH', '40', 'Critique / bloquant', '', 1, 0, NULL); diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 6ff739b5f40..9c65b4442d2 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -185,24 +185,13 @@ CREATE TABLE llx_ticketsup_extrafields import_key varchar(14) )ENGINE=innodb; -ALTER TABLE llx_c_ticketsup_category ADD INDEX idx_code (code); -CREATE TABLE llx_c_ticketsup_category -( - rowid integer AUTO_INCREMENT PRIMARY KEY, - code varchar(32) NOT NULL, - pos varchar(32) NOT NULL, - label varchar(128) NOT NULL, - active integer DEFAULT 1, - use_default integer DEFAULT 1, - description varchar(255) -)ENGINE=innodb; - -ALTER TABLE llx_c_ticketsup_severity ADD INDEX idx_code (code); - -CREATE TABLE llx_c_ticketsup_severity + +-- Create dictionaries tables for ticket +create table llx_c_ticketsup_severity ( rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, code varchar(32) NOT NULL, pos varchar(32) NOT NULL, label varchar(128) NOT NULL, @@ -212,11 +201,10 @@ CREATE TABLE llx_c_ticketsup_severity description varchar(255) )ENGINE=innodb; -ALTER TABLE llx_c_ticketsup_type ADD INDEX idx_code (code); - -CREATE TABLE llx_c_ticketsup_type +create table llx_c_ticketsup_type ( rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, code varchar(32) NOT NULL, pos varchar(32) NOT NULL, label varchar(128) NOT NULL, @@ -225,6 +213,41 @@ CREATE TABLE llx_c_ticketsup_type description varchar(255) )ENGINE=innodb; +create table llx_c_ticketsup_category +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, + code varchar(32) NOT NULL, + pos varchar(32) NOT NULL, + label varchar(128) NOT NULL, + active integer DEFAULT 1, + use_default integer DEFAULT 1, + description varchar(255) +)ENGINE=innodb; + +ALTER TABLE llx_c_ticketsup_category ADD UNIQUE INDEX uk_code (code, entity); +ALTER TABLE llx_c_ticketsup_severity ADD UNIQUE INDEX uk_code (code, entity); +ALTER TABLE llx_c_ticketsup_type ADD UNIQUE INDEX uk_code (code, entity); + + + +-- Load data +INSERT INTO llx_c_ticketsup_severity (code, pos, label, color, active, use_default, description) VALUES('LOW', '10', 'Low', '', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_severity (code, pos, label, color, active, use_default, description) VALUES('NORMAL', '20', 'Normal', '', 1, 1, NULL); +INSERT INTO llx_c_ticketsup_severity (code, pos, label, color, active, use_default, description) VALUES('HIGH', '30', 'High', '', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_severity (code, pos, label, color, active, use_default, description) VALUES('BLOCKING', '40', 'Critical / blocking', '', 1, 0, NULL); + +INSERT INTO llx_c_ticketsup_type (code, pos, label, active, use_default, description) VALUES('COM', '10', 'Commercial question', 1, 1, NULL); +INSERT INTO llx_c_ticketsup_type (code, pos, label, active, use_default, description) VALUES('ISSUE', '20', 'Issue or problem' , 1, 0, NULL); +INSERT INTO llx_c_ticketsup_type (code, pos, label, active, use_default, description) VALUES('REQUEST', '25', 'Change or enhancement request', 1, 0, NULL); +INSERT INTO llx_c_ticketsup_type (code, pos, label, active, use_default, description) VALUES('PROJECT', '30', 'Project', 0, 0, NULL); +INSERT INTO llx_c_ticketsup_type (code, pos, label, active, use_default, description) VALUES('OTHER', '40', 'Other', 1, 0, NULL); + +INSERT INTO llx_c_ticketsup_category (code, pos, label, active, use_default, description) VALUES('OTHER', '10', 'Other', 1, 1, NULL); + + + + ALTER TABLE llx_facturedet_rec ADD COLUMN date_start_fill integer DEFAULT 0; ALTER TABLE llx_facturedet_rec ADD COLUMN date_end_fill integer DEFAULT 0; diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_category.key.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_category.key.sql index 734fbcc8ece..a43346b87cf 100644 --- a/htdocs/install/mysql/tables/llx_c_ticketsup_category.key.sql +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_category.key.sql @@ -15,4 +15,4 @@ -- -- -ALTER TABLE llx_c_ticketsup_category ADD INDEX idx_code (code); +ALTER TABLE llx_c_ticketsup_category ADD UNIQUE INDEX uk_code (code, entity); diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_category.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_category.sql index 33b49b12df8..cce444d7f8a 100755 --- a/htdocs/install/mysql/tables/llx_c_ticketsup_category.sql +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_category.sql @@ -18,6 +18,7 @@ create table llx_c_ticketsup_category ( rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, code varchar(32) NOT NULL, pos varchar(32) NOT NULL, label varchar(128) NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_severity.key.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_severity.key.sql index a873969876e..2772b0b545e 100644 --- a/htdocs/install/mysql/tables/llx_c_ticketsup_severity.key.sql +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_severity.key.sql @@ -15,4 +15,4 @@ -- -- -ALTER TABLE llx_c_ticketsup_severity ADD INDEX idx_code (code); +ALTER TABLE llx_c_ticketsup_severity ADD UNIQUE INDEX uk_code (code, entity); diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_severity.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_severity.sql index a825000831d..9c26ec5cc32 100755 --- a/htdocs/install/mysql/tables/llx_c_ticketsup_severity.sql +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_severity.sql @@ -18,6 +18,7 @@ create table llx_c_ticketsup_severity ( rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, code varchar(32) NOT NULL, pos varchar(32) NOT NULL, label varchar(128) NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_type.key.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_type.key.sql index d451cc51a39..6dd4ec8fc9a 100644 --- a/htdocs/install/mysql/tables/llx_c_ticketsup_type.key.sql +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_type.key.sql @@ -15,4 +15,4 @@ -- -- -ALTER TABLE llx_c_ticketsup_type ADD INDEX idx_code (code); +ALTER TABLE llx_c_ticketsup_type ADD UNIQUE INDEX uk_code (code, entity); diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_type.sql b/htdocs/install/mysql/tables/llx_c_ticketsup_type.sql index 8983159ec0d..33f7b8a2973 100755 --- a/htdocs/install/mysql/tables/llx_c_ticketsup_type.sql +++ b/htdocs/install/mysql/tables/llx_c_ticketsup_type.sql @@ -18,6 +18,7 @@ create table llx_c_ticketsup_type ( rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, code varchar(32) NOT NULL, pos varchar(32) NOT NULL, label varchar(128) NOT NULL, diff --git a/htdocs/langs/en_US/ticketsup.lang b/htdocs/langs/en_US/ticketsup.lang index 8187e8220d9..9064222637a 100644 --- a/htdocs/langs/en_US/ticketsup.lang +++ b/htdocs/langs/en_US/ticketsup.lang @@ -29,7 +29,7 @@ Permission56005=See tickets of all thirdparties (not effective for external user TicketsupDictType=Tickets type TicketsupDictCategory=Tickets categories -TicketsupDictSeverity=Severity classifications +TicketsupDictSeverity=Tickets severity TicketTypeShortBUGSOFT=Dysfonctionnement logiciel TicketTypeShortBUGHARD=Dysfonctionnement matériel TicketTypeShortCOM=Commercial question @@ -39,8 +39,8 @@ TicketTypeShortOTHER=Other TicketSeverityShortLOW=Low TicketSeverityShortNORMAL=Normal -TicketSeverityShortLOWHIGH=Important -TicketSeverityShortHIGH=Critical +TicketSeverityShortHIGH=High +TicketSeverityShortBLOCKING=Critical/Blocking ErrorBadEmailAddress=Field '%s' incorrect MenuTicketsupMyAssign=My tickets diff --git a/htdocs/theme/eldy/img/menus/README.md b/htdocs/theme/eldy/img/menus/README.md index 2c3e65e4e23..72f376c3f2b 100644 --- a/htdocs/theme/eldy/img/menus/README.md +++ b/htdocs/theme/eldy/img/menus/README.md @@ -2,8 +2,8 @@ Tutorial to create a new image for menu: 1) First find an image. -2) With Gimp, open image and check there is a alpha channel. If not add one. -3) Convert image into back and white (Menu Image - Mode - Grey levels). +2) With Gimp, open image and check there is a alpha channel. If not add one (Menu Color - Convert to alpha). +3) Convert image into black and white (Menu Image - Mode - Grey levels). 4) Use the degrade tool with option (Menu Tools - Paint - Degrade - CTRL+L): * Mode: Erase color (you can also try "Clear only") * Opacity: 50 +/- diff --git a/htdocs/ticketsup/img/ticketsup-32.png b/htdocs/ticketsup/img/ticketsup-32.png deleted file mode 100644 index ce4b71ca624f73ce0f0b56b945b2ec254b21b383..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1412 zcmV-~1$+95P)$^!`kVuT1S#0y?(pjMjr;)97O zBpRYGq)h>n#u&knmO|7Z4KYy(rd;I~C~~P3q(U#0NK@=?chC56zQUp1ZR>-+=$D-2 zd^7X?=YMAA%zW@)UmjpQkO6c6`Y-y;1p)$CfDf1nbOQ}Q_#blYGmeJ=r-87zlwKek z$OH}pxBDI6u+L9NcseixVLG-w6#&aRhjJD;!${v*HZ2Xsa6Sr{3p4>2fgS*f!7$ZC z;{wnKK-sP!wzn9S*ARk05J&)37=mfe@x)A*gtEYNSzMD|z zPJTIfBbJ+lxCEBIm(T5{HMCxy%(YWCnR)y1`ah?;`yks_w#Gd3W_2pw;31-+HC#Kn z7>(wUw=BS@%nR`d#E!uF+6mZHlHgxVTVosN4m5J_kMForzhOwVo;7zP!$&M&+M+B{ zCZ!Px)nQRe#fqzaO|6&!DkTW>iG(3NdoNubo4Hb-02B?ueGyj<`{-=nO#0+KL_#3U zN2Mf|aeo5q_dE@{9F+jVQ6k};G#>pLvlz zkw6w;1LI;iA7^w~#VgR+9}Rn%z|-ddpoIPV-?dFfRsyc}AD?&`fbK zdW$d7_=rP5B^O9U6jYk1DC%%&Bfz7;LLdP6T{^#!Ei^Wf`<14}eM;t+^> za!?szb~pQ0hiRb!;1yFNy(?s70b^tLIeXK5;0U6gocII;AA*GvMTy4xL3{snV46!l z&B%y3(tGg)3&9tkfW;-?F5tn^)IKn+z#;P<0P-h6Wo#a#z`+=g07@rO&c`PZ^fw^fGm|b8m9#!lXa=?d zr+_&w`5YtLYHZwvo#tQx!aaiihWG?Nd8P+wF(YCDwid*wgB!pJ^WSHfXPlAUh>`yS z&;~6Iun}1VtYPggpKE+afp38=z!>vvF|z3W5&!nC1Z;U3Sc0Iy0fXJ|cKYx-x;H{W z;Z0x)Do&U!kC%egzjCbl4$x*UuC3++dQ)=I=t7izHHN6X0lbPzGNSbeA5y;R`p|Dg zrL`pp?}MbFgg|#<$u^QR8`zZpXUsDn92-tYa}Kt>4%L@Hh9TO5vXROa+y35-NP2dl z-eh1M!ehYe*gQ!`Qw49;o}l`C2XgB}`z2jhASwly0hAJsfpH#~*NNzk9M?BkRd{?7kvi0d!jdBXY@ SHh8K40000'; print ''; -print_barre_liste($langs->trans('TicketList'), $page, 'list.php', $param, $sortfield, $sortorder, '', $num, $num_total, 'img/ticketsup-32.png', 1); +print_barre_liste($langs->trans('TicketList'), $page, 'list.php', $param, $sortfield, $sortorder, '', $num, $num_total, 'title_ticketsup'); if ($mode == 'my_assign') { print '
    ' . $langs->trans('TicketAssignedToMeInfos') . '

    '; diff --git a/htdocs/ticketsup/new.php b/htdocs/ticketsup/new.php index 3d1a3c7c9f2..e08361e1e77 100644 --- a/htdocs/ticketsup/new.php +++ b/htdocs/ticketsup/new.php @@ -72,7 +72,7 @@ $form = new Form($db); if ($action == 'create_ticket') { $formticket = new FormTicketsup($db); - print load_fiche_titre($langs->trans('NewTicket'), '', 'img/ticketsup-32.png', 1); + print load_fiche_titre($langs->trans('NewTicket'), '', 'title_ticketsup'); $formticket->withfromsocid = $socid ? $socid : $user->societe_id; $formticket->withfromcontactid = $contactid ? $contactid : ''; From c76dce64d349a7bfdc6e3a72f304d365ceb913af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 13 Mar 2018 12:15:03 +0100 Subject: [PATCH 269/413] add object in pdf_build_address source --- htdocs/core/modules/commande/doc/pdf_einstein.modules.php | 2 +- htdocs/core/modules/contract/doc/pdf_strato.modules.php | 2 +- htdocs/core/modules/expedition/doc/pdf_merou.modules.php | 2 +- htdocs/core/modules/expedition/doc/pdf_rouget.modules.php | 2 +- htdocs/core/modules/facture/doc/pdf_crabe.modules.php | 2 +- htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php | 2 +- htdocs/core/modules/livraison/doc/pdf_typhon.modules.php | 2 +- htdocs/core/modules/propale/doc/pdf_azur.modules.php | 2 +- .../core/modules/supplier_invoice/pdf/pdf_canelle.modules.php | 2 +- htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php | 2 +- .../core/modules/supplier_proposal/doc/pdf_aurore.modules.php | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php index 7c24e49e89b..9d15b263b66 100644 --- a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php +++ b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php @@ -1330,7 +1330,7 @@ class pdf_einstein extends ModelePDFCommandes $carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$labelbeforecontactname." ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; } - $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); + $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender $posy=42+$top_shift; diff --git a/htdocs/core/modules/contract/doc/pdf_strato.modules.php b/htdocs/core/modules/contract/doc/pdf_strato.modules.php index 2cea64a72a6..74b5d43f489 100644 --- a/htdocs/core/modules/contract/doc/pdf_strato.modules.php +++ b/htdocs/core/modules/contract/doc/pdf_strato.modules.php @@ -583,7 +583,7 @@ class pdf_strato extends ModelePDFContract $carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$outputlangs->transnoentities("Name").": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; } - $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); + $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender $posy=42; diff --git a/htdocs/core/modules/expedition/doc/pdf_merou.modules.php b/htdocs/core/modules/expedition/doc/pdf_merou.modules.php index 68795126487..0ae6ed3ebe5 100644 --- a/htdocs/core/modules/expedition/doc/pdf_merou.modules.php +++ b/htdocs/core/modules/expedition/doc/pdf_merou.modules.php @@ -542,7 +542,7 @@ class pdf_merou extends ModelePdfExpedition $pdf->SetTextColor(0,0,0); // Sender properties - $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); + $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); $pdf->SetFont('','', $default_font_size - 3); $pdf->SetXY($blSocX,$blSocY+4); diff --git a/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php b/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php index f7eca910b7e..978f15d2ae8 100644 --- a/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php +++ b/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php @@ -935,7 +935,7 @@ class pdf_rouget extends ModelePdfExpedition $carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$outputlangs->transnoentities("Name").": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; } - $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); + $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender $posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; diff --git a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php index 21adfe4edb4..6a063ec0e86 100644 --- a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php +++ b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php @@ -1692,7 +1692,7 @@ class pdf_crabe extends ModelePDFFactures if ($showaddress) { // Sender properties - $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); + $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender $posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; diff --git a/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php b/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php index f63f05b07f9..2307f896973 100644 --- a/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php +++ b/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php @@ -584,7 +584,7 @@ class pdf_soleil extends ModelePDFFicheinter $carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$outputlangs->transnoentities("Name").": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; } - $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); + $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender $posy=42; diff --git a/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php b/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php index fcb0bb6b057..06d6920e866 100644 --- a/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php +++ b/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php @@ -799,7 +799,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder if ($showaddress) { // Sender properties - $carac_emetteur = pdf_build_address($outputlangs,$this->emetteur); + $carac_emetteur = pdf_build_address($outputlangs,$this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender $posy=42; diff --git a/htdocs/core/modules/propale/doc/pdf_azur.modules.php b/htdocs/core/modules/propale/doc/pdf_azur.modules.php index a54cfbf212f..fba77613828 100644 --- a/htdocs/core/modules/propale/doc/pdf_azur.modules.php +++ b/htdocs/core/modules/propale/doc/pdf_azur.modules.php @@ -1515,7 +1515,7 @@ class pdf_azur extends ModelePDFPropales $carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$labelbeforecontactname." ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; } - $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); + $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender $posy=42+$top_shift; diff --git a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php index 9cdb9ebc6a0..f927b064a69 100644 --- a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php +++ b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php @@ -1086,7 +1086,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices if ($showaddress) { // Sender properties - $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); + $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender $posy=42; diff --git a/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php b/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php index d272957d80d..f61000d3b08 100644 --- a/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php +++ b/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php @@ -1211,7 +1211,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders if ($showaddress) { // Sender properties - $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); + $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender $posy=42; diff --git a/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php b/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php index 7411933dd26..46d4e35d10e 100644 --- a/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php +++ b/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php @@ -1306,7 +1306,7 @@ class pdf_aurore extends ModelePDFSupplierProposal $carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$labelbeforecontactname.": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; } - $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); + $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender $posy=42; From 3aa0bdfe5c4a6dfe8e18311f28398ed3eb175854 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Tue, 13 Mar 2018 12:17:57 +0100 Subject: [PATCH 270/413] ADD trigger when modify, delete thirdparty More fix todo with new class of stripe.class.php --- .../nterface_99_modStripe_Stripe.class.php | 159 ++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 htdocs/core/triggers/nterface_99_modStripe_Stripe.class.php diff --git a/htdocs/core/triggers/nterface_99_modStripe_Stripe.class.php b/htdocs/core/triggers/nterface_99_modStripe_Stripe.class.php new file mode 100644 index 00000000000..e75d87c36f6 --- /dev/null +++ b/htdocs/core/triggers/nterface_99_modStripe_Stripe.class.php @@ -0,0 +1,159 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/triggers/interface_50_modStripe_Stripe.class.php + * \ingroup core + * \brief Fichier + * \remarks Son propre fichier d'actions peut etre cree par recopie de celui-ci: + * - Le nom du fichier doit etre: interface_99_modMymodule_Mytrigger.class.php + * ou: interface_99_all_Mytrigger.class.php + * - Le fichier doit rester stocke dans core/triggers + * - Le nom de la classe doit etre InterfaceMytrigger + * - Le nom de la propriete name doit etre Mytrigger + */ +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; +dol_include_once('/stripe/class/stripe.class.php'); +$path=dirname(__FILE__).'/'; +/** + * Class of triggers for stripe module + */ +class InterfaceStripe +{ + public $db; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + + $this->name = preg_replace('/^Interface/i', '', get_class($this)); + $this->family = 'Stripeconnect'; + $this->description = "Triggers of the module Stripeconnect"; + $this->version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' or version + $this->picto = 'stripe@stripe'; + } + + /** + * Trigger name + * + * @return string Name of trigger file + */ + public function getName() + { + return $this->name; + } + + + /** + * Trigger description + * + * @return string Description of trigger file + */ + public function getDesc() + { + return $this->description; + } + + /** + * Trigger version + * + * @return string Version of trigger file + */ + public function getVersion() + { + global $langs; + $langs->load("admin"); + + if ($this->version == 'development') { + return $langs->trans("Development"); + } elseif ($this->version == 'experimental') { + return $langs->trans("Experimental"); + } elseif ($this->version == 'dolibarr') { + return DOL_VERSION; + } elseif ($this->version) { + return $this->version; + } else { + return $langs->trans("Unknown"); + } + } + + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file + * is inside directory core/triggers + * + * @param string $action Event action code + * @param CommonObject $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param Conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) + { + // Put here code you want to execute when a Dolibarr business events occurs. + // Data and type of action are stored into $object and $action +global $langs,$db,$conf; +$langs->load("members"); +$langs->load("users"); +$langs->load("mails"); +$langs->load('other'); +/** Users */ +$ok=0; +$stripe=new Stripe($db); +if ($action == 'COMPANY_MODIFY') { + dol_syslog( + "Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id + ); +if ($stripe->GetStripeAccount($conf->entity)&&$object->client!=0) { +$cu=$stripe->CustomerStripe($object->id,$stripe->GetStripeAccount($conf->entity)); +if ($cu) { + if ($conf->entity=='1'){ +$customer = \Stripe\Customer::retrieve("$cu->id"); + }else{ +$customer = \Stripe\Customer::retrieve("$cu->id",array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); + } +if (!empty($object->email)) {$customer->email = "$object->email";} +$customer->description = "$object->name"; +$customer->save(); +}} + } +elseif ($action == 'COMPANY_DELETE') { + dol_syslog( + "Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id + ); +$cu=$stripe->CustomerStripe($object->id,$stripe->GetStripeAccount($conf->entity)); +if ($cu) { + if ($conf->entity==1){ + $customer = \Stripe\Customer::retrieve("$cu->id"); + }else{ + $customer = \Stripe\Customer::retrieve("$cu->id",array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); + } +$customer->delete(); +} + } + + return $ok; + } +} From 43803679232e819feb9d3c92c4ff6f10a3fcc3f4 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 12:54:53 +0100 Subject: [PATCH 271/413] Error management --- htdocs/core/class/html.formsms.class.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/html.formsms.class.php b/htdocs/core/class/html.formsms.class.php index 94e60ba8082..103b40e33df 100644 --- a/htdocs/core/class/html.formsms.class.php +++ b/htdocs/core/class/html.formsms.class.php @@ -205,8 +205,16 @@ function limitChars(textarea, limit, infodiv) try { $classname=ucfirst($classfile); - $sms = new $classname($this->db); - $resultsender = $sms->SmsSenderList(); + if (class_exists($classname)) + { + $sms = new $classname($this->db); + $resultsender = $sms->SmsSenderList(); + } + else + { + $sms = new stdClass(); + $sms->error='The SMS manager '.$classfile.' defined into SMS setup MAIN_SMS_SENDMODE is not found'; + } } catch(Exception $e) { From 3dd90a1f1a8b9f3ef25c7e4ed4bed9700a9d6245 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Tue, 13 Mar 2018 13:21:36 +0100 Subject: [PATCH 272/413] FIX name of file --- ...e_Stripe.class.php => interface_99_modStripe_Stripe.class.php} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename htdocs/core/triggers/{nterface_99_modStripe_Stripe.class.php => interface_99_modStripe_Stripe.class.php} (100%) diff --git a/htdocs/core/triggers/nterface_99_modStripe_Stripe.class.php b/htdocs/core/triggers/interface_99_modStripe_Stripe.class.php similarity index 100% rename from htdocs/core/triggers/nterface_99_modStripe_Stripe.class.php rename to htdocs/core/triggers/interface_99_modStripe_Stripe.class.php From e6d8219396c37fea03c385a2ca495951b4c750f9 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 13:26:03 +0100 Subject: [PATCH 273/413] Dolibarrize module ticket --- .../core/class/html.formticketsup.class.php | 29 ++++--- htdocs/core/lib/ticketsup.lib.php | 15 ++-- htdocs/ticketsup/card.php | 77 +++++++++++-------- htdocs/ticketsup/class/ticketsup.class.php | 17 ++-- .../ticketsup/{contacts.php => contact.php} | 21 +++-- htdocs/ticketsup/document.php | 2 +- htdocs/ticketsup/history.php | 2 +- htdocs/ticketsup/list.php | 43 +++++------ 8 files changed, 117 insertions(+), 89 deletions(-) rename htdocs/ticketsup/{contacts.php => contact.php} (94%) diff --git a/htdocs/core/class/html.formticketsup.class.php b/htdocs/core/class/html.formticketsup.class.php index 47df19ae8f5..bb77649dfcc 100644 --- a/htdocs/core/class/html.formticketsup.class.php +++ b/htdocs/core/class/html.formticketsup.class.php @@ -418,9 +418,10 @@ class FormTicketsup * @param int $empty 1=peut etre vide, 0 sinon * @param int $noadmininfo 0=Add admin info, 1=Disable admin info * @param int $maxlength Max length of label + * @param string $morecss More CSS * @return void */ - public function selectTypesTickets($selected = '', $htmlname = 'tickettype', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0) + public function selectTypesTickets($selected = '', $htmlname = 'tickettype', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0, $morecss='') { global $langs, $user; @@ -436,7 +437,7 @@ class FormTicketsup $ticketstat->loadCacheTypesTickets(); - print ''; if ($empty) { print ''; } @@ -503,6 +504,8 @@ class FormTicketsup if ($user->admin && !$noadmininfo) { print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } + + print ajax_combobox('select'.$htmlname); } /** @@ -513,11 +516,12 @@ class FormTicketsup * @param string $filtertype To filter on field type in llx_c_ticketsup_category (array('code'=>xx,'label'=>zz)) * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code * @param int $empty 1=peut etre vide, 0 sinon - * @param int $noadmininfo 0=Add admin info, 1=Disable admin info + * @param int $noadmininfo 0=Add admin info, 1=Disable admin info * @param int $maxlength Max length of label - * @return void + * @param string $morecss More CSS + * @return void */ - public function selectCategoriesTickets($selected = '', $htmlname = 'ticketcategory', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0) + public function selectCategoriesTickets($selected = '', $htmlname = 'ticketcategory', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0, $morecss='') { global $langs, $user; @@ -533,7 +537,7 @@ class FormTicketsup $ticketstat->loadCacheCategoriesTickets(); - print ''; if ($empty) { print ''; } @@ -601,6 +605,8 @@ class FormTicketsup if ($user->admin && !$noadmininfo) { print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } + + print ajax_combobox('select'.$htmlname); } /** @@ -611,11 +617,12 @@ class FormTicketsup * @param string $filtertype To filter on field type in llx_c_ticketsup_severity (array('code'=>xx,'label'=>zz)) * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code * @param int $empty 1=peut etre vide, 0 sinon - * @param int $noadmininfo 0=Add admin info, 1=Disable admin info + * @param int $noadmininfo 0=Add admin info, 1=Disable admin info * @param int $maxlength Max length of label - * @return void + * @param string $morecss More CSS + * @return void */ - public function selectSeveritiesTickets($selected = '', $htmlname = 'ticketseverity', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0) + public function selectSeveritiesTickets($selected = '', $htmlname = 'ticketseverity', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0, $morecss='') { global $langs, $user; @@ -631,7 +638,7 @@ class FormTicketsup $ticketstat->loadCacheSeveritiesTickets(); - print ''; if ($empty) { print ''; } @@ -698,6 +705,8 @@ class FormTicketsup if ($user->admin && !$noadmininfo) { print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } + + print ajax_combobox('select'.$htmlname); } /** diff --git a/htdocs/core/lib/ticketsup.lib.php b/htdocs/core/lib/ticketsup.lib.php index ca27e9e8024..68f8d820116 100644 --- a/htdocs/core/lib/ticketsup.lib.php +++ b/htdocs/core/lib/ticketsup.lib.php @@ -75,16 +75,19 @@ function ticketsup_prepare_head($object) $head[$h][2] = 'tabTicketsup'; $h++; - if (empty($user->socid)) { - $head[$h][0] = DOL_URL_ROOT.'/ticketsup/contacts.php?track_id=' . $object->track_id; - $head[$h][1] = $langs->trans('Contacts'); - $head[$h][2] = 'tabTicketContacts'; - $h++; + + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && empty($user->socid)) + { + $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external')); + $head[$h][0] = DOL_URL_ROOT.'/ticketsup/contact.php?track_id='.$object->track_id; + $head[$h][1] = $langs->trans('ContactsAddresses'); + if ($nbContact > 0) $head[$h][1].= ' '.$nbContact.''; + $head[$h][2] = 'contact'; + $h++; } complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticketsup'); - // Attached files include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; $upload_dir = $conf->ticketsup->dir_output . "/" . $object->track_id; diff --git a/htdocs/ticketsup/card.php b/htdocs/ticketsup/card.php index 5bf64d34cc8..dfc0704e824 100644 --- a/htdocs/ticketsup/card.php +++ b/htdocs/ticketsup/card.php @@ -77,10 +77,28 @@ if (GETPOST('modelselected')) { // Store current page url $url_page_current = dol_buildpath('/ticketsup/card.php', 1); -/*************************************************** - * PAGE - * - ****************************************************/ +if ($action == 'view' || $action == 'add_message' || $action == 'close' || $action == 'delete' || $action == 'editcustomer' || $action == 'progression' || $action == 'reopen' || $action == 'editsubject' || $action == 'edit_extrafields' || $action == 'set_extrafields' || $action == 'classify' || $action == 'sel_contract' || $action == 'edit_message_init' || $action == 'set_status' || $action == 'dellink') { + $res = $object->fetch($id, $track_id, $ref); +} + +// Security check +$result = restrictedArea($user, 'ticketsup', $object->dao->id); + + + +/* + * Actions + */ + +$permissiondellink = $user->rights->ticketsup->write; +include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + + + + +/* + * View + */ $userstat = new User($db); $form = new Form($db); @@ -90,21 +108,14 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti $res = $object->fetch($id, $track_id, $ref); if ($res > 0) { - // Security check - $result = restrictedArea($user, 'ticketsup', $object->dao->id); - // or for unauthorized internals users if (!$user->societe_id && ($conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY && $object->dao->fk_user_assign != $user->id) && !$user->rights->ticketsup->manage) { accessforbidden('', 0); } - - - $permissiondellink = $user->rights->ticketsup->write; - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - $help_url = 'FR:DocumentationModuleTicket'; $page_title = $object->getTitle($action); + llxHeader('', $page_title, $help_url); // Confirmation close @@ -193,7 +204,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti } else { print "ErrorRecordNotFound"; } - } elseif ($object->dao->fk_soc > 0) { + } elseif ($socid > 0) { $object->dao->fetch_thirdparty(); $head = societe_prepare_head($object->dao->thirdparty); dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); @@ -208,7 +219,9 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti } $head = ticketsup_prepare_head($object->dao); - dol_fiche_head($head, 'tabTicketsup', $langs->trans("Ticket"), 0, 'ticketsup'); + + dol_fiche_head($head, 'tabTicketsup', $langs->trans("Ticket"), -1, 'ticketsup'); + $object->dao->label = $object->dao->ref; // Author if ($object->dao->fk_user_create > 0) { @@ -409,11 +422,11 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti } } print ''; - + // View Original message $object->viewTicketOriginalMessage($user, $action); - - + + // Fin colonne gauche et début colonne droite print '
    '; @@ -579,9 +592,9 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti
    ' . $tab[$i]['libelle'] . '
    '; print '
    '; - + print dol_print_phone($tab[$i]['phone'], '', '', '', AC_TEL).'
    '; - + if (! empty($tab[$i]['phone_perso'])) { //print img_picto($langs->trans('PhonePerso'),'object_phoning.png','',0,0,0).' '; print '
    '.dol_print_phone($tab[$i]['phone_perso'], '', '', '', AC_TEL).'
    '; @@ -594,7 +607,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print ''; - + // Contract if ($action == 'sel_contract') { if (!empty($conf->contrat->enabled)) { $langs->load('contrats'); print load_fiche_titre($langs->trans('LinkToAContract'), '', 'title_commercial.png'); - + $form_contract = new FormContract($db); $form_contract->formSelectContract( $url_page_current.'?track_id='.$object->dao->track_id, @@ -641,7 +654,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print '
    '; print '
    '; - + print dol_fiche_end(); /* ActionBar */ @@ -650,7 +663,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti // Show button to mark as read if (($object->dao->fk_statut == '0' || empty($object->dao->date_read)) && !$user->societe_id) { print '
    '; - print '' . img_picto('', 'mark-read@ticketsup') . ' ' . $langs->trans('MarkAsRead') . ''; + print '' . img_picto('', 'mark-read@ticketsup', 'height="12px"') . ' ' . $langs->trans('MarkAsRead') . ''; print ''; print load_fiche_titre($langs->trans('TicketAddMessage'), '', 'messages@ticketsup'); @@ -724,7 +737,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->default_lang; } - + $formticket = new FormTicketsup($db); $formticket->action = $action; @@ -734,16 +747,16 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti $formticket->withfile = 2; $formticket->param = array('fk_user_create' => $user->id); $formticket->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); - + // Tableau des parametres complementaires du post $formticket->param['models']=$modelmail; $formticket->param['models_id']=GETPOST('modelmailselected', 'int'); //$formticket->param['socid']=$object->dao->fk_soc; $formticket->param['returnurl']=$_SERVER["PHP_SELF"].'?track_id='.$object->dao->track_id; - + $formticket->withsubstit = 1; - + if ($object->dao->fk_soc > 0) { $object->dao->fetch_thirdparty(); $formticket->substit['__THIRDPARTY_NAME__'] = $object->dao->thirdparty->name; @@ -761,13 +774,13 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti $userstat->fetch($object->dao->fk_user_assign); $formticket->substit['__TICKETSUP_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname); } - + if ($object->dao->fk_user_create > 0) { $userstat->fetch($object->dao->fk_user_create); $formticket->substit['__TICKETSUP_USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname); } - - + + $formticket->showMessageForm('100%'); print '
    '; } diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index f1f23b09dcd..f35f73c33e5 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -169,19 +169,19 @@ class Ticketsup extends CommonObject public $regeximgext = '\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff'; public $fields=array( - 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id"), - 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1), + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'position'=>1, 'visible'=>-2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id"), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>5, 'notnull'=>1, 'index'=>1), + 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object"), 'notify_tiers_at_create' => array('type'=>'integer', 'label'=>'NotifyThirdparty', 'visible'=>-2, 'enabled'=>0, 'position'=>20, 'notnull'=>1, 'index'=>1), - 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object"), 'track_id' => array('type'=>'varchar(255)', 'label'=>'TrackID', 'visible'=>0, 'enabled'=>1, 'position'=>30, 'notnull'=>-1, 'searchall'=>1, 'help'=>"Help text"), 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>1, 'help'=>"LinkToThirparty"), 'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php', 'label'=>'Project', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>1, 'help'=>"LinkToProject"), - 'origin_email' => array('type'=>'mail', 'label'=>'OriginEmail', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object"), + 'origin_email' => array('type'=>'mail', 'label'=>'OriginEmail', 'visible'=>1, 'enabled'=>1, 'position'=>11, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object"), 'fk_user_create' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Author', 'visible'=>1, 'enabled'=>1, 'position'=>510, 'notnull'=>1), 'fk_user_assign' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'AuthorAssign', 'visible'=>1, 'enabled'=>1, 'position'=>510, 'notnull'=>1), - 'subject' => array('type'=>'varchar(255)', 'label'=>'Subject', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), + 'subject' => array('type'=>'varchar(255)', 'label'=>'Subject', 'visible'=>1, 'enabled'=>1, 'position'=>12, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), 'message' => array('type'=>'text', 'label'=>'Message', 'visible'=>-2, 'enabled'=>1, 'position'=>60, 'notnull'=>-1,), - 'fk_statut' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array(0 => 'NotRead', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted')), + 'fk_statut' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>600, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array(0 => 'NotRead', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted')), 'resolution' => array('type'=>'integer', 'label'=>'Resolution', 'visible'=>-2, 'enabled'=>1, 'position'=>40, 'notnull'=>1), 'progress' => array('type'=>'varchar(100)', 'label'=>'Progression', 'visible'=>1, 'enabled'=>1, 'position'=>41, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), 'timing' => array('type'=>'varchar(20)', 'label'=>'Timing', 'visible'=>-1, 'enabled'=>1, 'position'=>42, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), @@ -2411,9 +2411,10 @@ class Ticketsup extends CommonObject * @param int $nodbprefix Do not include DB prefix to forge table name * @param string $morehtmlleft More html code to show before ref * @param string $morehtmlright More html code to show before navigation arrows + * @param string $onlybanner 1 * @return void */ - public function ticketsupBannerTab($paramid, $morehtml = '', $shownav = 1, $fieldid = 'id', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlright = '') + public function ticketsupBannerTab($paramid, $morehtml = '', $shownav = 1, $fieldid = 'id', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlright = '', $onlybanner=0) { global $conf, $form, $user, $langs; @@ -2425,7 +2426,7 @@ class Ticketsup extends CommonObject } $modulepart = 'ticketsup'; - print '
    '; + print '
    '; $width = 80; $height = 70; diff --git a/htdocs/ticketsup/contacts.php b/htdocs/ticketsup/contact.php similarity index 94% rename from htdocs/ticketsup/contacts.php rename to htdocs/ticketsup/contact.php index 9ef592b22a7..356aa47ffd5 100644 --- a/htdocs/ticketsup/contacts.php +++ b/htdocs/ticketsup/contact.php @@ -19,9 +19,9 @@ */ /** - * \file ticketsup/contacts.php + * \file ticketsup/contact.php * \ingroup ticketsup - * \brief Contacts des tickets + * \brief Contacts of tickets */ require '../main.inc.php'; @@ -61,7 +61,7 @@ if ($user->societe_id > 0) { } // Store current page url -$url_page_current = dol_buildpath('/ticketsup/contacts.php', 1); +$url_page_current = dol_buildpath('/ticketsup/contact.php', 1); $object = new Ticketsup($db); @@ -129,8 +129,9 @@ $userstatic = new User($db); /* *************************************************************************** */ if ($id > 0 || !empty($track_id) || !empty($ref)) { - if ($object->fetch($id, $track_id, $ref) > 0) { - if ($object->fk_soc > 0) { + if ($object->fetch($id, $track_id, $ref) > 0) + { + if ($socid > 0) { $object->fetch_thirdparty(); $head = societe_prepare_head($object->thirdparty); dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); @@ -143,8 +144,11 @@ if ($id > 0 || !empty($track_id) || !empty($ref)) { } elseif ($user->societe_id > 0) { $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } + $head = ticketsup_prepare_head($object); - dol_fiche_head($head, 'tabTicketContacts', $langs->trans("Ticket"), 0, 'ticketsup'); + + dol_fiche_head($head, 'contact', $langs->trans("Ticket"), -1, 'ticketsup'); + $object->label = $object->ref; // Author if ($object->fk_user_create > 0) { @@ -155,10 +159,11 @@ if ($id > 0 || !empty($track_id) || !empty($ref)) { $object->label .= $fuser->getNomUrl(0); } $linkback = '' . $langs->trans("BackToList") . ' '; - $object->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + $object->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback, 1); dol_fiche_end(); - print '
    '; + + //print '
    '; $permission = $user->rights->ticketsup->write; diff --git a/htdocs/ticketsup/document.php b/htdocs/ticketsup/document.php index f221dce73c2..0f528ee17bb 100644 --- a/htdocs/ticketsup/document.php +++ b/htdocs/ticketsup/document.php @@ -109,7 +109,7 @@ if ($object->id) { } $form = new Form($db); - if ($object->fk_soc > 0) { + if ($socid > 0) { $object->fetch_thirdparty(); $head = societe_prepare_head($object->thirdparty); dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); diff --git a/htdocs/ticketsup/history.php b/htdocs/ticketsup/history.php index 9bd69ade897..b4e0e0e9249 100644 --- a/htdocs/ticketsup/history.php +++ b/htdocs/ticketsup/history.php @@ -88,7 +88,7 @@ if ($action == 'view') { accessforbidden('', 0); } - if ($object->dao->fk_soc > 0) { + if ($socid > 0) { $object->dao->fetch_thirdparty(); $head = societe_prepare_head($object->dao->thirdparty); dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); diff --git a/htdocs/ticketsup/list.php b/htdocs/ticketsup/list.php index 52102b53596..b4c208e270b 100644 --- a/htdocs/ticketsup/list.php +++ b/htdocs/ticketsup/list.php @@ -35,12 +35,7 @@ if (!empty($conf->projet->enabled)) { } // Load traductions files requiredby by page -$langs->loadLangs( - array( - "ticketsup", - "companies", - "other") - ); +$langs->loadLangs(array("ticketsup","companies","other")); // Get parameters @@ -143,8 +138,6 @@ $url_page_current = dol_buildpath('/ticketsup/list.php', 1); /* * Actions - * - * Put here all code to do according to value of "$action" parameter */ if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } @@ -308,8 +301,13 @@ if ($socid && !$projectid && $user->rights->societe->lire) { $socstat = new Societe($db); $res = $socstat->fetch($socid); if ($res > 0) { + + $tmpobject = $object; + $object = $socstat; // $object must be of type Societe when calling societe_prepare_head $head = societe_prepare_head($socstat); - dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); + $object = $tmpobject; + + dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), -1, 'company'); dol_banner_tab($socstat, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); @@ -320,7 +318,7 @@ if ($socid && !$projectid && $user->rights->societe->lire) { // Customer code if ($socstat->client && !empty($socstat->code_client)) { - print ''; + print ''; print $langs->trans('CustomerCode') . ''; print $socstat->code_client; if ($socstat->check_codeclient() != 0) { @@ -360,7 +358,7 @@ if ($projectid) { $linkback = '' . $langs->trans("BackToList") . ''; // Ref - print '' . $langs->trans('Ref') . ''; + print '' . $langs->trans('Ref') . ''; // Define a complementary filter for search of next/prev ref. if (!$user->rights->projet->all->lire) { $objectsListId = $projectstat->getProjectsAuthorizedForUser($user, $mine, 0); @@ -374,7 +372,7 @@ if ($projectid) { // Customer print "" . $langs->trans("ThirdParty") . ""; - print ''; + print ''; if ($projectstat->thirdparty->id > 0) { print $projectstat->thirdparty->getNomUrl(1); } else { @@ -504,25 +502,24 @@ foreach($object->fields as $key => $val) if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; if ($key == 'status') $align.=($align?' ':'').'center'; if (! empty($arrayfields['t.'.$key]['checked'])) { - if ($key == 'fk_statut') { + if ($key == 'type_code') { print ''; - $object->printSelectStatus(dol_escape_htmltag($search[$key])); - print ''; - - } elseif ($key == 'type_code') { - print ''; - $formTicket->selectTypesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1); + $formTicket->selectTypesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 0, 1, 1, 0, 'maxwidth200'); print ''; } elseif ($key == 'category_code') { print ''; - $formTicket->selectCategoriesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1); + $formTicket->selectCategoriesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 0, 1, 1, 0, 'maxwidth200'); print ''; } elseif ($key == 'severity_code') { print ''; - $formTicket->selectSeveritiesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1); + $formTicket->selectSeveritiesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 0, 1, 1, 0, 'maxwidth200'); print ''; - } else { - + } elseif ($key == 'fk_statut') { + print ''; + $object->printSelectStatus(dol_escape_htmltag($search[$key])); + print ''; + } + else { print ''; } } From e6dd312bd5cf8683488c038e13a3094f379fc364 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 13:56:45 +0100 Subject: [PATCH 274/413] Debug ticket module --- htdocs/core/boxes/box_last_modified_ticketsup.php | 6 +++--- htdocs/core/boxes/box_last_ticketsup.php | 6 +++--- htdocs/core/modules/modTicketsup.class.php | 5 +++++ htdocs/langs/en_US/ticketsup.lang | 8 ++++---- htdocs/modulebuilder/template/myobject_list.php | 1 + htdocs/ticketsup/class/ticketsup.class.php | 5 ++--- htdocs/ticketsup/list.php | 10 ++++------ 7 files changed, 22 insertions(+), 19 deletions(-) diff --git a/htdocs/core/boxes/box_last_modified_ticketsup.php b/htdocs/core/boxes/box_last_modified_ticketsup.php index fd49653eced..c63864b0fe0 100644 --- a/htdocs/core/boxes/box_last_modified_ticketsup.php +++ b/htdocs/core/boxes/box_last_modified_ticketsup.php @@ -18,9 +18,9 @@ */ /** - * \file ticketsup/core/boxes/ticketsup_latest.php - * \ingroup ticketsup - * \brief This box shows latest UNREAD tickets + * \file core/boxes/box_last_modified_ticketsup.php + * \ingroup ticketsup + * \brief This box shows latest modified tickets */ require_once DOL_DOCUMENT_ROOT . "/core/boxes/modules_boxes.php"; diff --git a/htdocs/core/boxes/box_last_ticketsup.php b/htdocs/core/boxes/box_last_ticketsup.php index 6044bb179f5..5c39229835b 100644 --- a/htdocs/core/boxes/box_last_ticketsup.php +++ b/htdocs/core/boxes/box_last_ticketsup.php @@ -18,9 +18,9 @@ */ /** - * \file ticketsup/core/boxes/ticketsup_latest.php - * \ingroup ticketsup - * \brief This box shows latest tickets + * \file core/boxes/box_ticketsup_latest.php + * \ingroup ticketsup + * \brief This box shows latest created tickets */ require_once DOL_DOCUMENT_ROOT . "/core/boxes/modules_boxes.php"; diff --git a/htdocs/core/modules/modTicketsup.class.php b/htdocs/core/modules/modTicketsup.class.php index c6a6ada09f9..235ab092478 100644 --- a/htdocs/core/modules/modTicketsup.class.php +++ b/htdocs/core/modules/modTicketsup.class.php @@ -162,30 +162,35 @@ class modTicketsup extends DolibarrModules // Permissions $this->rights = array(); // Permission array used by this module + $r=0; $this->rights[$r][0] = 56001; // id de la permission $this->rights[$r][1] = "Read ticket"; // libelle de la permission $this->rights[$r][2] = 'r'; // type de la permission (deprecie a ce jour) $this->rights[$r][3] = 1; // La permission est-elle une permission par defaut $this->rights[$r][4] = 'read'; + $r++; $this->rights[$r][0] = 56002; // id de la permission $this->rights[$r][1] = "Create les tickets"; // libelle de la permission $this->rights[$r][2] = 'w'; // type de la permission (deprecie a ce jour) $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut $this->rights[$r][4] = 'write'; + $r++; $this->rights[$r][0] = 56003; // id de la permission $this->rights[$r][1] = "Delete les tickets"; // libelle de la permission $this->rights[$r][2] = 'd'; // type de la permission (deprecie a ce jour) $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut $this->rights[$r][4] = 'delete'; + $r++; $this->rights[$r][0] = 56004; // id de la permission $this->rights[$r][1] = "Manage tickets"; // libelle de la permission //$this->rights[$r][2] = 'd'; // type de la permission (deprecie a ce jour) $this->rights[$r][3] = 0; // La permission est-elle une permission par defaut $this->rights[$r][4] = 'manage'; + $r++; $this->rights[$r][0] = 56005; // id de la permission $this->rights[$r][1] = 'See all tickets, even if not assigned to (not effective for external users, always restricted to the thirdpardy they depends on)'; // libelle de la permission $this->rights[$r][2] = 'r'; // type de la permission (deprecie a ce jour) diff --git a/htdocs/langs/en_US/ticketsup.lang b/htdocs/langs/en_US/ticketsup.lang index 9064222637a..a4e04930def 100644 --- a/htdocs/langs/en_US/ticketsup.lang +++ b/htdocs/langs/en_US/ticketsup.lang @@ -291,11 +291,11 @@ TicketNotificationNumberEmailSent=Notification email sent : %s # # Boxes # -BoxLastTicketsup=Last tickets -BoxLastTicketsupDescription=Last %s tickets saved +BoxLastTicketsup=Latest created tickets +BoxLastTicketsupDescription=Latest %s created tickets BoxLastTicketsupContent= BoxLastTicketsupNoRecordedTickets=No recent unread tickets -BoxLastModifiedTicketsup=Last modified tickets -BoxLastModifiedTicketsupDescription=Last %s tickets modified +BoxLastModifiedTicketsup=Latest modified tickets +BoxLastModifiedTicketsupDescription=Latest %s modified tickets BoxLastModifiedTicketsupContent= BoxLastModifiedTicketsupNoRecordedTickets=No recent modified tickets diff --git a/htdocs/modulebuilder/template/myobject_list.php b/htdocs/modulebuilder/template/myobject_list.php index 2ef8fa97030..2ac18cb5db4 100644 --- a/htdocs/modulebuilder/template/myobject_list.php +++ b/htdocs/modulebuilder/template/myobject_list.php @@ -220,6 +220,7 @@ if ($object->ismultientitymanaged == 1) $sql.= " WHERE t.entity IN (".getEntity( else $sql.=" WHERE 1 = 1"; foreach($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) continue; $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); } diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index f35f73c33e5..a7b95bedbbe 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -181,7 +181,6 @@ class Ticketsup extends CommonObject 'fk_user_assign' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'AuthorAssign', 'visible'=>1, 'enabled'=>1, 'position'=>510, 'notnull'=>1), 'subject' => array('type'=>'varchar(255)', 'label'=>'Subject', 'visible'=>1, 'enabled'=>1, 'position'=>12, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), 'message' => array('type'=>'text', 'label'=>'Message', 'visible'=>-2, 'enabled'=>1, 'position'=>60, 'notnull'=>-1,), - 'fk_statut' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>600, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array(0 => 'NotRead', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted')), 'resolution' => array('type'=>'integer', 'label'=>'Resolution', 'visible'=>-2, 'enabled'=>1, 'position'=>40, 'notnull'=>1), 'progress' => array('type'=>'varchar(100)', 'label'=>'Progression', 'visible'=>1, 'enabled'=>1, 'position'=>41, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), 'timing' => array('type'=>'varchar(20)', 'label'=>'Timing', 'visible'=>-1, 'enabled'=>1, 'position'=>42, 'notnull'=>-1, 'searchall'=>1, 'help'=>""), @@ -191,8 +190,8 @@ class Ticketsup extends CommonObject 'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1), 'date_read' => array('type'=>'datetime', 'label'=>'TicketReadOn', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1), 'date_close' => array('type'=>'datetime', 'label'=>'TicketCloseOn', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1), - 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>501, 'notnull'=>1) - + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>501, 'notnull'=>1), + 'fk_statut' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>600, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array(0 => 'NotRead', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted')) ); /** diff --git a/htdocs/ticketsup/list.php b/htdocs/ticketsup/list.php index b4c208e270b..a54394522f8 100644 --- a/htdocs/ticketsup/list.php +++ b/htdocs/ticketsup/list.php @@ -214,8 +214,9 @@ if ($object->ismultientitymanaged == 1) $sql.= " WHERE t.entity IN (".getEntity( else $sql.=" WHERE 1 = 1"; foreach($search as $key => $val) { + if ($key == 'fk_statut' && $search[$key] == -1) continue; $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); - if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); + if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'fk_statut')?2:$mode_search)); } if ($search_all) $sql.= natural_search(array_keys($fieldstosearchall), $search_all); @@ -436,8 +437,9 @@ print ''; print ''; print ''; +$buttontocreate = ''; -print_barre_liste($langs->trans('TicketList'), $page, 'list.php', $param, $sortfield, $sortorder, '', $num, $num_total, 'title_ticketsup'); +print_barre_liste($langs->trans('TicketList'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_ticketsup', 0, $buttontocreate, '', $limit); if ($mode == 'my_assign') { print '
    ' . $langs->trans('TicketAssignedToMeInfos') . '

    '; @@ -674,10 +676,6 @@ print '
    '."\n"; print ''."\n"; -print ''; - if (in_array('builddoc',$arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { From 9f07ff0f9bca3529f740cb09bec93e212e3642ef Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 14:00:35 +0100 Subject: [PATCH 275/413] Fix travis --- htdocs/core/modules/modTicketsup.class.php | 40 +++------------------- 1 file changed, 5 insertions(+), 35 deletions(-) diff --git a/htdocs/core/modules/modTicketsup.class.php b/htdocs/core/modules/modTicketsup.class.php index 235ab092478..00d01031294 100644 --- a/htdocs/core/modules/modTicketsup.class.php +++ b/htdocs/core/modules/modTicketsup.class.php @@ -300,13 +300,12 @@ class modTicketsup extends DolibarrModules } /** - * Function called when module is enabled. - * The init function add constants, boxes, permissions and menus - * (defined in constructor) into Dolibarr database. - * It also creates data directories + * Function called when module is enabled. + * The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database. + * It also creates data directories * - * @param string $options Options when enabling module ('', 'noboxes') - * @return int 1 if OK, 0 if KO + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO */ public function init($options = '') { @@ -319,36 +318,7 @@ class modTicketsup extends DolibarrModules array("sql" => "insert into llx_c_action_trigger (rowid,code,label,description,elementtype,rang) values ('','TICKETMESSAGE_SENTBYMAIL','Send email for ticket','Executed when a response is made on a ticket','ticketsup','');", "ignoreerror" => 1), ); - $result = $this->loadTables(); - return $this->_init($sql, $options); } - /** - * Function called when module is disabled. - * Remove from database constants, boxes and permissions from Dolibarr database. - * Data directories are not deleted - * - * @param string $options Options when enabling module ('', 'noboxes') - * @return int 1 if OK, 0 if KO - */ - public function remove($options = '') - { - $sql = array(); - - return $this->_remove($sql, $options); - } - - /** - * Create tables, keys and data required by module - * Files llx_table1.sql, llx_table1.key.sql llx_data.sql with create table, create keys - * and create data commands must be stored in directory /ticketsup/sql/ - * This function is called by this->init - * - * @return int <=0 if KO, >0 if OK - */ - private function loadTables() - { - return $this->_load_tables(); - } } From b25f3ba3223f0a5dc4b6797fde5fd436516afed2 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 14:13:32 +0100 Subject: [PATCH 276/413] Fix to avoid stripe live mode beeing disabled when stripeconnect off --- htdocs/stripe/charge.php | 2 +- htdocs/stripe/class/actions_stripe.class.php | 14 +++++++------- htdocs/stripe/class/stripe.class.php | 2 +- htdocs/stripe/transaction.php | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/htdocs/stripe/charge.php b/htdocs/stripe/charge.php index 2c937e318a4..413ed3ec815 100644 --- a/htdocs/stripe/charge.php +++ b/htdocs/stripe/charge.php @@ -61,7 +61,7 @@ $societestatic = new Societe($db); $memberstatic = new Adherent($db); $acc = new Account($db); $stripe=new Stripe($db); -if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) +if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha'))) { $service = 'StripeTest'; dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); diff --git a/htdocs/stripe/class/actions_stripe.class.php b/htdocs/stripe/class/actions_stripe.class.php index 1dc4082a4f0..baeba001edf 100644 --- a/htdocs/stripe/class/actions_stripe.class.php +++ b/htdocs/stripe/class/actions_stripe.class.php @@ -55,11 +55,11 @@ class ActionsStripeconnect { $this->db = $db; } - + /** * formObjectOptions - * + * * @param array $parameters Parameters * @param Object $object Object * @param string $action Action @@ -68,7 +68,7 @@ class ActionsStripeconnect { global $db,$conf,$user,$langs,$form; - if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) + if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha'))) { $service = 'StripeTest'; dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); @@ -85,7 +85,7 @@ class ActionsStripeconnect $key=$value; } } - + if (is_object($object) && $object->element == 'societe') { @@ -106,7 +106,7 @@ class ActionsStripeconnect $this->resprints.= $langs->trans("NoStripe"); } $this->resprints.= ''; - + } elseif (is_object($object) && $object->element == 'member'){ $this->resprints.= ''; @@ -125,7 +125,7 @@ class ActionsStripeconnect $this->resprints.= $langs->trans("NoStripe"); } $this->resprints.= ''; - + $this->resprints.= ''; $this->resprints.= ''; } @@ -460,22 +471,23 @@ if ($socid && $action != 'edit' && $action != "create") print '
    '; $this->resprints.= $langs->trans('SubscriptionStripe'); @@ -167,7 +167,7 @@ class ActionsStripeconnect /** * addMoreActionsButtons - * + * * @param arra $parameters Parameters * @param Object $object Object * @param string $action action diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index d6d1601d405..efc7415327c 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -295,7 +295,7 @@ class Stripe extends CommonObject if (isset($charge->id)) {} } - if (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; + if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; else $service = 'StripeLive'; $return->statut = 'success'; diff --git a/htdocs/stripe/transaction.php b/htdocs/stripe/transaction.php index 56d94c36dee..5390b3a170c 100644 --- a/htdocs/stripe/transaction.php +++ b/htdocs/stripe/transaction.php @@ -55,7 +55,7 @@ $societestatic = new societe($db); $acc = new Account($db); $stripe = new Stripe($db); -if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox', 'alpha'))) +if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha'))) { $service = 'StripeTest'; dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); From d6e8872af4a37b985481507b0a499c6c3060abdf Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 14:14:33 +0100 Subject: [PATCH 277/413] Update interface_99_modStripe_Stripe.class.php --- .../interface_99_modStripe_Stripe.class.php | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/htdocs/core/triggers/interface_99_modStripe_Stripe.class.php b/htdocs/core/triggers/interface_99_modStripe_Stripe.class.php index e75d87c36f6..0fff7b6a58e 100644 --- a/htdocs/core/triggers/interface_99_modStripe_Stripe.class.php +++ b/htdocs/core/triggers/interface_99_modStripe_Stripe.class.php @@ -121,18 +121,27 @@ $langs->load("mails"); $langs->load('other'); /** Users */ $ok=0; -$stripe=new Stripe($db); +$stripe=new Stripe($db); +if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) +{ + $service = 'StripeTest'; +} +else +{ + $service = 'StripeLive'; +} + if ($action == 'COMPANY_MODIFY') { dol_syslog( "Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id ); -if ($stripe->GetStripeAccount($conf->entity)&&$object->client!=0) { -$cu=$stripe->CustomerStripe($object->id,$stripe->GetStripeAccount($conf->entity)); +if ($stripe->getStripeAccount($service) && $object->client!=0) { +$cu=$stripe->CustomerStripe($object->id,$stripe->getStripeAccount($service)); if ($cu) { if ($conf->entity=='1'){ $customer = \Stripe\Customer::retrieve("$cu->id"); }else{ -$customer = \Stripe\Customer::retrieve("$cu->id",array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); +$customer = \Stripe\Customer::retrieve("$cu->id",array("stripe_account" => $stripe->getStripeAccount($service))); } if (!empty($object->email)) {$customer->email = "$object->email";} $customer->description = "$object->name"; @@ -143,12 +152,12 @@ elseif ($action == 'COMPANY_DELETE') { dol_syslog( "Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id ); -$cu=$stripe->CustomerStripe($object->id,$stripe->GetStripeAccount($conf->entity)); +$cu=$stripe->CustomerStripe($object->id,$stripe->getStripeAccount($service)); if ($cu) { if ($conf->entity==1){ $customer = \Stripe\Customer::retrieve("$cu->id"); }else{ - $customer = \Stripe\Customer::retrieve("$cu->id",array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); + $customer = \Stripe\Customer::retrieve("$cu->id",array("stripe_account" => $stripe->getStripeAccount($service))); } $customer->delete(); } From 4b7f4d29d1d5d29d0d0d10ccde26acf6b895e4ce Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 14:19:26 +0100 Subject: [PATCH 278/413] Update interface_99_modStripe_Stripe.class.php --- htdocs/core/triggers/interface_99_modStripe_Stripe.class.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/htdocs/core/triggers/interface_99_modStripe_Stripe.class.php b/htdocs/core/triggers/interface_99_modStripe_Stripe.class.php index 0fff7b6a58e..f639695cc40 100644 --- a/htdocs/core/triggers/interface_99_modStripe_Stripe.class.php +++ b/htdocs/core/triggers/interface_99_modStripe_Stripe.class.php @@ -122,7 +122,9 @@ $langs->load('other'); /** Users */ $ok=0; $stripe=new Stripe($db); -if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) +if (empty($conf->stripe->enabled)) return 0; + +if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha'))) { $service = 'StripeTest'; } From 59b7187501f26acac7077fe62279c775343ec8f7 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 14:20:23 +0100 Subject: [PATCH 279/413] Rename interface_99_modStripe_Stripe.class.php to interface_80_modStripe_Stripe.class.php --- ...e_Stripe.class.php => interface_80_modStripe_Stripe.class.php} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename htdocs/core/triggers/{interface_99_modStripe_Stripe.class.php => interface_80_modStripe_Stripe.class.php} (100%) diff --git a/htdocs/core/triggers/interface_99_modStripe_Stripe.class.php b/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php similarity index 100% rename from htdocs/core/triggers/interface_99_modStripe_Stripe.class.php rename to htdocs/core/triggers/interface_80_modStripe_Stripe.class.php From f7dd7e89de2b700967a3729c6e9b05fb3532272d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 14:44:35 +0100 Subject: [PATCH 280/413] Add option to create stripe customer if not found (so we can use function to find without side effect) --- htdocs/stripe/class/stripe.class.php | 58 ++++++++++++++-------------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 4964b0bda38..a0f6008b6f8 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -124,25 +124,19 @@ class Stripe extends CommonObject /** - * customerStripe + * Get the Stripe customer of a thirdparty (with option to create it if not linked yet) * - * @param int $id Id of third party - * @return string Stripe account ref 'acc_xxxxxxxxxxxxx' - * @return \Stripe\StripeObject|\Stripe\ApiResource + * @param int $id Id of third party + * @param string $key Stripe account acc_.... + * @param int $status Status (0=test, 1=live) + * @param int $createifnotlinkedtostripe 1=Create the stripe customer and the link if the thirdparty is not yet linked to a stripe customer + * @return \Stripe\StripeObject|\Stripe\ApiResource|null Stripe Customer or null if not found */ - public function customerStripe($id,$key) + public function customerStripe($id, $key, $status=0, $createifnotlinkedtostripe=0) { global $conf; - if (empty($conf->global->STRIPECONNECT_LIVE)) { - $mode = 0; - } else { - if (empty($conf->global->STRIPE_LIVE)) { - $mode = 0; - } else { - $mode = $conf->global->STRIPE_LIVE; - } - } - $sql = "SELECT sa.key_account as key_account, sa.entity"; + + $sql = "SELECT sa.key_account as key_account, sa.entity"; // key_account is cu_.... $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa"; $sql.= " WHERE sa.fk_soc = " . $id; $sql.= " AND sa.entity IN (".getEntity('societe').")"; @@ -164,24 +158,28 @@ class Stripe extends CommonObject "stripe_account" => $key )); } - } else { + } + else + { if ($conf->entity == 1) { $customer = \Stripe\Customer::create(array( "email" => $soc->email, + "business_vat_id" => $soc->tva_intra, "description" => $soc->name )); } else { $customer = \Stripe\Customer::create(array( "email" => $soc->email, + "business_vat_id" => $soc->tva_intra, "description" => $soc->name ), array( "stripe_account" => $key )); } - $customer_id = "" . $customer->id . ""; - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_account (fk_soc,key_account,site,status,entity)"; - $sql .= " VALUES ($id,'$customer_id','stripe'," . $mode . "," . $conf->entity . ")"; - dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $customer_id = $customer->id; + + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_account (fk_soc, key_account, site, status, entity)"; + $sql .= " VALUES (".$id.", '".$this->db->escape($customer_id)."', 'stripe', " . $status . "," . $conf->entity . ")"; $resql = $this->db->query($sql); } } @@ -189,25 +187,28 @@ class Stripe extends CommonObject } /** - * createPaymentStripe Create charge with public/payment/newpayment.php, stripe/card.php, cronjobs or REST API + * Create charge with public/payment/newpayment.php, stripe/card.php, cronjobs or REST API * - * @param int $amount amount to pay - * @param string $currency EUR, GPB... + * @param int $amount Amount to pay + * @param string $currency EUR, GPB... * @param string $origin order, invoice, contract... * @param int $item if of element to pay * @param string $source src_xxxxx or card_xxxxx or ac_xxxxx - * @param string $customer Stripe account ref 'cu_xxxxxxxxxxxxx' via customerStripe() + * @param string $customer Stripe account ref 'cu_xxxxxxxxxxxxx' via customerStripe() * @param string $account Stripe account ref 'acc_xxxxxxxxxxxxx' via getStripeAccount() - * @param int $status Status + * @param int $status Status (0=test, 1=live) * @return Stripe */ public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account, $status=0) { global $conf; + if (empty($status)) $service = 'StripeTest'; + else $service = 'StripeLive'; + $sql = "SELECT sa.key_account as key_account, sa.entity"; $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa"; - $sql.= " WHERE sa.key_account = " . $customer; + $sql.= " WHERE sa.key_account = '" . $this->db->escape($customer) . "'"; //$sql.= " AND sa.entity IN (".getEntity('societe').")"; $sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status); @@ -223,7 +224,7 @@ class Stripe extends CommonObject } else { $key = NULL; } - + $stripeamount = round($amount * 100); $societe = new Societe($this->db); $societe->fetch($fksoc); @@ -293,9 +294,6 @@ class Stripe extends CommonObject if (isset($charge->id)) {} } - if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; - else $service = 'StripeLive'; - $return->statut = 'success'; $return->id = $charge->id; if ($charge->source->type == 'card') { From 9c92e092954b927efcbd251c7e445388e41a7e50 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 14:48:01 +0100 Subject: [PATCH 281/413] Fix syntax --- .../interface_80_modStripe_Stripe.class.php | 117 +++++++++--------- 1 file changed, 59 insertions(+), 58 deletions(-) diff --git a/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php b/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php index f639695cc40..a41ade1e01b 100644 --- a/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php +++ b/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php @@ -29,7 +29,7 @@ */ require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; dol_include_once('/stripe/class/stripe.class.php'); -$path=dirname(__FILE__).'/'; +$path=dirname(__FILE__).'/'; /** * Class of triggers for stripe module */ @@ -102,69 +102,70 @@ class InterfaceStripe * All functions "runTrigger" are triggered if file * is inside directory core/triggers * - * @param string $action Event action code - * @param CommonObject $object Object - * @param User $user Object user - * @param Translate $langs Object langs - * @param Conf $conf Object conf - * @return int <0 if KO, 0 if no triggered ran, >0 if OK + * @param string $action Event action code + * @param CommonObject $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param Conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK */ - public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) { // Put here code you want to execute when a Dolibarr business events occurs. // Data and type of action are stored into $object and $action -global $langs,$db,$conf; -$langs->load("members"); -$langs->load("users"); -$langs->load("mails"); -$langs->load('other'); -/** Users */ -$ok=0; -$stripe=new Stripe($db); -if (empty($conf->stripe->enabled)) return 0; + global $langs, $db, $conf; + $langs->load("members"); + $langs->load("users"); + $langs->load("mails"); + $langs->load('other'); + + $ok = 0; + $stripe = new Stripe($db); + if (empty($conf->stripe->enabled)) return 0; + + if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha')) + { + $service = 'StripeTest'; + } + else + { + $service = 'StripeLive'; + } + + if ($action == 'COMPANY_MODIFY') { + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + if ($stripe->getStripeAccount($service) && $object->client != 0) { + $cu = $stripe->customerStripe($object->id, $stripe->getStripeAccount($service)); + if ($cu) { + if ($conf->entity == '1') { + $customer = \Stripe\Customer::retrieve("$cu->id"); + } else { + $customer = \Stripe\Customer::retrieve("$cu->id", array( + "stripe_account" => $stripe->getStripeAccount($service) + )); + } + if (! empty($object->email)) { + $customer->email = "$object->email"; + } + $customer->description = "$object->name"; + $customer->save(); + } + } + } elseif ($action == 'COMPANY_DELETE') { + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + $cu = $stripe->customerStripe($object->id, $stripe->getStripeAccount($service)); + if ($cu) { + if ($conf->entity == 1) { + $customer = \Stripe\Customer::retrieve("$cu->id"); + } else { + $customer = \Stripe\Customer::retrieve("$cu->id", array( + "stripe_account" => $stripe->getStripeAccount($service) + )); + } + $customer->delete(); + } + } -if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha'))) -{ - $service = 'StripeTest'; -} -else -{ - $service = 'StripeLive'; -} - -if ($action == 'COMPANY_MODIFY') { - dol_syslog( - "Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id - ); -if ($stripe->getStripeAccount($service) && $object->client!=0) { -$cu=$stripe->CustomerStripe($object->id,$stripe->getStripeAccount($service)); -if ($cu) { - if ($conf->entity=='1'){ -$customer = \Stripe\Customer::retrieve("$cu->id"); - }else{ -$customer = \Stripe\Customer::retrieve("$cu->id",array("stripe_account" => $stripe->getStripeAccount($service))); - } -if (!empty($object->email)) {$customer->email = "$object->email";} -$customer->description = "$object->name"; -$customer->save(); -}} - } -elseif ($action == 'COMPANY_DELETE') { - dol_syslog( - "Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id - ); -$cu=$stripe->CustomerStripe($object->id,$stripe->getStripeAccount($service)); -if ($cu) { - if ($conf->entity==1){ - $customer = \Stripe\Customer::retrieve("$cu->id"); - }else{ - $customer = \Stripe\Customer::retrieve("$cu->id",array("stripe_account" => $stripe->getStripeAccount($service))); - } -$customer->delete(); -} - } - return $ok; } } From a955e743291a5282cd317ecd8d889633960b44f0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 15:19:31 +0100 Subject: [PATCH 282/413] Better MVC --- htdocs/societe/paymentmodes.php | 85 ++++++++++++++++------------ htdocs/stripe/class/stripe.class.php | 14 +++-- 2 files changed, 57 insertions(+), 42 deletions(-) diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index f4d9f1b6173..53f714b414c 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -69,6 +69,21 @@ $hookmanager->initHooks(array('thirdpartybancard','globalcard')); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('thirdpartybancard')); +if (! empty($conf->stripe->enabled)) +{ + $service = 'StripeTest'; + $servicestatus = 0; + if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox','alpha')) + { + $service = 'StripeLive'; + $servicestatus = 0; + } + + $stripe = new Stripe($db); + $stripeacc = $stripe->getStripeAccount($service); // Stripe OAuth connect account of dolibarr user (no network access here) + $stripecu = $stripe->getStripeCustomerAccount($object->id, $servicestatus); // Get thirdparty cu_... +} + /* @@ -91,7 +106,6 @@ if (empty($reshook)) } } - if ($action == 'update' && ! $_POST["cancel"]) { // Modification @@ -332,32 +346,29 @@ if (empty($reshook)) $id = $savid; } +// Action for stripe if (! empty($conf->stripe->enabled) && class_exists('Stripe')) { - $stripe=new Stripe($db); - - if (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; - else $service = 'StripeLive'; - - $customerstripe=$stripe->customerStripe($socid, $stripe->getStripeAccount($service)); - if ($customerstripe->id) { - $cu = \Stripe\Customer::retrieve("".$customerstripe->id."");} - - $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; if ($action == 'setassourcedefault') { - $cu->default_source = "$source"; // obtained with Stripe.js - $cu->save(); + $cu = \Stripe\Customer::retrieve($stripecu); - header('Location: '.$url); - exit; + $cu->default_source = "$source"; // obtained with Stripe.js + $cu->save(); + + $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; + header('Location: '.$url); + exit; } elseif ($action == 'delete') { - $cu->sources->retrieve("$source")->detach(); + $cu = \Stripe\Customer::retrieve($stripecu); - header('Location: '.$url); - exit; + $cu->sources->retrieve("$source")->detach(); + + $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; + header('Location: '.$url); + exit; } } @@ -446,13 +457,13 @@ if ($socid && $action != 'edit' && $action != "create") if ($conf->contrat->enabled && $user->rights->contrat->lire) $elementTypeArray['contract']=$langs->transnoentitiesnoconv('Contracts'); } - if (! (empty($conf->stripe->enabled))) + if (! empty($conf->stripe->enabled)) { - $stripe = new Stripe($db); - // Prospect/Customer + + // Stripe customer key 'cu_....' stored into llx_societe_account print '
    '.$langs->trans('StripeCustomerId').''; - print $stripe->getStripeCustomerAccount($object->id); + print $stripecu; print '
    '; print '
    '; + print '
    '; + if (! (empty($conf->stripe->enabled))) { - print load_fiche_titre($langs->trans('StripeGateways'), '', ''); + print load_fiche_titre($langs->trans('StripeGateways').($stripeacc ? ' ('.$stripeacc.')':''), '', ''); - if (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; - else $service = 'StripeLive'; - - if (is_object($stripe) && $stripe->getStripeAccount($service)) + $listofsources = array(); + if (is_object($stripe) && $stripeacc) { - $customerstripe=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service)); - } - - if ($customerstripe->id) { - $input=$customerstripe->sources->data; + $customerstripe=$stripe->customerStripe($object->id, $stripeacc, $servicestatus); + + if ($customerstripe->id) { + $listofsources=$customerstripe->sources->data; + } } + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''."\n"; print ''; print ''; @@ -484,9 +496,9 @@ if ($socid && $action != 'edit' && $action != "create") print ''; print "\n"; - if (is_array($input)) + if (is_array($listofsources)) { - foreach ($input as $src) + foreach ($listofsources as $src) { print ''; print ''; } } - if (empty($input)) + if (empty($listofsources)) { print ''; } print "
    '.$langs->trans('Type').''.$langs->trans('Default').'
    '; @@ -581,11 +593,12 @@ if ($socid && $action != 'edit' && $action != "create") print '
    '.$langs->trans("NoSource").'
    "; + print "
    "; } @@ -599,7 +612,7 @@ if ($socid && $action != 'edit' && $action != "create") $var = false; if (is_array($rib_list)) { - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''; print ''; diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index a0f6008b6f8..dfecc56a172 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -55,7 +55,7 @@ class Stripe extends CommonObject * Return main company OAuth Connect stripe account * * @param string $mode 'StripeTest' or 'StripeLive' - * @return int ??? + * @return string Stripe account 'acc_....' */ public function getStripeAccount($mode='StripeTest') { @@ -106,7 +106,7 @@ class Stripe extends CommonObject $sql.= " AND sa.entity IN (".getEntity('societe').")"; $sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status); - dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); + dol_syslog(get_class($this) . "::getStripeCustomerAccount Try to find the cu_.... of thirdparty id=".$id, LOG_DEBUG); $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { @@ -145,10 +145,9 @@ class Stripe extends CommonObject dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $soc = new Societe($this->db); - $soc->fetch($id); $num = $this->db->num_rows($resql); - if ($num) { + if ($num) + { $obj = $this->db->fetch_object($resql); $tiers = $obj->key_account; if ($conf->entity == 1) { @@ -159,8 +158,11 @@ class Stripe extends CommonObject )); } } - else + elseif ($createifnotlinkedtostripe) { + $soc = new Societe($this->db); + $soc->fetch($id); + if ($conf->entity == 1) { $customer = \Stripe\Customer::create(array( "email" => $soc->email, From 17b7c6268e81a0a13e1bc74e99e6efa9b489b3a6 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 15:29:52 +0100 Subject: [PATCH 283/413] FIX avoid "Array" on screen --- htdocs/projet/element.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/htdocs/projet/element.php b/htdocs/projet/element.php index 2b753a50468..8b791b7a9c7 100644 --- a/htdocs/projet/element.php +++ b/htdocs/projet/element.php @@ -1137,9 +1137,12 @@ foreach ($listofreferent as $key => $value) print ''; print ''; } - else // error + else { - print $elementarray; + if (! is_array($elementarray)) // error + { + print $elementarray; + } } print "
     
    "; print "
    \n"; From 1ff13cff7afc10f041cb21bb64b2d92b7ff27ca7 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Tue, 13 Mar 2018 15:43:11 +0100 Subject: [PATCH 284/413] Fix select by default gateway's icon --- htdocs/societe/paymentmodes.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 53f714b414c..abaaf0e694d 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -570,7 +570,7 @@ if ($socid && $action != 'edit' && $action != "create") print ''; // Default print ''; - if (($cu->default_source!=$src->id)) + if (($customerstripe->default_source!=$src->id)) { print ''; print ""; From af09a3714b3ea937730cb171b008635429d94bc8 Mon Sep 17 00:00:00 2001 From: atm-quentin Date: Tue, 13 Mar 2018 17:12:03 +0100 Subject: [PATCH 285/413] FIX reverse field to have object loaded in doaction --- htdocs/societe/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index 42abde0e09b..204eff383d5 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -73,7 +73,7 @@ $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('thirdpartycard','globalcard')); -if ($action == 'view' && $object->fetch($socid)<=0) +if ($object->fetch($socid)<=0 && $action == 'view') { $langs->load("errors"); print($langs->trans('ErrorRecordNotFound')); From 944ba69cd8d35dfe5b41ee86a74bb83733f18055 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 17:32:49 +0100 Subject: [PATCH 286/413] Add unique key. Dolibarrize view of stripe card. --- htdocs/core/class/html.form.class.php | 10 +- htdocs/core/lib/company.lib.php | 3 + .../install/mysql/migration/7.0.0-8.0.0.sql | 4 +- .../mysql/tables/llx_societe_account.key.sql | 1 + .../mysql/tables/llx_societe_account.sql | 2 +- .../class/societeaccount.class.php} | 54 +++--- htdocs/societe/paymentmodes.php | 159 +++++++++++++----- 7 files changed, 158 insertions(+), 75 deletions(-) rename htdocs/{website/class/websiteaccount.class.php => societe/class/societeaccount.class.php} (91%) diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 70274040fd3..4d263611390 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -81,9 +81,10 @@ class Form * @param string $moreparam More param to add on a href URL. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS. * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' ' + * @param string $paramid Key of parameter for id ('id', 'socid') * @return string HTML edit field */ - function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0) + function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0, $paramid='id') { global $conf,$langs; @@ -117,7 +118,7 @@ class Form if (! empty($notabletag)) $ret.=' '; if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; - if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).''; + if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).''; if (! empty($notabletag) && $notabletag == 1) $ret.=' : '; if (! empty($notabletag) && $notabletag == 3) $ret.=' '; if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; @@ -142,9 +143,10 @@ class Form * @param string $moreparam More param to add on a href URL * @param int $notabletag Do no output table tags * @param string $formatfunc Call a specific function to output field + * @param string $paramid Key of parameter for id ('id', 'socid') * @return string HTML edit field */ - function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='') + function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='', $paramid='id') { global $conf,$langs,$db; @@ -166,7 +168,7 @@ class Form $ret.='
    '; $ret.=''; $ret.=''; - $ret.=''; + $ret.=''; if (empty($notabletag)) $ret.=''; if (empty($notabletag)) $ret.=''; - } print '
    '; if (preg_match('/^(string|email)/',$typeofdata)) diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index 023729e680d..ea9a46bc54e 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -208,6 +208,9 @@ function societe_prepare_head(Societe $object) else { dol_print_error($db); } + + //if (! empty($conf->stripe->enabled) && $nbBankAccount > 0) $nbBankAccount = '...'; // No way to know exact number + if ($nbBankAccount > 0) $head[$h][1].= ' '.$nbBankAccount.''; $head[$h][2] = 'rib'; $h++; diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 9c65b4442d2..6f36d760c18 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -260,7 +260,7 @@ CREATE TABLE llx_societe_account( entity integer DEFAULT 1, key_account varchar(128), login varchar(128) NOT NULL, - pass_encoding varchar(24) NOT NULL, + pass_encoding varchar(24), pass_crypted varchar(128), pass_temp varchar(128), -- temporary password when asked for forget password fk_soc integer, @@ -278,6 +278,7 @@ CREATE TABLE llx_societe_account( -- END MODULEBUILDER FIELDS ) ENGINE=innodb; +-- VMYSQL4.3 ALTER TABLE llx_societe_account MODIFY COLUMN pass_encoding varchar(24) NULL; ALTER TABLE llx_societe_account ADD COLUMN key_account varchar(128); @@ -288,6 +289,7 @@ ALTER TABLE llx_societe_account ADD INDEX idx_societe_account_fk_website (fk_web ALTER TABLE llx_societe_account ADD INDEX idx_societe_account_fk_soc (fk_soc); ALTER TABLE llx_societe_account ADD UNIQUE INDEX uk_societe_account_login_website_soc(entity, fk_soc, login, site, fk_website); +ALTER TABLE llx_societe_account ADD UNIQUE INDEX uk_societe_account_key_account_soc(entity, fk_soc, key_account, site, fk_website); ALTER TABLE llx_societe_account ADD CONSTRAINT llx_societe_account_fk_website FOREIGN KEY (fk_website) REFERENCES llx_website(rowid); ALTER TABLE llx_societe_account ADD CONSTRAINT llx_societe_account_fk_societe FOREIGN KEY (fk_soc) REFERENCES llx_societe(rowid); diff --git a/htdocs/install/mysql/tables/llx_societe_account.key.sql b/htdocs/install/mysql/tables/llx_societe_account.key.sql index ece860300c1..3e0dc130554 100644 --- a/htdocs/install/mysql/tables/llx_societe_account.key.sql +++ b/htdocs/install/mysql/tables/llx_societe_account.key.sql @@ -23,6 +23,7 @@ ALTER TABLE llx_societe_account ADD INDEX idx_societe_account_fk_soc (fk_soc); -- END MODULEBUILDER INDEXES ALTER TABLE llx_societe_account ADD UNIQUE INDEX uk_societe_account_login_website_soc(entity, fk_soc, login, site, fk_website); +ALTER TABLE llx_societe_account ADD UNIQUE INDEX uk_societe_account_key_account_soc(entity, fk_soc, key_account, site, fk_website); ALTER TABLE llx_societe_account ADD CONSTRAINT llx_societe_account_fk_website FOREIGN KEY (fk_website) REFERENCES llx_website(rowid); ALTER TABLE llx_societe_account ADD CONSTRAINT llx_societe_account_fk_societe FOREIGN KEY (fk_soc) REFERENCES llx_societe(rowid); diff --git a/htdocs/install/mysql/tables/llx_societe_account.sql b/htdocs/install/mysql/tables/llx_societe_account.sql index 4dd17f441ed..7a0f87cbe5d 100644 --- a/htdocs/install/mysql/tables/llx_societe_account.sql +++ b/htdocs/install/mysql/tables/llx_societe_account.sql @@ -21,7 +21,7 @@ CREATE TABLE llx_societe_account( entity integer DEFAULT 1, key_account varchar(128), login varchar(128) NOT NULL, - pass_encoding varchar(24) NOT NULL, + pass_encoding varchar(24), pass_crypted varchar(128), pass_temp varchar(128), -- temporary password when asked for forget password fk_soc integer, diff --git a/htdocs/website/class/websiteaccount.class.php b/htdocs/societe/class/societeaccount.class.php similarity index 91% rename from htdocs/website/class/websiteaccount.class.php rename to htdocs/societe/class/societeaccount.class.php index f24847a4601..05ce15a8c94 100644 --- a/htdocs/website/class/websiteaccount.class.php +++ b/htdocs/societe/class/societeaccount.class.php @@ -20,9 +20,9 @@ */ /** - * \file class/websiteaccount.class.php - * \ingroup website - * \brief This file is a CRUD class file for WebsiteAccount (Create/Read/Update/Delete) + * \file class/societeaccount.class.php + * \ingroup societe + * \brief This file is a CRUD class file for SocieteAccount (Create/Read/Update/Delete) */ // Put here all includes required by your class file @@ -31,24 +31,24 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; /** - * Class for WebsiteAccount + * Class for SocieteAccount */ -class WebsiteAccount extends CommonObject +class SocieteAccount extends CommonObject { /** * @var string ID to identify managed object */ - public $element = 'websiteaccount'; + public $element = 'societeaccount'; /** * @var string Name of table without prefix where object is stored */ - public $table_element = 'website_account'; + public $table_element = 'societe_account'; /** - * @var array Does websiteaccount support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + * @var array Does societeaccount support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe */ public $ismultientitymanaged = 0; /** - * @var string String with name of icon for websiteaccount. Must be the part after the 'object_' into object_myobject.png + * @var string String with name of icon for societeaccount. Must be the part after the 'object_' into object_myobject.png */ public $picto = 'lock'; @@ -76,12 +76,15 @@ class WebsiteAccount extends CommonObject */ public $fields=array( 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',), - 'login' => array('type'=>'varchar(64)', 'label'=>'Login', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>'Login',), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>5, 'default'=>1), + 'key_account' => array('type'=>'varchar(128)', 'label'=>'KeyAccount', 'visible'=>-1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>'Key account',), + 'login' => array('type'=>'varchar(64)', 'label'=>'Login', 'visible'=>1, 'enabled'=>1, 'position'=>10), 'pass_encoding' => array('type'=>'varchar(24)', 'label'=>'PassEncoding', 'visible'=>0, 'enabled'=>1, 'position'=>30), 'pass_crypted' => array('type'=>'varchar(128)', 'label'=>'Password', 'visible'=>1, 'enabled'=>1, 'position'=>31, 'notnull'=>1), 'pass_temp' => array('type'=>'varchar(128)', 'label'=>'Temp', 'visible'=>0, 'enabled'=>0, 'position'=>32, 'notnull'=>-1,), 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>1, 'position'=>40, 'notnull'=>-1, 'index'=>1), - 'fk_website' => array('type'=>'integer:Website:website/class/website.class.php', 'label'=>'WebSite', 'visible'=>1, 'enabled'=>1, 'position'=>41, 'notnull'=>1, 'index'=>1), + 'site' => array('type'=>'varchar(128)', 'label'=>'Site', 'visible'=>-1, 'enabled'=>1, 'position'=>41), + 'fk_website' => array('type'=>'integer:Website:website/class/website.class.php', 'label'=>'WebSite', 'visible'=>1, 'enabled'=>1, 'position'=>42, 'notnull'=>1, 'index'=>1), 'date_last_login' => array('type'=>'datetime', 'label'=>'LastConnexion', 'visible'=>2, 'enabled'=>1, 'position'=>50, 'notnull'=>0,), 'date_previous_login' => array('type'=>'datetime', 'label'=>'PreviousConnexion', 'visible'=>2, 'enabled'=>1, 'position'=>51, 'notnull'=>0,), //'note_public' => array('type'=>'text', 'label'=>'NotePublic', 'visible'=>-1, 'enabled'=>1, 'position'=>45, 'notnull'=>-1,), @@ -94,9 +97,13 @@ class WebsiteAccount extends CommonObject 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'index'=>1, 'default'=>1, 'arrayofkeyval'=>array('1'=>'Active','0'=>'Disabled')), ); public $rowid; - public $login; + public $entity; + public $key_account; public $pass_encoding; public $pass_crypted; + public $pass_temp; + public $fk_soc; + public $site; public $date_last_login; public $date_previous_login; public $note_private; @@ -106,7 +113,6 @@ class WebsiteAccount extends CommonObject public $fk_user_modif; public $import_key; public $status; - public $fk_soc; // END MODULEBUILDER PROPERTIES @@ -117,21 +123,21 @@ class WebsiteAccount extends CommonObject /** * @var int Name of subtable line */ - //public $table_element_line = 'website_accountdet'; + //public $table_element_line = 'societe_accountdet'; /** * @var int Field with ID of parent key if this field has a parent */ - //public $fk_element = 'fk_website_account'; + //public $fk_element = 'fk_societe_account'; /** * @var int Name of subtable class that manage subtable lines */ - //public $class_element_line = 'WebsiteAccountline'; + //public $class_element_line = 'societeAccountline'; /** * @var array Array of child tables (child tables to delete before deleting a record) */ - //protected $childtables=array('website_accountdet'); + //protected $childtables=array('societe_accountdet'); /** - * @var WebsiteAccountLine[] Array of subtable lines + * @var societeAccountLine[] Array of subtable lines */ //public $lines = array(); @@ -235,7 +241,7 @@ class WebsiteAccount extends CommonObject { $this->lines=array(); - // Load lines with object WebsiteAccountLine + // Load lines with object societeAccountLine return count($this->lines)?1:0; } @@ -287,12 +293,12 @@ class WebsiteAccount extends CommonObject $this->ref = $this->login; - $label = '' . $langs->trans("WebsiteAccount") . ''; + $label = '' . $langs->trans("SocieteAccount") . ''; $label.= '
    '; $label.= '' . $langs->trans('Login') . ': ' . $this->ref; //$label.= '' . $langs->trans('WebSite') . ': ' . $this->ref; - $url = dol_buildpath('/website/websiteaccount_card.php',1).'?id='.$this->id; + $url = dol_buildpath('/societe/societeaccount_card.php',1).'?id='.$this->id; if ($option != 'nolink') { @@ -307,7 +313,7 @@ class WebsiteAccount extends CommonObject { if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowWebsiteAccount"); + $label=$langs->trans("ShowsocieteAccount"); $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; @@ -486,10 +492,10 @@ class WebsiteAccount extends CommonObject } /** - * Class WebsiteAccountLine. You can also remove this and generate a CRUD class for lines objects. + * Class societeAccountLine. You can also remove this and generate a CRUD class for lines objects. */ /* -class WebsiteAccountLine +class societeAccountLine { // @var int ID public $id; diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 53f714b414c..898c442b755 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -33,13 +33,11 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; -$langs->load("companies"); -$langs->load("commercial"); -$langs->load("banks"); -$langs->load("bills"); +$langs->loadLangs(array("companies","commercial","banks","bills")); // Security check $socid = GETPOST("socid","int"); @@ -50,6 +48,7 @@ $id=GETPOST("id","int"); $source=GETPOST("source","alpha"); $ribid=GETPOST("ribid","int"); $action=GETPOST("action", 'alpha', 3); +$cancel=GETPOST('cancel', 'alpha'); $object = new Societe($db); $object->fetch($socid); @@ -90,6 +89,11 @@ if (! empty($conf->stripe->enabled)) * Actions */ +if ($cancel) +{ + $action=''; +} + $parameters=array('id'=>$socid, 'objcanvas'=>$objcanvas); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); @@ -344,35 +348,88 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; $id = $savid; -} -// Action for stripe -if (! empty($conf->stripe->enabled) && class_exists('Stripe')) -{ - if ($action == 'setassourcedefault') + // Action for stripe + if (! empty($conf->stripe->enabled) && class_exists('Stripe')) { - $cu = \Stripe\Customer::retrieve($stripecu); + if ($action == 'setkey_account') + { + $error = 0; - $cu->default_source = "$source"; // obtained with Stripe.js - $cu->save(); + $newcu = GETPOST('key_account', 'alpha'); - $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - elseif ($action == 'delete') - { - $cu = \Stripe\Customer::retrieve($stripecu); + $db->begin(); - $cu->sources->retrieve("$source")->detach(); + $sql = 'UPDATE '.MAIN_DB_PREFIX."societe_account"; + $sql.= " SET key_account = '".$db->escape(GETPOST('key_account', 'alpha'))."'"; + $sql.= " WHERE site = 'stripe' AND fk_soc = ".$object->id." AND status = ".$servicestatus." AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified ! - $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; - header('Location: '.$url); - exit; + $resql = $db->query($sql); + $num = $db->num_rows($resql); + if (empty($num)) + { + $societeaccount = new SocieteAccount($db); + $societeaccount->fk_soc = $object->id; + $societeaccount->login = ''; + $societeaccount->pass_encoding = ''; + $societeaccount->site = 'stripe'; + $societeaccount->status = $servicestatus; + $societeaccount->key_account = $newcu; + $result = $societeaccount->create($user); + if ($result < 0) + { + $error++; + } + } + + if (! $error) + { + $stripecu = $newcu; + $db->commit(); + } + else + { + $db->rollback(); + } + } + + if ($action == 'setassourcedefault') + { + try { + $cu = \Stripe\Customer::retrieve($stripecu); + $cu->default_source = (string) $source; + $result = $cu->save(); + + $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + catch(Exception $e) + { + + } + } + elseif ($action == 'delete') + { + try { + $cu = \Stripe\Customer::retrieve($stripecu); + + $cu->sources->retrieve("$source")->detach(); + + $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + catch(Exception $e) + { + + } + } } } + /* * View */ @@ -459,13 +516,15 @@ if ($socid && $action != 'edit' && $action != "create") if (! empty($conf->stripe->enabled)) { - - + $permissiontowrite = $user->rights->societe->creer; // Stripe customer key 'cu_....' stored into llx_societe_account - print '
    '.$langs->trans('StripeCustomerId').''; - print $stripecu; + print '
    '; + //print $langs->trans('StripeCustomerId'); + print $form->editfieldkey("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', 0, 1, 'socid'); + print ''; + //print $stripecu; + print $form->editfieldval("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', null, null, '', 1, '', 'socid'); print '
    '; @@ -475,24 +534,30 @@ if ($socid && $action != 'edit' && $action != "create") if (! (empty($conf->stripe->enabled))) { - print load_fiche_titre($langs->trans('StripeGateways').($stripeacc ? ' ('.$stripeacc.')':''), '', ''); + print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc ? ' ('.$stripeacc.')':''), '', ''); $listofsources = array(); if (is_object($stripe) && $stripeacc) { - $customerstripe=$stripe->customerStripe($object->id, $stripeacc, $servicestatus); - - if ($customerstripe->id) { - $listofsources=$customerstripe->sources->data; + try { + $customerstripe=$stripe->customerStripe($object->id, $stripeacc, $servicestatus); + if ($customerstripe->id) { + $listofsources=$customerstripe->sources->data; + } + } + catch(Exception $e) + { + dol_syslog("Failed to get strip customer for thirdparty id =".$object->id); } } print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''."\n"; print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ''; print "\n"; @@ -500,7 +565,10 @@ if ($socid && $action != 'edit' && $action != "create") { foreach ($listofsources as $src) { - print ''; + print ''; + print ''; print ''; // Default print ''; print ''; @@ -603,8 +671,9 @@ if ($socid && $action != 'edit' && $action != "create") // List of bank accounts + print '
    '; - $morehtmlright=''.$langs->trans("Add").''; + $morehtmlright=''.$langs->trans("Add").''; print load_fiche_titre($langs->trans("AllRIB"), $morehtmlright, ''); From 2566170c68a769aef767f15510ece3b633ca0e48 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 17:47:43 +0100 Subject: [PATCH 287/413] Use code of societeaccount --- htdocs/core/lib/company.lib.php | 18 +++++++--- htdocs/societe/class/societeaccount.class.php | 34 +++++++++++++++++++ htdocs/stripe/class/stripe.class.php | 25 +++----------- 3 files changed, 52 insertions(+), 25 deletions(-) diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index ea9a46bc54e..3a295f7a941 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -178,6 +178,8 @@ function societe_prepare_head(Societe $object) // Bank accounts if (empty($conf->global->SOCIETE_DISABLE_BANKACCOUNT)) { + $nbBankAccount=0; + $foundonexternalonlinesystem=0; $langs->load("banks"); $title = $langs->trans("BankAccounts"); @@ -185,11 +187,16 @@ function societe_prepare_head(Societe $object) { $langs->load("stripe"); $title = $langs->trans("BankAccountsAndGateways"); + + $servicestatus = 0; + if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox','alpha')) $servicestatus = 1; + + include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; + $societeaccount = new SocieteAccount($db); + $stripecu = $societeaccount->getCustomerAccount($object->id, 'stripe', $servicestatus); // Get thirdparty cu_... + if ($stripecu) $foundonexternalonlinesystem++; } - $nbBankAccount=0; - $head[$h][0] = DOL_URL_ROOT .'/societe/paymentmodes.php?socid='.$object->id; - $head[$h][1] = $title; $sql = "SELECT COUNT(n.rowid) as nb"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib as n"; $sql.= " WHERE fk_soc = ".$object->id; @@ -211,7 +218,10 @@ function societe_prepare_head(Societe $object) //if (! empty($conf->stripe->enabled) && $nbBankAccount > 0) $nbBankAccount = '...'; // No way to know exact number - if ($nbBankAccount > 0) $head[$h][1].= ' '.$nbBankAccount.''; + $head[$h][0] = DOL_URL_ROOT .'/societe/paymentmodes.php?socid='.$object->id; + $head[$h][1] = $title; + if ($foundonexternalonlinesystem) $head[$h][1].= ' ...'; + elseif ($nbBankAccount > 0) $head[$h][1].= ' '.$nbBankAccount.''; $head[$h][2] = 'rib'; $h++; } diff --git a/htdocs/societe/class/societeaccount.class.php b/htdocs/societe/class/societeaccount.class.php index 05ce15a8c94..08b3617e540 100644 --- a/htdocs/societe/class/societeaccount.class.php +++ b/htdocs/societe/class/societeaccount.class.php @@ -246,6 +246,40 @@ class SocieteAccount extends CommonObject return count($this->lines)?1:0; } + /** + * Try to find the external customer id of a thirdparty for an another site/system. + * + * @param int $id Id of third party + * @param string $site Site (example: 'stripe', '...') + * @param int $status Status (0=test, 1=live) + * @return string Stripe customer ref 'cu_xxxxxxxxxxxxx' or '' + */ + public function getCustomerAccount($id, $site, $status=0) + { + global $conf; + + $sql = "SELECT sa.key_account as key_account, sa.entity"; + $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa"; + $sql.= " WHERE sa.fk_soc = " . $id; + $sql.= " AND sa.entity IN (".getEntity('societe').")"; + $sql.= " AND sa.site = '".$this->db->escape($site)."' AND sa.status = ".((int) $status); + + dol_syslog(get_class($this) . "::getCustomerAccount Try to find the system customer id of thirdparty id=".$id." (exemple: cu_.... for stripe)", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $key = $obj->key_account; + } else { + $key = ''; + } + } else { + $key = ''; + } + + return $key; + } + /** * Update object into database * diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index dfecc56a172..1053f3236c3 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -94,32 +94,15 @@ class Stripe extends CommonObject * * @param int $id Id of third party * @param int $status Status - * @return string Stripe customer ref 'cu_xxxxxxxxxxxxx' + * @return string Stripe customer ref 'cu_xxxxxxxxxxxxx' or '' */ public function getStripeCustomerAccount($id, $status=0) { global $conf; - $sql = "SELECT sa.key_account as key_account, sa.entity"; - $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa"; - $sql.= " WHERE sa.fk_soc = " . $id; - $sql.= " AND sa.entity IN (".getEntity('societe').")"; - $sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status); - - dol_syslog(get_class($this) . "::getStripeCustomerAccount Try to find the cu_.... of thirdparty id=".$id, LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) { - if ($this->db->num_rows($result)) { - $obj = $this->db->fetch_object($result); - $key = $obj->key_account; - } else { - $key = NULL; - } - } else { - $key = NULL; - } - - return $key; + include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; + $societeaccount = new SocieteAccount($this->db); + return $societeaccount->getCustomerAccount($object->id, 'stripe', $status); // Get thirdparty cu_... } From 0a642a2656eba44d53f5813d8999ad8a88643fb3 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 17:49:30 +0100 Subject: [PATCH 288/413] Fix regression --- htdocs/stripe/class/stripe.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 1053f3236c3..5f86c45f696 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -102,7 +102,7 @@ class Stripe extends CommonObject include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; $societeaccount = new SocieteAccount($this->db); - return $societeaccount->getCustomerAccount($object->id, 'stripe', $status); // Get thirdparty cu_... + return $societeaccount->getCustomerAccount($id, 'stripe', $status); // Get thirdparty cu_... } From 3f490906f9c372eaed7c8f08e84d909c82b55d08 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 17:52:15 +0100 Subject: [PATCH 289/413] Trans --- htdocs/langs/en_US/stripe.lang | 3 ++- htdocs/societe/paymentmodes.php | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 15d20dc0f1b..b1169eb776d 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -49,4 +49,5 @@ OAUTH_STRIPE_LIVE_ID=Stripe Connect Client ID (ca_...) BankAccountForBankTransfer=Bank account for fund payouts StripeAccount=Stripe account StripeChargeList=List of Stripe charges -StripeCustomerId=Stripe customer id \ No newline at end of file +StripeCustomerId=Stripe customer id +StripePaymentModes=Stripe payment modes \ No newline at end of file diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 898c442b755..273b5e53bb5 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -675,7 +675,7 @@ if ($socid && $action != 'edit' && $action != "create") $morehtmlright=''.$langs->trans("Add").''; - print load_fiche_titre($langs->trans("AllRIB"), $morehtmlright, ''); + print load_fiche_titre($langs->trans("BankAccounts"), $morehtmlright, ''); $rib_list = $object->get_all_rib(); $var = false; From 60283a8205ef7a75b90e53bd1e25b198cb22f0ec Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 18:07:22 +0100 Subject: [PATCH 290/413] Remove file incoterm.lang --- htdocs/langs/ar_SA/incoterm.lang | 3 --- htdocs/langs/bg_BG/incoterm.lang | 3 --- htdocs/langs/bn_BD/incoterm.lang | 3 --- htdocs/langs/bs_BA/incoterm.lang | 3 --- htdocs/langs/ca_ES/incoterm.lang | 3 --- htdocs/langs/cs_CZ/incoterm.lang | 3 --- htdocs/langs/da_DK/incoterm.lang | 3 --- htdocs/langs/de_DE/incoterm.lang | 3 --- htdocs/langs/el_GR/incoterm.lang | 3 --- htdocs/langs/en_US/admin.lang | 2 ++ htdocs/langs/en_US/incoterm.lang | 3 --- htdocs/langs/en_US/main.lang | 1 + htdocs/langs/es_ES/incoterm.lang | 3 --- htdocs/langs/et_EE/incoterm.lang | 3 --- htdocs/langs/eu_ES/incoterm.lang | 3 --- htdocs/langs/fa_IR/incoterm.lang | 3 --- htdocs/langs/fi_FI/incoterm.lang | 3 --- htdocs/langs/fr_CA/incoterm.lang | 2 -- htdocs/langs/fr_FR/incoterm.lang | 3 --- htdocs/langs/he_IL/incoterm.lang | 3 --- htdocs/langs/hr_HR/incoterm.lang | 3 --- htdocs/langs/hu_HU/incoterm.lang | 3 --- htdocs/langs/id_ID/incoterm.lang | 3 --- htdocs/langs/is_IS/incoterm.lang | 3 --- htdocs/langs/it_IT/incoterm.lang | 3 --- htdocs/langs/ja_JP/incoterm.lang | 3 --- htdocs/langs/ka_GE/incoterm.lang | 3 --- htdocs/langs/kn_IN/incoterm.lang | 3 --- htdocs/langs/ko_KR/incoterm.lang | 3 --- htdocs/langs/lo_LA/incoterm.lang | 3 --- htdocs/langs/lt_LT/incoterm.lang | 3 --- htdocs/langs/lv_LV/incoterm.lang | 3 --- htdocs/langs/mk_MK/incoterm.lang | 3 --- htdocs/langs/mn_MN/incoterm.lang | 3 --- htdocs/langs/nb_NO/incoterm.lang | 3 --- htdocs/langs/nl_NL/incoterm.lang | 3 --- htdocs/langs/pl_PL/incoterm.lang | 3 --- htdocs/langs/pt_BR/incoterm.lang | 2 -- htdocs/langs/pt_PT/incoterm.lang | 3 --- htdocs/langs/ro_RO/incoterm.lang | 3 --- htdocs/langs/ru_RU/incoterm.lang | 3 --- htdocs/langs/sk_SK/incoterm.lang | 3 --- htdocs/langs/sl_SI/incoterm.lang | 3 --- htdocs/langs/sq_AL/incoterm.lang | 3 --- htdocs/langs/sr_RS/incoterm.lang | 3 --- htdocs/langs/sv_SE/incoterm.lang | 3 --- htdocs/langs/sw_SW/incoterm.lang | 3 --- htdocs/langs/th_TH/incoterm.lang | 3 --- htdocs/langs/tr_TR/incoterm.lang | 3 --- htdocs/langs/uk_UA/incoterm.lang | 3 --- htdocs/langs/uz_UZ/incoterm.lang | 3 --- htdocs/langs/vi_VN/incoterm.lang | 3 --- htdocs/langs/zh_CN/incoterm.lang | 3 --- htdocs/langs/zh_TW/incoterm.lang | 3 --- 54 files changed, 3 insertions(+), 154 deletions(-) delete mode 100644 htdocs/langs/ar_SA/incoterm.lang delete mode 100644 htdocs/langs/bg_BG/incoterm.lang delete mode 100644 htdocs/langs/bn_BD/incoterm.lang delete mode 100644 htdocs/langs/bs_BA/incoterm.lang delete mode 100644 htdocs/langs/ca_ES/incoterm.lang delete mode 100644 htdocs/langs/cs_CZ/incoterm.lang delete mode 100644 htdocs/langs/da_DK/incoterm.lang delete mode 100644 htdocs/langs/de_DE/incoterm.lang delete mode 100644 htdocs/langs/el_GR/incoterm.lang delete mode 100644 htdocs/langs/en_US/incoterm.lang delete mode 100644 htdocs/langs/es_ES/incoterm.lang delete mode 100644 htdocs/langs/et_EE/incoterm.lang delete mode 100644 htdocs/langs/eu_ES/incoterm.lang delete mode 100644 htdocs/langs/fa_IR/incoterm.lang delete mode 100644 htdocs/langs/fi_FI/incoterm.lang delete mode 100644 htdocs/langs/fr_CA/incoterm.lang delete mode 100644 htdocs/langs/fr_FR/incoterm.lang delete mode 100644 htdocs/langs/he_IL/incoterm.lang delete mode 100644 htdocs/langs/hr_HR/incoterm.lang delete mode 100644 htdocs/langs/hu_HU/incoterm.lang delete mode 100644 htdocs/langs/id_ID/incoterm.lang delete mode 100644 htdocs/langs/is_IS/incoterm.lang delete mode 100644 htdocs/langs/it_IT/incoterm.lang delete mode 100644 htdocs/langs/ja_JP/incoterm.lang delete mode 100644 htdocs/langs/ka_GE/incoterm.lang delete mode 100644 htdocs/langs/kn_IN/incoterm.lang delete mode 100644 htdocs/langs/ko_KR/incoterm.lang delete mode 100644 htdocs/langs/lo_LA/incoterm.lang delete mode 100644 htdocs/langs/lt_LT/incoterm.lang delete mode 100644 htdocs/langs/lv_LV/incoterm.lang delete mode 100644 htdocs/langs/mk_MK/incoterm.lang delete mode 100644 htdocs/langs/mn_MN/incoterm.lang delete mode 100644 htdocs/langs/nb_NO/incoterm.lang delete mode 100644 htdocs/langs/nl_NL/incoterm.lang delete mode 100644 htdocs/langs/pl_PL/incoterm.lang delete mode 100644 htdocs/langs/pt_BR/incoterm.lang delete mode 100644 htdocs/langs/pt_PT/incoterm.lang delete mode 100644 htdocs/langs/ro_RO/incoterm.lang delete mode 100644 htdocs/langs/ru_RU/incoterm.lang delete mode 100644 htdocs/langs/sk_SK/incoterm.lang delete mode 100644 htdocs/langs/sl_SI/incoterm.lang delete mode 100644 htdocs/langs/sq_AL/incoterm.lang delete mode 100644 htdocs/langs/sr_RS/incoterm.lang delete mode 100644 htdocs/langs/sv_SE/incoterm.lang delete mode 100644 htdocs/langs/sw_SW/incoterm.lang delete mode 100644 htdocs/langs/th_TH/incoterm.lang delete mode 100644 htdocs/langs/tr_TR/incoterm.lang delete mode 100644 htdocs/langs/uk_UA/incoterm.lang delete mode 100644 htdocs/langs/uz_UZ/incoterm.lang delete mode 100644 htdocs/langs/vi_VN/incoterm.lang delete mode 100644 htdocs/langs/zh_CN/incoterm.lang delete mode 100644 htdocs/langs/zh_TW/incoterm.lang diff --git a/htdocs/langs/ar_SA/incoterm.lang b/htdocs/langs/ar_SA/incoterm.lang deleted file mode 100644 index e37b2fd78f8..00000000000 --- a/htdocs/langs/ar_SA/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=شروط التجارة الدولية -Module62000Desc=إضافة ميزات لإدارة شروط التجارة الدولية -IncotermLabel=شروط التجارة الدولية diff --git a/htdocs/langs/bg_BG/incoterm.lang b/htdocs/langs/bg_BG/incoterm.lang deleted file mode 100644 index 48ef90b01a5..00000000000 --- a/htdocs/langs/bg_BG/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Инкотерм -Module62000Desc=Добяване на свойства за управление на Инкотерм -IncotermLabel=Инкотермс diff --git a/htdocs/langs/bn_BD/incoterm.lang b/htdocs/langs/bn_BD/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/bn_BD/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/bs_BA/incoterm.lang b/htdocs/langs/bs_BA/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/bs_BA/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/ca_ES/incoterm.lang b/htdocs/langs/ca_ES/incoterm.lang deleted file mode 100644 index 259ec38c7cb..00000000000 --- a/htdocs/langs/ca_ES/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Afegir funcions per gestionar Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/cs_CZ/incoterm.lang b/htdocs/langs/cs_CZ/incoterm.lang deleted file mode 100644 index e0f966a95cb..00000000000 --- a/htdocs/langs/cs_CZ/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Přidat funkce pro správu Incotermu -IncotermLabel=Incoterms diff --git a/htdocs/langs/da_DK/incoterm.lang b/htdocs/langs/da_DK/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/da_DK/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/de_DE/incoterm.lang b/htdocs/langs/de_DE/incoterm.lang deleted file mode 100644 index c84e313a70c..00000000000 --- a/htdocs/langs/de_DE/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Funktion hinzufügen um Incoterms zu verwalten -IncotermLabel=Incoterms diff --git a/htdocs/langs/el_GR/incoterm.lang b/htdocs/langs/el_GR/incoterm.lang deleted file mode 100644 index e1b8fddb2dc..00000000000 --- a/htdocs/langs/el_GR/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Διεθνείς Εμπορικός Όρος -Module62000Desc=Προσθέστε δυνατότητες για τη διαχείριση του Διεθνή Εμπορικού Όρου -IncotermLabel=Διεθνείς Εμπορικοί Όροι diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index 6648e43501e..b9e4c33f227 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -621,6 +621,8 @@ Module59000Name=Margins Module59000Desc=Module to manage margins Module60000Name=Commissions Module60000Desc=Module to manage commissions +Module62000Name=Incoterm +Module62000Desc=Add features to manage Incoterm Module63000Name=Resources Module63000Desc=Manage resources (printers, cars, room, ...) you can then share into events Permission11=Read customer invoices diff --git a/htdocs/langs/en_US/incoterm.lang b/htdocs/langs/en_US/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/en_US/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index 4f402501c9a..063ea39127b 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -864,6 +864,7 @@ Project=Project Projects=Projects Rights=Permissions LineNb=Line nb +IncotermLabel=Incoterms # Week day Monday=Monday Tuesday=Tuesday diff --git a/htdocs/langs/es_ES/incoterm.lang b/htdocs/langs/es_ES/incoterm.lang deleted file mode 100644 index 0b5aa9e1153..00000000000 --- a/htdocs/langs/es_ES/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Añade funciones para gestionar Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/et_EE/incoterm.lang b/htdocs/langs/et_EE/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/et_EE/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/eu_ES/incoterm.lang b/htdocs/langs/eu_ES/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/eu_ES/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/fa_IR/incoterm.lang b/htdocs/langs/fa_IR/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/fa_IR/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/fi_FI/incoterm.lang b/htdocs/langs/fi_FI/incoterm.lang deleted file mode 100644 index 847faa62288..00000000000 --- a/htdocs/langs/fi_FI/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Lisää Incoterm ominaisuuksia -IncotermLabel=Incoterm-ehdot diff --git a/htdocs/langs/fr_CA/incoterm.lang b/htdocs/langs/fr_CA/incoterm.lang deleted file mode 100644 index d982800ae3e..00000000000 --- a/htdocs/langs/fr_CA/incoterm.lang +++ /dev/null @@ -1,2 +0,0 @@ -# Dolibarr language file - Source file is en_US - incoterm -Module62000Desc=Ajouter des fonctionnalités pour gérer Incoterm diff --git a/htdocs/langs/fr_FR/incoterm.lang b/htdocs/langs/fr_FR/incoterm.lang deleted file mode 100644 index dc5c853590c..00000000000 --- a/htdocs/langs/fr_FR/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Ajouts de fonctionnalités pour gérer les incoterms -IncotermLabel=Incoterms diff --git a/htdocs/langs/he_IL/incoterm.lang b/htdocs/langs/he_IL/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/he_IL/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/hr_HR/incoterm.lang b/htdocs/langs/hr_HR/incoterm.lang deleted file mode 100644 index b6e33607c35..00000000000 --- a/htdocs/langs/hr_HR/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Dodaj mogučnosti za upravljanje Incoterm-om -IncotermLabel=Incoterms diff --git a/htdocs/langs/hu_HU/incoterm.lang b/htdocs/langs/hu_HU/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/hu_HU/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/id_ID/incoterm.lang b/htdocs/langs/id_ID/incoterm.lang deleted file mode 100644 index bd7ab196fca..00000000000 --- a/htdocs/langs/id_ID/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Istilah Ekonomi Internasional -Module62000Desc=Tambah fitur untuk mengatur Istilah Ekonomi Internasional -IncotermLabel=Istilah Ekonomi Internasional diff --git a/htdocs/langs/is_IS/incoterm.lang b/htdocs/langs/is_IS/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/is_IS/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/it_IT/incoterm.lang b/htdocs/langs/it_IT/incoterm.lang deleted file mode 100644 index f3181020491..00000000000 --- a/htdocs/langs/it_IT/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Aggiunge funzioni per la gestione Incoterm -IncotermLabel=Import-Export diff --git a/htdocs/langs/ja_JP/incoterm.lang b/htdocs/langs/ja_JP/incoterm.lang deleted file mode 100644 index dc4c473efa9..00000000000 --- a/htdocs/langs/ja_JP/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=インコターム -Module62000Desc=インコタームを管理する機能を追加 -IncotermLabel=インコタームズ diff --git a/htdocs/langs/ka_GE/incoterm.lang b/htdocs/langs/ka_GE/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/ka_GE/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/kn_IN/incoterm.lang b/htdocs/langs/kn_IN/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/kn_IN/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/ko_KR/incoterm.lang b/htdocs/langs/ko_KR/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/ko_KR/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/lo_LA/incoterm.lang b/htdocs/langs/lo_LA/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/lo_LA/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/lt_LT/incoterm.lang b/htdocs/langs/lt_LT/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/lt_LT/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/lv_LV/incoterm.lang b/htdocs/langs/lv_LV/incoterm.lang deleted file mode 100644 index 1b96e667fb5..00000000000 --- a/htdocs/langs/lv_LV/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Inkoterms -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Inkoterms diff --git a/htdocs/langs/mk_MK/incoterm.lang b/htdocs/langs/mk_MK/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/mk_MK/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/mn_MN/incoterm.lang b/htdocs/langs/mn_MN/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/mn_MN/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/nb_NO/incoterm.lang b/htdocs/langs/nb_NO/incoterm.lang deleted file mode 100644 index 7fa8aee4c19..00000000000 --- a/htdocs/langs/nb_NO/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Legg til egenskaper for å administrere Incoterm -IncotermLabel=Incotermer diff --git a/htdocs/langs/nl_NL/incoterm.lang b/htdocs/langs/nl_NL/incoterm.lang deleted file mode 100644 index b70a7de1612..00000000000 --- a/htdocs/langs/nl_NL/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Onderdelen toevoegen voor Incoterms -IncotermLabel=Incoterms diff --git a/htdocs/langs/pl_PL/incoterm.lang b/htdocs/langs/pl_PL/incoterm.lang deleted file mode 100644 index 8278ec220a4..00000000000 --- a/htdocs/langs/pl_PL/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Międzynarodowe Reguły Handlu -Module62000Desc=Dodaj funkcje do zarządzania Międzynarodowymi Regułami Handlu -IncotermLabel=Formuły handlowe diff --git a/htdocs/langs/pt_BR/incoterm.lang b/htdocs/langs/pt_BR/incoterm.lang deleted file mode 100644 index 8aa2070c3e8..00000000000 --- a/htdocs/langs/pt_BR/incoterm.lang +++ /dev/null @@ -1,2 +0,0 @@ -# Dolibarr language file - Source file is en_US - incoterm -Module62000Desc=Adicionar recursos para gerenciar Incoterm diff --git a/htdocs/langs/pt_PT/incoterm.lang b/htdocs/langs/pt_PT/incoterm.lang deleted file mode 100644 index 8cb400335b1..00000000000 --- a/htdocs/langs/pt_PT/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Adione funções para gerir Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/ro_RO/incoterm.lang b/htdocs/langs/ro_RO/incoterm.lang deleted file mode 100644 index 7d95bf2b65a..00000000000 --- a/htdocs/langs/ro_RO/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Adaugă functionalitati pentru gestionarea Incoterm -IncotermLabel=Incoterm diff --git a/htdocs/langs/ru_RU/incoterm.lang b/htdocs/langs/ru_RU/incoterm.lang deleted file mode 100644 index ef59e2cfa93..00000000000 --- a/htdocs/langs/ru_RU/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Обязанности по доставке товаров -Module62000Desc=Добавить функции для управления обязанностями по доставке товаров -IncotermLabel=Обязанности по доставке товаров diff --git a/htdocs/langs/sk_SK/incoterm.lang b/htdocs/langs/sk_SK/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/sk_SK/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/sl_SI/incoterm.lang b/htdocs/langs/sl_SI/incoterm.lang deleted file mode 100644 index 57641257ec0..00000000000 --- a/htdocs/langs/sl_SI/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Mednarodni poslovni izraz -Module62000Desc=Mednarodnemu poslovnemu izrazu dodaj lastnost -IncotermLabel=Mednarodni Poslovni Izrazi diff --git a/htdocs/langs/sq_AL/incoterm.lang b/htdocs/langs/sq_AL/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/sq_AL/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/sr_RS/incoterm.lang b/htdocs/langs/sr_RS/incoterm.lang deleted file mode 100644 index 196cf598381..00000000000 --- a/htdocs/langs/sr_RS/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Dodavanje funkcionalnosti za upravljanje Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/sv_SE/incoterm.lang b/htdocs/langs/sv_SE/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/sv_SE/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/sw_SW/incoterm.lang b/htdocs/langs/sw_SW/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/sw_SW/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/th_TH/incoterm.lang b/htdocs/langs/th_TH/incoterm.lang deleted file mode 100644 index 4f05bda372b..00000000000 --- a/htdocs/langs/th_TH/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=เพิ่มคุณสมบัติในการจัดการ Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/tr_TR/incoterm.lang b/htdocs/langs/tr_TR/incoterm.lang deleted file mode 100644 index d08b03c056c..00000000000 --- a/htdocs/langs/tr_TR/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Uluslararası ticari terimleri -Module62000Desc=Uluslararası ticari terimleri yönetmek için özellik ekle -IncotermLabel=Uluslararası Ticaret Terimleri diff --git a/htdocs/langs/uk_UA/incoterm.lang b/htdocs/langs/uk_UA/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/uk_UA/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/uz_UZ/incoterm.lang b/htdocs/langs/uz_UZ/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/uz_UZ/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/vi_VN/incoterm.lang b/htdocs/langs/vi_VN/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/vi_VN/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms diff --git a/htdocs/langs/zh_CN/incoterm.lang b/htdocs/langs/zh_CN/incoterm.lang deleted file mode 100644 index f4ebcdeecbf..00000000000 --- a/htdocs/langs/zh_CN/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=国际贸易术语 -Module62000Desc=添加功能来管理国际贸易术语 -IncotermLabel=国际贸易术语解释通则 diff --git a/htdocs/langs/zh_TW/incoterm.lang b/htdocs/langs/zh_TW/incoterm.lang deleted file mode 100644 index 7ff371e3a95..00000000000 --- a/htdocs/langs/zh_TW/incoterm.lang +++ /dev/null @@ -1,3 +0,0 @@ -Module62000Name=Incoterm -Module62000Desc=Add features to manage Incoterm -IncotermLabel=Incoterms From a86da671badcef4595dba95b7d87c35f8be8e6b2 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 18:13:31 +0100 Subject: [PATCH 291/413] Remove verbose log --- htdocs/core/class/translate.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php index 62abbbbcc18..858b57d4c87 100644 --- a/htdocs/core/class/translate.class.php +++ b/htdocs/core/class/translate.class.php @@ -205,7 +205,7 @@ class Translate // Check cache if (! empty($this->_tab_loaded[$newdomain])) // File already loaded for this domain { - dol_syslog("Translate::Load already loaded for newdomain=".$newdomain); + //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain); return 0; } From c78e5d23eaefc486d6fb4f1946c284093fd87f3c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 20:23:59 +0100 Subject: [PATCH 292/413] Work on the customer payment mode tab --- .../install/mysql/migration/7.0.0-8.0.0.sql | 4 + htdocs/langs/en_US/modulebuilder.lang | 3 +- htdocs/modulebuilder/index.php | 76 ++- .../class/companypaymentmode.class.php | 473 ++++++++++++++++++ 4 files changed, 551 insertions(+), 5 deletions(-) create mode 100644 htdocs/societe/class/companypaymentmode.class.php diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 6f36d760c18..e4c0c406d72 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -294,3 +294,7 @@ ALTER TABLE llx_societe_account ADD UNIQUE INDEX uk_societe_account_key_account_ ALTER TABLE llx_societe_account ADD CONSTRAINT llx_societe_account_fk_website FOREIGN KEY (fk_website) REFERENCES llx_website(rowid); ALTER TABLE llx_societe_account ADD CONSTRAINT llx_societe_account_fk_societe FOREIGN KEY (fk_soc) REFERENCES llx_societe(rowid); + +ALTER TABLE llx_societe_rib MODIFY COLUMN max_total_amount_of_all_payments double(24,8); +ALTER TABLE llx_societe_rib MODIFY COLUMN total_amount_of_all_payments double(24,8); + diff --git a/htdocs/langs/en_US/modulebuilder.lang b/htdocs/langs/en_US/modulebuilder.lang index 9e30ee6f1de..6638e1fa674 100644 --- a/htdocs/langs/en_US/modulebuilder.lang +++ b/htdocs/langs/en_US/modulebuilder.lang @@ -93,4 +93,5 @@ AddLanguageFile=Add language file YouCanUseTranslationKey=You can use here a key that is the translation key found into language file (see tab "Languages") DropTableIfEmpty=(Delete table if empty) TableDoesNotExists=The table %s does not exists -TableDropped=Table %s deleted \ No newline at end of file +TableDropped=Table %s deleted +InitStructureFromExistingTable=Build the structure array string of an existing table \ No newline at end of file diff --git a/htdocs/modulebuilder/index.php b/htdocs/modulebuilder/index.php index dbc69c943dd..51ca2b9debb 100644 --- a/htdocs/modulebuilder/index.php +++ b/htdocs/modulebuilder/index.php @@ -181,6 +181,61 @@ if ($dirins && $action == 'addlanguage' && !empty($module)) $result = dolCopyDir($srcfile, $destfile, 0, 0); } +if ($dirins && $action == 'initobject' && $module && GETPOST('createtablearray','alpha')) +{ + $tablename = GETPOST('initfromtablename','alpha'); + $_results = $db->DDLDescTable($tablename); + if (empty($_results)) + { + setEventMessages($langs->trans("ErrorTableNotFound", $tablename), null, 'errors'); + } + else + { + /*public $fields=array( + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), + 'ref' =>array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), + 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1, 'css'=>'minwidth200', 'help'=>'Help text'), + 'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>1, 'default'=>'null', 'position'=>40, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text'), + 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>1, 'help'=>'LinkToThirparty'), + 'description' =>array('type'=>'text', 'label'=>'Descrption', 'enabled'=>1, 'visible'=>0, 'position'=>60), + 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61), + 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62), + 'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501), + //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502), + 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510), + 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511), + //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000), + 'status' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')), + );*/ + + $string = 'public $fields=array('."\n"; + $string.="
    "; + $i=10; + while ($obj = $db->fetch_object($_results)) + { + $fieldname = $obj->Field; + $type = $obj->Type; + if ($type == 'int(11)') $type='integer'; + $notnull = ($obj->Null == 'YES'?0:1); + $label = preg_replace('/_/', ' ', ucfirst($fieldname)); + if ($fieldname == 'rowid') $label='ID'; + + $string.= "'".$obj->Field."' =>array('type'=>'".$type."', 'label'=>'".$label."', 'enabled'=>1, 'visible'=>-2"; + if ($notnull) $string.= ", 'notnull'=>".$notnull; + $string.= ", 'position'=>".$i."),\n"; + $string.="
    "; + $i+=5; + } + $string.= ');'."\n"; + $string.="
    "; + print $string; + exit; + } +} + if ($dirins && $action == 'initobject' && $module && $objectname) { if (preg_match('/[^a-z0-9_]/i', $objectname)) @@ -490,7 +545,7 @@ if ($dirins && $action == 'addproperty' && !empty($module) && ! empty($tabobj)) setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null); clearstatcache(true); - + // Make a redirect to reload all data header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=objects&module='.$module.'&tabobj='.$objectname.'&nocache='.time()); @@ -525,7 +580,7 @@ if ($dirins && $action == 'confirm_deleteproperty' && $propertykey) setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null); clearstatcache(true); - + // Make a redirect to reload all data header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=objects&module='.$module.'&tabobj='.$objectname); @@ -1413,7 +1468,20 @@ elseif (! empty($module)) print $langs->trans("EnterNameOfObjectDesc").'

    '; print ''; - print ''; + print ''; + print '
    '; + print '
    '; + print '
    '; + print $langs->trans("Or"); + print '
    '; + print '
    '; + print '
    '; + //print ' '; + print $langs->trans("InitStructureFromExistingTable"); + print ''; + print ''; + print '
    '; + print ''; } elseif ($tabobj == 'deleteobject') @@ -1549,7 +1617,7 @@ elseif (! empty($module)) print '


    '; if(function_exists('opcache_invalidate')) opcache_invalidate($dirread.'/'.$pathtoclass,true); // remove the include cache hell ! - + if (empty($forceddirread)) { $result = dol_include_once($pathtoclass); diff --git a/htdocs/societe/class/companypaymentmode.class.php b/htdocs/societe/class/companypaymentmode.class.php new file mode 100644 index 00000000000..4dc509c251e --- /dev/null +++ b/htdocs/societe/class/companypaymentmode.class.php @@ -0,0 +1,473 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file class/companypaymentmode.class.php + * \ingroup monmodule + * \brief This file is a CRUD class file for CompanyPaymentMode (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for CompanyPaymentMode + */ +class CompanyPaymentMode extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element = 'companypaymentmode'; + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'societe_rib'; + /** + * @var int Does companypaymentmode support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 2; + /** + * @var int Does companypaymentmode support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + /** + * @var string String with name of icon for companypaymentmode. Must be the part after the 'object_' into object_companypaymentmode.png + */ + public $picto = 'generic'; + + + /** + * 'type' if the field format. + * 'label' the translation key. + * 'enabled' is a condition when the field must be managed. + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only. Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'position' is the sort order of field. + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'help' is a string visible as a tooltip on field + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * 'default' is a default value for creation (can still be replaced by the global setup of default values) + * 'showoncombobox' if field must be shown into the label of combobox + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' =>array('type'=>'integer', 'label'=>'Rowid', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>10), + 'fk_soc' =>array('type'=>'integer', 'label'=>'Fk soc', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>15), + 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>20), + 'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>25), + 'label' =>array('type'=>'varchar(30)', 'label'=>'Label', 'enabled'=>1, 'visible'=>-2, 'position'=>30), + 'bank' =>array('type'=>'varchar(255)', 'label'=>'Bank', 'enabled'=>1, 'visible'=>-2, 'position'=>35), + 'code_banque' =>array('type'=>'varchar(128)', 'label'=>'Code banque', 'enabled'=>1, 'visible'=>-2, 'position'=>40), + 'code_guichet' =>array('type'=>'varchar(6)', 'label'=>'Code guichet', 'enabled'=>1, 'visible'=>-2, 'position'=>45), + 'number' =>array('type'=>'varchar(255)', 'label'=>'Number', 'enabled'=>1, 'visible'=>-2, 'position'=>50), + 'cle_rib' =>array('type'=>'varchar(5)', 'label'=>'Cle rib', 'enabled'=>1, 'visible'=>-2, 'position'=>55), + 'bic' =>array('type'=>'varchar(20)', 'label'=>'Bic', 'enabled'=>1, 'visible'=>-2, 'position'=>60), + 'iban_prefix' =>array('type'=>'varchar(34)', 'label'=>'Iban prefix', 'enabled'=>1, 'visible'=>-2, 'position'=>65), + 'domiciliation' =>array('type'=>'varchar(255)', 'label'=>'Domiciliation', 'enabled'=>1, 'visible'=>-2, 'position'=>70), + 'proprio' =>array('type'=>'varchar(60)', 'label'=>'Proprio', 'enabled'=>1, 'visible'=>-2, 'position'=>75), + 'owner_address' =>array('type'=>'text', 'label'=>'Owner address', 'enabled'=>1, 'visible'=>-2, 'position'=>80), + 'default_rib' =>array('type'=>'tinyint(4)', 'label'=>'Default rib', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>85), + 'rum' =>array('type'=>'varchar(32)', 'label'=>'Rum', 'enabled'=>1, 'visible'=>-2, 'position'=>90), + 'date_rum' =>array('type'=>'date', 'label'=>'Date rum', 'enabled'=>1, 'visible'=>-2, 'position'=>95), + 'frstrecur' =>array('type'=>'varchar(16)', 'label'=>'Frstrecur', 'enabled'=>1, 'visible'=>-2, 'position'=>100), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'Import key', 'enabled'=>1, 'visible'=>-2, 'position'=>105), + 'type' =>array('type'=>'varchar(32)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-2, 'position'=>110), + 'last_four' =>array('type'=>'varchar(4)', 'label'=>'Last four', 'enabled'=>1, 'visible'=>-2, 'position'=>115), + 'card_type' =>array('type'=>'varchar(255)', 'label'=>'Card type', 'enabled'=>1, 'visible'=>-2, 'position'=>120), + 'cvn' =>array('type'=>'varchar(255)', 'label'=>'Cvn', 'enabled'=>1, 'visible'=>-2, 'position'=>125), + 'exp_date_month' =>array('type'=>'integer', 'label'=>'Exp date month', 'enabled'=>1, 'visible'=>-2, 'position'=>130), + 'exp_date_year' =>array('type'=>'integer', 'label'=>'Exp date year', 'enabled'=>1, 'visible'=>-2, 'position'=>135), + 'country_code' =>array('type'=>'varchar(10)', 'label'=>'Country code', 'enabled'=>1, 'visible'=>-2, 'position'=>140), + 'approved' =>array('type'=>'integer', 'label'=>'Approved', 'enabled'=>1, 'visible'=>-2, 'position'=>145), + 'email' =>array('type'=>'varchar(255)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-2, 'position'=>150), + 'max_total_amount_of_all_payments' =>array('type'=>'double(24,8)', 'label'=>'Max total amount of all payments', 'enabled'=>1, 'visible'=>-2, 'position'=>155), + 'preapproval_key' =>array('type'=>'varchar(255)', 'label'=>'Preapproval key', 'enabled'=>1, 'visible'=>-2, 'position'=>160), + 'total_amount_of_all_payments' =>array('type'=>'double(24,8)', 'label'=>'Total amount of all payments', 'enabled'=>1, 'visible'=>-2, 'position'=>165), + 'stripe_card_ref' =>array('type'=>'varchar(128)', 'label'=>'Stripe card ref', 'enabled'=>1, 'visible'=>-2, 'position'=>170), + 'status' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>175), + 'starting_date' =>array('type'=>'date', 'label'=>'Starting date', 'enabled'=>1, 'visible'=>-2, 'position'=>180), + 'ending_date' =>array('type'=>'date', 'label'=>'Ending date', 'enabled'=>1, 'visible'=>-2, 'position'=>185), + ); + public $rowid; + public $fk_soc; + public $entity; + public $label; + public $amount; + public $description; + public $note_public; + public $note_private; + public $date_creation; + public $tms; + public $fk_user_creat; + public $fk_user_modif; + public $import_key; + public $status; + // END MODULEBUILDER PROPERTIES + + + + // If this object has a subtable with lines + + /** + * @var int Name of subtable line + */ + //public $table_element_line = 'companypaymentmodedet'; + /** + * @var int Field with ID of parent key if this field has a parent + */ + //public $fk_element = 'fk_companypaymentmode'; + /** + * @var int Name of subtable class that manage subtable lines + */ + //public $class_element_line = 'CompanyPaymentModeline'; + /** + * @var array Array of child tables (child tables to delete before deleting a record) + */ + //protected $childtables=array('companypaymentmodedet'); + /** + * @var CompanyPaymentModeLine[] Array of subtable lines + */ + //public $lines = array(); + + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf; + + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; + if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + return $this->createCommon($user, $notrigger); + } + + /** + * Clone and object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $hookmanager, $langs; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $object->fetchCommon($fromid); + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + // Clear fields + $object->ref = "copy_of_".$object->ref; + $object->title = $langs->trans("CopyOf")." ".$object->title; + // ... + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines(); + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + /*public function fetchLines() + { + $this->lines=array(); + + // Load lines with object CompanyPaymentModeLine + + return count($this->lines)?1:0; + }*/ + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + } + + /** + * Return a link to the object card (with optionaly the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + function getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1) + { + global $db, $conf, $langs; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; + + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + + $result = ''; + $companylink = ''; + + $label = '' . $langs->trans("CompanyPaymentMode") . ''; + $label.= '
    '; + $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; + + $url = dol_buildpath('/monmodule/companypaymentmode_card.php',1).'?id='.$this->id; + + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + + $linkclose=''; + if (empty($notooltip)) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowCompanyPaymentMode"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + } + else $linkclose = ($morecss?' class="'.$morecss.'"':''); + + $linkstart = ''; + $linkend=''; + + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref; + $result .= $linkend; + //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + + return $result; + } + + /** + * Retourne le libelle du status d'un user (actif, inactif) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Label of status + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->status,$mode); + } + + /** + * Return the status + * + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + static function LibStatut($status,$mode=0) + { + global $langs; + + if ($mode == 0) + { + $prefix=''; + if ($status == 1) return $langs->trans('Enabled'); + if ($status == 0) return $langs->trans('Disabled'); + } + if ($mode == 1) + { + if ($status == 1) return $langs->trans('Enabled'); + if ($status == 0) return $langs->trans('Disabled'); + } + if ($mode == 2) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 3) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5'); + } + if ($mode == 4) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 5) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + } + if ($mode == 6) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + } + } + + /** + * Charge les informations d'ordre info dans l'objet commande + * + * @param int $id Id of order + * @return void + */ + function info($id) + { + $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; + $sql.= ' fk_user_creat, fk_user_modif'; + $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql.= ' WHERE t.rowid = '.$id; + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + + if ($obj->fk_user_valid) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + + if ($obj->fk_user_cloture) + { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } + + $this->db->free($result); + + } + else + { + dol_print_error($this->db); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } + +} From da617f7d3215ada6235f4a0b74632ecebfe0d35b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 22:43:50 +0100 Subject: [PATCH 293/413] Can work both with remote and local payment modes --- htdocs/core/class/commonobject.class.php | 5 +- htdocs/core/lib/functions.lib.php | 18 ++ htdocs/loan/class/loanschedule.class.php | 4 +- htdocs/loan/createschedule.php | 2 +- .../template/class/myobject.class.php | 15 +- .../class/companypaymentmode.class.php | 6 +- htdocs/societe/paymentmodes.php | 156 ++++++++++++++---- 7 files changed, 166 insertions(+), 40 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 6616745888b..4600cefbdc3 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -5527,7 +5527,7 @@ abstract class CommonObject $label = $val['label']; $type = $val['type']; $size = $val['css']; - + // Convert var to be able to share same code than showOutputField of extrafields if (preg_match('/varchar\((\d+)\)/', $type, $reg)) { @@ -6675,6 +6675,9 @@ abstract class CommonObject // TODO... } + + /* Part for comments */ + /** * Load comments linked with current task * @return boolean 1 if ok diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 80c4c12a68c..65753457000 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -3525,6 +3525,24 @@ function img_allow($allow, $titlealt = 'default') return '-'; } +/** + * Return image of a credit card according to its brand name + * + * @param string $brand Brand name of credit card + * @return string Return img tag + */ +function img_credit_card($brand) +{ + if ($brand == 'Visa') {$brand='cc-visa';} + elseif ($brand == 'MasterCard') {$brand='cc-mastercard';} + elseif ($brand == 'American Express') {$brand='cc-amex';} + elseif ($brand == 'Discover') {$brand='cc-discover';} + elseif ($brand == 'JCB') {$brand='cc-jcb';} + elseif ($brand == 'Diners Club') {$brand='cc-diners-club';} + elseif (! in_array($brand, array('cc-visa','cc-mastercard','cc-amex','cc-discover','cc-jcb','cc-diners-club'))) {$brand='credit-card';} + + return ''; +} /** * Show MIME img of a file diff --git a/htdocs/loan/class/loanschedule.class.php b/htdocs/loan/class/loanschedule.class.php index ebb1820bca0..a430f79366e 100644 --- a/htdocs/loan/class/loanschedule.class.php +++ b/htdocs/loan/class/loanschedule.class.php @@ -386,7 +386,7 @@ class LoanSchedule extends CommonObject * @param int $loanid Id object * @return int <0 if KO, >0 if OK */ - function fetchall($loanid) + function fetchAll($loanid) { global $langs; @@ -409,7 +409,7 @@ class LoanSchedule extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; $sql.= " WHERE t.fk_loan = ".$loanid; - dol_syslog(get_class($this)."::fetchall", LOG_DEBUG); + dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) diff --git a/htdocs/loan/createschedule.php b/htdocs/loan/createschedule.php index 4ab2499c265..0ecc0038835 100644 --- a/htdocs/loan/createschedule.php +++ b/htdocs/loan/createschedule.php @@ -89,7 +89,7 @@ if ($action == 'updateecheancier') { } $echeance = new LoanSchedule($db); -$echeance->fetchall($object->id); +$echeance->fetchAll($object->id); top_htmlhead('', ''); $var = ! $var; diff --git a/htdocs/modulebuilder/template/class/myobject.class.php b/htdocs/modulebuilder/template/class/myobject.class.php index e40b6b178e6..267a869fb46 100644 --- a/htdocs/modulebuilder/template/class/myobject.class.php +++ b/htdocs/modulebuilder/template/class/myobject.class.php @@ -142,12 +142,21 @@ class MyObject extends CommonObject */ public function __construct(DoliDB $db) { - global $conf; + global $conf, $user; $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; - if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible']=0; + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled']=0; + + // Unset fields that are disabled + foreach($this->fields as $key => $val) + { + if (isset($val['enabled']) && empty($val['enabled'])) + { + unset($this->fields[$key]); + } + } } /** diff --git a/htdocs/societe/class/companypaymentmode.class.php b/htdocs/societe/class/companypaymentmode.class.php index 4dc509c251e..baba6252284 100644 --- a/htdocs/societe/class/companypaymentmode.class.php +++ b/htdocs/societe/class/companypaymentmode.class.php @@ -112,10 +112,10 @@ class CompanyPaymentMode extends CommonObject 'status' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>175), 'starting_date' =>array('type'=>'date', 'label'=>'Starting date', 'enabled'=>1, 'visible'=>-2, 'position'=>180), 'ending_date' =>array('type'=>'date', 'label'=>'Ending date', 'enabled'=>1, 'visible'=>-2, 'position'=>185), + //'aaa' =>array('type'=>'date', 'label'=>'Ending date', 'enabled'=>0, 'visible'=>-2, 'position'=>185), ); public $rowid; public $fk_soc; - public $entity; public $label; public $amount; public $description; @@ -167,8 +167,8 @@ class CompanyPaymentMode extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; - if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible']=0; + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled']=0; } /** diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 273b5e53bb5..845bc3e4c1e 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -33,6 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; @@ -409,7 +410,7 @@ if (empty($reshook)) } } - elseif ($action == 'delete') + elseif ($action == 'deletecard') { try { $cu = \Stripe\Customer::retrieve($stripecu); @@ -534,7 +535,12 @@ if ($socid && $action != 'edit' && $action != "create") if (! (empty($conf->stripe->enabled))) { - print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc ? ' ('.$stripeacc.')':''), '', ''); + $morehtmlright=''; + if (! empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) + { + $morehtmlright=''.$langs->trans("Add").''; + } + print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc?' ('.$stripeacc.')':''), $morehtmlright, ''); $listofsources = array(); if (is_object($stripe) && $stripeacc) @@ -554,43 +560,131 @@ if ($socid && $action != 'edit' && $action != "create") print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '
    '.$langs->trans('Type').''.$langs->trans('Informations').''.$langs->trans('ID').''.$langs->trans('Type').''.$langs->trans('Informations').''.$langs->trans('Default').'
    '; + print $src->id; + print ''; if ($src->object=='card') { @@ -511,7 +579,7 @@ if ($socid && $action != 'edit' && $action != "create") elseif ($src->brand == 'JCB') {$brand='cc-jcb';} elseif ($src->brand == 'Diners Club') {$brand='cc-diners-club';} else {$brand='credit-card';} - print ''; + print ''; } elseif ($src->object=='source' && $src->type=='card') { @@ -522,11 +590,11 @@ if ($socid && $action != 'edit' && $action != "create") elseif ($src->card->brand == 'JCB') {$brand='cc-jcb';} elseif ($src->card->brand == 'Diners Club') {$brand='cc-diners-club';} else {$brand='credit-card';} - print ''; + print ''; } elseif ($src->object=='source' && $src->type=='sepa_debit') { - print ''; + print ''; } print''; @@ -570,13 +638,13 @@ if ($socid && $action != 'edit' && $action != "create") print ''; - if (($cu->default_source!=$src->id)) + if (($customerstripe->default_source != $src->id)) { print ''; - print ""; + print img_picto($langs->trans("Default"),'off'); print ''; } else { - print ""; + print img_picto($langs->trans("Default"),'on'); } print ''; @@ -587,7 +655,7 @@ if ($socid && $action != 'edit' && $action != "create") // print ''; // print ' '; print ''; - print ""; + print img_delete($langs->trans("Delete")); print ''; } print '
    '."\n"; print ''; - print ''; + if (! empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) + { + print ''; + } + print ''; print ''; print ''; print ''; print ''; + print ''; print "\n"; - if (is_array($listofsources)) + $nbremote = 0; + $nblocal = 0; + $arrayofstripecard = array(); + + // Show local sources + if (! empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) + { + //$societeaccount = new SocieteAccount($db); + $companypaymentmodetemp = new CompanyPaymentMode($db); + + $sql='SELECT rowid FROM '.MAIN_DB_PREFIX."societe_rib"; + $sql.=" WHERE type in ('card', 'paypal')"; + $sql.=" AND fk_soc = ".$object->id; + + $resql = $db->query($sql); + if ($resql) + { + $num_rows = $db->num_rows($resql); + if ($num_rows) + { + $i=0; + while ($i < $num_rows) + { + $nblocal++; + + $obj = $db->fetch_object($resql); + if ($obj) + { + $companypaymentmodetemp->fetch($obj->rowid); + + $arrayofstripecard[$obj->stripe_card_ref]=$obj->stripe_card_ref; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } + $i++; + } + } + else + { + print $langs->trans("NoPaymentMethodOnFile"); + } + } + else dol_print_error($db); + } + + // Show remote sources (not already shown as local source) + if (is_array($listofsources) && count($listofsources)) { foreach ($listofsources as $src) { + if (! empty($arrayofstripecard[$src->id])) continue; // Already in previous list + + $nbremote++; + print ''; + // Local ID + if (! empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) + { + print ''; + } print ''; print ''; + print ''; print ''; + print ''; + + print ''; } } - if (empty($listofsources)) + + if ($nbremote == 0 && $nblocal == 0) { - print ''; + print ''; } print "
    '.$langs->trans('ID').''.$langs->trans('LocalID').''.$langs->trans('StripeID').''.$langs->trans('Type').''.$langs->trans('Informations').''.$langs->trans('Default').''.$langs->trans('Note').'
    '; + print $obj->rowid; + print ''; + print $obj->stripe_card_ref; + print ''; + print img_credit_card($companypaymentmodetemp->type); + print ''; + if ($companypaymentmodetemp->last_four) print '**** '.$companypaymentmodetemp->last_four; + if ($companypaymentmodetemp->exp_date_month || $companypaymentmodetemp->exp_date_year) print ' - '.$companypaymentmodetemp->exp_date_month.'/'.$companypaymentmodetemp->exp_date_year.''; + print ''; + if ($companypaymentmodetemp->country_code) + { + $img=picto_from_langcode($companypaymentmodetemp->country_code); + print $img?$img.' ':''; + print getCountry($companypaymentmodetemp->country_code,1); + } + else print img_warning().' '.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("CompanyCountry")).''; + print ''; + print yn($obj->default_rib); + print ''; + if (empty($obj->stripe_card_ref)) print $langs->trans("Local"); + else print $langs->trans("LocalAndRemote"); + print ''; + if ($user->rights->societe->creer) + { + print ''; + print img_picto($langs->trans("Modify"),'edit'); + print ''; + print ' '; + print ''; + print img_delete($langs->trans("Delete")); + print ''; + } + print '
    '; + print ''; print $src->id; print ''; if ($src->object=='card') { - if ($src->brand == 'Visa') {$brand='cc-visa';} - elseif ($src->brand == 'MasterCard') {$brand='cc-mastercard';} - elseif ($src->brand == 'American Express') {$brand='cc-amex';} - elseif ($src->brand == 'Discover') {$brand='cc-discover';} - elseif ($src->brand == 'JCB') {$brand='cc-jcb';} - elseif ($src->brand == 'Diners Club') {$brand='cc-diners-club';} - else {$brand='credit-card';} - print ''; + print img_credit_card($src->brand); } elseif ($src->object=='source' && $src->type=='card') { - if ($src->card->brand == 'Visa') {$brand='cc-visa';} - elseif ($src->card->brand == 'MasterCard') {$brand='cc-mastercard';} - elseif ($src->card->brand == 'American Express') {$brand='cc-amex';} - elseif ($src->card->brand == 'Discover') {$brand='cc-discover';} - elseif ($src->card->brand == 'JCB') {$brand='cc-jcb';} - elseif ($src->card->brand == 'Diners Club') {$brand='cc-diners-club';} - else {$brand='credit-card';} - print ''; + print img_credit_card($src->card->brand); } elseif ($src->object=='source' && $src->type=='sepa_debit') { @@ -647,23 +741,25 @@ if ($socid && $action != 'edit' && $action != "create") print img_picto($langs->trans("Default"),'on'); } print ''; + print $langs->trans("Remote"); + print ''; if ($user->rights->societe->creer) { - // print ''; - // print img_picto($langs->trans("Modify"),'edit'); - // print ''; - // print ' '; - print ''; - print img_delete($langs->trans("Delete")); - print ''; + print ''; + print img_delete($langs->trans("Delete")); + print ''; } - print '
    '.$langs->trans("NoSource").'
    '.$langs->trans("None").'
    "; print "
    "; From fe68e8acddef8cdaeb6fb082dbf0c4d204bbcc1d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 13 Mar 2018 22:54:28 +0100 Subject: [PATCH 294/413] Trans --- htdocs/langs/en_US/stripe.lang | 4 +++- htdocs/societe/paymentmodes.php | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index b1169eb776d..51aaad35165 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -50,4 +50,6 @@ BankAccountForBankTransfer=Bank account for fund payouts StripeAccount=Stripe account StripeChargeList=List of Stripe charges StripeCustomerId=Stripe customer id -StripePaymentModes=Stripe payment modes \ No newline at end of file +StripePaymentModes=Stripe payment modes +LocalID=Local ID +StripeID=Stripe ID \ No newline at end of file diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 845bc3e4c1e..ae446a047d3 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -626,8 +626,16 @@ if ($socid && $action != 'edit' && $action != "create") } else print img_warning().' '.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("CompanyCountry")).''; print ''; + // Default print ''; - print yn($obj->default_rib); + if (empty($obj->default_rib)) + { + //print ''; + print img_picto($langs->trans("Default"),'off'); + //print ''; + } else { + print img_picto($langs->trans("Default"),'on'); + } print ''; print ''; if (empty($obj->stripe_card_ref)) print $langs->trans("Local"); @@ -734,9 +742,9 @@ if ($socid && $action != 'edit' && $action != "create") print ''; if (($customerstripe->default_source != $src->id)) { - print ''; - print img_picto($langs->trans("Default"),'off'); - print ''; + print ''; + print img_picto($langs->trans("Default"),'off'); + print ''; } else { print img_picto($langs->trans("Default"),'on'); } From e62df03681d9bcb735f394606f5d6cf7efe2f669 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Wed, 14 Mar 2018 08:59:05 +0100 Subject: [PATCH 295/413] Fix delete customer stripe with new database --- htdocs/public/stripe/ipn.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/public/stripe/ipn.php b/htdocs/public/stripe/ipn.php index bbd2d46a12f..19f9b8c80bc 100644 --- a/htdocs/public/stripe/ipn.php +++ b/htdocs/public/stripe/ipn.php @@ -323,7 +323,7 @@ elseif (($event->type == 'source.chargeable') && ($event->data->object->type == } elseif ($event->type == 'customer.deleted') { $db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_stripe WHERE fk_key = '".$event->data->object->id."' "; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_account WHERE key_account = '".$event->data->object->id."' and site='stripe' "; dol_syslog(get_class($this) . "::delete sql=" . $sql, LOG_DEBUG); $db->query($sql); $db->commit(); From 9a1588df1385567b527c1f78d3ed32637c925ca6 Mon Sep 17 00:00:00 2001 From: Sean Wang Date: Wed, 14 Mar 2018 16:38:22 +0800 Subject: [PATCH 296/413] Add missing $mode in BookKeeping::createStd() In accountancy ledger, creating new transaction, there is 'ERROR: 55000: currval of sequence "llx_accounting_bookkeeping_rowid_seq" is not yet defined in this session' occurred. According to dolibarr.log, this error will show up after createStd() {...Insert request to llx_accounting_bookkeeping_tmp...}. It query the "llx_accounting_bookkeeping_rowid_seq" instead of "llx_accounting_bookkeeping_tmp_rowid_seq", due to missing $mode at bookkeeping.class.php line504:last_insert_id(). --- htdocs/accountancy/class/bookkeeping.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 16f40139a38..d027b7c425b 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -501,7 +501,7 @@ class BookKeeping extends CommonObject } if (! $error) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element . $mode); if (! $notrigger) { // Uncomment this and change MYOBJECT to your own tag if you From 304595ee4f91c0bae0f4aa1e4403d05b692ccc65 Mon Sep 17 00:00:00 2001 From: Ferran Marcet Date: Wed, 14 Mar 2018 09:48:39 +0100 Subject: [PATCH 297/413] Fix: Can't activate tasks on projects configuration --- htdocs/projet/admin/project.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/projet/admin/project.php b/htdocs/projet/admin/project.php index 0252ab58f36..67317583273 100644 --- a/htdocs/projet/admin/project.php +++ b/htdocs/projet/admin/project.php @@ -1,11 +1,11 @@ * Copyright (C) 2011-2016 Laurent Destailleur - * Copyright (C) 2011-2012 Juanjo Menent + * Copyright (C) 2011-2015 Juanjo Menent * Copyright (C) 2011-2015 Philippe Grand * Copyright (C) 2013 Florian Henry - * Copyright (C) 2015 Juanjo Menent * Copyright (C) 2015 Marcos García + * Copyright (C) 2018 Ferran Marcet * * 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 @@ -59,7 +59,7 @@ if ($action == 'setmainoptions') else dolibarr_del_const($db, "PROJECT_USE_OPPORTUNITIES", $conf->entity); // Warning, the constant saved and used in code is PROJECT_HIDE_TASKS - if (GETPOST('PROJECT_USE_TASKS')) dolibarr_del_const($db, "PROJECT_USE_TASKS", $conf->entity); + if (GETPOST('PROJECT_USE_TASKS')) dolibarr_del_const($db, "PROJECT_HIDE_TASKS", $conf->entity); else dolibarr_set_const($db, "PROJECT_HIDE_TASKS",1,'chaine',0,'',$conf->entity); } From 35fbcb2c849d2decdf9146a7b833aad39fa72398 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 14 Mar 2018 10:48:56 +0100 Subject: [PATCH 298/413] Update company.lib.php --- htdocs/core/lib/company.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index d8b9d090473..7400d9d8471 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -466,7 +466,7 @@ function getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entc * @param int $entconv 0=Return value without entities and not converted to output charset, 1=Ready for html output * @return mixed String with state code or state name or Array('id','code','label')/Array('id','code','label','region_code','region') */ -function getState($id,$withcode='',$dbtouse=0,$withregion='',$outputlangs='',$entconv=1) +function getState($id,$withcode='',$dbtouse=0,$withregion=0,$outputlangs='',$entconv=1) { global $db,$langs; From e47dda72e7f2fc99f33860f847b89801ca09ae85 Mon Sep 17 00:00:00 2001 From: Ferran Marcet Date: Wed, 14 Mar 2018 11:08:38 +0100 Subject: [PATCH 299/413] Fix: Activate all also if there are inactive services --- htdocs/contrat/card.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 08c43551509..0ad017a94c8 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -6,7 +6,7 @@ * Copyright (C) 2010-2017 Juanjo Menent * Copyright (C) 2013 Christophe Battarel * Copyright (C) 2013-2014 Florian Henry - * Copyright (C) 2014-2016 Ferran Marcet + * Copyright (C) 2014-2018 Ferran Marcet * Copyright (C) 2014-2016 Marcos García * Copyright (C) 2015 Jean-François Ferry * @@ -2115,7 +2115,7 @@ else print ''; } - if ($object->nbofservicesclosed > 0) + if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0) { print ''; } From 268b07bcf0fbff4570fb716f0341e18ce0a13ef5 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 14 Mar 2018 11:51:13 +0100 Subject: [PATCH 300/413] Can add/delete credit card localy --- htdocs/core/class/html.form.class.php | 2 +- htdocs/core/class/translate.class.php | 2 +- .../install/mysql/migration/7.0.0-8.0.0.sql | 4 + .../install/mysql/tables/llx_societe_rib.sql | 2 +- htdocs/langs/en_US/stripe.lang | 8 +- .../class/companypaymentmode.class.php | 49 +++-- htdocs/societe/paymentmodes.php | 207 +++++++++++++++--- 7 files changed, 231 insertions(+), 43 deletions(-) diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 4d263611390..2dc47e6e900 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -4780,7 +4780,7 @@ class Form * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field. * @param datetime $adddateof Add a link "Date of invoice" using the following date. * @return string|null Nothing or string if nooutput is 1 - * @see form_date + * @see form_date, select_month, select_year, select_dayofweek */ function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='') { diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php index 858b57d4c87..69fe031459d 100644 --- a/htdocs/core/class/translate.class.php +++ b/htdocs/core/class/translate.class.php @@ -231,7 +231,7 @@ class Translate $filelangexists=is_file($file_lang_osencoded); - dol_syslog(get_class($this).'::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' newdomain='.$domain.' modulename='.$modulename.' file_lang='.$file_lang." => filelangexists=".$filelangexists); + //dol_syslog(get_class($this).'::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' newdomain='.$domain.' modulename='.$modulename.' file_lang='.$file_lang." => filelangexists=".$filelangexists); if ($filelangexists) { diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index e4c0c406d72..534cba912d5 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -119,6 +119,10 @@ ALTER TABLE llx_societe_rib ADD COLUMN starting_date date; ALTER TABLE llx_societe_rib ADD COLUMN total_amount_of_all_payments double(24,8); ALTER TABLE llx_societe_rib ADD COLUMN stripe_card_ref varchar(128); ALTER TABLE llx_societe_rib ADD COLUMN status integer NOT NULL DEFAULT 1; + +UPDATE llx_societe_rib set type = 'ban' where type = '' OR type IS NULL; +-- VMYSQL4.3 ALTER TABLE llx_societe_rib MODIFY COLUMN type varchar(32) NOT NULL; +-- VPGSQL8.2 ALTER TABLE llx_societe_rib ALTER COLUMN type SET NOT NULL; CREATE TABLE llx_ticketsup ( diff --git a/htdocs/install/mysql/tables/llx_societe_rib.sql b/htdocs/install/mysql/tables/llx_societe_rib.sql index 6157af37830..2463378067a 100644 --- a/htdocs/install/mysql/tables/llx_societe_rib.sql +++ b/htdocs/install/mysql/tables/llx_societe_rib.sql @@ -23,7 +23,7 @@ create table llx_societe_rib ( rowid integer AUTO_INCREMENT PRIMARY KEY, - type varchar(32) DEFAULT 'ban', -- 'ban' or 'paypal' or 'card' or 'stripe' + type varchar(32) DEFAULT 'ban' NOT NULL, -- 'ban' or 'paypal' or 'card' or 'stripe' label varchar(30), fk_soc integer NOT NULL, datec datetime, diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 51aaad35165..3db64381797 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -52,4 +52,10 @@ StripeChargeList=List of Stripe charges StripeCustomerId=Stripe customer id StripePaymentModes=Stripe payment modes LocalID=Local ID -StripeID=Stripe ID \ No newline at end of file +StripeID=Stripe ID +NameOnCard=Name on card +CardNumber=Card Number +ExpiryDate=Expiry Date +CVN=CVN +DeleteACard=Delete Card record +ConfirmDeleteCard=Are you sure you want to delete this Card record? diff --git a/htdocs/societe/class/companypaymentmode.class.php b/htdocs/societe/class/companypaymentmode.class.php index baba6252284..6a2095883c1 100644 --- a/htdocs/societe/class/companypaymentmode.class.php +++ b/htdocs/societe/class/companypaymentmode.class.php @@ -78,8 +78,6 @@ class CompanyPaymentMode extends CommonObject public $fields=array( 'rowid' =>array('type'=>'integer', 'label'=>'Rowid', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>10), 'fk_soc' =>array('type'=>'integer', 'label'=>'Fk soc', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>15), - 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>20), - 'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>25), 'label' =>array('type'=>'varchar(30)', 'label'=>'Label', 'enabled'=>1, 'visible'=>-2, 'position'=>30), 'bank' =>array('type'=>'varchar(255)', 'label'=>'Bank', 'enabled'=>1, 'visible'=>-2, 'position'=>35), 'code_banque' =>array('type'=>'varchar(128)', 'label'=>'Code banque', 'enabled'=>1, 'visible'=>-2, 'position'=>40), @@ -95,7 +93,6 @@ class CompanyPaymentMode extends CommonObject 'rum' =>array('type'=>'varchar(32)', 'label'=>'Rum', 'enabled'=>1, 'visible'=>-2, 'position'=>90), 'date_rum' =>array('type'=>'date', 'label'=>'Date rum', 'enabled'=>1, 'visible'=>-2, 'position'=>95), 'frstrecur' =>array('type'=>'varchar(16)', 'label'=>'Frstrecur', 'enabled'=>1, 'visible'=>-2, 'position'=>100), - 'import_key' =>array('type'=>'varchar(14)', 'label'=>'Import key', 'enabled'=>1, 'visible'=>-2, 'position'=>105), 'type' =>array('type'=>'varchar(32)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-2, 'position'=>110), 'last_four' =>array('type'=>'varchar(4)', 'label'=>'Last four', 'enabled'=>1, 'visible'=>-2, 'position'=>115), 'card_type' =>array('type'=>'varchar(255)', 'label'=>'Card type', 'enabled'=>1, 'visible'=>-2, 'position'=>120), @@ -112,21 +109,47 @@ class CompanyPaymentMode extends CommonObject 'status' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>175), 'starting_date' =>array('type'=>'date', 'label'=>'Starting date', 'enabled'=>1, 'visible'=>-2, 'position'=>180), 'ending_date' =>array('type'=>'date', 'label'=>'Ending date', 'enabled'=>1, 'visible'=>-2, 'position'=>185), - //'aaa' =>array('type'=>'date', 'label'=>'Ending date', 'enabled'=>0, 'visible'=>-2, 'position'=>185), + 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>20), + 'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>25), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'Import key', 'enabled'=>1, 'visible'=>-2, 'position'=>105), + //'aaa' =>array('type'=>'date', 'label'=>'Ending date', 'enabled'=>0, 'visible'=>-2, 'position'=>185), ); public $rowid; public $fk_soc; public $label; - public $amount; - public $description; - public $note_public; - public $note_private; - public $date_creation; - public $tms; - public $fk_user_creat; - public $fk_user_modif; - public $import_key; + public $bank; + public $code_banque; + public $code_guichet; + public $number; + public $cle_rib; + public $bic; + public $iban_prefix; + public $domiciliation; + public $proprio; + public $owner_address; + public $default_rib; + public $rum; + public $date_rum; + public $frstrecur; + public $type; + public $last_four; + public $card_type; + public $cvn; + public $exp_date_month; + public $exp_date_year; + public $country_code; + public $approved; + public $email; + public $max_total_amount_of_all_payments; + public $preapproval_key; + public $total_amount_of_all_payments; + public $stripe_card_ref; public $status; + public $starting_date; + public $ending_date; + public $datec; + public $tms; + public $import_key; // END MODULEBUILDER PROPERTIES diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index ae446a047d3..d24f4dd5f32 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -32,6 +32,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; @@ -111,7 +112,7 @@ if (empty($reshook)) } } - if ($action == 'update' && ! $_POST["cancel"]) + if ($action == 'update') { // Modification if (! GETPOST('label')) @@ -188,19 +189,14 @@ if (empty($reshook)) } } - if ($action == 'add' && ! $_POST["cancel"]) + if ($action == 'add') { $error=0; - if (! GETPOST('label')) + if (! GETPOST('label','alpha') || ! GETPOST('bank','alpha')) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $action='create'; - $error++; - } - if (! GETPOST('bank')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + if (! GETPOST('label','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + if (! GETPOST('bank','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); $action='create'; $error++; } @@ -291,6 +287,68 @@ if (empty($reshook)) } } + if ($action == 'addcard') + { + $error=0; + + if (! GETPOST('label','alpha') || ! GETPOST('proprio','alpha') || ! GETPOST('cardnumber','alpha') || ! GETPOST('exp_date_month','alpha') || ! GETPOST('exp_date_year','alpha') || ! GETPOST('cvn','alpha')) + { + if (! GETPOST('label','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + if (! GETPOST('proprio','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NameOnCard")), null, 'errors'); + if (! GETPOST('cardnumber','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardNumber")), null, 'errors'); + if (! (GETPOST('exp_date_month','alpha') > 0) || ! (GETPOST('exp_date_year','alpha') > 0)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpiryDate")), null, 'errors'); + if (! GETPOST('cvn','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CVN")), null, 'errors'); + $action='createcard'; + $error++; + } + + if (! $error) + { + // Ajout + $paymentmode = new CompanyPaymentMode($db); + + $paymentmode->fk_soc = $object->id; + $paymentmode->bank = GETPOST('bank','alpha'); + $paymentmode->label = GETPOST('label','alpha'); + $paymentmode->number = GETPOST('cardnumber','alpha'); + $paymentmode->last_four = substr(GETPOST('cardnumber','alpha'), -4); + $paymentmode->proprio = GETPOST('proprio','alpha'); + $paymentmode->exp_date_month = GETPOST('exp_date_month','int'); + $paymentmode->exp_date_year = GETPOST('exp_date_year','int'); + $paymentmode->cvn = GETPOST('cvn','alpha'); + $paymentmode->datec = dol_now(); + $paymentmode->default_rib = 0; + $paymentmode->type = 'card'; + $paymentmode->country_code = $mysoc->country_code; + + $db->begin(); + + if (! $error) + { + $result = $paymentmode->create($user); + if ($result < 0) + { + $error++; + setEventMessages($paymentmode->error, $paymentmode->errors, 'errors'); + $action='createcard'; // Force chargement page création + } + } + + if (! $error) + { + $db->commit(); + + $url=$_SERVER["PHP_SELF"].'?socid='.$object->id; + header('Location: '.$url); + exit; + } + else + { + $db->rollback(); + } + } + } + if ($action == 'setasbankdefault') { $account = new CompanyBankAccount($db); @@ -307,7 +365,29 @@ if (empty($reshook)) } } - if ($action == 'confirm_delete' && $_GET['confirm'] == 'yes') + if ($action == 'confirm_deletecard' && GETPOST('confirm','alpha') == 'yes') + { + $paymentmode = new CompanyPaymentMode($db); + if ($paymentmode->fetch($ribid?$ribid:$id)) + { + $result = $paymentmode->delete($user); + if ($result > 0) + { + $url = $_SERVER['PHP_SELF']."?socid=".$object->id; + header('Location: '.$url); + exit; + } + else + { + setEventMessages($paymentmode->error, $paymentmode->errors, 'errors'); + } + } + else + { + setEventMessages($paymentmode->error, $paymentmode->errors, 'errors'); + } + } + if ($action == 'confirm_delete' && GETPOST('confirm','alpha') == 'yes') { $account = new CompanyBankAccount($db); if ($account->fetch($ribid?$ribid:$id)) @@ -393,8 +473,25 @@ if (empty($reshook)) $db->rollback(); } } + if ($action == 'setlocalassourcedefault') + { + try { + $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib set default_rib = 0 WHERE type = 'card' AND default_rib <> 0"; + $db->query($sql); - if ($action == 'setassourcedefault') + $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib set default_rib = 1 WHERE type = 'card' AND rowid = ".GETPOST('id','int'); + $db->query($sql); + + $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + catch(Exception $e) + { + + } + } + elseif ($action == 'setassourcedefault') { try { $cu = \Stripe\Customer::retrieve($stripecu); @@ -436,6 +533,7 @@ if (empty($reshook)) */ $form = new Form($db); +$formother = new FormOther($db); $formfile = new FormFile($db); llxHeader(); @@ -452,31 +550,38 @@ else } if (empty($account->socid)) $account->socid=$object->id; -if ($socid && $action == 'edit' && $user->rights->societe->creer) +if ($socid && ($action == 'edit' || $action == 'editcard') && $user->rights->societe->creer) { print '
    '; print ''; print ''; print ''; } -if ($socid && $action == 'create' && $user->rights->societe->creer) +if ($socid && ($action == 'create' || $action == 'createcard') && $user->rights->societe->creer) { print ''; print ''; - print ''; + $actionforadd='add'; + if ($action == 'createcard') $actionforadd='addcard'; + print ''; } // View -if ($socid && $action != 'edit' && $action != "create") +if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' && $action != 'createcard') { dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"), -1, 'company'); - // Confirm delete third party + // Confirm delete ban if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $account->getRibLabel()), "confirm_delete", '', 0, 1); } + // Confirm delete card + if ($action == 'deletecard') + { + print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteACard"), $langs->trans("ConfirmDeleteCard", $account->getRibLabel()), "confirm_deletecard", '', 0, 1); + } $linkback = ''.$langs->trans("BackToList").''; @@ -533,6 +638,7 @@ if ($socid && $action != 'edit' && $action != "create") print '
    '; + // Stripe payment modes if (! (empty($conf->stripe->enabled))) { $morehtmlright=''; @@ -628,17 +734,17 @@ if ($socid && $action != 'edit' && $action != "create") print ''; // Default print ''; - if (empty($obj->default_rib)) + if (empty($companypaymentmodetemp->default_rib)) { - //print ''; + print ''; print img_picto($langs->trans("Default"),'off'); - //print ''; + print ''; } else { print img_picto($langs->trans("Default"),'on'); } print ''; print ''; - if (empty($obj->stripe_card_ref)) print $langs->trans("Local"); + if (empty($companypaymentmodetemp->stripe_card_ref)) print $langs->trans("Local"); else print $langs->trans("LocalAndRemote"); print ''; print ''; @@ -973,7 +1079,7 @@ if ($socid && $action != 'edit' && $action != "create") dol_fiche_end(); /* - if ($socid && $action != 'edit' && $action != 'create') + if ($socid && $action != 'edit' && $action != 'create' && $action != 'createcard') { // Barre d'actions print '
    '; @@ -1031,7 +1137,7 @@ if ($socid && $action != 'edit' && $action != "create") */ } -// Edit +// Edit BAN if ($socid && $action == 'edit' && $user->rights->societe->creer) { dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); @@ -1136,7 +1242,7 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) } -// Create +// Create BAN if ($socid && $action == 'create' && $user->rights->societe->creer) { dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); @@ -1151,7 +1257,7 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -1225,6 +1331,55 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) dol_fiche_end(); + dol_set_focus('#label'); + + print '
    '; + print ''; + print '     '; + print ''; + print '
    '; +} + +// Create Card +if ($socid && $action == 'createcard' && $user->rights->societe->creer) +{ + dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); + + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); + + print '
    '; + + print '
    '; + print '
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("Bank").'
    '; + + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print '
    '.$langs->trans("Label").'
    '.$langs->trans("NameOnCard").'
    '.$langs->trans("CardNumber").'
    '.$langs->trans("ExpiryDate").''; + print $formother->select_month(GETPOST('exp_date_month','int'), 'exp_date_month', 1); + print $formother->select_year(GETPOST('exp_date_year','int'), 'exp_date_year', 1, 5, 10, 0, 0, '', 'marginleftonly'); + print '
    '.$langs->trans("CVN").'
    '; + + print '
    '; + + dol_fiche_end(); + + dol_set_focus('#label'); + print '
    '; print ''; print '     '; @@ -1236,7 +1391,7 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) { print ''; } -if ($socid && $action == 'create' && $user->rights->societe->creer) +if ($socid && ($action == 'create' || $action == 'createcard') && $user->rights->societe->creer) { print ''; } From e179161bfac2c7c19dd7a699bcc1b213e919f40e Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Wed, 14 Mar 2018 12:01:15 +0100 Subject: [PATCH 301/413] FIX support for stripeconnect mode --- htdocs/societe/paymentmodes.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index ae446a047d3..8088cec0ebb 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -1,7 +1,7 @@ * Copyright (C) 2003 Jean-Louis Bergamo - * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2013 Peter Fontaine * Copyright (C) 2015-2016 Marcos García @@ -76,7 +76,7 @@ if (! empty($conf->stripe->enabled)) if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox','alpha')) { $service = 'StripeLive'; - $servicestatus = 0; + $servicestatus = 1; } $stripe = new Stripe($db); @@ -397,7 +397,7 @@ if (empty($reshook)) if ($action == 'setassourcedefault') { try { - $cu = \Stripe\Customer::retrieve($stripecu); + $cu=$stripe->customerStripe($object->id, $stripeacc, $servicestatus); $cu->default_source = (string) $source; $result = $cu->save(); @@ -413,7 +413,7 @@ if (empty($reshook)) elseif ($action == 'deletecard') { try { - $cu = \Stripe\Customer::retrieve($stripecu); + $cu=$stripe->customerStripe($object->id, $stripeacc, $servicestatus); $cu->sources->retrieve("$source")->detach(); From 5140c1c5d2002451cedf88aebc6848a6ba6e316a Mon Sep 17 00:00:00 2001 From: fmarcet Date: Wed, 14 Mar 2018 13:25:05 +0100 Subject: [PATCH 302/413] Fix: Merge categories when merging thirds --- htdocs/societe/card.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index 090afd3e935..c28d0d9db68 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -11,6 +11,7 @@ * Copyright (C) 2015 Marcos García * Copyright (C) 2015 Raphaël Doursenaud * Copyright (C) 2018 Nicolas ZABOURI + * Copyright (C) 2018 Ferran Marcet * * 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 @@ -180,9 +181,12 @@ if (empty($reshook)) // Merge categories $static_cat = new Categorie($db); - $custcats = $static_cat->containing($soc_origin->id, 'customer', 'id'); + $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id'); + $custcats = $static_cat->containing($object->id, 'customer', 'id'); + $custcats = array_merge($custcats,$custcats_ori); $object->setCategories($custcats, 'customer'); - $suppcats = $static_cat->containing($soc_origin->id, 'supplier', 'id'); + $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id'); + $suppcats = $static_cat->containing($object->id, 'supplier', 'id'); $object->setCategories($suppcats, 'supplier'); // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys. @@ -210,7 +214,7 @@ if (empty($reshook)) $objects = array( 'Adherent' => '/adherents/class/adherent.class.php', 'Societe' => '/societe/class/societe.class.php', - 'Categorie' => '/categories/class/categorie.class.php', + //'Categorie' => '/categories/class/categorie.class.php', 'ActionComm' => '/comm/action/class/actioncomm.class.php', 'Propal' => '/comm/propal/class/propal.class.php', 'Commande' => '/commande/class/commande.class.php', From 5c2a005e75e44677fa335cc6f66a81eff0242453 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 14 Mar 2018 13:56:21 +0100 Subject: [PATCH 303/413] Work on generic customer payment modes --- htdocs/core/class/commonobject.class.php | 12 +- htdocs/langs/en_US/main.lang | 5 +- .../class/companybankaccount.class.php | 4 +- .../class/companypaymentmode.class.php | 76 +++- htdocs/societe/paymentmodes.php | 376 +++++++++++------- 5 files changed, 317 insertions(+), 156 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 4600cefbdc3..43275b22afc 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -6481,19 +6481,21 @@ abstract class CommonObject /** * Load object in memory from the database * - * @param int $id Id object - * @param string $ref Ref - * @return int <0 if KO, 0 if not found, >0 if OK + * @param int $id Id object + * @param string $ref Ref + * @param string $morewhere More SQL filters (' AND ...') + * @return int <0 if KO, 0 if not found, >0 if OK */ - public function fetchCommon($id, $ref = null) + public function fetchCommon($id, $ref = null, $morewhere = '') { if (empty($id) && empty($ref)) return false; $sql = 'SELECT '.$this->get_field_list(); $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element; - if(!empty($id)) $sql.= ' WHERE rowid = '.$id; + if (!empty($id)) $sql.= ' WHERE rowid = '.$id; else $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']); + if ($morewhere) $sql.=$morewhere; $res = $this->db->query($sql); if ($res) diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index 063ea39127b..6473869be21 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -932,4 +932,7 @@ PayedBy=Payed by PayedTo=Payed to Monthly=Monthly Quarterly=Quarterly -Annual=Annual \ No newline at end of file +Annual=Annual +Local=Local +Remote=Remote +LocalAndRemote=Local and remote \ No newline at end of file diff --git a/htdocs/societe/class/companybankaccount.class.php b/htdocs/societe/class/companybankaccount.class.php index 97c8871202e..187f7c5ec65 100644 --- a/htdocs/societe/class/companybankaccount.class.php +++ b/htdocs/societe/class/companybankaccount.class.php @@ -197,7 +197,7 @@ class CompanyBankAccount extends Account * Load record from database * * @param int $id Id of record - * @param int $socid Id of company. If this is filled, function will return the default RIB of company + * @param int $socid Id of company. If this is filled, function will return the first default RIB of company * @return int <0 if KO, >0 if OK */ function fetch($id, $socid=0) @@ -208,7 +208,7 @@ class CompanyBankAccount extends Account $sql.= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib"; if ($id) $sql.= " WHERE rowid = ".$id; - if ($socid) $sql.= " WHERE fk_soc = ".$socid." AND default_rib = 1"; + if ($socid) $sql.= " WHERE fk_soc = ".$socid." AND default_rib = 1 AND type ='ban'"; $resql = $this->db->query($sql); if ($resql) diff --git a/htdocs/societe/class/companypaymentmode.class.php b/htdocs/societe/class/companypaymentmode.class.php index 6a2095883c1..662361a619d 100644 --- a/htdocs/societe/class/companypaymentmode.class.php +++ b/htdocs/societe/class/companypaymentmode.class.php @@ -258,13 +258,18 @@ class CompanyPaymentMode extends CommonObject /** * Load object in memory from the database * - * @param int $id Id object - * @param string $ref Ref - * @return int <0 if KO, 0 if not found, >0 if OK + * @param int $id Id object + * @param string $ref Ref + * @param int $socid Id of company to get first default payment mode + * @param string $type Filter on type ('ban', 'card', ...) + * @return int <0 if KO, 0 if not found, >0 if OK */ - public function fetch($id, $ref = null) + public function fetch($id, $ref = null, $socid = 0, $type = '') { - $result = $this->fetchCommon($id, $ref); + if ($socid) $sql.= " AND fk_soc = ".$this->db->escape($socid)." AND default_rib = 1"; + if ($type) $sql.= " AND type = '".$this->db->escape($type)."'"; + + $result = $this->fetchCommon($id, $ref, $morewhere); if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines(); return $result; } @@ -368,6 +373,67 @@ class CompanyPaymentMode extends CommonObject return $result; } + /** + * Set a Payment mode as Default + * + * @param int $id Payment mode ID + * @param string $alltypes 1=The default is for all payment types instead of per type + * @return int 0 if KO, 1 if OK + */ + function setAsDefault($id=0, $alltypes=0) + { + $sql1 = "SELECT rowid as id, fk_soc, type FROM ".MAIN_DB_PREFIX."societe_rib"; + $sql1.= " WHERE rowid = ".($id?$id:$this->id); + + dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); + $result1 = $this->db->query($sql1); + if ($result1) + { + if ($this->db->num_rows($result1) == 0) + { + return 0; + } + else + { + $obj = $this->db->fetch_object($result1); + + $type = ''; + if (empty($alltypes)) $type = $obj->type; + + $this->db->begin(); + + $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0"; + $sql2.= " WHERE default_rib <> 0 AND fk_soc = ".$obj->fk_soc; + if ($type) $sql2.= " AND type = '".$this->db->escape($type)."'"; + dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); + $result2 = $this->db->query($sql2); + + $sql3 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 1"; + $sql3.= " WHERE rowid = ".$obj->id; + if ($type) $sql3.= " AND type = '".$this->db->escape($type)."'"; + dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); + $result3 = $this->db->query($sql3); + + if (!$result2 || !$result3) + { + dol_print_error($this->db); + $this->db->rollback(); + return -1; + } + else + { + $this->db->commit(); + return 1; + } + } + } + else + { + dol_print_error($this->db); + return -1; + } + } + /** * Retourne le libelle du status d'un user (actif, inactif) * diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index d24f4dd5f32..9365511b78d 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -55,7 +55,8 @@ $cancel=GETPOST('cancel', 'alpha'); $object = new Societe($db); $object->fetch($socid); -$account = new CompanyBankAccount($db); +$companybankaccount = new CompanyBankAccount($db); +$companypaymentmode = new CompanyPaymentMode($db); $prelevement = new BonPrelevement($db); $extrafields = new ExtraFields($db); @@ -115,19 +116,14 @@ if (empty($reshook)) if ($action == 'update') { // Modification - if (! GETPOST('label')) + if (! GETPOST('label','alpha') || ! GETPOST('bank','alpha')) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + if (! GETPOST('label','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + if (! GETPOST('bank','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); $action='edit'; $error++; } - if (! GETPOST('bank')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); - $action='edit'; - $error++; - } - if ($account->needIBAN() == 1) + if ($companybankaccount->needIBAN() == 1) { if (! GETPOST('iban')) { @@ -143,43 +139,94 @@ if (empty($reshook)) } } - $account->fetch($id); + $companybankaccount->fetch($id); if (! $error) { - $account->socid = $object->id; + $companybankaccount->socid = $object->id; - $account->bank = GETPOST('bank','alpha'); - $account->label = GETPOST('label','alpha'); - $account->courant = GETPOST('courant','alpha'); - $account->clos = GETPOST('clos','alpha'); - $account->code_banque = GETPOST('code_banque','alpha'); - $account->code_guichet = GETPOST('code_guichet','alpha'); - $account->number = GETPOST('number','alpha'); - $account->cle_rib = GETPOST('cle_rib','alpha'); - $account->bic = GETPOST('bic','alpha'); - $account->iban = GETPOST('iban','alpha'); - $account->domiciliation = GETPOST('domiciliation','alpha'); - $account->proprio = GETPOST('proprio','alpha'); - $account->owner_address = GETPOST('owner_address','alpha'); - $account->frstrecur = GETPOST('frstrecur','alpha'); - $account->rum = GETPOST('rum','alpha'); - if (empty($account->rum)) + $companybankaccount->bank = GETPOST('bank','alpha'); + $companybankaccount->label = GETPOST('label','alpha'); + $companybankaccount->courant = GETPOST('courant','alpha'); + $companybankaccount->clos = GETPOST('clos','alpha'); + $companybankaccount->code_banque = GETPOST('code_banque','alpha'); + $companybankaccount->code_guichet = GETPOST('code_guichet','alpha'); + $companybankaccount->number = GETPOST('number','alpha'); + $companybankaccount->cle_rib = GETPOST('cle_rib','alpha'); + $companybankaccount->bic = GETPOST('bic','alpha'); + $companybankaccount->iban = GETPOST('iban','alpha'); + $companybankaccount->domiciliation = GETPOST('domiciliation','alpha'); + $companybankaccount->proprio = GETPOST('proprio','alpha'); + $companybankaccount->owner_address = GETPOST('owner_address','alpha'); + $companybankaccount->frstrecur = GETPOST('frstrecur','alpha'); + $companybankaccount->rum = GETPOST('rum','alpha'); + if (empty($companybankaccount->rum)) { - $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - $account->date_rum = dol_now(); + $companybankaccount->rum = $prelevement->buildRumNumber($object->code_client, $companybankaccount->datec, $companybankaccount->id); + $companybankaccount->date_rum = dol_now(); } - $result = $account->update($user); + $result = $companybankaccount->update($user); if (! $result) { - setEventMessages($account->error, $account->errors, 'errors'); + setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors'); } else { // If this account is the default bank account, we disable others - if ($account->default_rib) + if ($companybankaccount->default_rib) { - $account->setAsDefault($id); // This will make sure there is only one default rib + $companybankaccount->setAsDefault($id); // This will make sure there is only one default rib + } + + $url=$_SERVER["PHP_SELF"].'?socid='.$object->id; + header('Location: '.$url); + exit; + } + } + } + + if ($action == 'updatecard') + { + // Modification + if (! GETPOST('label','alpha') || ! GETPOST('proprio','alpha') || ! GETPOST('cardnumber','alpha') || ! GETPOST('exp_date_month','alpha') || ! GETPOST('exp_date_year','alpha') || ! GETPOST('cvn','alpha')) + { + if (! GETPOST('label','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + if (! GETPOST('proprio','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NameOnCard")), null, 'errors'); + if (! GETPOST('cardnumber','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardNumber")), null, 'errors'); + if (! (GETPOST('exp_date_month','alpha') > 0) || ! (GETPOST('exp_date_year','alpha') > 0)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpiryDate")), null, 'errors'); + if (! GETPOST('cvn','alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CVN")), null, 'errors'); + $action='createcard'; + $error++; + } + + $companypaymentmode->fetch($id); + if (! $error) + { + $companypaymentmode->fk_soc = $object->id; + + $companypaymentmode->bank = GETPOST('bank','alpha'); + $companypaymentmode->label = GETPOST('label','alpha'); + $companypaymentmode->number = GETPOST('cardnumber','alpha'); + $companypaymentmode->last_four = substr(GETPOST('cardnumber','alpha'), -4); + $companypaymentmode->proprio = GETPOST('proprio','alpha'); + $companypaymentmode->exp_date_month = GETPOST('exp_date_month','int'); + $companypaymentmode->exp_date_year = GETPOST('exp_date_year','int'); + $companypaymentmode->cvn = GETPOST('cvn','alpha'); + $companypaymentmode->country_code = $mysoc->country_code; + + $companypaymentmode->stripe_card_ref = GETPOST('stripe_card_ref','alpha'); + + $result = $companypaymentmode->update($user); + if (! $result) + { + setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors'); + } + else + { + // If this account is the default bank account, we disable others + if ($companypaymentmode->default_rib) + { + $companypaymentmode->setAsDefault($id); // This will make sure there is only one default rib } $url=$_SERVER["PHP_SELF"].'?socid='.$object->id; @@ -204,31 +251,32 @@ if (empty($reshook)) if (! $error) { // Ajout - $account = new CompanyBankAccount($db); + $companybankaccount = new CompanyBankAccount($db); - $account->socid = $object->id; + $companybankaccount->socid = $object->id; - $account->bank = GETPOST('bank','alpha'); - $account->label = GETPOST('label','alpha'); - $account->courant = GETPOST('courant','alpha'); - $account->clos = GETPOST('clos','alpha'); - $account->code_banque = GETPOST('code_banque','alpha'); - $account->code_guichet = GETPOST('code_guichet','alpha'); - $account->number = GETPOST('number','alpha'); - $account->cle_rib = GETPOST('cle_rib','alpha'); - $account->bic = GETPOST('bic','alpha'); - $account->iban = GETPOST('iban','alpha'); - $account->domiciliation = GETPOST('domiciliation','alpha'); - $account->proprio = GETPOST('proprio','alpha'); - $account->owner_address = GETPOST('owner_address','alpha'); - $account->frstrecur = GETPOST('frstrecur'); - $account->rum = GETPOST('rum','alpha'); - $account->datec = dol_now(); + $companybankaccount->bank = GETPOST('bank','alpha'); + $companybankaccount->label = GETPOST('label','alpha'); + $companybankaccount->courant = GETPOST('courant','alpha'); + $companybankaccount->clos = GETPOST('clos','alpha'); + $companybankaccount->code_banque = GETPOST('code_banque','alpha'); + $companybankaccount->code_guichet = GETPOST('code_guichet','alpha'); + $companybankaccount->number = GETPOST('number','alpha'); + $companybankaccount->cle_rib = GETPOST('cle_rib','alpha'); + $companybankaccount->bic = GETPOST('bic','alpha'); + $companybankaccount->iban = GETPOST('iban','alpha'); + $companybankaccount->domiciliation = GETPOST('domiciliation','alpha'); + $companybankaccount->proprio = GETPOST('proprio','alpha'); + $companybankaccount->owner_address = GETPOST('owner_address','alpha'); + $companybankaccount->frstrecur = GETPOST('frstrecur'); + $companybankaccount->rum = GETPOST('rum','alpha'); + $companybankaccount->datec = dol_now(); + $companybankaccount->status = 1; $db->begin(); // This test can be done only once properties were set - if ($account->needIBAN() == 1) + if ($companybankaccount->needIBAN() == 1) { if (! GETPOST('iban')) { @@ -246,28 +294,28 @@ if (empty($reshook)) if (! $error) { - $result = $account->create($user); + $result = $companybankaccount->create($user); if ($result < 0) { $error++; - setEventMessages($account->error, $account->errors, 'errors'); + setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors'); $action='create'; // Force chargement page création } - if (empty($account->rum)) + if (empty($companybankaccount->rum)) { - $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - $account->date_rum = dol_now(); + $companybankaccount->rum = $prelevement->buildRumNumber($object->code_client, $companybankaccount->datec, $companybankaccount->id); + $companybankaccount->date_rum = dol_now(); } } if (! $error) { - $result = $account->update($user); // This will set the UMR number. + $result = $companybankaccount->update($user); // This will set the UMR number. if ($result < 0) { $error++; - setEventMessages($account->error, $account->errors, 'errors'); + setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors'); $action='create'; } } @@ -305,31 +353,34 @@ if (empty($reshook)) if (! $error) { // Ajout - $paymentmode = new CompanyPaymentMode($db); + $companypaymentmode = new CompanyPaymentMode($db); - $paymentmode->fk_soc = $object->id; - $paymentmode->bank = GETPOST('bank','alpha'); - $paymentmode->label = GETPOST('label','alpha'); - $paymentmode->number = GETPOST('cardnumber','alpha'); - $paymentmode->last_four = substr(GETPOST('cardnumber','alpha'), -4); - $paymentmode->proprio = GETPOST('proprio','alpha'); - $paymentmode->exp_date_month = GETPOST('exp_date_month','int'); - $paymentmode->exp_date_year = GETPOST('exp_date_year','int'); - $paymentmode->cvn = GETPOST('cvn','alpha'); - $paymentmode->datec = dol_now(); - $paymentmode->default_rib = 0; - $paymentmode->type = 'card'; - $paymentmode->country_code = $mysoc->country_code; + $companypaymentmode->fk_soc = $object->id; + $companypaymentmode->bank = GETPOST('bank','alpha'); + $companypaymentmode->label = GETPOST('label','alpha'); + $companypaymentmode->number = GETPOST('cardnumber','alpha'); + $companypaymentmode->last_four = substr(GETPOST('cardnumber','alpha'), -4); + $companypaymentmode->proprio = GETPOST('proprio','alpha'); + $companypaymentmode->exp_date_month = GETPOST('exp_date_month','int'); + $companypaymentmode->exp_date_year = GETPOST('exp_date_year','int'); + $companypaymentmode->cvn = GETPOST('cvn','alpha'); + $companypaymentmode->datec = dol_now(); + $companypaymentmode->default_rib = 0; + $companypaymentmode->type = 'card'; + $companypaymentmode->country_code = $mysoc->country_code; + $companypaymentmode->status = 1; + + $companypaymentmode->stripe_card_ref = GETPOST('stripe_card_ref','alpha'); $db->begin(); if (! $error) { - $result = $paymentmode->create($user); + $result = $companypaymentmode->create($user); if ($result < 0) { $error++; - setEventMessages($paymentmode->error, $paymentmode->errors, 'errors'); + setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors'); $action='createcard'; // Force chargement page création } } @@ -349,10 +400,10 @@ if (empty($reshook)) } } - if ($action == 'setasbankdefault') + if ($action == 'setasbankdefault' && GETPOST('ribid','int') > 0) { - $account = new CompanyBankAccount($db); - $res = $account->setAsDefault(GETPOST('ribid','int')); + $companybankaccount = new CompanyBankAccount($db); + $res = $companybankaccount->setAsDefault(GETPOST('ribid','int')); if ($res) { $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; @@ -367,10 +418,10 @@ if (empty($reshook)) if ($action == 'confirm_deletecard' && GETPOST('confirm','alpha') == 'yes') { - $paymentmode = new CompanyPaymentMode($db); - if ($paymentmode->fetch($ribid?$ribid:$id)) + $companypaymentmode = new CompanyPaymentMode($db); + if ($companypaymentmode->fetch($ribid?$ribid:$id)) { - $result = $paymentmode->delete($user); + $result = $companypaymentmode->delete($user); if ($result > 0) { $url = $_SERVER['PHP_SELF']."?socid=".$object->id; @@ -379,20 +430,20 @@ if (empty($reshook)) } else { - setEventMessages($paymentmode->error, $paymentmode->errors, 'errors'); + setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors'); } } else { - setEventMessages($paymentmode->error, $paymentmode->errors, 'errors'); + setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors'); } } if ($action == 'confirm_delete' && GETPOST('confirm','alpha') == 'yes') { - $account = new CompanyBankAccount($db); - if ($account->fetch($ribid?$ribid:$id)) + $companybankaccount = new CompanyBankAccount($db); + if ($companybankaccount->fetch($ribid?$ribid:$id)) { - $result = $account->delete($user); + $result = $companybankaccount->delete($user); if ($result > 0) { $url = $_SERVER['PHP_SELF']."?socid=".$object->id; @@ -401,12 +452,12 @@ if (empty($reshook)) } else { - setEventMessages($account->error, $account->errors, 'errors'); + setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors'); } } else { - setEventMessages($account->error, $account->errors, 'errors'); + setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors'); } } @@ -476,11 +527,7 @@ if (empty($reshook)) if ($action == 'setlocalassourcedefault') { try { - $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib set default_rib = 0 WHERE type = 'card' AND default_rib <> 0"; - $db->query($sql); - - $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib set default_rib = 1 WHERE type = 'card' AND rowid = ".GETPOST('id','int'); - $db->query($sql); + $companypaymentmode->setAsDefault($id); $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; header('Location: '.$url); @@ -540,21 +587,26 @@ llxHeader(); $head=societe_prepare_head($object); +// Load Bank account if (! $id) { - $account->fetch(0,$object->id); + $companybankaccount->fetch(0, $object->id); + $companypaymentmode->fetch(0, null, $object->id, 'card'); } else { - $account->fetch($id); + $companybankaccount->fetch($id); + $companypaymentmode->fetch($id); } -if (empty($account->socid)) $account->socid=$object->id; +if (empty($companybankaccount->socid)) $companybankaccount->socid=$object->id; if ($socid && ($action == 'edit' || $action == 'editcard') && $user->rights->societe->creer) { print '
    '; print ''; - print ''; + $actionforadd='update'; + if ($action == 'editcard') $actionforadd='updatecard'; + print ''; print ''; } if ($socid && ($action == 'create' || $action == 'createcard') && $user->rights->societe->creer) @@ -575,12 +627,12 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' // Confirm delete ban if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $account->getRibLabel()), "confirm_delete", '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $companybankaccount->getRibLabel()), "confirm_delete", '', 0, 1); } // Confirm delete card if ($action == 'deletecard') { - print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteACard"), $langs->trans("ConfirmDeleteCard", $account->getRibLabel()), "confirm_deletecard", '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteACard"), $langs->trans("ConfirmDeleteCard", $companybankaccount->getRibLabel()), "confirm_deletecard", '', 0, 1); } $linkback = ''.$langs->trans("BackToList").''; @@ -638,7 +690,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print '
    '; - // Stripe payment modes + // List of Stripe payment modes if (! (empty($conf->stripe->enabled))) { $morehtmlright=''; @@ -708,14 +760,14 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { $companypaymentmodetemp->fetch($obj->rowid); - $arrayofstripecard[$obj->stripe_card_ref]=$obj->stripe_card_ref; + $arrayofstripecard[$companypaymentmodetemp->stripe_card_ref]=$companypaymentmodetemp->stripe_card_ref; print ''; print ''; - print $obj->rowid; + print $companypaymentmodetemp->id; print ''; print ''; - print $obj->stripe_card_ref; + print $companypaymentmodetemp->stripe_card_ref; print ''; print ''; print img_credit_card($companypaymentmodetemp->type); @@ -1078,20 +1130,8 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' } dol_fiche_end(); -/* - if ($socid && $action != 'edit' && $action != 'create' && $action != 'createcard') - { - // Barre d'actions - print '
    '; - if ($user->rights->societe->creer) - { - print ''.$langs->trans("Add").''; - } - print '
    '; - } -*/ if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC)) { print '
    '; @@ -1152,41 +1192,41 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; // Show fields of bank account - foreach ($account->getFieldsToShow(1) as $val) { + foreach ($companybankaccount->getFieldsToShow(1) as $val) { $require=false; if ($val == 'BankCode') { $name = 'code_banque'; $size = 8; - $content = $account->code_banque; + $content = $companybankaccount->code_banque; } elseif ($val == 'DeskCode') { $name = 'code_guichet'; $size = 8; - $content = $account->code_guichet; + $content = $companybankaccount->code_guichet; } elseif ($val == 'BankAccountNumber') { $name = 'number'; $size = 18; - $content = $account->number; + $content = $companybankaccount->number; } elseif ($val == 'BankAccountNumberKey') { $name = 'cle_rib'; $size = 3; - $content = $account->cle_rib; + $content = $companybankaccount->cle_rib; } elseif ($val == 'IBAN') { $name = 'iban'; $size = 30; - $content = $account->iban; - if ($account->needIBAN()) $require=true; + $content = $companybankaccount->iban; + if ($companybankaccount->needIBAN()) $require=true; } elseif ($val == 'BIC') { $name = 'bic'; $size = 12; - $content = $account->bic; - if ($account->needIBAN()) $require=true; + $content = $companybankaccount->bic; + if ($companybankaccount->needIBAN()) $require=true; } print ''.$langs->trans($val).''; @@ -1196,16 +1236,16 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) print '"; print ''; - print ''; + print ''; print "\n"; print '"; print '
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("BankName").'
    '.$langs->trans("BankAccountDomiciliation").''; print '
    '.$langs->trans("BankAccountOwner").'
    '.$langs->trans("BankAccountOwnerAddress").''; print '
    '; @@ -1216,15 +1256,15 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) print ''; - if (empty($account->rum)) $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); + if (empty($companybankaccount->rum)) $companybankaccount->rum = $prelevement->buildRumNumber($object->code_client, $companybankaccount->datec, $companybankaccount->id); // RUM print ''; - print ''; + print ''; print ''; print '
    '.$langs->trans("RUM").'
    '.$langs->trans("WithdrawMode").''; $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); - print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur','alpha')?GETPOST('frstrecur','alpha'):$account->frstrecur), 0); + print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur','alpha')?GETPOST('frstrecur','alpha'):$companybankaccount->frstrecur), 0); print '
    '; @@ -1241,6 +1281,53 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) print '
    '; } +// Edit Card +if ($socid && $action == 'editcard' && $user->rights->societe->creer) +{ + dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); + + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); + + print '
    '; + + print '
    '; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print '"; + print ''; + + print '
    '.$langs->trans("Label").'
    '.$langs->trans("NameOnCard").'
    '.$langs->trans("CardNumber").'
    '.$langs->trans("ExpiryDate").''; + print $formother->select_month($companypaymentmode->exp_date_month, 'exp_date_month', 1); + print $formother->select_year($companypaymentmode->exp_date_year, 'exp_date_year', 1, 5, 10, 0, 0, '', 'marginleftonly'); + print '
    '.$langs->trans("CVN").'
    '.$langs->trans("StripeID")." ('card_....')
    '; + print '
    '; + + dol_fiche_end(); + + print '
    '; + print ''; + print '     '; + print ''; + print '
    '; +} + // Create BAN if ($socid && $action == 'create' && $user->rights->societe->creer) @@ -1257,13 +1344,13 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; // Show fields of bank account - foreach ($account->getFieldsToShow(1) as $val) { + foreach ($companybankaccount->getFieldsToShow(1) as $val) { $require=false; if ($val == 'BankCode') { @@ -1281,11 +1368,11 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) } elseif ($val == 'IBAN') { $name = 'iban'; $size = 30; - if ($account->needIBAN()) $require=true; + if ($companybankaccount->needIBAN()) $require=true; } elseif ($val == 'BIC') { $name = 'bic'; $size = 12; - if ($account->needIBAN()) $require=true; + if ($companybankaccount->needIBAN()) $require=true; } print ''.$langs->trans($val).''; @@ -1299,7 +1386,7 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) print ""; print ''; - print ''; + print ''; print "\n"; print ''; @@ -682,6 +707,17 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print ''; } @@ -698,20 +734,20 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { $morehtmlright=''.$langs->trans("Add").''; } - print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc?' ('.$stripeacc.')':''), $morehtmlright, ''); + print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc?' ('.$stripeacc.')':' (API mode)'), $morehtmlright, ''); $listofsources = array(); - if (is_object($stripe) && $stripeacc) + if (is_object($stripe)) { try { - $customerstripe=$stripe->customerStripe($object->id, $stripeacc, $servicestatus); + $customerstripe=$stripe->customerStripe($object, $stripeacc, $servicestatus); if ($customerstripe->id) { $listofsources=$customerstripe->sources->data; } } catch(Exception $e) { - dol_syslog("Failed to get strip customer for thirdparty id =".$object->id); + dol_syslog("Error when searching/loading Stripe customer for thirdparty id =".$object->id); } } @@ -816,10 +852,6 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' $i++; } } - else - { - print $langs->trans("NoPaymentMethodOnFile"); - } } else dol_print_error($db); } diff --git a/htdocs/stripe/class/actions_stripe.class.php b/htdocs/stripe/class/actions_stripe.class.php index baeba001edf..0451c1d4782 100644 --- a/htdocs/stripe/class/actions_stripe.class.php +++ b/htdocs/stripe/class/actions_stripe.class.php @@ -99,7 +99,7 @@ class ActionsStripeconnect $this->resprints.= ''; $this->resprints.= ''; $addcolumforpicto=($delallowed || $printer || $morepicto); - $out.= ''; } else $out = $hookmanager->resPrint; // Replace line @@ -811,7 +811,7 @@ class FormFile if (count($file_list) == 0 && count($link_list) == 0 && $headershown) { - $out.=''."\n"; + $out.=''."\n"; } } @@ -861,7 +861,7 @@ class FormFile preg_match('/\/([0-9]+)\/[^\/]+\/'.preg_quote($modulesubdir).'$/', $filedir, $regs); $entity = ((! empty($regs[1]) && $regs[1] > 1) ? $regs[1] : $conf->entity); } - + $filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+'; $file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$'); // Get list of files starting with name of ref (but not followed by "-" to discard uploaded files) diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 28eaa1abacc..433d81e523b 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -734,7 +734,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { $morehtmlright=''.$langs->trans("Add").''; } - print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc?' ('.$stripeacc.')':' (API mode)'), $morehtmlright, ''); + print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc?' (Stripe connection with Stripe Connect account '.$stripeacc.')':' (Stripe connection with default API credentials)'), $morehtmlright, ''); $listofsources = array(); if (is_object($stripe)) @@ -1152,7 +1152,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { $colspan=8; if (! empty($conf->prelevement->enabled)) $colspan+=2; - print ''; + print ''; } print '
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("Bank").'
    '.$langs->trans("BankAccountOwner").'
    '.$langs->trans("BankAccountOwnerAddress").''; @@ -1355,13 +1442,13 @@ if ($socid && $action == 'createcard' && $user->rights->societe->creer) print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; + print '"; + print ''; + print '
    '.$langs->trans("Label").'
    '.$langs->trans("NameOnCard").'
    '.$langs->trans("CardNumber").'
    '.$langs->trans("ExpiryDate").''; @@ -1372,6 +1459,9 @@ if ($socid && $action == 'createcard' && $user->rights->societe->creer) print '
    '.$langs->trans("CVN").'
    '.$langs->trans("StripeID")." ('card_....')
    '; print ''; @@ -1387,7 +1477,7 @@ if ($socid && $action == 'createcard' && $user->rights->societe->creer) print ''; } -if ($socid && $action == 'edit' && $user->rights->societe->creer) +if ($socid && ($action == 'edit' || $action == 'editcard') && $user->rights->societe->creer) { print ''; } From b2326813180c9855eba9410e41d7e04e0207e97d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 14 Mar 2018 16:53:16 +0100 Subject: [PATCH 304/413] NEW Add a button to create Stripe customer from the Payment mode tab --- .../interface_80_modStripe_Stripe.class.php | 4 +- htdocs/langs/en_US/stripe.lang | 1 + htdocs/societe/class/societeaccount.class.php | 4 +- htdocs/societe/paymentmodes.php | 54 ++++++++--- htdocs/stripe/class/actions_stripe.class.php | 13 ++- htdocs/stripe/class/stripe.class.php | 93 +++++++++++-------- htdocs/stripe/config.php | 22 ++--- 7 files changed, 119 insertions(+), 72 deletions(-) diff --git a/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php b/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php index a41ade1e01b..495f439eb09 100644 --- a/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php +++ b/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php @@ -135,7 +135,7 @@ class InterfaceStripe if ($action == 'COMPANY_MODIFY') { dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); if ($stripe->getStripeAccount($service) && $object->client != 0) { - $cu = $stripe->customerStripe($object->id, $stripe->getStripeAccount($service)); + $cu = $stripe->customerStripe($object, $stripe->getStripeAccount($service)); if ($cu) { if ($conf->entity == '1') { $customer = \Stripe\Customer::retrieve("$cu->id"); @@ -153,7 +153,7 @@ class InterfaceStripe } } elseif ($action == 'COMPANY_DELETE') { dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); - $cu = $stripe->customerStripe($object->id, $stripe->getStripeAccount($service)); + $cu = $stripe->customerStripe($object, $stripe->getStripeAccount($service)); if ($cu) { if ($conf->entity == 1) { $customer = \Stripe\Customer::retrieve("$cu->id"); diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 3db64381797..f096248bc39 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -59,3 +59,4 @@ ExpiryDate=Expiry Date CVN=CVN DeleteACard=Delete Card record ConfirmDeleteCard=Are you sure you want to delete this Card record? +CreateCustomerOnStripe=Create customer on Stripe diff --git a/htdocs/societe/class/societeaccount.class.php b/htdocs/societe/class/societeaccount.class.php index 08b3617e540..111da0c46ea 100644 --- a/htdocs/societe/class/societeaccount.class.php +++ b/htdocs/societe/class/societeaccount.class.php @@ -263,8 +263,10 @@ class SocieteAccount extends CommonObject $sql.= " WHERE sa.fk_soc = " . $id; $sql.= " AND sa.entity IN (".getEntity('societe').")"; $sql.= " AND sa.site = '".$this->db->escape($site)."' AND sa.status = ".((int) $status); + $sql.= " AND key_account IS NOT NULL AND key_account <> ''"; + //$sql.= " ORDER BY sa.key_account DESC"; - dol_syslog(get_class($this) . "::getCustomerAccount Try to find the system customer id of thirdparty id=".$id." (exemple: cu_.... for stripe)", LOG_DEBUG); + dol_syslog(get_class($this) . "::getCustomerAccount Try to find the system customer id of thirdparty id=".$id." (exemple: cus_.... for stripe)", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 9365511b78d..28eaa1abacc 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -41,6 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; $langs->loadLangs(array("companies","commercial","banks","bills")); + // Security check $socid = GETPOST("socid","int"); if ($user->societe_id) $socid=$user->societe_id; @@ -82,8 +83,8 @@ if (! empty($conf->stripe->enabled)) } $stripe = new Stripe($db); - $stripeacc = $stripe->getStripeAccount($service); // Stripe OAuth connect account of dolibarr user (no network access here) - $stripecu = $stripe->getStripeCustomerAccount($object->id, $servicestatus); // Get thirdparty cu_... + $stripeacc = $stripe->getStripeAccount($service); // Get Stripe OAuth connect account (no network access here) + $stripecu = $stripe->getStripeCustomerAccount($object->id, $servicestatus); // Get remote Stripe customer 'cus_...' (no network access here) } @@ -474,6 +475,7 @@ if (empty($reshook)) $_POST['lang_id'] = GETPOST('lang_idrib'.GETPOST('companybankid')); $_POST['model'] = GETPOST('modelrib'.GETPOST('companybankid')); } + $id = $socid; $upload_dir = $conf->societe->multidir_output[$object->entity]; $permissioncreate=$user->rights->societe->creer; @@ -484,6 +486,29 @@ if (empty($reshook)) // Action for stripe if (! empty($conf->stripe->enabled) && class_exists('Stripe')) { + if ($action == 'synccustomertostripe') + { + if ($object->client == 0) + { + $error++; + setEventMessages('ThisThirdpartyIsNotACustomer', null, 'errors'); + } + else + { + // Creation of Stripe customer + update of societe_account + $cu = $stripe->customerStripe($object, $stripeacc, $servicestatus, 1); + if (! $cu) + { + $error++; + setEventMessages($stripe->error, $stripe->errors, 'errors'); + } + else + { + $stripecu = $cu->id; + } + } + } + if ($action == 'setkey_account') { $error = 0; @@ -655,7 +680,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' if ($object->client) { print '
    '; - print $langs->trans('CustomerCode').''; + print $langs->trans('CustomerCode').''; print $object->code_client; if ($object->check_codeclient() <> 0) print ' ('.$langs->trans("WrongCustomerCode").')'; print '
    '; //print $stripecu; print $form->editfieldval("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', null, null, '', 1, '', 'socid'); + print ''; + if (empty($stripecu)) + { + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '; + } print '
    '; $stripe=new Stripe($db); if ($stripe->getStripeAccount($service)&&$object->client!=0) { - $customer=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service)); + $customer=$stripe->customerStripe($object,$stripe->getStripeAccount($service)); $this->resprints.= $customer->id; } else { @@ -117,8 +117,9 @@ class ActionsStripeconnect $this->resprints.= ''; $stripe=new Stripe($db); - if ($stripe->getStripeAccount($service)&&$object->fk_soc>'0') { - $customer=$stripe->customerStripe($object->fk_soc,$stripe->getStripeAccount($service)); + if ($stripe->getStripeAccount($service) && $object->fk_soc > 0) { + $object->fetch_thirdparty(); + $customer=$stripe->customerStripe($object->thirdparty, $stripe->getStripeAccount($service)); $this->resprints.= $customer->id; } else { @@ -135,7 +136,8 @@ class ActionsStripeconnect $this->resprints.= ''; $stripe=new Stripe($db); if (7==4) { - $customer=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service)); + $object->fetch_thirdparty(); + $customer=$stripe->customerStripe($object,$stripe->getStripeAccount($service)); $this->resprints.= $customer->id; } else { @@ -154,7 +156,8 @@ class ActionsStripeconnect $this->resprints.= ''; $stripe=new Stripe($db); if (7==4) { - $customer=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service)); + $object->fetch_thirdparty(); + $customer=$stripe->customerStripe($object,$stripe->getStripeAccount($service)); $this->resprints.= $customer->id; } else { diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 5f86c45f696..cf02ec6b65b 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -20,7 +20,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; +require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; // This set stripe global env /** @@ -86,6 +86,7 @@ class Stripe extends CommonObject dol_print_error($this->db); } + dol_syslog("No dedicated Stipe Connect account available for entity".$conf->entity); return $key; } @@ -102,30 +103,33 @@ class Stripe extends CommonObject include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; $societeaccount = new SocieteAccount($this->db); - return $societeaccount->getCustomerAccount($id, 'stripe', $status); // Get thirdparty cu_... + return $societeaccount->getCustomerAccount($id, 'stripe', $status); // Get thirdparty cus_... } /** * Get the Stripe customer of a thirdparty (with option to create it if not linked yet) * - * @param int $id Id of third party - * @param string $key Stripe account acc_.... + * @param Societe $object Object thirdparty to check, or create on stripe (create on strip also update the stripe_account table for current entity) + * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect * @param int $status Status (0=test, 1=live) * @param int $createifnotlinkedtostripe 1=Create the stripe customer and the link if the thirdparty is not yet linked to a stripe customer - * @return \Stripe\StripeObject|\Stripe\ApiResource|null Stripe Customer or null if not found + * @return \Stripe\StripeCustomer|null Stripe Customer or null if not found */ - public function customerStripe($id, $key, $status=0, $createifnotlinkedtostripe=0) + public function customerStripe($object, $key='', $status=0, $createifnotlinkedtostripe=0) { - global $conf; + global $conf, $user; - $sql = "SELECT sa.key_account as key_account, sa.entity"; // key_account is cu_.... + $customer = null; + + $sql = "SELECT sa.key_account as key_account, sa.entity"; // key_account is cus_.... $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa"; - $sql.= " WHERE sa.fk_soc = " . $id; + $sql.= " WHERE sa.fk_soc = " . $object->id; $sql.= " AND sa.entity IN (".getEntity('societe').")"; $sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status); + $sql.= " AND key_account IS NOT NULL AND key_account <> ''"; - dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); + dol_syslog(get_class($this) . "::fetch search stripe customer id for thirdparty id=".$object->id, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -133,41 +137,52 @@ class Stripe extends CommonObject { $obj = $this->db->fetch_object($resql); $tiers = $obj->key_account; - if ($conf->entity == 1) { - $customer = \Stripe\Customer::retrieve("$tiers"); - } else { - $customer = \Stripe\Customer::retrieve("$tiers", array( - "stripe_account" => $key - )); + try { + if (empty($key)) { // If the Stripe connect account not set, we use common API usage + $customer = \Stripe\Customer::retrieve("$tiers"); + } else { + $customer = \Stripe\Customer::retrieve("$tiers", array("stripe_account" => $key)); + } + } + catch(Exception $e) + { + } } elseif ($createifnotlinkedtostripe) { - $soc = new Societe($this->db); - $soc->fetch($id); + $dataforcustomer = array( + "email" => $object->email, + "business_vat_id" => $object->tva_intra, + "description" => $object->name, + "metadata" => array('dol_id'=>$object->id, 'dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity) + ); - if ($conf->entity == 1) { - $customer = \Stripe\Customer::create(array( - "email" => $soc->email, - "business_vat_id" => $soc->tva_intra, - "description" => $soc->name - )); - } else { - $customer = \Stripe\Customer::create(array( - "email" => $soc->email, - "business_vat_id" => $soc->tva_intra, - "description" => $soc->name - ), array( - "stripe_account" => $key - )); + //$a = \Stripe\Stripe::getApiKey(); + //var_dump($a);var_dump($key);exit; + try { + if (empty($key)) { // If the Stripe connect account not set, we use common API usage + $customer = \Stripe\Customer::create($dataforcustomer); + } else { + $customer = \Stripe\Customer::create($dataforcustomer, array("stripe_account" => $key)); + } + $customer_id = $customer->id; + + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_account (fk_soc, login, key_account, site, status, entity, date_creation, fk_user_creat)"; + $sql .= " VALUES (".$object->id.", '', '".$this->db->escape($customer_id)."', 'stripe', " . $status . ", " . $conf->entity . ", '".$this->db->idate(dol_now())."', ".$user->id.")"; + $resql = $this->db->query($sql); + if (! $resql) + { + $this->error = $this->db->lasterror(); + } + } + catch(Exception $e) + { + //print $e->getMessage(); } - $customer_id = $customer->id; - - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_account (fk_soc, key_account, site, status, entity)"; - $sql .= " VALUES (".$id.", '".$this->db->escape($customer_id)."', 'stripe', " . $status . "," . $conf->entity . ")"; - $resql = $this->db->query($sql); } } + return $customer; } @@ -178,8 +193,8 @@ class Stripe extends CommonObject * @param string $currency EUR, GPB... * @param string $origin order, invoice, contract... * @param int $item if of element to pay - * @param string $source src_xxxxx or card_xxxxx or ac_xxxxx - * @param string $customer Stripe account ref 'cu_xxxxxxxxxxxxx' via customerStripe() + * @param string $source src_xxxxx or card_xxxxx + * @param string $customer Stripe customer ref 'cus_xxxxxxxxxxxxx' via customerStripe() * @param string $account Stripe account ref 'acc_xxxxxxxxxxxxx' via getStripeAccount() * @param int $status Status (0=test, 1=live) * @return Stripe diff --git a/htdocs/stripe/config.php b/htdocs/stripe/config.php index 31959b3516f..db982e878f9 100644 --- a/htdocs/stripe/config.php +++ b/htdocs/stripe/config.php @@ -15,44 +15,38 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . + * + * Set Stripe environment: set the ApiKey and AppInfo */ /** -* \file htdocs/public/stripe/config.php +* \file htdocs/stripe/config.php * \ingroup Stripe * \brief Page to move config in api */ -require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/stripe/lib/stripe.lib.php'; require_once DOL_DOCUMENT_ROOT.'/includes/stripe/init.php'; +require_once DOL_DOCUMENT_ROOT.'/includes/stripe/lib/Stripe.php'; global $stripe; global $conf; -//use \includes\stripe as stripe; -$stripe = array(); +$stripearrayofkeys = array(); if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha')) { - $stripe = array( + $stripearrayofkeys = array( "secret_key" => $conf->global->STRIPE_TEST_SECRET_KEY, "publishable_key" => $conf->global->STRIPE_TEST_PUBLISHABLE_KEY ); } else { - $stripe = array( + $stripearrayofkeys = array( "secret_key" => $conf->global->STRIPE_LIVE_SECRET_KEY, "publishable_key" => $conf->global->STRIPE_LIVE_PUBLISHABLE_KEY ); } -require_once DOL_DOCUMENT_ROOT."/includes/stripe/lib/Stripe.php"; -require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - -\Stripe\Stripe::setApiKey($stripe['secret_key']); - -require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - +\Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']); \Stripe\Stripe::setAppInfo("Stripe", DOL_VERSION, "https://www.dolibarr.org"); // add dolibarr version From 9994b1f1330cc9c461c6ce826b08fbf222acb43b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 14 Mar 2018 17:12:32 +0100 Subject: [PATCH 305/413] Work on stripe interface --- htdocs/core/class/html.formfile.class.php | 8 ++++---- htdocs/societe/paymentmodes.php | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index 077a29d4595..4a07f096a5d 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -616,7 +616,7 @@ class FormFile $out.= '
    '; + $out.= ''; // Model if (! empty($modellist)) @@ -778,7 +778,7 @@ class FormFile $res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file); if (empty($res)) { - $out .= $hookmanager->resPrint; // Complete line + $out.= $hookmanager->resPrint; // Complete line $out.= '
    '.$langs->trans("None").'
    '.$langs->trans("None").'
    '.$langs->trans("NoBANRecord").'
    '.$langs->trans("NoBANRecord").'
    '; From 8c535db04c2b019c22d86ab721925f95974d63b7 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 14 Mar 2018 17:15:31 +0100 Subject: [PATCH 306/413] Use .... before end of card number --- htdocs/societe/paymentmodes.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 433d81e523b..7ae6c4eadfd 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -809,7 +809,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print img_credit_card($companypaymentmodetemp->type); print ''; print ''; - if ($companypaymentmodetemp->last_four) print '**** '.$companypaymentmodetemp->last_four; + if ($companypaymentmodetemp->last_four) print '....'.$companypaymentmodetemp->last_four; if ($companypaymentmodetemp->exp_date_month || $companypaymentmodetemp->exp_date_year) print ' - '.$companypaymentmodetemp->exp_date_month.'/'.$companypaymentmodetemp->exp_date_year.''; print ''; if ($companypaymentmodetemp->country_code) @@ -892,7 +892,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print''; if ($src->object=='card') { - print '**** '.$src->last4.' - '.$src->exp_month.'/'.$src->exp_year.''; + print '....'.$src->last4.' - '.$src->exp_month.'/'.$src->exp_year.''; print ''; if ($src->country) { @@ -904,7 +904,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' } elseif ($src->object=='source' && $src->type=='card') { - print $src->owner->name.'
    **** '.$src->card->last4.' - '.$src->card->exp_month.'/'.$src->card->exp_year.''; + print $src->owner->name.'
    ....'.$src->card->last4.' - '.$src->card->exp_month.'/'.$src->card->exp_year.''; print ''; if ($src->card->country) From a5dc5839060a3fdcfa45ac8851ad5a3331412166 Mon Sep 17 00:00:00 2001 From: Philippe GRAND Date: Wed, 14 Mar 2018 19:10:22 +0100 Subject: [PATCH 307/413] use loadLangs for translation files --- .../modules/commande/doc/pdf_einstein.modules.php | 7 +++---- .../modules/contract/doc/pdf_strato.modules.php | 10 ++++------ .../modules/expedition/doc/pdf_merou.modules.php | 13 +++---------- 3 files changed, 10 insertions(+), 20 deletions(-) diff --git a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php index 9d15b263b66..7c002f969aa 100644 --- a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php +++ b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php @@ -97,10 +97,9 @@ class pdf_einstein extends ModelePDFCommandes public function __construct($db) { global $conf,$langs,$mysoc; - - $langs->load("main"); - $langs->load("bills"); - $langs->load("products"); + + // Translations + $langs->loadLangs(array("main", "bills", "products")); $this->db = $db; $this->name = "einstein"; diff --git a/htdocs/core/modules/contract/doc/pdf_strato.modules.php b/htdocs/core/modules/contract/doc/pdf_strato.modules.php index 74b5d43f489..7a009876fac 100644 --- a/htdocs/core/modules/contract/doc/pdf_strato.modules.php +++ b/htdocs/core/modules/contract/doc/pdf_strato.modules.php @@ -4,7 +4,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2008 Raphael Bertrand (Resultic) * Copyright (C) 2011 Fabrice CHERRIER - * Copyright (C) 2013 Philippe Grand + * Copyright (C) 2013-2018 Philippe Grand * Copyright (C) 2015 Marcos García * * This program is free software; you can redistribute it and/or modify @@ -126,11 +126,9 @@ class pdf_strato extends ModelePDFContract if (! is_object($outputlangs)) $outputlangs=$langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; - - $outputlangs->load("main"); - $outputlangs->load("dict"); - $outputlangs->load("companies"); - $outputlangs->load("contracts"); + + // Translations + $langs->loadLangs(array("main", "dict", "companies", "contracts")); if ($conf->contrat->dir_output) { diff --git a/htdocs/core/modules/expedition/doc/pdf_merou.modules.php b/htdocs/core/modules/expedition/doc/pdf_merou.modules.php index 0ae6ed3ebe5..9fed3e6589b 100644 --- a/htdocs/core/modules/expedition/doc/pdf_merou.modules.php +++ b/htdocs/core/modules/expedition/doc/pdf_merou.modules.php @@ -91,16 +91,9 @@ class pdf_merou extends ModelePdfExpedition if (! is_object($outputlangs)) $outputlangs=$langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; - - $outputlangs->load("main"); - $outputlangs->load("dict"); - $outputlangs->load("companies"); - $outputlangs->load("bills"); - $outputlangs->load("products"); - $outputlangs->load("propal"); - $outputlangs->load("deliveries"); - $outputlangs->load("sendings"); - $outputlangs->load("productbatch"); + + // Translations + $langs->loadLangs(array("main", "bills", "products", "dict", "companies", "propal", "deliveries", "sendings", "productbatch")); if ($conf->expedition->dir_output) { From 13ce041313d9c44a9ac04211dac7ba3db6f83077 Mon Sep 17 00:00:00 2001 From: Philippe GRAND Date: Wed, 14 Mar 2018 19:26:46 +0100 Subject: [PATCH 308/413] use loadLangs for translation files --- .../modules/expedition/doc/pdf_rouget.modules.php | 13 +++---------- .../expensereport/doc/pdf_standard.modules.php | 10 ++++------ .../core/modules/facture/doc/pdf_crabe.modules.php | 9 +++------ .../modules/fichinter/doc/pdf_soleil.modules.php | 8 +++----- 4 files changed, 13 insertions(+), 27 deletions(-) diff --git a/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php b/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php index 978f15d2ae8..56b2c8d7dc4 100644 --- a/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php +++ b/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php @@ -122,16 +122,9 @@ class pdf_rouget extends ModelePdfExpedition if (! is_object($outputlangs)) $outputlangs=$langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; - - $outputlangs->load("main"); - $outputlangs->load("dict"); - $outputlangs->load("companies"); - $outputlangs->load("bills"); - $outputlangs->load("products"); - $outputlangs->load("propal"); - $outputlangs->load("deliveries"); - $outputlangs->load("sendings"); - $outputlangs->load("productbatch"); + + // Translations + $langs->loadLangs(array("main", "bills", "products", "dict", "companies", "propal", "deliveries", "sendings", "productbatch")); $nblignes = count($object->lines); diff --git a/htdocs/core/modules/expensereport/doc/pdf_standard.modules.php b/htdocs/core/modules/expensereport/doc/pdf_standard.modules.php index c236c9ad017..1b8db6d02c3 100644 --- a/htdocs/core/modules/expensereport/doc/pdf_standard.modules.php +++ b/htdocs/core/modules/expensereport/doc/pdf_standard.modules.php @@ -1,7 +1,7 @@ * Copyright (C) 2015 Alexandre Spangaro - * Copyright (C) 2016 Philippe Grand + * Copyright (C) 2016-2018 Philippe Grand * * 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 @@ -154,11 +154,9 @@ class pdf_standard extends ModeleExpenseReport if (! is_object($outputlangs)) $outputlangs=$langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; - - $outputlangs->load("main"); - $outputlangs->load("dict"); - $outputlangs->load("trips"); - $outputlangs->load("projects"); + + // Translations + $langs->loadLangs(array("main", "trips", "projects", "dict")); $nblignes = count($object->lines); diff --git a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php index 6a063ec0e86..1af1cd1875c 100644 --- a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php +++ b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php @@ -176,12 +176,9 @@ class pdf_crabe extends ModelePDFFactures if (! is_object($outputlangs)) $outputlangs=$langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; - - $outputlangs->load("main"); - $outputlangs->load("dict"); - $outputlangs->load("companies"); - $outputlangs->load("bills"); - $outputlangs->load("products"); + + // Translations + $langs->loadLangs(array("main", "bills", "products", "dict", "companies")); $nblignes = count($object->lines); diff --git a/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php b/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php index 2307f896973..b7600f0869f 100644 --- a/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php +++ b/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php @@ -112,11 +112,9 @@ class pdf_soleil extends ModelePDFFicheinter if (! is_object($outputlangs)) $outputlangs=$langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; - - $outputlangs->load("main"); - $outputlangs->load("dict"); - $outputlangs->load("companies"); - $outputlangs->load("interventions"); + + // Translations + $langs->loadLangs(array("main", "interventions", "dict", "companies")); if ($conf->ficheinter->dir_output) { From 743a61159d2cc6c882956419ecab85e190bc5f7f Mon Sep 17 00:00:00 2001 From: Philippe GRAND Date: Wed, 14 Mar 2018 19:34:33 +0100 Subject: [PATCH 309/413] use loadLangs for translation files --- .../core/modules/livraison/doc/pdf_typhon.modules.php | 10 ++++------ .../core/modules/project/doc/pdf_baleine.modules.php | 7 +++---- htdocs/core/modules/project/doc/pdf_beluga.modules.php | 7 +++---- .../core/modules/project/doc/pdf_timespent.modules.php | 7 +++---- htdocs/core/modules/propale/doc/pdf_azur.modules.php | 6 +++--- .../supplier_invoice/pdf/pdf_canelle.modules.php | 6 +++--- .../supplier_order/pdf/pdf_muscadet.modules.php | 6 +++--- .../supplier_payment/doc/pdf_standard.modules.php | 6 +++--- .../supplier_proposal/doc/pdf_aurore.modules.php | 6 +++--- 9 files changed, 28 insertions(+), 33 deletions(-) diff --git a/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php b/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php index 06d6920e866..e3f5471a6c3 100644 --- a/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php +++ b/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php @@ -3,7 +3,7 @@ * Copyright (C) 2005-2014 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke * Copyright (C) 2008 Chiptronik - * Copyright (C) 2011-2012 Philippe Grand + * Copyright (C) 2011-2018 Philippe Grand * Copyright (C) 2015 Marcos García * This program is free software; you can redistribute it and/or modify @@ -65,11 +65,9 @@ class pdf_typhon extends ModelePDFDeliveryOrder function __construct($db) { global $conf,$langs,$mysoc; - - $langs->load("main"); - $langs->load("bills"); - $langs->load("sendings"); - $langs->load("companies"); + + // Translations + $langs->loadLangs(array("main", "bills", "sendings", "companies")); $this->db = $db; $this->name = "typhon"; diff --git a/htdocs/core/modules/project/doc/pdf_baleine.modules.php b/htdocs/core/modules/project/doc/pdf_baleine.modules.php index 66108da54f8..4b6273388ad 100644 --- a/htdocs/core/modules/project/doc/pdf_baleine.modules.php +++ b/htdocs/core/modules/project/doc/pdf_baleine.modules.php @@ -48,10 +48,9 @@ class pdf_baleine extends ModelePDFProjects function __construct($db) { global $conf,$langs,$mysoc; - - $langs->load("main"); - $langs->load("projects"); - $langs->load("companies"); + + // Translations + $langs->loadLangs(array("main", "projects", "companies")); $this->db = $db; $this->name = "baleine"; diff --git a/htdocs/core/modules/project/doc/pdf_beluga.modules.php b/htdocs/core/modules/project/doc/pdf_beluga.modules.php index f2d06d2ebb2..959cc152a0f 100644 --- a/htdocs/core/modules/project/doc/pdf_beluga.modules.php +++ b/htdocs/core/modules/project/doc/pdf_beluga.modules.php @@ -64,10 +64,9 @@ class pdf_beluga extends ModelePDFProjects function __construct($db) { global $conf,$langs,$mysoc; - - $langs->load("main"); - $langs->load("projects"); - $langs->load("companies"); + + // Translations + $langs->loadLangs(array("main", "projects", "companies")); $this->db = $db; $this->name = "beluga"; diff --git a/htdocs/core/modules/project/doc/pdf_timespent.modules.php b/htdocs/core/modules/project/doc/pdf_timespent.modules.php index 21853f1bbf8..6843e9c5a33 100644 --- a/htdocs/core/modules/project/doc/pdf_timespent.modules.php +++ b/htdocs/core/modules/project/doc/pdf_timespent.modules.php @@ -47,10 +47,9 @@ class pdf_timespent extends ModelePDFProjects function __construct($db) { global $conf,$langs,$mysoc; - - $langs->load("main"); - $langs->load("projects"); - $langs->load("companies"); + + // Translations + $langs->loadLangs(array("main", "projects", "companies")); $this->db = $db; $this->name = "timespent"; diff --git a/htdocs/core/modules/propale/doc/pdf_azur.modules.php b/htdocs/core/modules/propale/doc/pdf_azur.modules.php index fba77613828..c27b8a7008e 100644 --- a/htdocs/core/modules/propale/doc/pdf_azur.modules.php +++ b/htdocs/core/modules/propale/doc/pdf_azur.modules.php @@ -68,9 +68,9 @@ class pdf_azur extends ModelePDFPropales function __construct($db) { global $conf,$langs,$mysoc; - - $langs->load("main"); - $langs->load("bills"); + + // Translations + $langs->loadLangs(array("main", "bills")); $this->db = $db; $this->name = "azur"; diff --git a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php index f927b064a69..22b746486c8 100644 --- a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php +++ b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php @@ -63,9 +63,9 @@ class pdf_canelle extends ModelePDFSuppliersInvoices function __construct($db) { global $conf,$langs,$mysoc; - - $langs->load("main"); - $langs->load("bills"); + + // Translations + $langs->loadLangs(array("main", "bills")); $this->db = $db; $this->name = "canelle"; diff --git a/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php b/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php index f61000d3b08..374dde2c64f 100644 --- a/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php +++ b/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php @@ -3,7 +3,7 @@ * Copyright (C) 2005-2011 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke * Copyright (C) 2010-2014 Juanjo Menent - * Copyright (C) 2015 Marcos García + * Copyright (C) 2015 Marcos García * Copyright (C) 2017 Ferran Marcet * * This program is free software; you can redistribute it and/or modify @@ -68,8 +68,8 @@ class pdf_muscadet extends ModelePDFSuppliersOrders { global $conf,$langs,$mysoc; - $langs->load("main"); - $langs->load("bills"); + // Translations + $langs->loadLangs(array("main", "bills")); $this->db = $db; $this->name = "muscadet"; diff --git a/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php b/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php index ffecb1dbdd7..8c9ed049841 100644 --- a/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php +++ b/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php @@ -65,9 +65,9 @@ class pdf_standard extends ModelePDFSuppliersPayments function __construct($db) { global $conf,$langs,$mysoc; - - $langs->load("main"); - $langs->load("bills"); + + // Translations + $langs->loadLangs(array("main", "bills")); $this->db = $db; $this->name = "standard"; diff --git a/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php b/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php index 46d4e35d10e..5d790f3c6dc 100644 --- a/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php +++ b/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php @@ -65,9 +65,9 @@ class pdf_aurore extends ModelePDFSupplierProposal function __construct($db) { global $conf,$langs,$mysoc; - - $langs->load("main"); - $langs->load("bills"); + + // Translations + $langs->loadLangs(array("main", "bills")); $this->db = $db; $this->name = "aurore"; From 302fed86464db7e6e23d455585efd90c0b407c58 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 14 Mar 2018 20:08:44 +0100 Subject: [PATCH 310/413] More fa image to replace png picto --- htdocs/accountancy/bookkeeping/list.php | 2 +- htdocs/core/class/html.formfile.class.php | 4 ++-- htdocs/core/lib/functions.lib.php | 25 ++++++++++++++------- htdocs/product/class/product.class.php | 10 ++++----- htdocs/societe/paymentmodes.php | 20 ++++++++--------- htdocs/theme/eldy/style.css.php | 9 +++++--- htdocs/theme/md/img/menus/ticketsup.png | Bin 0 -> 916 bytes htdocs/theme/md/style.css.php | 16 ++++++++++--- htdocs/ticketsup/class/ticketsup.class.php | 4 ++-- 9 files changed, 56 insertions(+), 34 deletions(-) create mode 100644 htdocs/theme/md/img/menus/ticketsup.png diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index ad8be2608c1..749033f8392 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -694,7 +694,7 @@ if ($num > 0) } // Action column - print ''; + print ''; print '' . img_edit() . ' '; print '' . img_delete() . ''; print ''; diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index 4a07f096a5d..5eef895bb0c 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -755,7 +755,7 @@ class FormFile $out.= ($param?'&'.$param:''); //$out.= '&modulepart='.$modulepart; // TODO obsolete ? //$out.= '&urlsource='.urlencode($urlsource); // TODO obsolete ? - $out.= '">'.img_picto($langs->trans("Delete"), 'delete.png').''; + $out.= '">'.img_picto($langs->trans("Delete"), 'delete').''; } if ($printer) { @@ -1233,7 +1233,7 @@ class FormFile if ($permtoeditline) { // Link to resize - print ''.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','class="paddingrightonly"',1).''; + print ''.img_picto($langs->trans("Resize"),'resize','class="paddingrightonly"').''; } } diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 65753457000..bed4bcc8d6a 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -3052,18 +3052,26 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ } else { + $pictowithoutext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto); + //if (in_array($picto, array('switch_off', 'switch_on', 'off', 'on'))) - if (in_array($picto, array('switch_off', 'switch_on', 'off', 'on'))) + if (in_array($pictowithoutext, array('delete', 'edit', 'off', 'on', 'resize', 'switch_off', 'switch_on'))) { - $fakey = $picto; $facolor=''; $fasize=''; - if ($picto == 'switch_off') { $fakey = 'fa-toggle-off'; $facolor='#999'; $fasize='2em'; } - if ($picto == 'switch_on') { $fakey = 'fa-toggle-on'; $facolor='#227722'; $fasize='2em'; } - if ($picto == 'off') { $fakey = 'fa-square-o'; $fasize='1.3em'; } - if ($picto == 'on') { $fakey = 'fa-check-square-o'; $fasize='1.3em'; } - $enabledisablehtml=''; - $enabledisablehtml.=''; + $fakey = $pictowithoutext; $facolor=''; $fasize=''; + if ($pictowithoutext == 'switch_off') { $fakey = 'fa-toggle-off'; $facolor='#999'; $fasize='2em'; } + elseif ($pictowithoutext == 'switch_on') { $fakey = 'fa-toggle-on'; $facolor='#227722'; $fasize='2em'; } + elseif ($pictowithoutext == 'off') { $fakey = 'fa-square-o'; $fasize='1.3em'; } + elseif ($pictowithoutext == 'on') { $fakey = 'fa-check-square-o'; $fasize='1.3em'; } + elseif ($pictowithoutext == 'delete') { $fakey = 'fa-trash'; $facolor='#444'; } + elseif ($pictowithoutext == 'edit') { $fakey = 'fa-pencil'; $facolor='#444'; } + elseif ($pictowithoutext == 'resize') { $fakey = 'fa-crop'; $facolor='#444'; } + else { $fakey = 'fa-'.$pictowithoutext; $facolor='#999'; } + + if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) { $morecss.=($morecss?' ':'').$reg[1]; } + $enabledisablehtml =''; if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $enabledisablehtml.=$titlealt; $enabledisablehtml.=''; + return $enabledisablehtml; } @@ -3306,6 +3314,7 @@ function img_delete($titlealt = 'default', $other = 'class="pictodelete"') if ($titlealt == 'default') $titlealt = $langs->trans('Delete'); return img_picto($titlealt, 'delete.png', $other); + //return ''; } /** diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index 8b6cc95368e..633d85e854b 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -1716,7 +1716,7 @@ class Product extends CommonObject $price_ttc = price2num($price_ttc,'MU'); if ( $newminprice !== '' || $newminprice === 0) - { + { $price_min = price2num($newminprice,'MU'); $price_min_ttc = price2num($newminprice) * (1 + ($newvat / 100)); $price_min_ttc = price2num($price_min_ttc,'MU'); @@ -2279,8 +2279,8 @@ class Product extends CommonObject } } } - - // If stock decrease is on invoice validation, the theorical stock continue to + + // If stock decrease is on invoice validation, the theorical stock continue to // count the orders to ship in theorical stock when some are already removed b invoice validation. // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is on, we make a compensation. if (! empty($conf->global->STOCK_CALCULATE_ON_BILL)) @@ -4285,7 +4285,7 @@ class Product extends CommonObject if ($user->rights->produit->creer || $user->rights->service->creer) { // Link to resize - $return.= ''.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','',1).'   '; + $return.= ''.img_picto($langs->trans("Resize"), 'resize', '').'   '; // Link to delete $return.= ''; @@ -4311,7 +4311,7 @@ class Product extends CommonObject if ($user->rights->produit->creer || $user->rights->service->creer) { // Link to resize - $return.= ''.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','',1).'   '; + $return.= ''.img_picto($langs->trans("Resize"), 'resize', '').'   '; // Link to delete $return.= ''; diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 7ae6c4eadfd..73a6b62c181 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -1,12 +1,12 @@ * Copyright (C) 2003 Jean-Louis Bergamo - * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2013 Peter Fontaine * Copyright (C) 2015-2016 Marcos García * Copyright (C) 2017 Ferran Marcet - * Copyright (C) 2018 ptibogxiv + * Copyright (C) 2018 ptibogxiv * * 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 @@ -703,10 +703,10 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' // Stripe customer key 'cu_....' stored into llx_societe_account print ''; //print $langs->trans('StripeCustomerId'); - print $form->editfieldkey("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', 0, 1, 'socid'); + print $form->editfieldkey("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', 0, 2, 'socid'); print ''; //print $stripecu; - print $form->editfieldval("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', null, null, '', 1, '', 'socid'); + print $form->editfieldval("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', null, null, '', 2, '', 'socid'); print ''; if (empty($stripecu)) { @@ -734,7 +734,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { $morehtmlright=''.$langs->trans("Add").''; } - print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc?' (Stripe connection with Stripe Connect account '.$stripeacc.')':' (Stripe connection with default API credentials)'), $morehtmlright, ''); + print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc?' (Stripe connection with Stripe OAuth Connect account '.$stripeacc.')':' (Stripe connection with keys from Stripe module setup)'), $morehtmlright, ''); $listofsources = array(); if (is_object($stripe)) @@ -835,7 +835,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' if (empty($companypaymentmodetemp->stripe_card_ref)) print $langs->trans("Local"); else print $langs->trans("LocalAndRemote"); print ''; - print ''; + print ''; if ($user->rights->societe->creer) { print ''; @@ -843,7 +843,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print ''; print ' '; print ''; - print img_delete($langs->trans("Delete")); + print img_picto($langs->trans("Delete"), 'delete'); print ''; } print ''; @@ -942,11 +942,11 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print ''; print $langs->trans("Remote"); print ''; - print ''; + print ''; if ($user->rights->societe->creer) { print ''; - print img_delete($langs->trans("Delete")); + print img_picto($langs->trans("Delete"), 'delete'); print ''; } print ''; @@ -1130,7 +1130,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print ''; // Edit/Delete - print ''; + print ''; if ($user->rights->societe->creer) { print ''; diff --git a/htdocs/theme/eldy/style.css.php b/htdocs/theme/eldy/style.css.php index cba140486db..6293802540e 100644 --- a/htdocs/theme/eldy/style.css.php +++ b/htdocs/theme/eldy/style.css.php @@ -801,6 +801,9 @@ select.flat.selectlimit { .fa-file-text-o, .fa-file-code-o, .fa-file-powerpoint-o, .fa-file-excel-o, .fa-file-word-o, .fa-file-o, .fa-file-image-o, .fa-file-video-o, .fa-file-audio-o, .fa-file-archive-o, .fa-file-pdf-o { color: #055; } +.fa-trash, .fa-crop, .fa-pencil { + font-size: 1.4em; +} /* DOL_XXX for future usage (when left menu has been removed). If we do not use datatable */ /*.table-responsive { @@ -1325,11 +1328,11 @@ div.nopadding { .pictowarning, .pictopreview { padding-: 3px; } -.pictoedit, .pictowarning, .pictodelete { +.pictowarning { vertical-align: text-bottom; } -.fiche img.pictoedit { - opacity: 0.7; +.fiche img.pictoedit, .fiche span.pictoedit { + opacity: 0.4; } .colorthumb { padding-left: 1px !important; diff --git a/htdocs/theme/md/img/menus/ticketsup.png b/htdocs/theme/md/img/menus/ticketsup.png new file mode 100644 index 0000000000000000000000000000000000000000..98beeaf593ac4baf79eb72d410a706d124a1ed7c GIT binary patch literal 916 zcmV;F18e+=P)kdg00002VoOIv0063u zBQgL0010qNS#tmY4c7nw4c7reD4Tcy000McNliru;sXv72QWw9ricIl10_jBK~zY` z&6Q0|lvfmnpAU3|aZqCs44nY#v{Xbb5-?PvCPqz&37d*d+J#%%CT>^|ckPO#ach$X zcWf$YH%(z@+DIx%Z7HUrf(dA({DhJygz`7@bTJTSo&wJhr|8)eG z5#w=?eEm{$d55{c93s5S0)xTQYZOPQB#+-%3IN&uo;26g_MiuZo4;bJ< zu$V#Lpq^2l1k39fjeE&M0Pggf13q=!IaTKz_o)M3b0>g@yky)+cn9mYRm9s&P)G}n z6o!j~KxH_drkgLBWH@A>(r_-FPyp>}&nIo4!wNt!!zd72mDei4VRi%K;Vi`xQLd)dA1rc}C`+V5 zbR5{t;cS8kIV4$YYJr4D0X#|~TuDcgBsoN~35Iw@F01OB;w})S27nr(z+G1LUqmji z7|JGi$ShEneySivA06zX8h~nc(LrC3Nb=qQwKmD{oD-3 z!pvgIfq4eA2!drMfpeV9ob(0vDK&1KQtq?Xej4qzo8u#YirZNDFc zfwX1WU_)r4SYoRqYOl3hIYNsQ>Vh5Cn4g8@d%~~$OP#P~YqO4d-RG)4@l(%w#B$3$ z;#oiOv8vC#ZtR~OztLV7O~;IPyyHwbTeR24fAeV+d&8H`I`6Wo%g#INOK(`b$=9|8 qNeQ*oaDr-}pI`ZfpMyX6U&h~dzpw7?&g63d0000: 3px; } -.pictoedit, .pictowarning, .pictodelete { +.pictowarning { vertical-align: text-bottom; } +.fiche img.pictoedit, .fiche span.pictoedit { + opacity: 0.9; +} img.hideonsmartphone.pictoactionview { vertical-align: bottom; } @@ -1682,6 +1688,10 @@ div.mainmenu.project { background-image: url(); } +div.mainmenu.ticketsup { + background-image: url(); +} + div.mainmenu.tools { background-image: url(); } @@ -1696,7 +1706,7 @@ div.mainmenu.website { $moduletomainmenu=array('user'=>'','syslog'=>'','societe'=>'companies','projet'=>'project','propale'=>'commercial','commande'=>'commercial', 'produit'=>'products','service'=>'products','stock'=>'products', 'don'=>'accountancy','tax'=>'accountancy','banque'=>'accountancy','facture'=>'accountancy','compta'=>'accountancy','accounting'=>'accountancy','adherent'=>'members','import'=>'tools','export'=>'tools','mailing'=>'tools', - 'contrat'=>'commercial','ficheinter'=>'commercial','deplacement'=>'commercial', + 'contrat'=>'commercial','ficheinter'=>'commercial','ticketsup'=>'ticketsup','deplacement'=>'commercial', 'fournisseur'=>'companies', 'barcode'=>'','fckeditor'=>'','categorie'=>'', ); @@ -1712,7 +1722,7 @@ $generic=1; // Put here list of menu entries when the div.mainmenu.menuentry was previously defined $divalreadydefined=array('home','companies','products','commercial','externalsite','accountancy','project','tools','members','agenda','ftp','holiday','hrm','bookmark','cashdesk','ecm','geoipmaxmind','gravatar','clicktodial','paypal','stripe','webservices','website'); // Put here list of menu entries we are sure we don't want -$divnotrequired=array('multicurrency','salaries','margin','opensurvey','paybox','expensereport','incoterm','prelevement','propal','workflow','notification','supplier_proposal','cron','product','productbatch','expedition'); +$divnotrequired=array('multicurrency','salaries','ticketsup','margin','opensurvey','paybox','expensereport','incoterm','prelevement','propal','workflow','notification','supplier_proposal','cron','product','productbatch','expedition'); foreach($mainmenuusedarray as $val) { if (empty($val) || in_array($val,$divalreadydefined)) continue; diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index a7b95bedbbe..3795978289e 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -2612,7 +2612,7 @@ class Ticketsup extends CommonObject } if ($user->rights->produit->creer || $user->rights->service->creer) { // Link to resize - $return .= '' . img_picto($langs->trans("Resize"), DOL_URL_ROOT . '/theme/common/transform-crop-and-resize', '', 1) . '   '; + $return .= '' . img_picto($langs->trans("Resize"), 'resize', '') . '   '; // Link to delete $return .= ''; @@ -2641,7 +2641,7 @@ class Ticketsup extends CommonObject if ($showaction) { if ($user->rights->produit->creer || $user->rights->service->creer) { // Link to resize - $return .= '' . img_picto($langs->trans("Resize"), DOL_URL_ROOT . '/theme/common/transform-crop-and-resize', '', 1) . '   '; + $return .= '' . img_picto($langs->trans("Resize"), 'resize', '') . '   '; // Link to delete $return .= ''; From bf4a0e46aa3bdd56aee844c7646be6569d8b6a6c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 14 Mar 2018 21:07:45 +0100 Subject: [PATCH 311/413] Add a credit card on stripe --- htdocs/langs/en_US/stripe.lang | 1 + htdocs/societe/paymentmodes.php | 53 ++++++++++++++- htdocs/stripe/class/stripe.class.php | 96 ++++++++++++++++++++++++++-- 3 files changed, 144 insertions(+), 6 deletions(-) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index f096248bc39..df42e31878a 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -60,3 +60,4 @@ CVN=CVN DeleteACard=Delete Card record ConfirmDeleteCard=Are you sure you want to delete this Card record? CreateCustomerOnStripe=Create customer on Stripe +CreateCardOnStripe=Create card on Stripe diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 73a6b62c181..6fe4b0c64a0 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -508,6 +508,42 @@ if (empty($reshook)) } } } + if ($action == 'synccardtostripe') + { + $companypaymentmode = new CompanyPaymentMode($db); + $companypaymentmode->fetch($id); + + if ($companypaymentmode->type != 'card') + { + $error++; + setEventMessages('ThisPaymentModeIsNotACard', null, 'errors'); + } + else + { + // Get the Stripe customer + $cu = $stripe->customerStripe($object, $stripeacc, $servicestatus); + if (! $cu) + { + $error++; + setEventMessages($stripe->error, $stripe->errors, 'errors'); + } + + if (! $error) + { + // Creation of Stripe card + update of societe_account + $card = $stripe->cardStripe($cu, $companypaymentmode, $stripeacc, $servicestatus, 1); + if (! $card) + { + $error++; + setEventMessages($stripe->error, $stripe->errors, 'errors'); + } + else + { + $stripecard = $card->id; + } + } + } + } if ($action == 'setkey_account') { @@ -612,6 +648,16 @@ llxHeader(); $head=societe_prepare_head($object); +// Show sandbox warning +/*if (! empty($conf->paypal->enabled) && (! empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox','alpha'))) // We can force sand box with param 'forcesandbox' +{ + dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Paypal'),'','warning'); +}*/ +if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha'))) +{ + dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); +} + // Load Bank account if (! $id) { @@ -810,7 +856,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print ''; print ''; if ($companypaymentmodetemp->last_four) print '....'.$companypaymentmodetemp->last_four; - if ($companypaymentmodetemp->exp_date_month || $companypaymentmodetemp->exp_date_year) print ' - '.$companypaymentmodetemp->exp_date_month.'/'.$companypaymentmodetemp->exp_date_year.''; + if ($companypaymentmodetemp->exp_date_month || $companypaymentmodetemp->exp_date_year) print ' - '.sprintf("%02d", $companypaymentmodetemp->exp_date_month).'/'.$companypaymentmodetemp->exp_date_year.''; print ''; if ($companypaymentmodetemp->country_code) { @@ -838,6 +884,11 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print ''; if ($user->rights->societe->creer) { + if ($stripecu && empty($companypaymentmodetemp->stripe_card_ref)) + { + print ''.$langs->trans("CreateCardOnStripe").''; + } + print ''; print img_picto($langs->trans("Modify"),'edit'); print ''; diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index cf02ec6b65b..82aca6580ef 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -110,13 +110,13 @@ class Stripe extends CommonObject /** * Get the Stripe customer of a thirdparty (with option to create it if not linked yet) * - * @param Societe $object Object thirdparty to check, or create on stripe (create on strip also update the stripe_account table for current entity) + * @param Societe $object Object thirdparty to check, or create on stripe (create on stripe also update the stripe_account table for current entity) * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect * @param int $status Status (0=test, 1=live) * @param int $createifnotlinkedtostripe 1=Create the stripe customer and the link if the thirdparty is not yet linked to a stripe customer * @return \Stripe\StripeCustomer|null Stripe Customer or null if not found */ - public function customerStripe($object, $key='', $status=0, $createifnotlinkedtostripe=0) + public function customerStripe(Societe $object, $key='', $status=0, $createifnotlinkedtostripe=0) { global $conf, $user; @@ -166,10 +166,9 @@ class Stripe extends CommonObject } else { $customer = \Stripe\Customer::create($dataforcustomer, array("stripe_account" => $key)); } - $customer_id = $customer->id; $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_account (fk_soc, login, key_account, site, status, entity, date_creation, fk_user_creat)"; - $sql .= " VALUES (".$object->id.", '', '".$this->db->escape($customer_id)."', 'stripe', " . $status . ", " . $conf->entity . ", '".$this->db->idate(dol_now())."', ".$user->id.")"; + $sql .= " VALUES (".$object->id.", '', '".$this->db->escape($customer->id)."', 'stripe', " . $status . ", " . $conf->entity . ", '".$this->db->idate(dol_now())."', ".$user->id.")"; $resql = $this->db->query($sql); if (! $resql) { @@ -178,14 +177,101 @@ class Stripe extends CommonObject } catch(Exception $e) { - //print $e->getMessage(); + $this->error = $e->getMessage(); } } } + else + { + dol_print_error($this->db); + } return $customer; } + /** + * Get the Stripe card of a company payment mode (with option to create it if not linked yet) + * + * @param \Stripe\StripeCustomer $cu Object stripe customer + * @param CompanyPaymentMode $object Object companypaymentmode to check, or create on stripe (create on stripe also update the societe_rib table for current entity) + * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect + * @param int $status Status (0=test, 1=live) + * @param int $createifnotlinkedtostripe 1=Create the stripe card and the link if the card is not yet linked to a stripe card + * @return \Stripe\StripeCard|null Stripe Card or null if not found + */ + public function cardStripe($cu, CompanyPaymentMode $object, $key='', $status=0, $createifnotlinkedtostripe=0) + { + global $conf, $user; + + $customer = null; + + $sql = "SELECT sa.stripe_card_ref as stripe_card_ref"; // key_account is cus_.... + $sql.= " FROM " . MAIN_DB_PREFIX . "societe_rib as sa"; + $sql.= " WHERE sa.rowid = " . $object->id; + //$sql.= " AND sa.entity IN (".getEntity('societe').")"; + $sql.= " AND sa.type = 'card'"; + + dol_syslog(get_class($this) . "::fetch search stripe card id for paymentmode id=".$object->id, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + if ($num) + { + $obj = $this->db->fetch_object($resql); + $cardref = $obj->stripe_card_ref; + if ($cardref) + { + try { + if (empty($key)) { // If the Stripe connect account not set, we use common API usage + $card = \Stripe\Card::retrieve("$cardref"); + } else { + $card = \Stripe\Card::retrieve("$cardref", array("stripe_account" => $key)); + } + } + catch(Exception $e) + { + + } + } + elseif ($createifnotlinkedtostripe) + { + $dataforcard = array( + "source" => 'eee', + "metadata" => array('dol_id'=>$object->id, 'dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity) + ); + + //$a = \Stripe\Stripe::getApiKey(); + //var_dump($a);var_dump($key);exit; + try { + if (empty($key)) { // If the Stripe connect account not set, we use common API usage + $card = $cu->sources->create($dataforcard); + } else { + $card = $cu->sources->create($dataforcard, array("stripe_account" => $key)); + } + + $sql = "UPDATE INTO " . MAIN_DB_PREFIX . "societe_rib (fk_soc, login, key_account, site, status, entity, date_creation, fk_user_creat)"; + $sql .= " VALUES (".$object->id.", '', '".$this->db->escape($card->id)."', 'stripe', " . $status . ", " . $conf->entity . ", '".$this->db->idate(dol_now())."', ".$user->id.")"; + $resql = $this->db->query($sql); + if (! $resql) + { + $this->error = $this->db->lasterror(); + } + } + catch(Exception $e) + { + $this->error = $e->getMessage(); + } + } + } + } + else + { + dol_print_error($this->db); + } + + return $card; + } + /** * Create charge with public/payment/newpayment.php, stripe/card.php, cronjobs or REST API * From 3c8c5102c34da6cdb46c99ddda8dcbc42892e676 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 14 Mar 2018 23:34:05 +0100 Subject: [PATCH 312/413] Rename var to avoid conflicts --- htdocs/public/payment/newpayment.php | 4 ++-- htdocs/public/stripe/newpayment.php | 10 ++++------ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/htdocs/public/payment/newpayment.php b/htdocs/public/payment/newpayment.php index 3ad3f2d33fd..7230170e1aa 100644 --- a/htdocs/public/payment/newpayment.php +++ b/htdocs/public/payment/newpayment.php @@ -1384,7 +1384,7 @@ if (preg_match('/^dopayment/',$action)) /* print ''; } + print '
    '; print ''."\n"; + print ''; print ''; print ''; @@ -273,6 +275,7 @@ class FormMargin print ''; } print '
    '.$langs->trans('Margins').'
    '; + print '
    '; } } From fd275a636cc4703f1114f6855cdb706e8224e57c Mon Sep 17 00:00:00 2001 From: All3kcis Date: Fri, 16 Mar 2018 11:45:46 +0100 Subject: [PATCH 374/413] Add batch status Add batch status, for correct display with getNomUrl --- htdocs/product/list.php | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/product/list.php b/htdocs/product/list.php index 662c15507f0..e31a88e6f5c 100644 --- a/htdocs/product/list.php +++ b/htdocs/product/list.php @@ -698,6 +698,7 @@ else $product_static->type = $obj->fk_product_type; $product_static->status_buy = $obj->tobuy; $product_static->status = $obj->tosell; + $product_static->status_batch = $obj->tobatch; $product_static->entity = $obj->entity; $product_static->pmp = $obj->pmp; From ff765a2efeac84cac39dbd1c3bd9cce084f1dc69 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 16 Mar 2018 10:14:14 +0100 Subject: [PATCH 375/413] FIX Look and feel v7 --- htdocs/fourn/commande/contact.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/commande/contact.php b/htdocs/fourn/commande/contact.php index ff17df2bd9d..262d73a6082 100644 --- a/htdocs/fourn/commande/contact.php +++ b/htdocs/fourn/commande/contact.php @@ -140,7 +140,7 @@ if ($id > 0 || ! empty($ref)) $object->fetch_thirdparty(); $head = ordersupplier_prepare_head($object); - dol_fiche_head($head, 'contact', $langs->trans("SupplierOrder"), 0, 'order'); + dol_fiche_head($head, 'contact', $langs->trans("SupplierOrder"), -1, 'order'); // Supplier order card From 46e8692620e8e245820ef274065ba3e91b4842de Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 16 Mar 2018 09:52:45 +0100 Subject: [PATCH 376/413] Escape db --- htdocs/core/lib/admin.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/admin.lib.php b/htdocs/core/lib/admin.lib.php index 65cc2965bea..051cda10e7a 100644 --- a/htdocs/core/lib/admin.lib.php +++ b/htdocs/core/lib/admin.lib.php @@ -513,7 +513,7 @@ function dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $not $sql.= " VALUES ("; $sql.= $db->encrypt($name,1); $sql.= ", ".$db->encrypt($value,1); - $sql.= ",'".$type."',".$visible.",'".$db->escape($note)."',".$entity.")"; + $sql.= ",'".$db->escape($type)."',".$visible.",'".$db->escape($note)."',".$entity.")"; //print "sql".$value."-".pg_escape_string($value)."-".$sql;exit; //print "xx".$db->escape($value); From 07fb29f0c44592f038e266b4fa698ba438485dc4 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 16 Mar 2018 01:05:49 +0100 Subject: [PATCH 377/413] Fix var not initialized --- htdocs/compta/facture/class/api_invoices.class.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index c1f8774095a..a114829d43c 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -937,8 +937,6 @@ class Invoices extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $request_data = (object) $payment_data; - if (! empty($conf->banque->enabled)) { if(empty($accountid)) { throw new RestException(400, 'Account ID is mandatory'); @@ -962,6 +960,10 @@ class Invoices extends DolibarrApi $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); $this->db->begin(); + + $amounts = array(); + $multicurrency_amounts = array(); + // Clean parameters amount if payment is for a credit note if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { $resteapayer = price2num($resteapayer,'MT'); From bbb095bcb20ec253520d4098c024977fbf38157c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 15 Mar 2018 10:43:04 +0100 Subject: [PATCH 378/413] FIX css --- htdocs/compta/localtax/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/compta/localtax/card.php b/htdocs/compta/localtax/card.php index 317d3ae813d..f3dfbf05a05 100644 --- a/htdocs/compta/localtax/card.php +++ b/htdocs/compta/localtax/card.php @@ -169,7 +169,7 @@ if ($action == 'create') print ''; print ""; - print ''; From 1c0fdcda7a1881109bed4e4e0d1b8f29b4a11412 Mon Sep 17 00:00:00 2001 From: All3kcis Date: Fri, 16 Mar 2018 13:57:02 +0100 Subject: [PATCH 379/413] Add status batch for getNomUrl --- htdocs/product/index.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/htdocs/product/index.php b/htdocs/product/index.php index 6eebc4d85e2..fd29143613a 100644 --- a/htdocs/product/index.php +++ b/htdocs/product/index.php @@ -272,7 +272,7 @@ print '
    '; * Last modified products */ $max=15; -$sql = "SELECT p.rowid, p.label, p.price, p.ref, p.fk_product_type, p.tosell, p.tobuy, p.fk_price_expression,"; +$sql = "SELECT p.rowid, p.label, p.price, p.ref, p.fk_product_type, p.tosell, p.tobuy, p.tobatch, p.fk_price_expression,"; $sql.= " p.entity,"; $sql.= " p.tms as datem"; $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; @@ -336,7 +336,8 @@ if ($result) $product_static->ref=$objp->ref; $product_static->label = $objp->label; $product_static->type=$objp->fk_product_type; - $product_static->entity = $objp->entity; + $product_static->entity = $objp->entity; + $product_static->status_batch = $objp->tobatch; print $product_static->getNomUrl(1,'',16); print "\n"; print '
    '; From c574a74a2e4664468ed7bb7050d4ce705d484736 Mon Sep 17 00:00:00 2001 From: All3kcis Date: Fri, 16 Mar 2018 13:59:04 +0100 Subject: [PATCH 380/413] Add status batch for getNomUrl --- htdocs/product/stock/mouvement.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/product/stock/mouvement.php b/htdocs/product/stock/mouvement.php index b41a990fbc1..41c8f9ae1f0 100644 --- a/htdocs/product/stock/mouvement.php +++ b/htdocs/product/stock/mouvement.php @@ -415,7 +415,7 @@ $formother=new FormOther($db); $formproduct=new FormProduct($db); if (!empty($conf->projet->enabled)) $formproject=new FormProjets($db); -$sql = "SELECT p.rowid, p.ref as product_ref, p.label as produit, p.fk_product_type as type, p.entity,"; +$sql = "SELECT p.rowid, p.ref as product_ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.entity,"; $sql.= " e.ref as stock, e.rowid as entrepot_id, e.lieu,"; $sql.= " m.rowid as mid, m.value as qty, m.datem, m.fk_user_author, m.label, m.inventorycode, m.fk_origin, m.origintype,"; $sql.= " m.batch, m.price,"; @@ -891,6 +891,7 @@ if ($resql) $productstatic->label=$objp->produit; $productstatic->type=$objp->type; $productstatic->entity=$objp->entity; + $productstatic->status_batch=$objp->tobatch; $productlot->id = $objp->lotid; $productlot->batch= $objp->batch; From a7e33150ce5ce93fe7043c2b5bd0814bd4852c01 Mon Sep 17 00:00:00 2001 From: All3kcis Date: Fri, 16 Mar 2018 14:09:38 +0100 Subject: [PATCH 381/413] add status batch for getNomUrl --- htdocs/product/stock/card.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/htdocs/product/stock/card.php b/htdocs/product/stock/card.php index f732c44fc31..1566e5d36c0 100644 --- a/htdocs/product/stock/card.php +++ b/htdocs/product/stock/card.php @@ -446,7 +446,7 @@ else $totalunit=0; $totalvalue=$totalvaluesell=0; - $sql = "SELECT p.rowid as rowid, p.ref, p.label as produit, p.fk_product_type as type, p.pmp as ppmp, p.price, p.price_ttc, p.entity,"; + $sql = "SELECT p.rowid as rowid, p.ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.pmp as ppmp, p.price, p.price_ttc, p.entity,"; $sql.= " ps.reel as value"; $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps, ".MAIN_DB_PREFIX."product as p"; $sql.= " WHERE ps.fk_product = p.rowid"; @@ -487,10 +487,11 @@ else print ''; print "'; From 3ccdb4d829fb13915d8f0514395fd97afabc1641 Mon Sep 17 00:00:00 2001 From: Maxime Kohlhaas Date: Fri, 16 Mar 2018 14:22:46 +0100 Subject: [PATCH 382/413] New filter on product supplier price import update --- htdocs/core/modules/modProduct.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/modules/modProduct.class.php b/htdocs/core/modules/modProduct.class.php index b2a0a6faf4f..f90323cda0e 100644 --- a/htdocs/core/modules/modProduct.class.php +++ b/htdocs/core/modules/modProduct.class.php @@ -320,7 +320,7 @@ class modProduct extends DolibarrModules 'sp.unitprice'=>'50', 'sp.remise_percent'=>'0' ); - $this->import_updatekeys_array[$r]=array('sp.fk_product'=>'ProductOrService','sp.ref_fourn'=>'SupplierRef'); + $this->import_updatekeys_array[$r]=array('sp.fk_product'=>'ProductOrService','sp.ref_fourn'=>'SupplierRef','sp.fk_soc'=>'Supplier'); } if (! empty($conf->global->PRODUIT_MULTIPRICES)) From 452c9e22bb4a443a8387a22b37a79cdbceb9b406 Mon Sep 17 00:00:00 2001 From: philippe-opendsi Date: Fri, 16 Mar 2018 15:24:49 +0100 Subject: [PATCH 383/413] Add mass action on project's list to close projects --- htdocs/langs/en_US/projects.lang | 4 ++- htdocs/projet/list.php | 48 ++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/htdocs/langs/en_US/projects.lang b/htdocs/langs/en_US/projects.lang index a064d032083..8d62a4190ca 100644 --- a/htdocs/langs/en_US/projects.lang +++ b/htdocs/langs/en_US/projects.lang @@ -222,4 +222,6 @@ NoAssignedTasks=No assigned tasks (assign project/tasks the current user from th # Comments trans AllowCommentOnTask=Allow user comments on tasks AllowCommentOnProject=Allow user comments on projects - +DontHavePermissionForCloseProject=You do not have permissions to close the project %s +DontHaveTheValidateStatus=The project %s must be open to be closed +RecordsClosed=%s project(s) closed diff --git a/htdocs/projet/list.php b/htdocs/projet/list.php index e148caeb328..90f0fc56755 100644 --- a/htdocs/projet/list.php +++ b/htdocs/projet/list.php @@ -195,6 +195,52 @@ if (empty($reshook)) $permtodelete = $user->rights->projet->supprimer; $uploaddir = $conf->projet->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + + // Close records + if (! $error && $massaction == 'close' && $user->rights->projet->creer) + { + $db->begin(); + + $objecttmp=new $objectclass($db); + $nbok = 0; + foreach($toselect as $toselectid) + { + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + $userWrite = $object->restrictedProjectArea($user,'write'); + if ($userWrite > 0 && $objecttmp->statut == 1) { + $result = $objecttmp->setClose($user); + if ($result <= 0) { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } else $nbok++; + } elseif($userWrite <= 0) { + setEventMessages($langs->trans("DontHavePermissionForCloseProject", $objecttmp->ref), null, 'warnings'); + } else { + setEventMessages($langs->trans("DontHaveTheValidateStatus", $objecttmp->ref), null, 'warnings'); + } + } + else + { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + } + + if (! $error) + { + if ($nbok > 1) setEventMessages($langs->trans("RecordsClosed", $nbok), null, 'mesgs'); + else setEventMessages($langs->trans("RecordsClosed", $nbok), null, 'mesgs'); + $db->commit(); + } + else + { + $db->rollback(); + } + } } @@ -390,7 +436,9 @@ $arrayofmassactions = array( ); //if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if ($user->rights->societe->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete"); +if ($user->rights->projet->creer) $arrayofmassactions['close']=$langs->trans("Close"); if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); print '
    '; From f258d31a98c93d2b036607032f99eee9c591f9ce Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 16 Mar 2018 16:10:04 +0100 Subject: [PATCH 384/413] Triggers for Strips payment modes --- htdocs/core/class/html.formother.class.php | 13 +-- .../interface_80_modStripe_Stripe.class.php | 98 +++++++++++++------ htdocs/societe/paymentmodes.php | 7 +- htdocs/societe/societecontact.php | 3 + htdocs/stripe/class/stripe.class.php | 2 +- 5 files changed, 83 insertions(+), 40 deletions(-) diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index d2d138b8478..3f07066bf2e 100644 --- a/htdocs/core/class/html.formother.class.php +++ b/htdocs/core/class/html.formother.class.php @@ -815,13 +815,14 @@ class FormOther /** * Return HTML combo list of month * - * @param string $selected Preselected value - * @param string $htmlname Name of HTML select object - * @param int $useempty Show empty in list - * @param int $longlabel Show long label + * @param string $selected Preselected value + * @param string $htmlname Name of HTML select object + * @param int $useempty Show empty in list + * @param int $longlabel Show long label + * @param string $morecss More Css * @return string */ - function select_month($selected='',$htmlname='monthid',$useempty=0,$longlabel=0) + function select_month($selected='', $htmlname='monthid', $useempty=0, $longlabel=0, $morecss='') { global $langs; @@ -830,7 +831,7 @@ class FormOther if ($longlabel) $montharray = monthArray($langs, 0); // Get array else $montharray = monthArray($langs, 1); - $select_month = ''; if ($useempty) { $select_month .= ''; diff --git a/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php b/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php index 495f439eb09..13c5b7ece00 100644 --- a/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php +++ b/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php @@ -123,49 +123,91 @@ class InterfaceStripe $stripe = new Stripe($db); if (empty($conf->stripe->enabled)) return 0; - if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha')) - { - $service = 'StripeTest'; - } - else + $service = 'StripeTest'; + $servicestatus = 0; + if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox', 'alpha')) { $service = 'StripeLive'; + $servicestatus = 1; } + // If customer is linked to Strip, we update/delete Stripe too if ($action == 'COMPANY_MODIFY') { dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); - if ($stripe->getStripeAccount($service) && $object->client != 0) { - $cu = $stripe->customerStripe($object, $stripe->getStripeAccount($service)); - if ($cu) { - if ($conf->entity == '1') { - $customer = \Stripe\Customer::retrieve("$cu->id"); - } else { - $customer = \Stripe\Customer::retrieve("$cu->id", array( - "stripe_account" => $stripe->getStripeAccount($service) - )); + + $stripeacc = $stripe->getStripeAccount($service); // No need of network access for this + + if ($object->client != 0) { + $customer = $stripe->customerStripe($object, $stripeacc, $servicestatus); + if ($customer) { + if (! empty($object->email)) + { + $customer->email = $object->email; } - if (! empty($object->email)) { - $customer->email = "$object->email"; - } - $customer->description = "$object->name"; + $customer->description = $object->name; + // TODO More data + //$customer->vat = $object->tva_intra + $customer->save(); } } - } elseif ($action == 'COMPANY_DELETE') { + } + if ($action == 'COMPANY_DELETE') { dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); - $cu = $stripe->customerStripe($object, $stripe->getStripeAccount($service)); - if ($cu) { - if ($conf->entity == 1) { - $customer = \Stripe\Customer::retrieve("$cu->id"); - } else { - $customer = \Stripe\Customer::retrieve("$cu->id", array( - "stripe_account" => $stripe->getStripeAccount($service) - )); - } + + $stripeacc = $stripe->getStripeAccount($service); // No need of network access for this + + $customer = $stripe->customerStripe($object, $stripeacc, $servicestatus); + if ($customer) { $customer->delete(); } } + // If payment mode is linked to Strip, we update/delete Stripe too + if ($action == 'COMPANYPAYMENTMODE_MODIFY' && $object->type == 'card') { + + // For creation of credit card, we do not create in Stripe automatically + + } + if ($action == 'COMPANYPAYMENTMODE_MODIFY' && $object->type == 'card') { + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + + $stripeacc = $stripe->getStripeAccount($service); // No need of network access for this + + $thirdparty=new Societe($this->db); + $thirdparty->fetch($object->fk_soc); + + if ($object->client != 0) { + $card = $stripe->cardStripe($thirdparty, $object, $stripeacc, $servicestatus); + if (card) { + /*if (! empty($object->email)) + { + $customer->email = $object->email; + } + $customer->description = $object->name; + // TODO More data + //$customer->vat = $object->tva_intra + + card->save(); + */ + } + } + } + if ($action == 'COMPANYPAYMENTMODE_DELETE' && $object->type == 'card') { + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + + $stripeacc = $stripe->getStripeAccount($service); // No need of network access for this + + $thirdparty=new Societe($this->db); + $thirdparty->fetch($object->fk_soc); + + $card = $stripe->cardStripe($thirdparty, $object, $stripeacc, $servicestatus); + if ($card) { + if (method_exists($card, 'detach')) $card->detach(); + else $card->delete(); + } + } + return $ok; } } diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 83ba4c7a899..7f373c8de4e 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -69,9 +69,6 @@ $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); $hookmanager->initHooks(array('thirdpartybancard','globalcard')); -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('thirdpartybancard')); - if (! empty($conf->stripe->enabled)) { $service = 'StripeTest'; @@ -368,8 +365,8 @@ if (empty($reshook)) $companypaymentmode->datec = dol_now(); $companypaymentmode->default_rib = 0; $companypaymentmode->type = 'card'; - $companypaymentmode->country_code = $mysoc->country_code; - $companypaymentmode->status = 1; + $companypaymentmode->country_code = $object->country_code; + $companypaymentmode->status = $servicestatus; $companypaymentmode->stripe_card_ref = GETPOST('stripe_card_ref','alpha'); diff --git a/htdocs/societe/societecontact.php b/htdocs/societe/societecontact.php index 67a44d87ccf..6b3e833abb0 100644 --- a/htdocs/societe/societecontact.php +++ b/htdocs/societe/societecontact.php @@ -45,6 +45,9 @@ $result = restrictedArea($user, 'societe', $id,''); $object = new Societe($db); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('contactthirdparty','globalcard')); + /* * Actions diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index fe973e3b603..329f26ca40e 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -55,7 +55,7 @@ class Stripe extends CommonObject * Return main company OAuth Connect stripe account * * @param string $mode 'StripeTest' or 'StripeLive' - * @return string Stripe account 'acc_....' + * @return string Stripe account 'acc_....' or '' if no OAuth token found */ public function getStripeAccount($mode='StripeTest') { From 1a70e7a7c455c3f67bacc8f92d6f53c6a289690a Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 16 Mar 2018 16:42:26 +0100 Subject: [PATCH 385/413] Triggers for Strips payment modes --- .../interface_80_modStripe_Stripe.class.php | 61 ++++++++++++------- htdocs/societe/paymentmodes.php | 2 +- htdocs/stripe/class/stripe.class.php | 7 ++- 3 files changed, 45 insertions(+), 25 deletions(-) diff --git a/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php b/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php index 13c5b7ece00..b6428c51b28 100644 --- a/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php +++ b/htdocs/core/triggers/interface_80_modStripe_Stripe.class.php @@ -172,39 +172,56 @@ class InterfaceStripe if ($action == 'COMPANYPAYMENTMODE_MODIFY' && $object->type == 'card') { dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); - $stripeacc = $stripe->getStripeAccount($service); // No need of network access for this + $stripeacc = $stripe->getStripeAccount($service); // No need of network access for this + $stripecu = $stripe->getStripeCustomerAccount($object->fk_soc); // No need of network access for this - $thirdparty=new Societe($this->db); - $thirdparty->fetch($object->fk_soc); + if ($stripecu) { + // Get customer (required to get a card) + if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage + $customer = \Stripe\Customer::retrieve($stripecu); + } else { + $customer = \Stripe\Customer::retrieve($stripecu, array("stripe_account" => $stripeacc)); + } - if ($object->client != 0) { - $card = $stripe->cardStripe($thirdparty, $object, $stripeacc, $servicestatus); - if (card) { - /*if (! empty($object->email)) - { - $customer->email = $object->email; + if ($customer) + { + $card = $stripe->cardStripe($customer, $object, $stripeacc, $servicestatus); + if ($card) { + $card->metadata=array('dol_id'=>$object->id, 'dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR'])); + try { + $card->save($dataforcard); + } + catch(Exception $e) + { + $this->error = $e->getMessages(); + } } - $customer->description = $object->name; - // TODO More data - //$customer->vat = $object->tva_intra - - card->save(); - */ } } } if ($action == 'COMPANYPAYMENTMODE_DELETE' && $object->type == 'card') { dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); - $stripeacc = $stripe->getStripeAccount($service); // No need of network access for this + $stripeacc = $stripe->getStripeAccount($service); // No need of network access for this + $stripecu = $stripe->getStripeCustomerAccount($object->fk_soc); // No need of network access for this - $thirdparty=new Societe($this->db); - $thirdparty->fetch($object->fk_soc); + if ($stripecu) + { + // Get customer (required to get a card) + if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage + $customer = \Stripe\Customer::retrieve($stripecu); + } else { + $customer = \Stripe\Customer::retrieve($stripecu, array("stripe_account" => $stripeacc)); + } - $card = $stripe->cardStripe($thirdparty, $object, $stripeacc, $servicestatus); - if ($card) { - if (method_exists($card, 'detach')) $card->detach(); - else $card->delete(); + if ($customer) + { + $card = $stripe->cardStripe($customer, $object, $stripeacc, $servicestatus); + if ($card) { + if (method_exists($card, 'detach')) $card->detach(); + else $card->delete(); + } + } } } diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 7f373c8de4e..8d0d1891b84 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -210,7 +210,7 @@ if (empty($reshook)) $companypaymentmode->exp_date_month = GETPOST('exp_date_month','int'); $companypaymentmode->exp_date_year = GETPOST('exp_date_year','int'); $companypaymentmode->cvn = GETPOST('cvn','alpha'); - $companypaymentmode->country_code = $mysoc->country_code; + $companypaymentmode->country_code = $object->country_code; $companypaymentmode->stripe_card_ref = GETPOST('stripe_card_ref','alpha'); diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 329f26ca40e..e093e93521a 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -223,15 +223,17 @@ class Stripe extends CommonObject { try { if (empty($key)) { // If the Stripe connect account not set, we use common API usage - $card = \Stripe\Card::retrieve("$cardref"); + $card = $cu->sources->retrieve($cardref); } else { - $card = \Stripe\Card::retrieve("$cardref", array("stripe_account" => $key)); + $card = $cu->sources->retrieve($cardref, array("stripe_account" => $key)); } } catch(Exception $e) { $this->error = $e->getMessage(); + dol_syslog($this->error, LOG_WARNING); } + } elseif ($createifnotlinkedtostripe) { @@ -277,6 +279,7 @@ class Stripe extends CommonObject catch(Exception $e) { $this->error = $e->getMessage(); + dol_syslog($this->error, LOG_WARNING); } } } From 9cd5fabba8a59c33b4be0d738ee446192a6f6669 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 16 Mar 2018 16:51:24 +0100 Subject: [PATCH 386/413] fix scrutinizer --- htdocs/adherents/class/adherent.class.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 913853f430f..d9bca123000 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -1509,7 +1509,7 @@ class Adherent extends CommonObject $vattouse=get_default_tva($mysoc, $mysoc, $idprodsubscription); } //print xx".$vattouse." - ".$mysoc." - ".$customer;exit; - $result=$invoice->addline($label,0,1,$vattouse,0,0,$idprodsubscription,0,$datesubscription,$datesubend,0,0,'','TTC',$amount,1); + $result=$invoice->addline($label,0,1,$vattouse,0,0,$idprodsubscription,0,$datesubscription,'',0,0,'','TTC',$amount,1); if ($result <= 0) { $this->error=$invoice->error; @@ -1577,7 +1577,7 @@ class Adherent extends CommonObject } } - if (! $error) + if (! $error && !empty($bank_line_id)) { // Update fk_bank into subscription table $sql = 'UPDATE '.MAIN_DB_PREFIX.'subscription SET fk_bank='.$bank_line_id; @@ -1614,7 +1614,7 @@ class Adherent extends CommonObject // Generate PDF (whatever is option MAIN_DISABLE_PDF_AUTOUPDATE) so we can include it into email //if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - $invoice->generateDocument($invoice->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $invoice->generateDocument($invoice->modelpdf, $outputlangs, 0, 0, 0); } } From 68b1e5f8fd96f39866fe08deb3c5da2072a4cf87 Mon Sep 17 00:00:00 2001 From: Philippe GRAND Date: Fri, 16 Mar 2018 17:40:19 +0100 Subject: [PATCH 387/413] New [*use loadLangs for translation files*] --- .../bank/doc/pdf_sepamandate.modules.php | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/htdocs/core/modules/bank/doc/pdf_sepamandate.modules.php b/htdocs/core/modules/bank/doc/pdf_sepamandate.modules.php index e44ab8cafd8..2061b03d2ae 100644 --- a/htdocs/core/modules/bank/doc/pdf_sepamandate.modules.php +++ b/htdocs/core/modules/bank/doc/pdf_sepamandate.modules.php @@ -46,11 +46,9 @@ class pdf_sepamandate extends ModeleBankAccountDoc function __construct($db) { global $conf,$langs,$mysoc; - - $langs->load("main"); - $langs->load("bank"); - $langs->load("withdrawals"); - $langs->load("companies"); + + // Translations + $langs->loadLangs(array("main", "bank", "withdrawals", "companies")); $this->db = $db; $this->name = "sepamandate"; @@ -104,13 +102,9 @@ class pdf_sepamandate extends ModeleBankAccountDoc if (! is_object($outputlangs)) $outputlangs=$langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; - - $outputlangs->load("main"); - $outputlangs->load("dict"); - $outputlangs->load("companies"); - $outputlangs->load("projects"); - $outputlangs->load("withdrawals"); - $outputlangs->load("bills"); + + // Translations + $outputlangs->loadLangs(array("main", "dict", "withdrawals", "companies", "projects", "bills")); if (! empty($conf->bank->dir_output)) { From 2bbf738cb8214186a8a7f10829939bac7f4b3a8a Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 16 Mar 2018 18:20:28 +0100 Subject: [PATCH 388/413] FIX Sql escape --- htdocs/core/class/html.formmail.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index 55345d68cc7..f562d36e2a1 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -1011,8 +1011,8 @@ class FormMail extends Form $sql.= " AND entity IN (".getEntity('c_email_templates').")"; $sql.= " AND (private = 0 OR fk_user = ".$user->id.")"; // Get all public or private owned if ($active >= 0) $sql.=" AND active = ".$active; - if ($label) $sql.=" AND label ='".$this->db->escape($label)."'"; - if (is_object($outputlangs)) $sql.= " AND (lang = '".$outputlangs->defaultlang."' OR lang IS NULL OR lang = '')"; + if ($label) $sql.=" AND label ='".$db->escape($label)."'"; + if (is_object($outputlangs)) $sql.= " AND (lang = '".$db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')"; if ($id > 0) $sql.= " AND rowid=".$id; if ($id == -1) $sql.= " AND position=0"; if (is_object($outputlangs)) $sql.= $db->order("position,lang,label","ASC,DESC,ASC"); // We want line with lang set first, then with lang null or '' From e323084cf82fe613815a4c1f98a82e0c99e1efb7 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 16 Mar 2018 19:03:16 +0100 Subject: [PATCH 389/413] Better template --- htdocs/core/class/html.formmail.class.php | 15 ++++++++++++--- .../template/class/myobject.class.php | 3 ++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index f562d36e2a1..5ff93994e73 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -996,7 +996,7 @@ class FormMail extends Form * @param string $type_template Get message for type=$type_template, type='all' also included. * @param string $user Use template public or limited to this user * @param Translate $outputlangs Output lang object - * @param int $id Id of template to find, or -1 for first found with lower position, or 0 for first found whatever is position + * @param int $id Id of template to find, or -1 for first found with position 0, or 0 for first found whatever is position or -2 for exact match with label (no aswer if not found) * @param int $active 1=Only active template, 0=Only disabled, -1=All * @param string $label Label of template * @return ModelMail @@ -1005,6 +1005,12 @@ class FormMail extends Form { $ret = new ModelMail(); + if ($id == -2 && empty($label)) + { + $this->error = 'LabelIsMandatoryWhenIdIs-2'; + return -1; + } + $sql = "SELECT label, topic, joinfiles, content, content_lines, lang"; $sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates'; $sql.= " WHERE (type_template='".$db->escape($type_template)."' OR type_template='all')"; @@ -1034,8 +1040,11 @@ class FormMail extends Form $ret->content_lines = $obj->content_lines; $ret->joinfiles = $obj->joinfiles; } - else // If there is no template at all - { + elseif($id == -2) { + // Not found with the provided label + return -1; + } + else { // If there is no template at all $defaultmessage=''; if ($type_template=='facture_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoice"); } elseif ($type_template=='facture_relance') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder"); } diff --git a/htdocs/modulebuilder/template/class/myobject.class.php b/htdocs/modulebuilder/template/class/myobject.class.php index 267a869fb46..d0259c2f9cb 100644 --- a/htdocs/modulebuilder/template/class/myobject.class.php +++ b/htdocs/modulebuilder/template/class/myobject.class.php @@ -461,10 +461,11 @@ class MyObject extends CommonObject /** * Action executed by scheduler - * CAN BE A CRON TASK + * CAN BE A CRON TASK. In such a case, paramerts come from the schedule job setup field 'Parameters' * * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) */ + //public function doScheduledJob($param1, $param2, ...) public function doScheduledJob() { global $conf, $langs; From cfeb0dccfebca0a9b02185594ff5363e4f4ac71d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 16 Mar 2018 19:29:22 +0100 Subject: [PATCH 390/413] Better support for MAIN_AUTHENTICATION_POST_METHOD --- htdocs/main.inc.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index c9c6c2d4cde..115155e629a 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -502,7 +502,7 @@ if (! defined('NOLOGIN')) $allowedmethodtopostusername = 2; if (defined('MAIN_AUTHENTICATION_POST_METHOD')) $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD'); $usertotest = (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username","alpha",$allowedmethodtopostusername)); - $passwordtotest = GETPOST('password','none',2); + $passwordtotest = GETPOST('password','none',$allowedmethodtopostusername); $entitytotest = (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1)); // Define if we received data to test the login. From 57e2240354730f767b45d51e5b62483ce900732e Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 17 Mar 2018 11:21:50 +0100 Subject: [PATCH 391/413] NEW Edit of extrafields position page on the edit form --- htdocs/core/tpl/admin_extrafields_edit.tpl.php | 4 ++-- htdocs/core/tpl/admin_extrafields_view.tpl.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/core/tpl/admin_extrafields_edit.tpl.php b/htdocs/core/tpl/admin_extrafields_edit.tpl.php index 9fb5eb27a64..e08983f9e10 100644 --- a/htdocs/core/tpl/admin_extrafields_edit.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_edit.tpl.php @@ -131,8 +131,8 @@ $langs->load("modulebuilder"); }); - -?attrname=" method="post"> + +?attrname=" id="formeditextrafield" method="post"> diff --git a/htdocs/core/tpl/admin_extrafields_view.tpl.php b/htdocs/core/tpl/admin_extrafields_view.tpl.php index 23e5aff0cae..ecdda360309 100644 --- a/htdocs/core/tpl/admin_extrafields_view.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_view.tpl.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2010-2018 Laurent Destailleur * Copyright (C) 2012-2017 Regis Houssin * * This program is free software; you can redistribute it and/or modify @@ -91,7 +91,7 @@ if (is_array($extrafields->attributes[$elementtype]['type']) && count($extrafiel if (! empty($conf->multicompany->enabled)) { print '
    '; } - print '\n"; print ""; } From dc0fc739311887a2b9277ca9af7faff8099fcc6d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 17 Mar 2018 12:15:32 +0100 Subject: [PATCH 392/413] Code comment --- htdocs/core/class/extrafields.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 861848e6924..2d5ba165365 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -134,7 +134,7 @@ class ExtraFields * * @param string $attrname Code of attribute * @param string $label label of attribute - * @param int $type Type of attribute ('boolean', 'int', 'varchar', 'text', 'html', 'date', 'datehour','price','phone','mail','password','url','select','checkbox', ...) + * @param int $type Type of attribute ('boolean','int','varchar','text','html','date','datehour','price','phone','mail','password','url','select','checkbox','separate',...) * @param int $pos Position of attribute * @param string $size Size/length of attribute * @param string $elementtype Element type ('member', 'product', 'thirdparty', ...) From cb1069cf0b991244b81b11b25f744a3107892f39 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 17 Mar 2018 13:21:27 +0100 Subject: [PATCH 393/413] Use font-awesome for the picto to move/transfer a line --- htdocs/contrat/card.php | 5 +++-- htdocs/core/lib/functions.lib.php | 3 ++- htdocs/theme/eldy/style.css.php | 3 ++- htdocs/theme/md/style.css.php | 3 ++- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index de69513e62a..fe0cbb9e27b 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -1640,13 +1640,14 @@ else print ' - + $objectlink) echo price($objectlink->total_ht); } ?> - + $objectlink) // For now, shipments must stay linked to order, so link is not deletable if($object->element != 'shipping') { ?> - ">transnoentitiesnoconv("RemoveLink")); ?> + ">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?> diff --git a/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php b/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php index ca3ec7c89c0..d2dd999350d 100644 --- a/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php +++ b/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php @@ -67,7 +67,7 @@ foreach($linkedObjectBlock as $key => $objectlink) } } ?> - + $objectlink) print $objectlink->getLibStatut(3); ?> - + $objectlink) - + diff --git a/htdocs/core/class/html.formticketsup.class.php b/htdocs/core/class/html.formticketsup.class.php index bbbed8c2bef..1570cb34883 100644 --- a/htdocs/core/class/html.formticketsup.class.php +++ b/htdocs/core/class/html.formticketsup.class.php @@ -173,12 +173,12 @@ class FormTicketsup print "\n"; } - // Customer + // Customer or supplier if ($this->withcompany) { // altairis: force company and contact id for external user if (empty($user->socid)) { // Company - print ''; } else { print ''; @@ -296,9 +296,9 @@ class FormTicketsup print $this->selectSeveritiesTickets((GETPOST('severity_code') ? GETPOST('severity_code') : $this->severity_code), 'severity_code', '', '2'); print ''; - // Not notify tiers at create - print ''; // TITLE diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 457f1ad1ed5..f4759240cd5 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -3063,7 +3063,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ $pictowithoutext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto); //if (in_array($picto, array('switch_off', 'switch_on', 'off', 'on'))) - if (in_array($pictowithoutext, array('delete', 'edit', 'off', 'on', 'resize', 'switch_off', 'switch_on', 'uparrow'))) + if (in_array($pictowithoutext, array('delete', 'edit', 'off', 'on', 'resize', 'switch_off', 'switch_on', 'unlink', 'uparrow'))) { $fakey = $pictowithoutext; $facolor=''; $fasize=''; if ($pictowithoutext == 'switch_off') { $fakey = 'fa-toggle-off'; $facolor='#999'; $fasize='2em'; } @@ -3074,6 +3074,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ elseif ($pictowithoutext == 'edit') { $fakey = 'fa-pencil'; $facolor='#444'; } elseif ($pictowithoutext == 'resize') { $fakey = 'fa-crop'; $facolor='#444'; } elseif ($pictowithoutext == 'uparrow') { $fakey = 'fa-mail-forward'; $facolor='#555'; } + elseif ($pictowithoutext == 'unlink') { $fakey = 'fa-chain-broken'; $facolor='#555'; } else { $fakey = 'fa-'.$pictowithoutext; $facolor='#999'; } if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) { $morecss.=($morecss?' ':'').$reg[1]; } diff --git a/htdocs/expedition/tpl/linkedobjectblock.tpl.php b/htdocs/expedition/tpl/linkedobjectblock.tpl.php index 88811da2eab..e62356066e5 100644 --- a/htdocs/expedition/tpl/linkedobjectblock.tpl.php +++ b/htdocs/expedition/tpl/linkedobjectblock.tpl.php @@ -61,7 +61,7 @@ foreach($linkedObjectBlock as $key => $objectlink) // For now, shipments must stay linked to order, so link is not deletable if($object->element != 'commande') { ?> - ">transnoentitiesnoconv("RemoveLink")); ?> + ">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?> diff --git a/htdocs/expensereport/tpl/linkedobjectblock.tpl.php b/htdocs/expensereport/tpl/linkedobjectblock.tpl.php index 95894a8987e..2d040834a12 100644 --- a/htdocs/expensereport/tpl/linkedobjectblock.tpl.php +++ b/htdocs/expensereport/tpl/linkedobjectblock.tpl.php @@ -52,7 +52,7 @@ foreach($linkedObjectBlock as $key => $objectlink) echo price($objectlink->total_ht); } ?> - + $objectlink) - + $objectlink) echo price($objectlink->total_ht); } ?> - + $objectlink) } } ?> - + array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1, 'css'=>'minwidth200', 'help'=>'Help text'), 'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>1, 'default'=>'null', 'position'=>40, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text'), - 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>1, 'help'=>'LinkToThirparty'), + 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>0, 'help'=>'LinkToThirparty'), 'description' =>array('type'=>'text', 'label'=>'Descrption', 'enabled'=>1, 'visible'=>0, 'position'=>60), 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61), 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62), diff --git a/htdocs/supplier_proposal/tpl/linkedobjectblock.tpl.php b/htdocs/supplier_proposal/tpl/linkedobjectblock.tpl.php index 8c49e42f557..ca604e61fcc 100644 --- a/htdocs/supplier_proposal/tpl/linkedobjectblock.tpl.php +++ b/htdocs/supplier_proposal/tpl/linkedobjectblock.tpl.php @@ -55,7 +55,7 @@ foreach($linkedObjectBlock as $key => $objectlink) echo price($objectlink->total_ht); } ?> - + projet->enabled)) { - include DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; include_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; include_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php'; } @@ -41,30 +41,23 @@ if (!empty($conf->contrat->enabled)) { include_once DOL_DOCUMENT_ROOT . '/core/class/html.formcontract.class.php'; } -if (!class_exists('Contact')) { - include DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; -} - // Load traductions files requiredby by page -$langs->load("companies"); -$langs->load("other"); -$langs->load("ticketsup"); +$langs->loadLangs(array("companies","other","ticketsup")); // Get parameters $id = GETPOST('id', 'int'); $track_id = GETPOST('track_id', 'alpha', 3); -$action = GETPOST('action', 'alpha', 3); $ref = GETPOST('ref', 'alpha'); $projectid = GETPOST('projectid', 'int'); +$action = GETPOST('action', 'alpha', 3); // Initialize technical object to manage hooks of ticketsup. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('ticketsupcard','globalcard')); -$object = new ActionsTicketsup($db); -$object->doActions($action); - $extrafields = new ExtraFields($db); -$extralabels = $extrafields->fetch_name_optionals_label($object->dao->table_element); +$extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + +$object = new Ticketsup($db); if (!$action) { $action = 'view'; @@ -75,14 +68,14 @@ if (GETPOST('modelselected')) { } // Store current page url -$url_page_current = dol_buildpath('/ticketsup/card.php', 1); +$url_page_current = DOL_URL_ROOT.'/ticketsup/card.php'; -if ($action == 'view' || $action == 'add_message' || $action == 'close' || $action == 'delete' || $action == 'editcustomer' || $action == 'progression' || $action == 'reopen' || $action == 'editsubject' || $action == 'edit_extrafields' || $action == 'set_extrafields' || $action == 'classify' || $action == 'sel_contract' || $action == 'edit_message_init' || $action == 'set_status' || $action == 'dellink') { +if ($id || $track_id || $ref) { $res = $object->fetch($id, $track_id, $ref); } // Security check -$result = restrictedArea($user, 'ticketsup', $object->dao->id); +$result = restrictedArea($user, 'ticketsup', $object->id); @@ -90,6 +83,9 @@ $result = restrictedArea($user, 'ticketsup', $object->dao->id); * Actions */ +$actionobject = new ActionsTicketsup($db); +$actionobject->doActions($action, $object); + $permissiondellink = $user->rights->ticketsup->write; include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once @@ -105,38 +101,38 @@ $form = new Form($db); $formticket = new FormTicketsup($db); if ($action == 'view' || $action == 'add_message' || $action == 'close' || $action == 'delete' || $action == 'editcustomer' || $action == 'progression' || $action == 'reopen' || $action == 'editsubject' || $action == 'edit_extrafields' || $action == 'set_extrafields' || $action == 'classify' || $action == 'sel_contract' || $action == 'edit_message_init' || $action == 'set_status' || $action == 'dellink') { - $res = $object->fetch($id, $track_id, $ref); if ($res > 0) { // or for unauthorized internals users - if (!$user->societe_id && ($conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY && $object->dao->fk_user_assign != $user->id) && !$user->rights->ticketsup->manage) { + if (!$user->societe_id && ($conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY && $object->fk_user_assign != $user->id) && !$user->rights->ticketsup->manage) { accessforbidden('', 0); } $help_url = 'FR:DocumentationModuleTicket'; - $page_title = $object->getTitle($action); + $page_title = $actionobject->getTitle($action); llxHeader('', $page_title, $help_url); // Confirmation close if ($action == 'close') { - print $form->formconfirm($url_page_current . "?track_id=" . $track_id, $langs->trans("CloseATicket"), $langs->trans("ConfirmCloseAticket"), "confirm_close", '', '', 1); + print $form->formconfirm($url_page_current . "?track_id=" . $object->track_id, $langs->trans("CloseATicket"), $langs->trans("ConfirmCloseAticket"), "confirm_close", '', '', 1); if ($ret == 'html') { print '
    '; } } // Confirmation delete if ($action == 'delete') { - print $form->formconfirm($url_page_current . "?track_id=" . $track_id, $langs->trans("Delete"), $langs->trans("ConfirmDeleteTicket"), "confirm_delete_ticket", '', '', 1); + print $form->formconfirm($url_page_current . "?track_id=" . $object->track_id, $langs->trans("Delete"), $langs->trans("ConfirmDeleteTicket"), "confirm_delete_ticket", '', '', 1); } // Confirm reopen if ($action == 'reopen') { - print $form->formconfirm($url_page_current . '?track_id=' . $track_id, $langs->trans('ReOpen'), $langs->trans('ConfirmReOpenTicket'), 'confirm_reopen', '', '', 1); + print $form->formconfirm($url_page_current . '?track_id=' . $object->track_id, $langs->trans('ReOpen'), $langs->trans('ConfirmReOpenTicket'), 'confirm_reopen', '', '', 1); } // Confirmation status change if ($action == 'set_status') { $new_status = GETPOST('new_status'); - print $form->formconfirm($url_page_current . "?track_id=" . $track_id . "&new_status=" . GETPOST('new_status'), $langs->trans("TicketChangeStatus"), $langs->trans("TicketConfirmChangeStatus", $langs->transnoentities($object->dao->statuts_short[$new_status])), "confirm_set_status", '', '', 1); + //var_dump($url_page_current . "?track_id=" . $object->track_id); + print $form->formconfirm($url_page_current . "?track_id=" . $object->track_id . "&new_status=" . GETPOST('new_status'), $langs->trans("TicketChangeStatus"), $langs->trans("TicketConfirmChangeStatus", $langs->transnoentities($object->statuts_short[$new_status])), "confirm_set_status", '', '', 1); } // project info @@ -205,39 +201,39 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print "ErrorRecordNotFound"; } } elseif ($socid > 0) { - $object->dao->fetch_thirdparty(); - $head = societe_prepare_head($object->dao->thirdparty); + $object->fetch_thirdparty(); + $head = societe_prepare_head($object->thirdparty); dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); - dol_banner_tab($object->dao->thirdparty, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); + dol_banner_tab($object->thirdparty, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); dol_fiche_end(); } if (!$user->societe_id && $conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY) { - $object->dao->next_prev_filter = "te.fk_user_assign = '" . $user->id . "'"; + $object->next_prev_filter = "te.fk_user_assign = '" . $user->id . "'"; } elseif ($user->societe_id > 0) { - $object->dao->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; + $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } - $head = ticketsup_prepare_head($object->dao); + $head = ticketsup_prepare_head($object); dol_fiche_head($head, 'tabTicketsup', $langs->trans("Ticket"), -1, 'ticketsup'); - $object->dao->label = $object->dao->ref; + $object->label = $object->ref; // Author - if ($object->dao->fk_user_create > 0) { - $object->dao->label .= ' - ' . $langs->trans("CreatedBy") . ' '; + if ($object->fk_user_create > 0) { + $object->label .= ' - ' . $langs->trans("CreatedBy") . ' '; $langs->load("users"); $fuser = new User($db); - $fuser->fetch($object->dao->fk_user_create); - $object->dao->label .= $fuser->getNomUrl(0); + $fuser->fetch($object->fk_user_create); + $object->label .= $fuser->getNomUrl(0); } - if (!empty($object->dao->origin_email)) { - $object->dao->label .= ' - ' . $langs->trans("CreatedBy") . ' '; - $object->dao->label .= $object->dao->origin_email . ' (' . $langs->trans("TicketEmailOriginIssuer") . ')'; + if (!empty($object->origin_email)) { + $object->label .= ' - ' . $langs->trans("CreatedBy") . ' '; + $object->label .= $object->origin_email . ' (' . $langs->trans("TicketEmailOriginIssuer") . ')'; } $linkback = '' . $langs->trans("BackToList") . ' '; - $object->dao->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + $object->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); print '
    '; print '
    '; @@ -245,12 +241,12 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti // Track ID print '
    '; // Creation date print ''; // Read date - if (!empty($object->dao->date_read)) { + if (!empty($object->date_read)) { print ''; print ''; } // Close date - if (!empty($object->dao->date_close)) { + if (!empty($object->date_close)) { print ''; } print ''; - // Customer + // Thirdparty print ''; @@ -315,41 +311,41 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print $langs->trans('Project'); print ''; if ($action != 'classify' && $user->rights->ticketsup->write) { - print ''; + print ''; } print '
    '.$langs->trans("DatePayment").''; + print ''.$langs->trans("DatePayment").''; print $form->select_date($datep,"datep",'','','','add',1,1); print '
    '.dol_trunc($objp->label,32).'
    "; $productstatic->id=$objp->rowid; - $productstatic->ref = $objp->ref; - $productstatic->label = $objp->produit; + $productstatic->ref = $objp->ref; + $productstatic->label = $objp->produit; $productstatic->type=$objp->type; $productstatic->entity=$objp->entity; + $productstatic->status_batch=$objp->tobatch; print $productstatic->getNomUrl(1,'stock',16); print ''.($extrafields->attributes[$elementtype]['entityid'][$key]==0?$langs->trans("All"):$extrafields->attributes[$elementtype]['entitylabel'][$key]).''.img_edit().''; + print ''.img_edit().''; print "  ".img_delete()."
    '; if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) { - print ''; + print ''; + print ''; print img_picto($langs->trans("MoveToAnotherContract"),'uparrow'); print ''; } if ($user->rights->contrat->creer && ($object->statut >= 0)) { - print ''; + print ''; print img_edit(); print ''; } diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index b5794758d23..457f1ad1ed5 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -3063,7 +3063,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ $pictowithoutext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto); //if (in_array($picto, array('switch_off', 'switch_on', 'off', 'on'))) - if (in_array($pictowithoutext, array('delete', 'edit', 'off', 'on', 'resize', 'switch_off', 'switch_on'))) + if (in_array($pictowithoutext, array('delete', 'edit', 'off', 'on', 'resize', 'switch_off', 'switch_on', 'uparrow'))) { $fakey = $pictowithoutext; $facolor=''; $fasize=''; if ($pictowithoutext == 'switch_off') { $fakey = 'fa-toggle-off'; $facolor='#999'; $fasize='2em'; } @@ -3073,6 +3073,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ elseif ($pictowithoutext == 'delete') { $fakey = 'fa-trash'; $facolor='#444'; } elseif ($pictowithoutext == 'edit') { $fakey = 'fa-pencil'; $facolor='#444'; } elseif ($pictowithoutext == 'resize') { $fakey = 'fa-crop'; $facolor='#444'; } + elseif ($pictowithoutext == 'uparrow') { $fakey = 'fa-mail-forward'; $facolor='#555'; } else { $fakey = 'fa-'.$pictowithoutext; $facolor='#999'; } if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) { $morecss.=($morecss?' ':'').$reg[1]; } diff --git a/htdocs/theme/eldy/style.css.php b/htdocs/theme/eldy/style.css.php index 6293802540e..c3ed6e76ab5 100644 --- a/htdocs/theme/eldy/style.css.php +++ b/htdocs/theme/eldy/style.css.php @@ -1331,7 +1331,8 @@ div.nopadding { .pictowarning { vertical-align: text-bottom; } -.fiche img.pictoedit, .fiche span.pictoedit { +.fiche .arearef img.pictoedit, .fiche .arearef span.pictoedit, +.fiche .fichecenter img.pictoedit, .fiche .fichecenter span.pictoedit { opacity: 0.4; } .colorthumb { diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php index c088e0d4acd..5b8d82aaa53 100644 --- a/htdocs/theme/md/style.css.php +++ b/htdocs/theme/md/style.css.php @@ -1339,7 +1339,8 @@ table.noborder tr.liste_titre td { .pictowarning { vertical-align: text-bottom; } -.fiche img.pictoedit, .fiche span.pictoedit { +.fiche .arearef img.pictoedit, .fiche .arearef span.pictoedit, +.fiche .fichecenter img.pictoedit, .fiche .fichecenter span.pictoedit { opacity: 0.9; } img.hideonsmartphone.pictoactionview { From 7b71e29fa0f1014abaaa67727c6b3075b66e7a36 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 17 Mar 2018 15:17:35 +0100 Subject: [PATCH 394/413] Duplicate translation --- htdocs/compta/prelevement/ligne.php | 5 ++--- htdocs/langs/en_US/withdrawals.lang | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/htdocs/compta/prelevement/ligne.php b/htdocs/compta/prelevement/ligne.php index 20ac3d18082..bb5598cf81f 100644 --- a/htdocs/compta/prelevement/ligne.php +++ b/htdocs/compta/prelevement/ligne.php @@ -33,13 +33,12 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $langs->load("banks"); $langs->load("categories"); +$langs->load("bills"); +$langs->load("withdrawals"); // Security check if ($user->societe_id > 0) accessforbidden(); -$langs->load("bills"); -$langs->load("withdrawals"); - // Get supervariables $action = GETPOST('action','alpha'); $id = GETPOST('id','int'); diff --git a/htdocs/langs/en_US/withdrawals.lang b/htdocs/langs/en_US/withdrawals.lang index 8c350b12d79..5a25a9e96e2 100644 --- a/htdocs/langs/en_US/withdrawals.lang +++ b/htdocs/langs/en_US/withdrawals.lang @@ -1,8 +1,8 @@ # Dolibarr language file - Source file is en_US - withdrawals CustomersStandingOrdersArea=Direct debit payment orders area SuppliersStandingOrdersArea=Direct credit payment orders area -StandingOrders=Direct debit payment orders -StandingOrder=Direct debit payment order +StandingOrdersPayment=Direct debit payment orders +StandingOrderPayment=Direct debit payment order NewStandingOrder=New direct debit order StandingOrderToProcess=To process WithdrawalsReceipts=Direct debit orders From bd81487f71b31221f42a16b354200ceafab8e501 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josep=20Llu=C3=ADs?= Date: Sat, 17 Mar 2018 19:35:34 +0100 Subject: [PATCH 395/413] FIX: add contact permission on contact box In contact box is only checked the "societe" permission. Contact permission should be checked too. --- htdocs/core/boxes/box_contacts.php | 140 ++++++++++++++--------------- 1 file changed, 70 insertions(+), 70 deletions(-) diff --git a/htdocs/core/boxes/box_contacts.php b/htdocs/core/boxes/box_contacts.php index a67d2c3ac02..813c32305f8 100644 --- a/htdocs/core/boxes/box_contacts.php +++ b/htdocs/core/boxes/box_contacts.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2015 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2015 Frederic France + * Copyright (C) 2018 Josep Lluís Amador * * 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 @@ -20,7 +21,7 @@ /** * \file htdocs/core/boxes/box_contacts.php - * \ingroup societes + * \ingroup contacts * \brief Module to show box of contacts */ @@ -36,7 +37,7 @@ class box_contacts extends ModeleBoxes var $boxcode="lastcontacts"; var $boximg="object_contact"; var $boxlabel="BoxLastContacts"; - var $depends = array("societe"); + var $depends = array("societe","contact"); var $db; var $param; @@ -57,7 +58,7 @@ class box_contacts extends ModeleBoxes $this->db=$db; - $this->hidden=! ($user->rights->societe->lire); + $this->hidden=! ($user->rights->societe->lire && $user->rights->contact->lire); } /** @@ -75,12 +76,12 @@ class box_contacts extends ModeleBoxes $this->info_box_head = array('text' => $langs->trans("BoxTitleLastModifiedContacts",$max)); - if ($user->rights->societe->lire) + if ($user->rights->societe->lire && $user->rights->contact->lire) { $sql = "SELECT sp.rowid as id, sp.lastname, sp.firstname, sp.civility as civility_id, sp.datec, sp.tms, sp.fk_soc, sp.statut as status"; $sql.= ", sp.address, sp.zip, sp.town, sp.phone, sp.phone_perso, sp.phone_mobile"; $sql.= ", s.nom as socname, s.name_alias"; - $sql.= ", s.client, s.fournisseur, s.code_client, s.code_fournisseur"; + $sql.= ", s.client, s.fournisseur, s.code_client, s.code_fournisseur"; $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON sp.fk_soc = s.rowid"; if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -91,98 +92,97 @@ class box_contacts extends ModeleBoxes $sql.= $db->plimit($max, 0); $result = $db->query($sql); - if ($result) { + if ($result) { $num = $db->num_rows($result); $contactstatic=new Contact($db); $societestatic=new Societe($db); $line = 0; - while ($line < $num) - { + while ($line < $num) + { $objp = $db->fetch_object($result); $datec=$db->jdate($objp->datec); $datem=$db->jdate($objp->tms); - $contactstatic->id=$objp->id; + $contactstatic->id=$objp->id; $contactstatic->lastname=$objp->lastname; - $contactstatic->firstname=$objp->firstname; - $contactstatic->civility_id=$objp->civility_id; + $contactstatic->firstname=$objp->firstname; + $contactstatic->civility_id=$objp->civility_id; $contactstatic->statut=$objp->status; - $contactstatic->phone_pro = $objp->phone; - $contactstatic->phone_perso = $objp->phone_perso; - $contactstatic->phone_mobile = $objp->phone_mobile; - $contactstatic->address = $objp->address; - $contactstatic->zip = $objp->zip; - $contactstatic->town = $objp->town; + $contactstatic->phone_pro = $objp->phone; + $contactstatic->phone_perso = $objp->phone_perso; + $contactstatic->phone_mobile = $objp->phone_mobile; + $contactstatic->address = $objp->address; + $contactstatic->zip = $objp->zip; + $contactstatic->town = $objp->town; $societestatic->id = $objp->fk_soc; - $societestatic->name = $objp->socname; - $societestatic->name_alias = $objp->name_alias; - $societestatic->code_client = $objp->code_client; - $societestatic->code_fournisseur = $objp->code_fournisseur; - $societestatic->client = $objp->client; - $societestatic->fournisseur = $objp->fournisseur; + $societestatic->name = $objp->socname; + $societestatic->name_alias = $objp->name_alias; + $societestatic->code_client = $objp->code_client; + $societestatic->code_fournisseur = $objp->code_fournisseur; + $societestatic->client = $objp->client; + $societestatic->fournisseur = $objp->fournisseur; - $this->info_box_contents[$line][] = array( - 'td' => '', - 'text' => $contactstatic->getNomUrl(1), - 'asis' => 1, - ); + $this->info_box_contents[$line][] = array( + 'td' => '', + 'text' => $contactstatic->getNomUrl(1), + 'asis' => 1, + ); - $this->info_box_contents[$line][] = array( - 'td' => '', - 'text' => ($objp->fk_soc > 0 ? $societestatic->getNomUrl(1) : ''), - 'asis' => 1, - ); + $this->info_box_contents[$line][] = array( + 'td' => '', + 'text' => ($objp->fk_soc > 0 ? $societestatic->getNomUrl(1) : ''), + 'asis' => 1, + ); - $this->info_box_contents[$line][] = array( - 'td' => 'class="right"', - 'text' => dol_print_date($datem, "day"), - ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => dol_print_date($datem, "day"), + ); - $this->info_box_contents[$line][] = array( - 'td' => 'align="right" class="nowrap" width="18"', - 'text' => $contactstatic->getLibStatut(3), - 'asis'=>1, - ); + $this->info_box_contents[$line][] = array( + 'td' => 'align="right" class="nowrap" width="18"', + 'text' => $contactstatic->getLibStatut(3), + 'asis'=>1, + ); - $line++; - } + $line++; + } - if ($num==0) - $this->info_box_contents[$line][0] = array( - 'td' => 'align="center"', - 'text'=>$langs->trans("NoRecordedContacts"), - ); + if ($num==0) + $this->info_box_contents[$line][0] = array( + 'td' => 'align="center"', + 'text'=>$langs->trans("NoRecordedContacts"), + ); - $db->free($result); - } else { - $this->info_box_contents[0][0] = array( - 'td' => '', - 'maxlength'=>500, - 'text' => ($db->error().' sql='.$sql), - ); - } - } else { - $this->info_box_contents[0][0] = array( - 'td' => 'align="left" class="nohover opacitymedium"', - 'text' => $langs->trans("ReadPermissionNotAllowed") - ); - } - - } + $db->free($result); + } else { + $this->info_box_contents[0][0] = array( + 'td' => '', + 'maxlength'=>500, + 'text' => ($db->error().' sql='.$sql), + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'align="left" class="nohover opacitymedium"', + 'text' => $langs->trans("ReadPermissionNotAllowed") + ); + } + } /** * Method to show box * - * @param array $head Array with properties of box title - * @param array $contents Array with properties of box lines - * @param int $nooutput No print, only return string + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string * @return string */ - function showBox($head = null, $contents = null, $nooutput=0) - { + function showBox($head = null, $contents = null, $nooutput=0) + { return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); } From b2a4e3d023116118fdf00c1ac7321343a613568d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josep=20Llu=C3=ADs?= Date: Sun, 18 Mar 2018 08:20:43 +0100 Subject: [PATCH 396/413] Error in fix --- htdocs/core/boxes/box_contacts.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/core/boxes/box_contacts.php b/htdocs/core/boxes/box_contacts.php index 813c32305f8..936d269f82a 100644 --- a/htdocs/core/boxes/box_contacts.php +++ b/htdocs/core/boxes/box_contacts.php @@ -37,7 +37,7 @@ class box_contacts extends ModeleBoxes var $boxcode="lastcontacts"; var $boximg="object_contact"; var $boxlabel="BoxLastContacts"; - var $depends = array("societe","contact"); + var $depends = array("societe"); var $db; var $param; @@ -58,7 +58,7 @@ class box_contacts extends ModeleBoxes $this->db=$db; - $this->hidden=! ($user->rights->societe->lire && $user->rights->contact->lire); + $this->hidden=! ($user->rights->societe->lire && $user->rights->societe->contact->lire); } /** @@ -76,7 +76,7 @@ class box_contacts extends ModeleBoxes $this->info_box_head = array('text' => $langs->trans("BoxTitleLastModifiedContacts",$max)); - if ($user->rights->societe->lire && $user->rights->contact->lire) + if ($user->rights->societe->lire && $user->rights->societe->contact->lire) { $sql = "SELECT sp.rowid as id, sp.lastname, sp.firstname, sp.civility as civility_id, sp.datec, sp.tms, sp.fk_soc, sp.statut as status"; $sql.= ", sp.address, sp.zip, sp.town, sp.phone, sp.phone_perso, sp.phone_mobile"; From d4ae0395edbf7649f578fc5438189fc3b25ee497 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 18 Mar 2018 19:13:42 +0100 Subject: [PATCH 397/413] NEW Look and feel v8: Use a different picto for delete and unlink --- .../adherents/tpl/linkedobjectblock.tpl.php | 2 +- .../comm/propal/tpl/linkedobjectblock.tpl.php | 2 +- htdocs/commande/tpl/linkedobjectblock.tpl.php | 2 +- .../facture/tpl/linkedobjectblock.tpl.php | 2 +- .../tpl/linkedobjectblockForRec.tpl.php | 2 +- htdocs/contrat/tpl/linkedobjectblock.tpl.php | 6 +- .../core/class/html.formticketsup.class.php | 12 +- htdocs/core/lib/functions.lib.php | 3 +- .../expedition/tpl/linkedobjectblock.tpl.php | 2 +- .../tpl/linkedobjectblock.tpl.php | 2 +- .../fichinter/tpl/linkedobjectblock.tpl.php | 2 +- .../commande/tpl/linkedobjectblock.tpl.php | 2 +- .../facture/tpl/linkedobjectblock.tpl.php | 2 +- htdocs/langs/en_US/ticketsup.lang | 12 +- .../template/class/myobject.class.php | 2 +- .../tpl/linkedobjectblock.tpl.php | 2 +- htdocs/ticketsup/card.php | 259 ++++++------ .../class/actions_ticketsup.class.php | 381 +++++++++--------- htdocs/ticketsup/class/ticketsup.class.php | 23 +- htdocs/ticketsup/history.php | 60 +-- htdocs/ticketsup/index.php | 4 +- htdocs/ticketsup/new.php | 13 +- 22 files changed, 406 insertions(+), 391 deletions(-) diff --git a/htdocs/adherents/tpl/linkedobjectblock.tpl.php b/htdocs/adherents/tpl/linkedobjectblock.tpl.php index 118f51a1a89..f89b8da20f6 100644 --- a/htdocs/adherents/tpl/linkedobjectblock.tpl.php +++ b/htdocs/adherents/tpl/linkedobjectblock.tpl.php @@ -53,7 +53,7 @@ foreach($linkedObjectBlock as $key => $objectlink) echo price($objectlink->amount); } ?> ">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    ">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    date_contrat,'day'); ?> rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE)) + if ($user->rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE)) { $totalcontrat = 0; foreach ($objectlink->lines as $linecontrat) { @@ -65,7 +65,7 @@ foreach($linkedObjectBlock as $key => $objectlink) echo price($totalcontrat); } ?> getLibStatut(7); ?>">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    ' . $langs->trans("Customer") . ''; + print '
    ' . $langs->trans("Thirdparty") . ''; $events = array(); $events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php', 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); print $form->select_company($this->withfromsocid, 'socid', '', 1, 1, '', $events); @@ -242,7 +242,7 @@ class FormTicketsup // If no socid, set to first one (id=1) to avoid full contacts list $selectedCompany = $this->withfromsocid > 0 ? $this->withfromsocid : 1; $nbofcontacts = $form->select_contacts($selectedCompany, $this->withfromcontactid, 'contactid', 0, '', '', 0, 'minwidth200'); - $formcompany->selectTypeContact($ticketstatic, '', 'type', 'external'); + $formcompany->selectTypeContact($ticketstatic, '', 'type', 'external', '', 0, 'maginleftonly'); print '
    '; - print 'withnotnotifytiersatcreate?' checked="checked"':'').'>'; + // Notify thirdparty at creation + print '
    '; + print 'withnotnotifytiersatcreate?'':' checked="checked"').'>'; print '
    getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    datev,'day'); ?> getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    ' . $langs->trans("TicketTrackId") . ''; - if (!empty($object->dao->track_id)) { - if (empty($object->dao->ref)) { - $object->ref = $object->dao->id; + if (!empty($object->track_id)) { + if (empty($object->ref)) { + $object->ref = $object->id; print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'track_id'); } else { - print $object->dao->track_id; + print $object->track_id; } } else { print $langs->trans('None'); @@ -259,51 +255,51 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti // Subject print '
    '; - print $form->editfieldkey("Subject", 'subject', $object->dao->subject, $object->dao, $user->rights->ticketsup->write && !$user->societe_id, 'string'); + print $form->editfieldkey("Subject", 'subject', $object->subject, $object, $user->rights->ticketsup->write && !$user->societe_id, 'string'); print ''; - print $form->editfieldval("Subject", 'subject', $object->dao->subject, $object->dao, $user->rights->ticketsup->write && !$user->societe_id, 'string'); + print $form->editfieldval("Subject", 'subject', $object->subject, $object, $user->rights->ticketsup->write && !$user->societe_id, 'string'); print '
    ' . $langs->trans("DateCreation") . ''; - print dol_print_date($object->dao->datec, 'dayhour'); + print dol_print_date($object->datec, 'dayhour'); print '
    ' . $langs->trans("TicketReadOn") . ''; - print dol_print_date($object->dao->date_read, 'dayhour'); + print dol_print_date($object->date_read, 'dayhour'); print '
    ' . $langs->trans("TicketTimeToRead") . ''; - print '' . convertSecondToTime($object->dao->date_read - $object->dao->datec) . ''; + print '' . convertSecondToTime($object->date_read - $object->datec) . ''; print '
    ' . $langs->trans("TicketCloseOn") . ''; - print dol_print_date($object->dao->date_close, 'dayhour'); + print dol_print_date($object->date_close, 'dayhour'); print '
    '; print ''; - if ($action != 'editcustomer' && $object->dao->fk_statut < 8 && !$user->societe_id && $user->rights->ticketsup->write) { - print ''; + if ($action != 'editcustomer' && $object->fk_statut < 8 && !$user->societe_id && $user->rights->ticketsup->write) { + print ''; } print '
    '; - print $langs->trans('Customer'); + print $langs->trans('ThirdParty'); print '' . img_edit($langs->transnoentitiesnoconv('Edit'), 1) . '' . img_edit($langs->transnoentitiesnoconv('Edit'), 1) . '
    '; print '
    '; if ($action == 'editcustomer') { - $form->form_thirdparty($url_page_current . '?track_id=' . $object->dao->track_id, $object->dao->fk_soc, 'editcustomer', ($object->dao->fk_soc ? 's.rowid <> ' . $object->dao->fk_soc : ''), 1); + $form->form_thirdparty($url_page_current . '?track_id=' . $object->track_id, $object->fk_soc, 'editcustomer', ($object->fk_soc ? 's.rowid <> ' . $object->fk_soc : ''), 1); } else { - $form->form_thirdparty($url_page_current . '?track_id=' . $object->dao->track_id, $object->dao->fk_soc, 'none', 's.rowid <> ' . $object->dao->fk_soc, 1); + $form->form_thirdparty($url_page_current . '?track_id=' . $object->track_id, $object->fk_soc, 'none', 's.rowid <> ' . $object->fk_soc, 1); } print '
    ' . img_edit($langs->trans('SetProject')) . '' . img_edit($langs->trans('SetProject')) . '
    '; print ''; if ($action == 'classify') { - $form->form_project($url_page_current . '?track_id=' . $object->dao->track_id, $object->dao->socid, $object->dao->fk_project, 'projectid'); + $form->form_project($url_page_current . '?track_id=' . $object->track_id, $object->socid, $object->fk_project, 'projectid'); } else { - $form->form_project($url_page_current . '?track_id=' . $object->dao->track_id, $object->dao->socid, $object->dao->fk_project, 'none'); + $form->form_project($url_page_current . '?track_id=' . $object->track_id, $object->socid, $object->fk_project, 'none'); } print ''; } // User assigned print '' . $langs->trans("UserAssignedTo") . ''; - if ($object->dao->fk_user_assign > 0) { - $userstat->fetch($object->dao->fk_user_assign); + if ($object->fk_user_assign > 0) { + $userstat->fetch($object->fk_user_assign); print $userstat->getNomUrl(1); } else { print $langs->trans('None'); } // Show user list to assignate one if status is "read" - if (GETPOST('set') == "assign_ticket" && $object->dao->fk_statut < 8 && !$user->societe_id && $user->rights->ticketsup->write) { + if (GETPOST('set') == "assign_ticket" && $object->fk_statut < 8 && !$user->societe_id && $user->rights->ticketsup->write) { print ''; print ''; print ''; - print ''; + print ''; print ' '; print $form->select_dolusers($user->id, 'fk_user_assign', 0); print ' '; print ''; } - if ($object->dao->fk_statut < 8 && GETPOST('set') != "assign_ticket" && $user->rights->ticketsup->manage) { - print '' . img_picto('', 'edit') . ' ' . $langs->trans('Modify') . ''; + if ($object->fk_statut < 8 && GETPOST('set') != "assign_ticket" && $user->rights->ticketsup->manage) { + print '' . img_picto('', 'edit') . ' ' . $langs->trans('Modify') . ''; } print ''; @@ -358,8 +354,8 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print ''; - if ($action != 'progression' && $object->dao->fk_statut < 8 && !$user->societe_id) { - print ''; + if ($action != 'progression' && $object->fk_statut < 8 && !$user->societe_id) { + print ''; } print '
    '; print $langs->trans('Progression') . ''; print '' . img_edit($langs->trans('Modify')) . '' . img_edit($langs->trans('Modify')) . '
    '; print ''; @@ -368,21 +364,21 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print ''; print ''; print ''; - print ''; + print ''; print ' '; print ''; } else { - print($object->dao->progress > 0 ? $object->dao->progress : '0') . '%'; + print($object->progress > 0 ? $object->progress : '0') . '%'; } print ''; print ''; // Timing (Duration sum of linked fichinter - $object->dao->fetchObjectLinked(); - $num = count($object->dao->linkedObjects); + $object->fetchObjectLinked(); + $num = count($object->linkedObjects); $timing = 0; if ($num) { - foreach ($object->dao->linkedObjects as $objecttype => $objects) { + foreach ($object->linkedObjects as $objecttype => $objects) { if ($objecttype = "fichinter") { foreach ($objects as $fichinter) { $timing += $fichinter->duration; @@ -404,28 +400,28 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print '
    '; print ''; print ''; - print ''; + print ''; - print $object->dao->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit'); print ''; print ' '; print ' '; print ''; print '
    '; } else { - print $object->dao->showOptionals($extrafields); + print $object->showOptionals($extrafields); if ($user->rights->ticketsup->write) { print ''; - print '' . img_picto('', 'edit') . ' ' . $langs->trans('Edit') . ''; + print '' . img_picto('', 'edit') . ' ' . $langs->trans('Edit') . ''; print ''; } } } print ''; - // View Original message - $object->viewTicketOriginalMessage($user, $action); + // View Original message + $actionobject->viewTicketOriginalMessage($user, $action); // Fin colonne gauche et début colonne droite @@ -481,7 +477,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print ''; print ' '; print ''; - print $formticket->{$property['list_function']}($object->dao->type_code, 'update_value', '', 0); + print $formticket->{$property['list_function']}($object->type_code, 'update_value', '', 0); print ''; print ' '; print ''; @@ -494,7 +490,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti } else { // Type print '' . $langs->trans("Type") . ''; - print $object->dao->type_label; + print $object->type_label; if ($user->admin && !$noadmininfo) { print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } @@ -503,7 +499,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti // Category print '' . $langs->trans("Category") . ''; - print $object->dao->category_label; + print $object->category_label; if ($user->admin && !$noadmininfo) { print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } @@ -512,7 +508,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti // Severity print '' . $langs->trans("TicketSeverity") . ''; - print $object->dao->severity_label; + print $object->severity_label; if ($user->admin && !$noadmininfo) { print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } @@ -522,14 +518,16 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print ''; // End table actions // Display navbar with links to change ticket status - if (!$user->societe_id && $user->rights->ticketsup->write && $object->dao->fk_status < 8 && GETPOST('set') !== 'properties') { - $object->viewStatusActions(); + print ''; + if (!$user->societe_id && $user->rights->ticketsup->write && $object->fk_status < 8 && GETPOST('set') !== 'properties') { + $actionobject->viewStatusActions($object); } + print load_fiche_titre($langs->trans('Contacts'), '', 'title_companies.png'); + print '
    '; print '
    '; - print '
    '; print '
    ' . $langs->trans("Source") . '
    @@ -545,7 +543,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti $contactstatic = new Contact($db); $userstatic = new User($db); foreach (array('internal', 'external') as $source) { - $tmpobject = $object->dao; + $tmpobject = $object; $tab = $tmpobject->listeContact(-1, $source); $num = count($tab); $i = 0; @@ -607,7 +605,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print ''; + print '
    '; // Contract if ($action == 'sel_contract') { @@ -644,8 +643,8 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti $form_contract = new FormContract($db); $form_contract->formSelectContract( - $url_page_current.'?track_id='.$object->dao->track_id, - $object->dao->fk_soc, + $url_page_current.'?track_id='.$object->track_id, + $object->fk_soc, GETPOST('contractid'), 'contractid' ); @@ -657,53 +656,47 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti print dol_fiche_end(); + /* ActionBar */ print '
    '; - // Show button to mark as read - if (($object->dao->fk_statut == '0' || empty($object->dao->date_read)) && !$user->societe_id) { - print '
    '; - print '' . img_picto('', 'mark-read@ticketsup', 'height="12px"') . ' ' . $langs->trans('MarkAsRead') . ''; - print 'dao->fk_statut < 8 && $action != "add_message") { - print ''; + if ($object->fk_statut < 8 && $action != "add_message") { + print ''; } // Link to create an intervention // socid is needed otherwise fichinter ask it and forgot origin after form submit :\ - if (!$object->dao->fk_soc && $user->rights->ficheinter->creer) { + if (!$object->fk_soc && $user->rights->ficheinter->creer) { print ''; } - if ($object->dao->fk_soc > 0 && $object->dao->fk_statut < 8 && $user->rights->ficheinter->creer) { - print ''; + if ($object->fk_soc > 0 && $object->fk_statut < 8 && $user->rights->ficheinter->creer) { + print ''; } // Button to edit Properties - if ($object->dao->fk_statut < 5 && $user->rights->ticketsup->write) { - print ''; + if ($object->fk_statut < 5 && $user->rights->ticketsup->write) { + print ''; } // Button to link to a contract - if ($user->rights->ticketsup->write && $object->dao->fk_statut < 5 && $user->rights->contrat->creer) { - print ''; + if ($user->rights->ticketsup->write && $object->fk_statut < 5 && $user->rights->contrat->creer) { + print ''; } // Close ticket if statut is read - if ($object->dao->fk_statut > 0 && $object->dao->fk_statut < 8 && $user->rights->ticketsup->write) { - print ''; + if ($object->fk_statut > 0 && $object->fk_statut < 8 && $user->rights->ticketsup->write) { + print ''; } // Re-open ticket - if (!$user->socid && $object->dao->fk_statut == 8 && !$user->societe_id) { - print ''; + if (!$user->socid && $object->fk_statut == 8 && !$user->societe_id) { + print ''; } // Delete ticket if ($user->rights->ticketsup->delete && !$user->societe_id) { - print ''; + print ''; } print '
    '; @@ -715,7 +708,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti // Message list print load_fiche_titre($langs->trans('TicketMessagesList'), '', 'messages@ticketsup'); $show_private_message = ($user->societe_id ? 0 : 1); - $object->viewTicketTimelineMessages($show_private_message); + $actionobject->viewTicketTimelineMessages($show_private_message, true, $object); print '
    '; @@ -741,8 +734,8 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti $formticket = new FormTicketsup($db); $formticket->action = $action; - $formticket->track_id = $object->dao->track_id; - $formticket->id = $object->dao->id; + $formticket->track_id = $object->track_id; + $formticket->id = $object->id; $formticket->withfile = 2; $formticket->param = array('fk_user_create' => $user->id); @@ -751,32 +744,32 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti // Tableau des parametres complementaires du post $formticket->param['models']=$modelmail; $formticket->param['models_id']=GETPOST('modelmailselected', 'int'); - //$formticket->param['socid']=$object->dao->fk_soc; - $formticket->param['returnurl']=$_SERVER["PHP_SELF"].'?track_id='.$object->dao->track_id; + //$formticket->param['socid']=$object->fk_soc; + $formticket->param['returnurl']=$_SERVER["PHP_SELF"].'?track_id='.$object->track_id; $formticket->withsubstit = 1; - if ($object->dao->fk_soc > 0) { - $object->dao->fetch_thirdparty(); - $formticket->substit['__THIRDPARTY_NAME__'] = $object->dao->thirdparty->name; + if ($object->fk_soc > 0) { + $object->fetch_thirdparty(); + $formticket->substit['__THIRDPARTY_NAME__'] = $object->thirdparty->name; } $formticket->substit['__SIGNATURE__'] = $user->signature; - $formticket->substit['__TICKETSUP_TRACKID__'] = $object->dao->track_id; - $formticket->substit['__TICKETSUP_REF__'] = $object->dao->ref; - $formticket->substit['__TICKETSUP_SUBJECT__'] = $object->dao->subject; - $formticket->substit['__TICKETSUP_TYPE__'] = $object->dao->type_code; - $formticket->substit['__TICKETSUP_CATEGORY__'] = $object->dao->category_code; - $formticket->substit['__TICKETSUP_SEVERITY__'] = $object->dao->severity_code; - $formticket->substit['__TICKETSUP_MESSAGE__'] = $object->dao->message; - $formticket->substit['__TICKETSUP_PROGRESSION__'] = $object->dao->progress; - if ($object->dao->fk_user_assign > 0) { - $userstat->fetch($object->dao->fk_user_assign); + $formticket->substit['__TICKETSUP_TRACKID__'] = $object->track_id; + $formticket->substit['__TICKETSUP_REF__'] = $object->ref; + $formticket->substit['__TICKETSUP_SUBJECT__'] = $object->subject; + $formticket->substit['__TICKETSUP_TYPE__'] = $object->type_code; + $formticket->substit['__TICKETSUP_CATEGORY__'] = $object->category_code; + $formticket->substit['__TICKETSUP_SEVERITY__'] = $object->severity_code; + $formticket->substit['__TICKETSUP_MESSAGE__'] = $object->message; + $formticket->substit['__TICKETSUP_PROGRESSION__'] = $object->progress; + if ($object->fk_user_assign > 0) { + $userstat->fetch($object->fk_user_assign); $formticket->substit['__TICKETSUP_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname); } - if ($object->dao->fk_user_create > 0) { - $userstat->fetch($object->dao->fk_user_create); + if ($object->fk_user_create > 0) { + $userstat->fetch($object->fk_user_create); $formticket->substit['__TICKETSUP_USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname); } @@ -792,7 +785,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti * * Put here code to view linked object ****************************************************/ -$somethingshown = $form->showLinkedObjectBlock($object->dao); +$somethingshown = $form->showLinkedObjectBlock($object); // End of page llxFooter(''); diff --git a/htdocs/ticketsup/class/actions_ticketsup.class.php b/htdocs/ticketsup/class/actions_ticketsup.class.php index 317f3f187ff..1186b7fbd1e 100644 --- a/htdocs/ticketsup/class/actions_ticketsup.class.php +++ b/htdocs/ticketsup/class/actions_ticketsup.class.php @@ -79,21 +79,20 @@ class ActionsTicketsup * doActions * * @param string $action Action type + * @param Ticketsup $object Object Ticketsup * @return int 0 */ - public function doActions(&$action = '') + public function doActions(&$action = '', Ticketsup $object=null) { global $conf, $user, $langs, $mysoc; - $this->getInstanceDao(); - /* * Add file in email form */ if (GETPOST('addfile')) { // altairis : allow files from public interface if (GETPOST('track_id')) { - $res = $this->dao->fetch('', GETPOST('track_id','alpha')); + $res = $object->fetch('', GETPOST('track_id','alpha')); } ////if($res > 0) @@ -101,13 +100,13 @@ class ActionsTicketsup include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; // Set tmp directory TODO Use a dedicated directory for temp mails files - $vardir = $conf->ticketsup->dir_output . (!empty($this->dao->track_id) ? '/' . dol_sanitizeFileName($this->dao->track_id) : ''); + $vardir = $conf->ticketsup->dir_output . (!empty($object->track_id) ? '/' . dol_sanitizeFileName($object->track_id) : ''); $upload_dir_tmp = $vardir . '/temp'; if (!dol_is_dir($upload_dir_tmp)) { dol_mkdir($upload_dir_tmp); } dol_add_file_process($upload_dir_tmp, 0, 0, 'addedfile', dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '-__file__'); - $action = !empty($this->dao->track_id) ? 'add_message' : 'create_ticket'; + $action = !empty($object->track_id) ? 'add_message' : 'create_ticket'; ////} } @@ -117,7 +116,7 @@ class ActionsTicketsup if (GETPOST('removedfile')) { // altairis : allow files from public interface if (GETPOST('track_id')) { - $res = $this->dao->fetch('', GETPOST('track_id')); + $res = $object->fetch('', GETPOST('track_id')); } ////if($res > 0) @@ -125,12 +124,12 @@ class ActionsTicketsup include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; // Set tmp directory - $vardir = $conf->ticketsup->dir_output . (!empty($this->dao->track_id) ? '/' . dol_sanitizeFileName($this->dao->track_id) : ''); + $vardir = $conf->ticketsup->dir_output . (!empty($object->track_id) ? '/' . dol_sanitizeFileName($object->track_id) : ''); $upload_dir_tmp = $vardir . '/temp'; // TODO Delete only files that was uploaded from email form dol_remove_file_process($_POST['removedfile'], 0); - $action = !empty($this->dao->track_id) ? 'add_message' : 'create_ticket'; + $action = !empty($object->track_id) ? 'add_message' : 'create_ticket'; ////} } @@ -150,28 +149,28 @@ class ActionsTicketsup if (!$error) { $this->db->begin(); - $this->dao->track_id = generate_random_id(16); + $object->track_id = generate_random_id(16); - $this->dao->ref = GETPOST("ref", 'alpha'); - $this->dao->fk_soc = GETPOST("socid", 'int'); - $this->dao->subject = GETPOST("subject", 'alpha'); - $this->dao->message = GETPOST("message"); + $object->ref = GETPOST("ref", 'alpha'); + $object->fk_soc = GETPOST("socid", 'int'); + $object->subject = GETPOST("subject", 'alpha'); + $object->message = GETPOST("message"); - $this->dao->type_code = GETPOST("type_code", 'alpha'); - $this->dao->category_code = GETPOST("category_code", 'alpha'); - $this->dao->severity_code = GETPOST("severity_code", 'alpha'); + $object->type_code = GETPOST("type_code", 'alpha'); + $object->category_code = GETPOST("category_code", 'alpha'); + $object->severity_code = GETPOST("severity_code", 'alpha'); $notNotifyTiers = GETPOST("not_notify_tiers_at_create", 'alpha'); - $this->dao->notify_tiers_at_create = empty($notNotifyTiers) ? 1 : 0; + $object->notify_tiers_at_create = empty($notNotifyTiers) ? 1 : 0; $extrafields = new ExtraFields($this->db); - $extralabels = $extrafields->fetch_name_optionals_label($this->dao->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $this->dao); + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); - $id = $this->dao->create($user); + $id = $object->create($user); if ($id <= 0) { $error++; - $this->error = $this->dao->error; - $this->errors = $this->dao->errors; + $this->error = $object->error; + $this->errors = $object->errors; $action = 'create_ticket'; } @@ -186,31 +185,31 @@ class ActionsTicketsup $type_contact = GETPOST("type", 'alpha'); if ($contactid > 0 && $type_contact) { - $result = $this->dao->add_contact($contactid, GETPOST("type"), 'external'); + $result = $object->add_contact($contactid, GETPOST("type"), 'external'); } // altairis: link ticket to project if (GETPOST('projectid')) { - $this->dao->setProject(GETPOST('projectid')); + $object->setProject(GETPOST('projectid')); } // Auto assign user if ($conf->global->TICKETS_AUTO_ASSIGN_USER_CREATE) { - $result = $this->dao->assignUser($user, $user->id, 1); - $this->dao->add_contact($user->id, "SUPPORTTEC", 'internal'); + $result = $object->assignUser($user, $user->id, 1); + $object->add_contact($user->id, "SUPPORTTEC", 'internal'); } // Auto assign contrat $contractid = 0; if ($conf->global->TICKETS_AUTO_ASSIGN_CONTRACT_CREATE) { $contrat = new Contrat($this->db); - $contrat->socid = $this->dao->fk_soc; + $contrat->socid = $object->fk_soc; $list = $contrat->getListOfContracts(); if (is_array($list) && !empty($list)) { if (count($list) == 1) { $contractid = $list[0]->id; - $this->dao->setContract($contractid); + $object->setContract($contractid); } else { } } @@ -219,13 +218,13 @@ class ActionsTicketsup // Auto create fiche intervention if ($conf->global->TICKETS_AUTO_CREATE_FICHINTER_CREATE) { $fichinter = new Fichinter($this->db); - $fichinter->socid = $this->dao->fk_soc; + $fichinter->socid = $object->fk_soc; $fichinter->fk_project = GETPOST('projectid', 'int'); $fichinter->fk_contrat = $contractid; $fichinter->author = $user->id; $fichinter->modelpdf = 'soleil'; - $fichinter->origin = $this->dao->element; - $fichinter->origin_id = $this->dao->id; + $fichinter->origin = $object->element; + $fichinter->origin_id = $object->id; // Extrafields $extrafields = new ExtraFields($this->db); @@ -242,7 +241,7 @@ class ActionsTicketsup if (!empty($backtopage)) { $url = $backtopage; } else { - $url = 'card.php?track_id=' . $this->dao->track_id; + $url = 'card.php?track_id=' . $object->track_id; } header("Location: " . $url); @@ -259,7 +258,7 @@ class ActionsTicketsup if ($action == 'edit' && $user->rights->ticketsup->write) { $error = 0; - if ($this->dao->fetch(GETPOST('id')) < 0) { + if ($object->fetch(GETPOST('id')) < 0) { $error++; array_push($this->errors, $langs->trans("ErrorTicketIsNotValid")); $_GET["action"] = $_POST["action"] = ''; @@ -269,7 +268,7 @@ class ActionsTicketsup if (GETPOST('update') && GETPOST('id') && $user->rights->ticketsup->write) { $error = 0; - $ret = $this->dao->fetch(GETPOST('id')); + $ret = $object->fetch(GETPOST('id')); if ($ret < 0) { $error++; array_push($this->errors, $langs->trans("ErrorTicketIsNotValid")); @@ -287,15 +286,15 @@ class ActionsTicketsup if (!$error) { $this->db->begin(); - $this->dao->label = GETPOST("label"); - $this->dao->description = GETPOST("description"); + $object->label = GETPOST("label"); + $object->description = GETPOST("description"); //... - $ret = $this->dao->update(GETPOST('id'), $user); + $ret = $object->update(GETPOST('id'), $user); if ($ret <= 0) { $error++; - $this->errors = $this->dao->error; - $this->errors = $this->dao->errors; + $this->errors = $object->error; + $this->errors = $object->errors; $action = 'edit'; } @@ -308,29 +307,29 @@ class ActionsTicketsup } if ($action == "mark_ticket_read" && $user->rights->ticketsup->write) { - $this->dao->fetch('', GETPOST("track_id")); + $object->fetch('', GETPOST("track_id")); - if ($this->dao->markAsRead($user) > 0) { + if ($object->markAsRead($user) > 0) { // Log action in ticket logs table $log_action = $langs->trans('TicketLogMesgReadBy', $user->getFullName($langs)); - $ret = $this->dao->createTicketLog($user, $log_action); + $ret = $object->createTicketLog($user, $log_action); if ($ret > 0) { setEventMessages($langs->trans('TicketMarkedAsRead'), null, 'mesgs'); } else { setEventMessages($langs->trans('TicketMarkedAsReadButLogActionNotSaved'), null, 'errors'); } - header("Location: card.php?track_id=" . $this->dao->track_id . "&action=view"); + header("Location: card.php?track_id=" . $object->track_id . "&action=view"); exit; } else { - array_push($this->errors, $this->dao->error); + array_push($this->errors, $object->error); } $action = 'view'; } if ($action == "assign_user" && GETPOST('btn_assign_user') && $user->rights->ticketsup->write) { - $this->dao->fetch('', GETPOST("track_id")); + $object->fetch('', GETPOST("track_id")); - $useroriginassign = $this->dao->fk_user_assign; + $useroriginassign = $object->fk_user_assign; $usertoassign = GETPOST('fk_user_assign'); if (!$usertoassign) { $error++; @@ -339,38 +338,38 @@ class ActionsTicketsup } if (!$error) { - $ret = $this->dao->assignUser($user, $usertoassign); + $ret = $object->assignUser($user, $usertoassign); if ($ret) { // Si déjà un user assigné on le supprime des contacts if ($useroriginassign > 0) { - $internal_contacts = $this->dao->listeContact(-1, 'internal'); + $internal_contacts = $object->listeContact(-1, 'internal'); foreach ($internal_contacts as $key => $contact) { if ($contact['code'] == "SUPPORTTEC" && $contact['id'] == $useroriginassign) { } { //print "user à effacer : ".$useroriginassign; - $this->dao->delete_contact($contact['rowid']); + $object->delete_contact($contact['rowid']); } } } - $this->dao->add_contact($usertoassign, "SUPPORTTEC", 'internal', $notrigger = 0); + $object->add_contact($usertoassign, "SUPPORTTEC", 'internal', $notrigger = 0); } // Log action in ticket logs table - $this->dao->fetch_user($usertoassign); - $log_action = $langs->trans('TicketLogAssignedTo', $this->dao->user->getFullName($langs)); - $ret = $this->dao->createTicketLog($user, $log_action); + $object->fetch_user($usertoassign); + $log_action = $langs->trans('TicketLogAssignedTo', $object->user->getFullName($langs)); + $ret = $object->createTicketLog($user, $log_action); if ($ret > 0) { setEventMessages($langs->trans('TicketAssigned'), null, 'mesgs'); } else { setEventMessages($langs->trans('TicketAssignedButLogActionNotSaved'), null, 'errors'); } - header("Location: card.php?track_id=" . $this->dao->track_id . "&action=view"); + header("Location: card.php?track_id=" . $object->track_id . "&action=view"); exit; } else { - array_push($this->errors, $this->dao->error); + array_push($this->errors, $object->error); } $action = 'view'; } @@ -381,18 +380,18 @@ class ActionsTicketsup $fieldtomodify = GETPOST('property') . '_code'; $fieldtomodify_label = GETPOST('property') . '_label'; - $oldvalue_code = $this->dao->$fieldtomodify; - $newvalue_code = $this->dao->getValueFrom('c_ticketsup_' . GETPOST('property'), GETPOST('update_value'), 'code'); + $oldvalue_code = $object->$fieldtomodify; + $newvalue_code = $object->getValueFrom('c_ticketsup_' . GETPOST('property'), GETPOST('update_value'), 'code'); - $oldvalue_label = $this->dao->$fieldtomodify_label; - $newvalue_label = $this->dao->getValueFrom('c_ticketsup_' . GETPOST('property'), GETPOST('update_value'), 'label'); + $oldvalue_label = $object->$fieldtomodify_label; + $newvalue_label = $object->getValueFrom('c_ticketsup_' . GETPOST('property'), GETPOST('update_value'), 'label'); - $this->dao->$fieldtomodify = $newvalue_code; + $object->$fieldtomodify = $newvalue_code; - $ret = $this->dao->update($user); + $ret = $object->update($user); if ($ret > 0) { $log_action = $langs->trans('TicketLogPropertyChanged', $oldvalue_label, $newvalue_label); - $ret = $this->dao->createTicketLog($user, $log_action); + $ret = $object->createTicketLog($user, $log_action); if ($ret > 0) { setEventMessages($langs->trans('TicketUpdated'), null, 'mesgs'); } @@ -406,13 +405,13 @@ class ActionsTicketsup if (!empty($backtopage)) { $url = $backtopage; } else { - $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + $url = 'card.php?action=view&track_id=' . $object->track_id; } header("Location: " . $url); exit; } else { - setEventMessages($this->dao->error, null, 'errors'); + setEventMessages($object->error, null, 'errors'); $action = 'add_message'; } } @@ -423,10 +422,10 @@ class ActionsTicketsup if ($action == "confirm_close" && GETPOST('confirm', 'alpha') == 'yes' && $user->rights->ticketsup->write) { $this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')); - if ($this->dao->close()) { + if ($object->close()) { // Log action in ticket logs table $log_action = $langs->trans('TicketLogClosedBy', $user->getFullName($langs)); - $ret = $this->dao->createTicketLog($user, $log_action); + $ret = $object->createTicketLog($user, $log_action); if ($ret > 0) { setEventMessages('
    ' . $langs->trans('TicketMarkedAsClosed') . '
    '); } else { @@ -442,10 +441,10 @@ class ActionsTicketsup if ($action == "confirm_public_close" && GETPOST('confirm', 'alpha') == 'yes') { $this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')); - if (($_SESSION['email_customer'] == $this->dao->origin_email || $_SESSION['email_customer'] == $this->dao->thirdparty->email) && $this->dao->close()) { + if (($_SESSION['email_customer'] == $object->origin_email || $_SESSION['email_customer'] == $object->thirdparty->email) && $object->close()) { // Log action in ticket logs table $log_action = $langs->trans('TicketLogClosedBy', $_SESSION['email_customer']); - $ret = $this->dao->createTicketLog($user, $log_action); + $ret = $object->createTicketLog($user, $log_action); if ($ret > 0) { setEventMessages('
    ' . $langs->trans('TicketMarkedAsClosed') . '
    ', null, 'mesgs'); } else { @@ -461,7 +460,7 @@ class ActionsTicketsup if ($action == 'confirm_delete_ticket' && GETPOST('confirm', 'alpha') == "yes" && $user->rights->ticketsup->delete) { if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { - if ($this->dao->delete($user) > 0) { + if ($object->delete($user) > 0) { setEventMessages('
    ' . $langs->trans('TicketDeletedSuccess') . '
    ', null, 'mesgs'); Header("Location: index.php"); exit; @@ -476,7 +475,7 @@ class ActionsTicketsup // Set parent company if ($action == 'set_thirdparty' && $user->rights->societe->creer) { if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { - $result = $this->dao->setCustomer(GETPOST('editcustomer', 'int')); + $result = $object->setCustomer(GETPOST('editcustomer', 'int')); $url = 'card.php?action=view&track_id=' . GETPOST('track_id', 'alpha'); header("Location: " . $url); exit(); @@ -485,11 +484,11 @@ class ActionsTicketsup if ($action == 'set_progression' && $user->rights->ticketsup->write) { if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { - $result = $this->dao->setProgression(GETPOST('progress')); + $result = $object->setProgression(GETPOST('progress')); // Log action in ticket logs table $log_action = $langs->trans('TicketLogProgressSetTo', GETPOST('progress')); - $ret = $this->dao->createTicketLog($user, $log_action); - $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + $ret = $object->createTicketLog($user, $log_action); + $url = 'card.php?action=view&track_id=' . $object->track_id; header("Location: " . $url); exit(); } @@ -498,19 +497,19 @@ class ActionsTicketsup if ($action == 'setsubject') { if ($this->fetch(GETPOST('id', 'int'))) { if ($action == 'setsubject') { - $this->dao->subject = trim(GETPOST('subject', 'alpha')); + $object->subject = trim(GETPOST('subject', 'alpha')); } - if ($action == 'setsubject' && empty($this->dao->subject)) { + if ($action == 'setsubject' && empty($object->subject)) { $mesg .= ($mesg ? '
    ' : '') . $langs->trans("ErrorFieldRequired", $langs->transnoentities("Subject")); } if (!$mesg) { - if ($this->dao->update($user) >= 0) { - header("Location: " . $_SERVER['PHP_SELF'] . "?track_id=" . $this->dao->track_id); + if ($object->update($user) >= 0) { + header("Location: " . $_SERVER['PHP_SELF'] . "?track_id=" . $object->track_id); exit; } - $mesg = $this->dao->error; + $mesg = $object->error; } } } @@ -519,13 +518,13 @@ class ActionsTicketsup $res = $this->fetch('', GETPOST('track_id')); $extrafields = new ExtraFields($this->db); - $extralabels = $extrafields->fetch_name_optionals_label($this->dao->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $this->dao); + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); - $ret = $this->dao->update($user); + $ret = $object->update($user); if ($ret > 0) { setEventMessages($langs->trans('TicketUpdated'), null, 'mesgs'); - $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + $url = 'card.php?action=view&track_id=' . $object->track_id; header("Location: " . $url); exit(); } @@ -535,13 +534,13 @@ class ActionsTicketsup elseif ($action == 'confirm_reopen' && $user->rights->ticketsup->manage && !GETPOST('cancel')) { if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { // prevent browser refresh from reopening ticket several times - if ($this->dao->fk_statut == 8) { - $res = $this->dao->setStatut(4); + if ($object->fk_statut == 8) { + $res = $object->setStatut(4); if ($res) { // Log action in ticket logs table $log_action = $langs->trans('TicketLogReopen'); - $ret = $this->dao->createTicketLog($user, $log_action); - $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + $ret = $object->createTicketLog($user, $log_action); + $url = 'card.php?action=view&track_id=' . $object->track_id; header("Location: " . $url); exit(); } @@ -550,16 +549,16 @@ class ActionsTicketsup } // Categorisation dans projet elseif ($action == 'classin' && $user->rights->ticketsup->write) { if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { - $this->dao->setProject(GETPOST('projectid')); - $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + $object->setProject(GETPOST('projectid')); + $url = 'card.php?action=view&track_id=' . $object->track_id; header("Location: " . $url); exit(); } } // Categorisation dans contrat elseif ($action == 'setcontract' && $user->rights->ticketsup->write) { if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { - $this->dao->setContract(GETPOST('contractid')); - $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + $object->setContract(GETPOST('contractid')); + $url = 'card.php?action=view&track_id=' . $object->track_id; header("Location: " . $url); exit(); } @@ -567,19 +566,19 @@ class ActionsTicketsup // altairis: manage cancel button if (!GETPOST('cancel')) { $this->fetch('', GETPOST('track_id')); - $oldvalue_message = $this->dao->message; + $oldvalue_message = $object->message; $fieldtomodify = GETPOST('message_initial'); - $this->dao->message = $fieldtomodify; - $ret = $this->dao->update($user); + $object->message = $fieldtomodify; + $ret = $object->update($user); if ($ret > 0) { $log_action = $langs->trans('TicketInitialMessageModified') . " \n"; // include the Diff class dol_include_once('/ticketsup/class/utils_diff.class.php'); // output the result of comparing two files as plain text - $log_action .= Diff::toString(Diff::compare(strip_tags($oldvalue_message), strip_tags($this->dao->message))); + $log_action .= Diff::toString(Diff::compare(strip_tags($oldvalue_message), strip_tags($object->message))); - $ret = $this->dao->createTicketLog($user, $log_action); + $ret = $object->createTicketLog($user, $log_action); if ($ret > 0) { setEventMessages($langs->trans('TicketMessageSuccesfullyUpdated'), null, 'mesgs'); } @@ -591,13 +590,13 @@ class ActionsTicketsup elseif ($action == 'confirm_set_status' && $user->rights->ticketsup->write && !GETPOST('cancel')) { if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { $new_status = GETPOST('new_status', 'int'); - $old_status = $this->dao->fk_statut; - $res = $this->dao->setStatut($new_status); + $old_status = $object->fk_statut; + $res = $object->setStatut($new_status); if ($res) { // Log action in ticket logs table - $log_action = $langs->trans('TicketLogStatusChanged', $langs->transnoentities($this->dao->statuts_short[$old_status]), $langs->transnoentities($this->dao->statuts_short[$new_status])); - $ret = $this->dao->createTicketLog($user, $log_action); - $url = 'card.php?action=view&track_id=' . $this->dao->track_id; + $log_action = $langs->trans('TicketLogStatusChanged', $langs->transnoentities($object->statuts_short[$old_status]), $langs->transnoentities($object->statuts_short[$new_status])); + $ret = $object->createTicketLog($user, $log_action); + $url = 'card.php?action=view&track_id=' . $object->track_id; header("Location: " . $url); exit(); } @@ -624,9 +623,9 @@ class ActionsTicketsup $contactstatic = new Contact($this->db); $error = 0; - $ret = $this->dao->fetch('', GETPOST('track_id')); - $this->dao->socid = $this->dao->fk_soc; - $this->dao->fetch_thirdparty(); + $ret = $object->fetch('', GETPOST('track_id')); + $object->socid = $object->fk_soc; + $object->fetch_thirdparty(); if ($ret < 0) { $error++; array_push($this->errors, $langs->trans("ErrorTicketIsNotValid")); @@ -640,15 +639,15 @@ class ActionsTicketsup } if (!$error) { - $this->dao->message = GETPOST("message"); - $this->dao->private = GETPOST("private_message"); + $object->message = GETPOST("message"); + $object->private = GETPOST("private_message"); $send_email = GETPOST('send_email', 'int'); - $id = $this->dao->createTicketMessage($user); + $id = $object->createTicketMessage($user); if ($id <= 0) { $error++; - $this->errors = $this->dao->error; - $this->errors = $this->dao->errors; + $this->errors = $object->error; + $this->errors = $object->errors; $action = 'add_message'; } @@ -660,14 +659,14 @@ class ActionsTicketsup */ if ($send_email > 0) { // Retrieve internal contact datas - $internal_contacts = $this->dao->getInfosTicketInternalContact(); + $internal_contacts = $object->getInfosTicketInternalContact(); $sendto = array(); if (is_array($internal_contacts) && count($internal_contacts) > 0) { // altairis: set default subject $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE; - $subject = GETPOST('subject') ? GETPOST('subject') : '[' . $label_title . '- ticket #' . $this->dao->track_id . '] ' . $langs->trans('TicketNewMessage'); + $subject = GETPOST('subject') ? GETPOST('subject') : '[' . $label_title . '- ticket #' . $object->track_id . '] ' . $langs->trans('TicketNewMessage'); - $message_intro = $langs->trans('TicketNotificationEmailBody', "#" . $this->dao->id); + $message_intro = $langs->trans('TicketNotificationEmailBody', "#" . $object->id); $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE; $message = $langs->trans('TicketMessageMailIntroText'); @@ -677,9 +676,9 @@ class ActionsTicketsup // Coordonnées client $message .= "\n\n"; $message .= "==============================================\n"; - $message .= !empty($this->dao->thirdparty->name) ? $langs->trans('Thirdparty') . " : " . $this->dao->thirdparty->name : ''; - $message .= !empty($this->dao->thirdparty->town) ? "\n" . $langs->trans('Town') . " : " . $this->dao->thirdparty->town : ''; - $message .= !empty($this->dao->thirdparty->phone) ? "\n" . $langs->trans('Phone') . " : " . $this->dao->thirdparty->phone : ''; + $message .= !empty($object->thirdparty->name) ? $langs->trans('Thirdparty') . " : " . $object->thirdparty->name : ''; + $message .= !empty($object->thirdparty->town) ? "\n" . $langs->trans('Town') . " : " . $object->thirdparty->town : ''; + $message .= !empty($object->thirdparty->phone) ? "\n" . $langs->trans('Phone') . " : " . $object->thirdparty->phone : ''; // Build array to display recipient list foreach ($internal_contacts as $key => $info_sendto) { @@ -698,10 +697,10 @@ class ActionsTicketsup } $message .= "\n"; // URL ticket - $url_internal_ticket = dol_buildpath('/ticketsup/card.php', 2) . '?track_id=' . $this->dao->track_id; + $url_internal_ticket = dol_buildpath('/ticketsup/card.php', 2) . '?track_id=' . $object->track_id; // altairis: make html link on url - $message .= "\n" . $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal') . ' : ' . '' . $this->dao->track_id . '' . "\n"; + $message .= "\n" . $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal') . ' : ' . '' . $object->track_id . '' . "\n"; // Add global email address recipient // altairis: use new TICKETS_NOTIFICATION_EMAIL_TO configuration variable @@ -718,18 +717,18 @@ class ActionsTicketsup /* * Email for externals users if not private */ - if (empty($this->dao->private)) { + if (empty($object->private)) { // Retrieve email of all contacts (external) - $external_contacts = $this->dao->getInfosTicketExternalContact(); + $external_contacts = $object->getInfosTicketExternalContact(); // If no contact, get email from thirdparty if (is_array($external_contacts) && count($external_contacts) === 0) { - if (!empty($this->dao->fk_soc)) { - $this->dao->fetch_thirdparty($this->dao->fk_soc); - $array_company = array(array('firstname' => '', 'lastname' => $this->dao->thirdparty->name, 'email' => $this->dao->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $this->dao->thirdparty->id)); + if (!empty($object->fk_soc)) { + $object->fetch_thirdparty($object->fk_soc); + $array_company = array(array('firstname' => '', 'lastname' => $object->thirdparty->name, 'email' => $object->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $object->thirdparty->id)); $external_contacts = array_merge($external_contacts, $array_company); - } elseif (empty($this->dao->fk_soc) && !empty($this->dao->origin_email)) { - $array_external = array(array('firstname' => '', 'lastname' => $this->dao->origin_email, 'email' => $this->dao->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $this->dao->thirdparty->id)); + } elseif (empty($object->fk_soc) && !empty($object->origin_email)) { + $array_external = array(array('firstname' => '', 'lastname' => $object->origin_email, 'email' => $object->thirdparty->email, 'libelle' => $langs->transnoentities('Customer'), 'socid' => $object->thirdparty->id)); $external_contacts = array_merge($external_contacts, $array_external); } } @@ -738,7 +737,7 @@ class ActionsTicketsup if (is_array($external_contacts) && count($external_contacts) > 0) { // altairis: get default subject for email to external contacts $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE; - $subject = GETPOST('subject') ? GETPOST('subject') : '[' . $label_title . '- ticket #' . $this->dao->track_id . '] ' . $langs->trans('TicketNewMessage'); + $subject = GETPOST('subject') ? GETPOST('subject') : '[' . $label_title . '- ticket #' . $object->track_id . '] ' . $langs->trans('TicketNewMessage'); $message_intro = GETPOST('mail_intro') ? GETPOST('mail_intro') : $conf->global->TICKETS_MESSAGE_MAIL_INTRO; $message_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKETS_MESSAGE_MAIL_SIGNATURE; @@ -753,7 +752,7 @@ class ActionsTicketsup continue; } - if ($info_sendto['email'] != '' && $info_sendto['email'] != $this->dao->origin_email) { + if ($info_sendto['email'] != '' && $info_sendto['email'] != $object->origin_email) { if(!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . ">"; $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1') . ' (' . strtolower($info_sendto['libelle']) . ')'; @@ -768,8 +767,8 @@ class ActionsTicketsup dol_buildpath('/ticketsup/public/view.php', 2) ) : dol_buildpath('/ticketsup/card.php', 2) - ) . '?track_id=' . $this->dao->track_id; - $message .= "\n" . $langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : ' . '' . $this->dao->track_id . '' . "\n"; + ) . '?track_id=' . $object->track_id; + $message .= "\n" . $langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : ' . '' . $object->track_id . '' . "\n"; // Build final message $message = $message_intro . $message; @@ -777,14 +776,14 @@ class ActionsTicketsup // Add signature $message .= '
    ' . $message_signature; - if (!empty($this->dao->origin_email)) { - $sendto[] = $this->dao->origin_email; + if (!empty($object->origin_email)) { + $sendto[] = $object->origin_email; } - if ($this->dao->fk_soc > 0 && ! in_array($this->dao->origin_email, $sendto)) { - $this->dao->socid = $this->dao->fk_soc; - $this->dao->fetch_thirdparty(); - if(!empty($this->dao->thirdparty->email)) $sendto[] = $this->dao->thirdparty->email; + if ($object->fk_soc > 0 && ! in_array($object->origin_email, $sendto)) { + $object->socid = $object->fk_soc; + $object->fetch_thirdparty(); + if(!empty($object->thirdparty->email)) $sendto[] = $object->thirdparty->email; } // altairis: Add global email address reciepient @@ -803,13 +802,13 @@ class ActionsTicketsup $this->copyFilesForTicket(); // Set status to "answered" if not set yet, only for internal users - if ($this->dao->fk_statut < 3 && !$user->societe_id) { - $this->dao->setStatut(3); + if ($object->fk_statut < 3 && !$user->societe_id) { + $object->setStatut(3); } return 1; } else { - setEventMessages($this->dao->error, $this->dao->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); return -1; } } else { @@ -830,9 +829,9 @@ class ActionsTicketsup global $mysoc, $conf, $langs; $error = 0; - $ret = $this->dao->fetch('', GETPOST('track_id')); - $this->dao->socid = $this->dao->fk_soc; - $this->dao->fetch_thirdparty(); + $ret = $object->fetch('', GETPOST('track_id')); + $object->socid = $object->fk_soc; + $object->fetch_thirdparty(); if ($ret < 0) { $error++; array_push($this->errors, $langs->trans("ErrorTicketIsNotValid")); @@ -846,12 +845,12 @@ class ActionsTicketsup } if (!$error) { - $this->dao->message = GETPOST("message"); - $id = $this->dao->createTicketMessage($user); + $object->message = GETPOST("message"); + $id = $object->createTicketMessage($user); if ($id <= 0) { $error++; - $this->errors = $this->dao->error; - $this->errors = $this->dao->errors; + $this->errors = $object->error; + $this->errors = $object->errors; $action = 'add_message'; } @@ -859,24 +858,24 @@ class ActionsTicketsup setEventMessages($langs->trans('TicketMessageSuccessfullyAdded'), null, 'mesgs'); // Retrieve internal contact datas - $internal_contacts = $this->dao->getInfosTicketInternalContact(); + $internal_contacts = $object->getInfosTicketInternalContact(); $sendto = array(); if (is_array($internal_contacts) && count($internal_contacts) > 0) { - $subject = '[' . $mysoc->name . '- ticket #' . $this->dao->track_id . '] ' . $langs->trans('TicketNewMessage'); + $subject = '[' . $mysoc->name . '- ticket #' . $object->track_id . '] ' . $langs->trans('TicketNewMessage'); - $message = $langs->trans('TicketMessageMailIntroAutoNewPublicMessage', $this->dao->subject); + $message = $langs->trans('TicketMessageMailIntroAutoNewPublicMessage', $object->subject); $message .= "\n"; $message .= GETPOST('message'); $message .= "\n"; // Coordonnées client - if ($this->dao->thirdparty->id > 0) { + if ($object->thirdparty->id > 0) { $message .= "\n\n"; $message .= "==============================================\n"; - $message .= $langs->trans('Thirparty') . " : " . $this->dao->thirdparty->name; - $message .= !empty($this->dao->thirdparty->town) ? $langs->trans('Town') . " : " . $this->dao->thirdparty->town : ''; + $message .= $langs->trans('Thirparty') . " : " . $object->thirdparty->name; + $message .= !empty($object->thirdparty->town) ? $langs->trans('Town') . " : " . $object->thirdparty->town : ''; $message .= "\n"; - $message .= !empty($this->dao->thirdparty->phone) ? $langs->trans('Phone') . " : " . $this->dao->thirdparty->phone : ''; + $message .= !empty($object->thirdparty->phone) ? $langs->trans('Phone') . " : " . $object->thirdparty->phone : ''; $message .= "\n"; } @@ -893,7 +892,7 @@ class ActionsTicketsup } // URL ticket - $url_internal_ticket = dol_buildpath('/ticketsup/card.php', 2) . '?track_id=' . $this->dao->track_id; + $url_internal_ticket = dol_buildpath('/ticketsup/card.php', 2) . '?track_id=' . $object->track_id; $message .= "\n" . $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal') . ' : ' . $url_internal_ticket . "\n"; $message .= "\n\n"; @@ -913,12 +912,12 @@ class ActionsTicketsup */ // Retrieve email of all contacts external - $external_contacts = $this->dao->getInfosTicketExternalContact(); + $external_contacts = $object->getInfosTicketExternalContact(); $sendto = array(); if (is_array($external_contacts) && count($external_contacts) > 0) { - $subject = '[' . $mysoc->name . '- ticket #' . $this->dao->track_id . '] ' . $langs->trans('TicketNewMessage'); + $subject = '[' . $mysoc->name . '- ticket #' . $object->track_id . '] ' . $langs->trans('TicketNewMessage'); - $message = $langs->trans('TicketMessageMailIntroAutoNewPublicMessage', $this->dao->subject); + $message = $langs->trans('TicketMessageMailIntroAutoNewPublicMessage', $object->subject); $message .= "\n"; $message .= GETPOST('message'); @@ -934,28 +933,28 @@ class ActionsTicketsup $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient') . ' : ' . $recipient . "\n" : ''); } - $url_public_ticket = ($conf->global->TICKETS_URL_PUBLIC_INTERFACE ? $conf->global->TICKETS_URL_PUBLIC_INTERFACE . '/view.php' : dol_buildpath('/ticketsup/public/view.php', 2)) . '?track_id=' . $this->dao->track_id; + $url_public_ticket = ($conf->global->TICKETS_URL_PUBLIC_INTERFACE ? $conf->global->TICKETS_URL_PUBLIC_INTERFACE . '/view.php' : dol_buildpath('/ticketsup/public/view.php', 2)) . '?track_id=' . $object->track_id; $message .= "\n\n" . $langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : ' . $url_public_ticket . "\n"; // Add signature $message .= '\n\n' . $message_signature; - if (!empty($this->dao->origin_email) && !in_array($this->dao->origin_email, $sendto)) { - $sendto[] = $this->dao->origin_email; + if (!empty($object->origin_email) && !in_array($object->origin_email, $sendto)) { + $sendto[] = $object->origin_email; } - if ($this->dao->fk_soc > 0 && !in_array($this->dao->origin_email, $sendto)) { - $sendto[] = $this->dao->thirdparty->email; + if ($object->fk_soc > 0 && !in_array($object->origin_email, $sendto)) { + $sendto[] = $object->thirdparty->email; } $this->sendTicketMessageByEmail($subject, $message, '', $sendto); } $this->copyFilesForTicket(); - $url = 'view.php?action=view_ticket&track_id=' . $this->dao->track_id; + $url = 'view.php?action=view_ticket&track_id=' . $object->track_id; header("Location: " . $url); exit; } else { - setEventMessages($this->dao->error, $this->dao->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } else { setEventMessages($this->error, $this->errors, 'errors'); @@ -1090,19 +1089,20 @@ class ActionsTicketsup /** * View list of logs with timeline view * - * @param boolean $show_user Show user who make action + * @param boolean $show_user Show user who make action + * @param Ticketsup $object Object */ - public function viewTimelineTicketLogs($show_user = true) + public function viewTimelineTicketLogs($show_user = true, $object = true) { global $conf, $langs, $bc; // Load logs in cache - $ret = $this->dao->loadCacheLogsTicket(); + $ret = $object->loadCacheLogsTicket(); - if (is_array($this->dao->cache_logs_ticket) && count($this->dao->cache_logs_ticket) > 0) { + if (is_array($object->cache_logs_ticket) && count($object->cache_logs_ticket) > 0) { print '
    '; - foreach ($this->dao->cache_logs_ticket as $id => $arraylogs) { + foreach ($object->cache_logs_ticket as $id => $arraylogs) { print '
    '; print '
    '; //print ''; @@ -1263,21 +1263,22 @@ class ActionsTicketsup /** * View list of message for ticket with timeline display * - * @param boolean $show_private Show private messages - * @param boolean $show_user Show user who make action + * @param boolean $show_private Show private messages + * @param boolean $show_user Show user who make action + * @param Ticketsup $object Object ticketsup */ - public function viewTicketTimelineMessages($show_private, $show_user = true) + public function viewTicketTimelineMessages($show_private, $show_user, Ticketsup $object) { global $conf, $langs, $user, $bc; // Load logs in cache - $ret = $this->dao->loadCacheMsgsTicket(); + $ret = $object->loadCacheMsgsTicket(); $action = GETPOST('action'); - if (is_array($this->dao->cache_msgs_ticket) && count($this->dao->cache_msgs_ticket) > 0) { + if (is_array($object->cache_msgs_ticket) && count($object->cache_msgs_ticket) > 0) { print '
    '; - foreach ($this->dao->cache_msgs_ticket as $id => $arraymsgs) { + foreach ($object->cache_msgs_ticket as $id => $arraymsgs) { if (!$arraymsgs['private'] || ($arraymsgs['private'] == "1" && $show_private) ) { @@ -1460,49 +1461,43 @@ class ActionsTicketsup /** * Print html navbar with link to set ticket status -<<<<<<< HEAD - * $selected : 0=>'NotRead', 1=>'Read', 3=>'Answered', 4=>'Assigned', 5 => 'InProgress', 6=> 'Waiting', 8=>'Closed', 9=>'Deleted' * + * @param Ticketsup $object Ticket sup * @return void -======= - * - * @global type $langs ->>>>>>> branch 'develop' of git@github.com:Dolibarr/dolibarr.git */ - public function viewStatusActions() + public function viewStatusActions(Ticketsup $object) { global $langs; + print '
    '; print '
    '; print '
    '; print '
    '; print '' . $langs->trans('TicketChangeStatus') . ''; print '
    '; // Exclude status which requires specific method - $exclude_status = array(4, 9, 8); + $exclude_status = array(Ticketsup::STATUS_CLOSED, Ticketsup::STATUS_CANCELED); // Exclude actual status - $exclude_status = array_merge($exclude_status, array(intval($this->dao->fk_statut))); - - // If status is new, don't show link which allow mark ticket as read - // Specific method exists to mark a ticket as read - if ($this->dao->fk_statut == '0') { - $exclude_status = array_merge($exclude_status, array(1)); - } + $exclude_status = array_merge($exclude_status, array(intval($object->fk_statut))); // Sort results to be similar to status object list - sort($exclude_status); + //sort($exclude_status); //print '
    '; - foreach ($this->dao->statuts_short as $status => $statut_label) { + foreach ($object->statuts_short as $status => $statut_label) { if (!in_array($status, $exclude_status)) { print ''; } } - print '

    '; + print '

    '; } diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index 3795978289e..7f011d7f459 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -191,9 +191,24 @@ class Ticketsup extends CommonObject 'date_read' => array('type'=>'datetime', 'label'=>'TicketReadOn', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1), 'date_close' => array('type'=>'datetime', 'label'=>'TicketCloseOn', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1), 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>501, 'notnull'=>1), - 'fk_statut' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>600, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array(0 => 'NotRead', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted')) + 'fk_statut' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>600, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array(0 => 'Unread', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted')) ); + /** + * Status + */ + const STATUS_NOT_READ = 0; + const STATUS_READ = 1; + const STATUS_ANSWERED = 3; + const STATUS_ASSIGNED = 4; + const STATUS_IN_PROGRESS = 5; + const STATUS_WAITING = 6; + const STATUS_CLOSED = 8; + const STATUS_CANCELED = 9; + + + + /** * Constructor * @@ -203,8 +218,8 @@ class Ticketsup extends CommonObject { $this->db = $db; - $this->statuts_short = array(0 => 'NotRead', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted'); - $this->statuts = array(0 => 'NotRead', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted'); + $this->statuts_short = array(0 => 'Unread', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted'); + $this->statuts = array(0 => 'Unread', 1 => 'Read', 3 => 'Answered', 4 => 'Assigned', 5 => 'InProgress', 6 => 'Waiting', 8 => 'Closed', 9 => 'Deleted'); } /** @@ -422,7 +437,7 @@ class Ticketsup extends CommonObject global $langs; // Check parameters - if (!$id && !$track_id && !$ref) { + if (! $id && ! $track_id && ! $ref) { $this->error = 'ErrorWrongParameters'; dol_print_error(get_class($this) . "::fetch " . $this->error); return -1; diff --git a/htdocs/ticketsup/history.php b/htdocs/ticketsup/history.php index b4e0e0e9249..6994cbeafc1 100644 --- a/htdocs/ticketsup/history.php +++ b/htdocs/ticketsup/history.php @@ -49,25 +49,33 @@ if (!$user->rights->ticketsup->read) { accessforbidden(); } -$object = new ActionsTicketsup($db); - -$object->doActions($action); - $extrafields = new ExtraFields($db); -$extralabels = $extrafields->fetch_name_optionals_label($object->dao->table_element); +$extralabels = $extrafields->fetch_name_optionals_label($object->table_element); if (!$action) { - $action = 'view'; + $action = 'view'; } -/*************************************************** - * PAGE - * - * Put here all code to build page - ****************************************************/ +$object = new Ticketsup($db); +$object->fetch($id, $track_id, $ref); + + +/* + * Actions + */ + +$actionobject = new ActionsTicketsup($db); + +$actionobject->doActions($action, $object); + + + +/* + * View + */ $help_url = 'FR:DocumentationModuleTicket'; -$page_title = $object->getTitle($action); +$page_title = $actionobject->getTitle($action); llxHeader('', $page_title, $help_url); $userstat = new User($db); @@ -79,20 +87,20 @@ if ($action == 'view') { if ($res > 0) { // restrict access for externals users - if ($user->societe_id > 0 && ($object->dao->fk_soc != $user->societe_id) + if ($user->societe_id > 0 && ($object->fk_soc != $user->societe_id) ) { accessforbidden('', 0); } // or for unauthorized internals users - if (!$user->societe_id && ($conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY && $object->dao->fk_user_assign != $user->id) && !$user->rights->ticketsup->manage) { + if (!$user->societe_id && ($conf->global->TICKETS_LIMIT_VIEW_ASSIGNED_ONLY && $object->fk_user_assign != $user->id) && !$user->rights->ticketsup->manage) { accessforbidden('', 0); } if ($socid > 0) { - $object->dao->fetch_thirdparty(); - $head = societe_prepare_head($object->dao->thirdparty); + $object->fetch_thirdparty(); + $head = societe_prepare_head($object->thirdparty); dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); - dol_banner_tab($object->dao->thirdparty, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); + dol_banner_tab($object->thirdparty, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); dol_fiche_end(); } @@ -101,26 +109,28 @@ if ($action == 'view') { } elseif ($user->societe_id > 0) { $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } - $head = ticketsup_prepare_head($object->dao); + $head = ticketsup_prepare_head($object); dol_fiche_head($head, 'tabTicketLogs', $langs->trans("Ticket"), 0, 'ticketsup'); - $object->dao->label = $object->dao->ref; + $object->label = $object->ref; // Author - if ($object->dao->fk_user_create > 0) { - $object->dao->label .= ' - ' . $langs->trans("CreatedBy") . ' '; + if ($object->fk_user_create > 0) { + $object->label .= ' - ' . $langs->trans("CreatedBy") . ' '; $langs->load("users"); $fuser = new User($db); - $fuser->fetch($object->dao->fk_user_create); - $object->dao->label .= $fuser->getNomUrl(0); + $fuser->fetch($object->fk_user_create); + $object->label .= $fuser->getNomUrl(0); } $linkback = '' . $langs->trans("BackToList") . ' '; - $object->dao->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + + // TODO Merge this with dol_banner_tab + $object->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); dol_fiche_end(); print '
    '; // Logs list print load_fiche_titre($langs->trans('TicketHistory'), '', 'history@ticketsup'); - $object->viewTimelineTicketLogs(); + $actionobject->viewTimelineTicketLogs(true, $object); print '
    '; print '
    '; } diff --git a/htdocs/ticketsup/index.php b/htdocs/ticketsup/index.php index 37cf7bf959c..2274ae0b889 100644 --- a/htdocs/ticketsup/index.php +++ b/htdocs/ticketsup/index.php @@ -53,7 +53,7 @@ $year = GETPOST('year') > 0 ? GETPOST('year') : $nowyear; $startyear = $year - 1; $endyear = $year; -$object = new ActionsTicketsup($db); +$object = new Ticketsup($db); /* @@ -180,7 +180,7 @@ if ($result) { if ((round($tick['unread']) ? 1 : 0) +(round($tick['read']) ? 1 : 0) +(round($tick['answered']) ? 1 : 0) +(round($tick['assigned']) ? 1 : 0) +(round($tick['inprogress']) ? 1 : 0) +(round($tick['waiting']) ? 1 : 0) +(round($tick['closed']) ? 1 : 0) +(round($tick['deleted']) ? 1 : 0) >= 2 ) { $dataseries = array(); - $dataseries[] = array('label' => $langs->trans("NotRead"), 'data' => round($tick['unread'])); + $dataseries[] = array('label' => $langs->trans("Unread"), 'data' => round($tick['unread'])); $dataseries[] = array('label' => $langs->trans("Read"), 'data' => round($tick['read'])); $dataseries[] = array('label' => $langs->trans("Answered"), 'data' => round($tick['answered'])); $dataseries[] = array('label' => $langs->trans("Assigned"), 'data' => round($tick['assigned'])); diff --git a/htdocs/ticketsup/new.php b/htdocs/ticketsup/new.php index e08361e1e77..c784d5f04ac 100644 --- a/htdocs/ticketsup/new.php +++ b/htdocs/ticketsup/new.php @@ -39,7 +39,6 @@ $socid = GETPOST('socid', 'int'); $contactid = GETPOST('contactid', 'int'); $msg_id = GETPOST('msg_id', 'int'); $notNotifyTiers = GETPOST("not_notify_tiers_at_create", 'alpha'); -$notnotifytiersatcreate = !empty($notNotifyTiers); $action = GETPOST('action', 'alpha', 3); @@ -48,14 +47,15 @@ if (!$user->rights->ticketsup->read || !$user->rights->ticketsup->write) { accessforbidden(); } -$object = new ActionsTicketsup($db); +$object = new Ticketsup($db); +$actionobject = new ActionsTicketsup($db); /* * Actions */ -$object->doActions($action); +$actionobject->doActions($action, $object); @@ -63,11 +63,12 @@ $object->doActions($action); * View */ +$form = new Form($db); + $help_url = 'FR:DocumentationModuleTicket'; -$page_title = $object->getTitle($action); +$page_title = $actionobject->getTitle($action); llxHeader('', $page_title, $help_url); -$form = new Form($db); if ($action == 'create_ticket') { $formticket = new FormTicketsup($db); @@ -77,7 +78,7 @@ if ($action == 'create_ticket') { $formticket->withfromsocid = $socid ? $socid : $user->societe_id; $formticket->withfromcontactid = $contactid ? $contactid : ''; $formticket->withtitletopic = 1; - $formticket->withnotnotifytiersatcreate = $notnotifytiersatcreate; + $formticket->withnotnotifytiersatcreate = $notnotifytiersatcreate?1:0; $formticket->withusercreate = 1; $formticket->withref = 1; $formticket->fk_user_create = $user->id; From 51b6723b080231010d5a100dcdf1f2bd71078512 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 18 Mar 2018 20:01:11 +0100 Subject: [PATCH 398/413] Dolibarrize module ticket --- .../core/class/html.formticketsup.class.php | 6 +- htdocs/core/lib/functions.lib.php | 22 +++++- htdocs/ticketsup/card.php | 17 +++-- .../class/actions_ticketsup.class.php | 16 ++-- htdocs/ticketsup/class/ticketsup.class.php | 76 +------------------ htdocs/ticketsup/contact.php | 23 ++++-- htdocs/ticketsup/document.php | 25 ++++-- htdocs/ticketsup/history.php | 25 ++++-- htdocs/ticketsup/new.php | 4 +- 9 files changed, 100 insertions(+), 114 deletions(-) diff --git a/htdocs/core/class/html.formticketsup.class.php b/htdocs/core/class/html.formticketsup.class.php index 1570cb34883..3310b83eb09 100644 --- a/htdocs/core/class/html.formticketsup.class.php +++ b/htdocs/core/class/html.formticketsup.class.php @@ -178,7 +178,7 @@ class FormTicketsup // altairis: force company and contact id for external user if (empty($user->socid)) { // Company - print '' . $langs->trans("Thirdparty") . ''; + print '' . $langs->trans("ThirdParty") . ''; $events = array(); $events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php', 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); print $form->select_company($this->withfromsocid, 'socid', '', 1, 1, '', $events); @@ -297,8 +297,8 @@ class FormTicketsup print ''; // Notify thirdparty at creation - print ''; - print 'withnotnotifytiersatcreate?'':' checked="checked"').'>'; + print ''; + print 'withnotifytiersatcreate?' checked="checked"':'').'>'; print ''; // TITLE diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index f4759240cd5..2177559c0ab 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -1340,6 +1340,25 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r //} } } + elseif ($object->element == 'ticketsup') + { + $width=80; $cssclass='photoref'; + $showimage=$object->is_photo_available($conf->ticketsup->dir_output.'/'.$object->track_id); + $maxvisiblephotos=(isset($conf->global->TICKETSUP_MAX_VISIBLE_PHOTO)?$conf->global->TICKETSUP_MAX_VISIBLE_PHOTO:2); + if ($conf->browser->phone) $maxvisiblephotos=1; + if ($showimage) $morehtmlleft.='
    '.$object->show_photos($conf->ticketsup->dir_output,'small',$maxvisiblephotos,0,0,0,$width,0).'
    '; + else + { + if (!empty($conf->global->TICKETSUP_NODISPLAYIFNOPHOTO)) { + $nophoto=''; + $morehtmlleft.='
    '; + } + //elseif ($conf->browser->layout != 'phone') { // Show no photo link + $nophoto='/public/theme/common/nophoto.png'; + $morehtmlleft.='
    No photo
    '; + //} + } + } else { if ($showimage) @@ -3063,7 +3082,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ $pictowithoutext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto); //if (in_array($picto, array('switch_off', 'switch_on', 'off', 'on'))) - if (in_array($pictowithoutext, array('delete', 'edit', 'off', 'on', 'resize', 'switch_off', 'switch_on', 'unlink', 'uparrow'))) + if (in_array($pictowithoutext, array('delete', 'edit', 'off', 'on', 'printer', 'resize', 'switch_off', 'switch_on', 'unlink', 'uparrow'))) { $fakey = $pictowithoutext; $facolor=''; $fasize=''; if ($pictowithoutext == 'switch_off') { $fakey = 'fa-toggle-off'; $facolor='#999'; $fasize='2em'; } @@ -3072,6 +3091,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ elseif ($pictowithoutext == 'on') { $fakey = 'fa-check-square-o'; $fasize='1.3em'; } elseif ($pictowithoutext == 'delete') { $fakey = 'fa-trash'; $facolor='#444'; } elseif ($pictowithoutext == 'edit') { $fakey = 'fa-pencil'; $facolor='#444'; } + elseif ($pictowithoutext == 'printer') { $fakey = 'fa-print'; $fasize='1.2em'; $facolor='#444'; } elseif ($pictowithoutext == 'resize') { $fakey = 'fa-crop'; $facolor='#444'; } elseif ($pictowithoutext == 'uparrow') { $fakey = 'fa-mail-forward'; $facolor='#555'; } elseif ($pictowithoutext == 'unlink') { $fakey = 'fa-chain-broken'; $facolor='#555'; } diff --git a/htdocs/ticketsup/card.php b/htdocs/ticketsup/card.php index 759f87f3b0c..55ebed62c7d 100644 --- a/htdocs/ticketsup/card.php +++ b/htdocs/ticketsup/card.php @@ -203,6 +203,7 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti } elseif ($socid > 0) { $object->fetch_thirdparty(); $head = societe_prepare_head($object->thirdparty); + dol_fiche_head($head, 'ticketsup', $langs->trans("ThirdParty"), 0, 'company'); dol_banner_tab($object->thirdparty, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); dol_fiche_end(); @@ -218,22 +219,26 @@ if ($action == 'view' || $action == 'add_message' || $action == 'close' || $acti dol_fiche_head($head, 'tabTicketsup', $langs->trans("Ticket"), -1, 'ticketsup'); - $object->label = $object->ref; + $morehtmlref ='
    '; + $morehtmlref.= $object->subject; // Author if ($object->fk_user_create > 0) { - $object->label .= ' - ' . $langs->trans("CreatedBy") . ' '; + $morehtmlref .= '
    ' . $langs->trans("CreatedBy") . ' '; $langs->load("users"); $fuser = new User($db); $fuser->fetch($object->fk_user_create); - $object->label .= $fuser->getNomUrl(0); + $morehtmlref .= $fuser->getNomUrl(0); } if (!empty($object->origin_email)) { - $object->label .= ' - ' . $langs->trans("CreatedBy") . ' '; - $object->label .= $object->origin_email . ' (' . $langs->trans("TicketEmailOriginIssuer") . ')'; + $morehtmlref .= '
    ' . $langs->trans("CreatedBy") . ' '; + $morehtmlref .= $object->origin_email . ' (' . $langs->trans("TicketEmailOriginIssuer") . ')'; } + $morehtmlref.='
    '; + $linkback = '' . $langs->trans("BackToList") . ' '; - $object->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + + dol_banner_tab($object, 'ref', $linkback, ($user->societe_id ? 0 : 1), 'ref', 'ref', $morehtmlref); print '
    '; print '
    '; diff --git a/htdocs/ticketsup/class/actions_ticketsup.class.php b/htdocs/ticketsup/class/actions_ticketsup.class.php index 1186b7fbd1e..4d0acda3e35 100644 --- a/htdocs/ticketsup/class/actions_ticketsup.class.php +++ b/htdocs/ticketsup/class/actions_ticketsup.class.php @@ -152,15 +152,15 @@ class ActionsTicketsup $object->track_id = generate_random_id(16); $object->ref = GETPOST("ref", 'alpha'); - $object->fk_soc = GETPOST("socid", 'int'); + $object->fk_soc = GETPOST("socid", 'int') > 0 ? GETPOST("socid", 'int') : 0; $object->subject = GETPOST("subject", 'alpha'); $object->message = GETPOST("message"); $object->type_code = GETPOST("type_code", 'alpha'); $object->category_code = GETPOST("category_code", 'alpha'); $object->severity_code = GETPOST("severity_code", 'alpha'); - $notNotifyTiers = GETPOST("not_notify_tiers_at_create", 'alpha'); - $object->notify_tiers_at_create = empty($notNotifyTiers) ? 1 : 0; + $notifyTiers = GETPOST("notify_tiers_at_create", 'alpha'); + $object->notify_tiers_at_create = empty($notifyTiers) ? 0 : 1; $extrafields = new ExtraFields($this->db); $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); @@ -174,7 +174,8 @@ class ActionsTicketsup $action = 'create_ticket'; } - if (!$error && $id > 0) { + if (!$error && $id > 0) + { $this->db->commit(); // File transfer @@ -189,7 +190,7 @@ class ActionsTicketsup } // altairis: link ticket to project - if (GETPOST('projectid')) { + if (GETPOST('projectid') > 0) { $object->setProject(GETPOST('projectid')); } @@ -216,7 +217,8 @@ class ActionsTicketsup } // Auto create fiche intervention - if ($conf->global->TICKETS_AUTO_CREATE_FICHINTER_CREATE) { + if ($conf->global->TICKETS_AUTO_CREATE_FICHINTER_CREATE) + { $fichinter = new Fichinter($this->db); $fichinter->socid = $object->fk_soc; $fichinter->fk_project = GETPOST('projectid', 'int'); @@ -623,6 +625,8 @@ class ActionsTicketsup $contactstatic = new Contact($this->db); $error = 0; + + $object = new Ticketsup($this->db); $ret = $object->fetch('', GETPOST('track_id')); $object->socid = $object->fk_soc; $object->fetch_thirdparty(); diff --git a/htdocs/ticketsup/class/ticketsup.class.php b/htdocs/ticketsup/class/ticketsup.class.php index 7f011d7f459..584f9508f6d 100644 --- a/htdocs/ticketsup/class/ticketsup.class.php +++ b/htdocs/ticketsup/class/ticketsup.class.php @@ -352,8 +352,8 @@ class Ticketsup extends CommonObject $sql .= ") VALUES ("; $sql .= " " . (!isset($this->ref) ? '' : "'" . $this->db->escape($this->ref) . "'") . ","; $sql .= " " . (!isset($this->track_id) ? 'NULL' : "'" . $this->db->escape($this->track_id) . "'") . ","; - $sql .= " " . (!isset($this->fk_soc) ? '0' : "'" . $this->db->escape($this->fk_soc) . "'") . ","; - $sql .= " " . (!isset($this->fk_project) ? '0' : "'" . $this->db->escape($this->fk_project) . "'") . ","; + $sql .= " " . ($this->fk_soc > 0 ? $this->db->escape($this->fk_soc) : "null") . ","; + $sql .= " " . ($this->fk_project > 0 ? $this->db->escape($this->fk_project) : "null") . ","; $sql .= " " . (!isset($this->origin_email) ? 'NULL' : "'" . $this->db->escape($this->origin_email) . "'") . ","; $sql .= " " . ($this->fk_user_create > 0 ? $this->fk_user_create : ($user->id > 0 ? $user->id : 'NULL')) . ","; $sql .= " " . ($this->fk_user_assign > 0 ? $this->fk_user_assign : 'NULL') . ","; @@ -2412,78 +2412,6 @@ class Ticketsup extends CommonObject return $defaultref; } - /** - * Show tab footer of a card - * - * @param string $paramid Name of parameter to use to name the id into the URL next/previous link - * @param string $morehtml More html content to output just before the nav bar - * @param int $shownav Show Condition (navigation is shown if value is 1) - * @param string $fieldid Nom du champ en base a utiliser pour select next et previous (we make the select max and min on this field) - * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous - * @param string $morehtmlref More html to show after ref - * @param string $moreparam More param to add in nav link url. - * @param int $nodbprefix Do not include DB prefix to forge table name - * @param string $morehtmlleft More html code to show before ref - * @param string $morehtmlright More html code to show before navigation arrows - * @param string $onlybanner 1 - * @return void - */ - public function ticketsupBannerTab($paramid, $morehtml = '', $shownav = 1, $fieldid = 'id', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlright = '', $onlybanner=0) - { - global $conf, $form, $user, $langs; - - $maxvisiblephotos = 1; - $showimage = 1; - $showbarcode = empty($conf->barcode->enabled) ? 0 : ($this->barcode ? 1 : 0); - if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) { - $showbarcode = 0; - } - - $modulepart = 'ticketsup'; - print '
    '; - - $width = 80; - $height = 70; - $cssclass = 'photoref'; - //$showimage=$this->is_photo_available($conf->ticketsup->multidir_output[$this->entity]); - $showimage = $this->is_photo_available($conf->ticketsup->dir_output . '/' . $this->track_id); - $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : $maxvisiblephotos); - if ($conf->browser->phone) { - $maxvisiblephotos = 1; - } - - if ($showimage) { - $morehtmlleft .= '
    ' - . $this->show_photos($conf->ticketsup->dir_output, 'small', $maxvisiblephotos, 0, 0, 0, $height, $width, 0) - . '
    '; - } else { - $nophoto = '/public/theme/common/nophoto.png'; - $morehtmlleft .= '
    No photo
    '; - } - $morehtmlright .= $this->getLibStatut(2); - - if (!empty($this->name_alias)) { - $morehtmlref .= '
    ' . $this->name_alias . '
    '; - } - // For thirdparty - if (!empty($this->label)) { - $morehtmlref .= '
    ' . $this->label . '
    '; - } - // For product - if ($this->element != 'product') { - $morehtmlref .= '
    '; - $morehtmlref .= $this->getBannerAddress('refaddress', $this); - $morehtmlref .= '
    '; - } - if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { - $morehtmlref .= '
    '; - $morehtmlref .= $langs->trans("TechnicalID") . ': ' . $this->id; - $morehtmlref .= '
    '; - } - print $form->showrefnav($this, 'ref', $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlright); - print '
    '; - print '
    '; - } /** * Return if at least one photo is available diff --git a/htdocs/ticketsup/contact.php b/htdocs/ticketsup/contact.php index 356aa47ffd5..5dceabe9476 100644 --- a/htdocs/ticketsup/contact.php +++ b/htdocs/ticketsup/contact.php @@ -149,17 +149,26 @@ if ($id > 0 || !empty($track_id) || !empty($ref)) { dol_fiche_head($head, 'contact', $langs->trans("Ticket"), -1, 'ticketsup'); - $object->label = $object->ref; + $morehtmlref ='
    '; + $morehtmlref.= $object->subject; // Author if ($object->fk_user_create > 0) { - $object->label .= ' - ' . $langs->trans("CreatedBy") . ' '; - $langs->load("users"); - $fuser = new User($db); - $fuser->fetch($object->fk_user_create); - $object->label .= $fuser->getNomUrl(0); + $morehtmlref .= '
    ' . $langs->trans("CreatedBy") . ' '; + + $langs->load("users"); + $fuser = new User($db); + $fuser->fetch($object->fk_user_create); + $morehtmlref .= $fuser->getNomUrl(0); } + if (!empty($object->origin_email)) { + $morehtmlref .= '
    ' . $langs->trans("CreatedBy") . ' '; + $morehtmlref .= $object->origin_email . ' (' . $langs->trans("TicketEmailOriginIssuer") . ')'; + } + $morehtmlref.='
    '; + $linkback = '' . $langs->trans("BackToList") . ' '; - $object->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback, 1); + + dol_banner_tab($object, 'ref', $linkback, ($user->societe_id ? 0 : 1), 'ref', 'ref', $morehtmlref); dol_fiche_end(); diff --git a/htdocs/ticketsup/document.php b/htdocs/ticketsup/document.php index 0f528ee17bb..a19a972c143 100644 --- a/htdocs/ticketsup/document.php +++ b/htdocs/ticketsup/document.php @@ -123,18 +123,29 @@ if ($object->id) { $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } $head = ticketsup_prepare_head($object); + dol_fiche_head($head, 'tabTicketDocument', $langs->trans("Ticket"), 0, 'ticketsup'); - $object->label = $object->ref; + + $morehtmlref ='
    '; + $morehtmlref.= $object->subject; // Author if ($object->fk_user_create > 0) { - $object->label .= ' - ' . $langs->trans("CreatedBy") . ' '; - $langs->load("users"); - $fuser = new User($db); - $fuser->fetch($object->fk_user_create); - $object->label .= $fuser->getNomUrl(0); + $morehtmlref .= '
    ' . $langs->trans("CreatedBy") . ' '; + + $langs->load("users"); + $fuser = new User($db); + $fuser->fetch($object->fk_user_create); + $morehtmlref .= $fuser->getNomUrl(0); } + if (!empty($object->origin_email)) { + $morehtmlref .= '
    ' . $langs->trans("CreatedBy") . ' '; + $morehtmlref .= $object->origin_email . ' (' . $langs->trans("TicketEmailOriginIssuer") . ')'; + } + $morehtmlref.='
    '; + $linkback = '' . $langs->trans("BackToList") . ' '; - $object->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + + dol_banner_tab($object, 'ref', $linkback, ($user->societe_id ? 0 : 1), 'ref', 'ref', $morehtmlref); dol_fiche_end(); diff --git a/htdocs/ticketsup/history.php b/htdocs/ticketsup/history.php index 6994cbeafc1..56f8e95fe0b 100644 --- a/htdocs/ticketsup/history.php +++ b/htdocs/ticketsup/history.php @@ -110,20 +110,29 @@ if ($action == 'view') { $object->next_prev_filter = "te.fk_soc = '" . $user->societe_id . "'"; } $head = ticketsup_prepare_head($object); + dol_fiche_head($head, 'tabTicketLogs', $langs->trans("Ticket"), 0, 'ticketsup'); - $object->label = $object->ref; + + $morehtmlref ='
    '; + $morehtmlref.= $object->subject; // Author if ($object->fk_user_create > 0) { - $object->label .= ' - ' . $langs->trans("CreatedBy") . ' '; - $langs->load("users"); - $fuser = new User($db); - $fuser->fetch($object->fk_user_create); - $object->label .= $fuser->getNomUrl(0); + $morehtmlref .= '
    ' . $langs->trans("CreatedBy") . ' '; + + $langs->load("users"); + $fuser = new User($db); + $fuser->fetch($object->fk_user_create); + $morehtmlref .= $fuser->getNomUrl(0); } + if (!empty($object->origin_email)) { + $morehtmlref .= '
    ' . $langs->trans("CreatedBy") . ' '; + $morehtmlref .= $object->origin_email . ' (' . $langs->trans("TicketEmailOriginIssuer") . ')'; + } + $morehtmlref.='
    '; + $linkback = '' . $langs->trans("BackToList") . ' '; - // TODO Merge this with dol_banner_tab - $object->ticketsupBannerTab('ref', '', ($user->societe_id ? 0 : 1), 'ref', 'subject', '', '', '', $morehtmlleft, $linkback); + dol_banner_tab($object, 'ref', $linkback, ($user->societe_id ? 0 : 1), 'ref', 'ref', $morehtmlref); dol_fiche_end(); diff --git a/htdocs/ticketsup/new.php b/htdocs/ticketsup/new.php index c784d5f04ac..605db702c4a 100644 --- a/htdocs/ticketsup/new.php +++ b/htdocs/ticketsup/new.php @@ -38,7 +38,7 @@ $id = GETPOST('id', 'int'); $socid = GETPOST('socid', 'int'); $contactid = GETPOST('contactid', 'int'); $msg_id = GETPOST('msg_id', 'int'); -$notNotifyTiers = GETPOST("not_notify_tiers_at_create", 'alpha'); +$notifyTiers = GETPOST("notify_tiers_at_create", 'alpha'); $action = GETPOST('action', 'alpha', 3); @@ -78,7 +78,7 @@ if ($action == 'create_ticket') { $formticket->withfromsocid = $socid ? $socid : $user->societe_id; $formticket->withfromcontactid = $contactid ? $contactid : ''; $formticket->withtitletopic = 1; - $formticket->withnotnotifytiersatcreate = $notnotifytiersatcreate?1:0; + $formticket->withnotifytiersatcreate = ($notifyTiers?1:0); $formticket->withusercreate = 1; $formticket->withref = 1; $formticket->fk_user_create = $user->id; From 1bb4f3e07a5fb550aeca93e70bdb020eefa2cc36 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 18 Mar 2018 20:20:10 +0100 Subject: [PATCH 399/413] Dolibarrize module ticket --- htdocs/langs/en_US/ticketsup.lang | 2 +- htdocs/theme/eldy/style.css.php | 7 +++++-- htdocs/ticketsup/class/actions_ticketsup.class.php | 2 +- htdocs/ticketsup/index.php | 3 +++ htdocs/ticketsup/list.php | 2 +- 5 files changed, 11 insertions(+), 5 deletions(-) diff --git a/htdocs/langs/en_US/ticketsup.lang b/htdocs/langs/en_US/ticketsup.lang index 2ef8e473e0a..60f98a8e543 100644 --- a/htdocs/langs/en_US/ticketsup.lang +++ b/htdocs/langs/en_US/ticketsup.lang @@ -180,7 +180,7 @@ TicketMessageSuccessfullyAdded=Message successfully added TicketMessagesList=Message list NoMsgForThisTicket=No message for this ticket Properties=Classification -LatestNewTickets=Last %s tickets newest (not read) +LatestNewTickets=Latest %s newest tickets (not read) TicketSeverity=Severity ShowTicket=See ticket RelatedTickets=Related tickets diff --git a/htdocs/theme/eldy/style.css.php b/htdocs/theme/eldy/style.css.php index c3ed6e76ab5..157fa85e77d 100644 --- a/htdocs/theme/eldy/style.css.php +++ b/htdocs/theme/eldy/style.css.php @@ -830,6 +830,9 @@ div.fiche>form>div.div-table-responsive { div.fiche>div.tabBar>form>div.div-table-responsive { min-height: 392px; } +div.fiche { + text-align: justify; +} .flexcontainer { browser->name, array('chrome','firefox'))) echo 'display: inline-flex;'."\n"; ?> @@ -3117,8 +3120,8 @@ ul.noborder li:nth-child(even):not(.liste_titre) { { .boxstats, .boxstats130 { margin: 3px; - border: 1px solid #ccc; - box-shadow: none; + /*border: 1px solid #ccc; + box-shadow: none; */ } .boxstats130 { text-align: diff --git a/htdocs/ticketsup/class/actions_ticketsup.class.php b/htdocs/ticketsup/class/actions_ticketsup.class.php index 4d0acda3e35..08c28ad3085 100644 --- a/htdocs/ticketsup/class/actions_ticketsup.class.php +++ b/htdocs/ticketsup/class/actions_ticketsup.class.php @@ -464,7 +464,7 @@ class ActionsTicketsup if ($this->fetch(GETPOST('id', 'int'), GETPOST('track_id', 'alpha')) >= 0) { if ($object->delete($user) > 0) { setEventMessages('
    ' . $langs->trans('TicketDeletedSuccess') . '
    ', null, 'mesgs'); - Header("Location: index.php"); + Header("Location: ".DOL_URL_ROOT."/ticketsup/list.php"); exit; } else { $langs->load("errors"); diff --git a/htdocs/ticketsup/index.php b/htdocs/ticketsup/index.php index 2274ae0b889..cef4faa80ba 100644 --- a/htdocs/ticketsup/index.php +++ b/htdocs/ticketsup/index.php @@ -300,6 +300,8 @@ if ($result) { $i = 0; $transRecordedType = $langs->trans("LatestNewTickets", $max); + + print '
    '; print ''; print ''; print ''; @@ -355,6 +357,7 @@ if ($result) { } print "
    ' . $transRecordedType . '' . $langs->trans('Ref') . '
    "; + print '
    '; } else { dol_print_error($db); } diff --git a/htdocs/ticketsup/list.php b/htdocs/ticketsup/list.php index a54394522f8..934a528763e 100644 --- a/htdocs/ticketsup/list.php +++ b/htdocs/ticketsup/list.php @@ -17,7 +17,7 @@ */ /** - * Tickets List + * Tickets List * * @package ticketsup */ From 9c221c10aa57104e8f63fa40fcfd5c44c1cf04b5 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 18 Mar 2018 21:04:16 +0100 Subject: [PATCH 400/413] Load trans --- htdocs/societe/paymentmodes.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 8d0d1891b84..a63d55c5e8f 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -39,7 +39,7 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; -$langs->loadLangs(array("companies","commercial","banks","bills")); +$langs->loadLangs(array("companies","commercial","banks","bills",'paypal','stripe')); // Security check From 7e488c7ccdc38c3638f9e82710965d3de85725b8 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 18 Mar 2018 22:11:30 +0100 Subject: [PATCH 401/413] Trans --- htdocs/langs/en_US/stripe.lang | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index df42e31878a..dcf94d4a17b 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -61,3 +61,4 @@ DeleteACard=Delete Card record ConfirmDeleteCard=Are you sure you want to delete this Card record? CreateCustomerOnStripe=Create customer on Stripe CreateCardOnStripe=Create card on Stripe +ShowInStripe=Show in Stripe \ No newline at end of file From 6a6cf956b1afe9a05d2ecf61cfbf09c2611e4595 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 18 Mar 2018 23:32:06 +0100 Subject: [PATCH 402/413] FIX update of nb of period of loan --- htdocs/loan/card.php | 4 ++-- htdocs/loan/class/loan.class.php | 11 +++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/htdocs/loan/card.php b/htdocs/loan/card.php index 06e0066968d..59b4da544db 100644 --- a/htdocs/loan/card.php +++ b/htdocs/loan/card.php @@ -182,8 +182,8 @@ if (empty($reshook)) $object->datestart = $datestart; $object->dateend = $dateend; $object->capital = $capital; - $object->nbterm = GETPOST("nbterm"); - $object->rate = GETPOST("rate"); + $object->nbterm = GETPOST("nbterm",'int'); + $object->rate = price2num(GETPOST("rate",'alpha')); $accountancy_account_capital = GETPOST('accountancy_account_capital'); $accountancy_account_insurance = GETPOST('accountancy_account_insurance'); diff --git a/htdocs/loan/class/loan.class.php b/htdocs/loan/class/loan.class.php index 19e8f5f84bf..1de0e908c97 100644 --- a/htdocs/loan/class/loan.class.php +++ b/htdocs/loan/class/loan.class.php @@ -292,11 +292,18 @@ class Loan extends CommonObject { $this->db->begin(); + if (! is_numeric($this->nbterm)) + { + $this->error='BadValueForParameterForNbTerm'; + return -1; + } + $sql = "UPDATE ".MAIN_DB_PREFIX."loan"; $sql.= " SET label='".$this->db->escape($this->label)."',"; $sql.= " capital='".price2num($this->db->escape($this->capital))."',"; $sql.= " datestart='".$this->db->idate($this->datestart)."',"; $sql.= " dateend='".$this->db->idate($this->dateend)."',"; + $sql.= " nbterm=".$this->nbterm.","; $sql.= " accountancy_account_capital = '".$this->db->escape($this->account_capital)."',"; $sql.= " accountancy_account_insurance = '".$this->db->escape($this->account_insurance)."',"; $sql.= " accountancy_account_interest = '".$this->db->escape($this->account_interest)."',"; @@ -431,12 +438,12 @@ class Loan extends CommonObject $linkstart = ''; $linkend = ''; - + $result .= $linkstart; if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); if ($withpicto != 2) $result.= ($maxlen?dol_trunc($this->ref,$maxlen):$this->ref); $result .= $linkend; - + return $result; } From 8223047d4a6b457cda1c299a248c8859fd8a035f Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 18 Mar 2018 23:37:28 +0100 Subject: [PATCH 403/413] South africa vat rates --- htdocs/install/mysql/data/llx_c_tva.sql | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/htdocs/install/mysql/data/llx_c_tva.sql b/htdocs/install/mysql/data/llx_c_tva.sql index 9d343f46a8f..47fccc476a8 100644 --- a/htdocs/install/mysql/data/llx_c_tva.sql +++ b/htdocs/install/mysql/data/llx_c_tva.sql @@ -259,6 +259,10 @@ INSERT INTO llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) VALUES (20 INSERT INTO llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) VALUES (2022, 202,'9.5', '0', 'VAT reduced rate', 1); INSERT INTO llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) VALUES (2023, 202, '0', '0', 'VAT Rate 0', 1); +-- SOUTH AFRICA (id country=205) +INSERT INTO llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) VALUES (2051, 205, '15', '0', 'VAT standard rate', 1); +INSERT INTO llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) VALUES (2053, 205, '0', '0', 'VAT Rate 0', 1); + -- SPAIN (id country=4) insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,localtax1,localtax1_type,localtax2,localtax2_type,note,active) values ( 41, 4,'21','0','5.2','3','-19:-15:-9','5','VAT standard rate',1); insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,localtax1,localtax1_type,localtax2,localtax2_type,note,active) values ( 42, 4,'10','0','1.4','3','-19:-15:-9','5','VAT reduced rate',1); From 39228f6221c4aaae3886f2273fd9f0b9e8eb56c3 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sun, 18 Mar 2018 23:37:46 +0100 Subject: [PATCH 404/413] South africa vat rates --- htdocs/install/mysql/data/llx_00_c_country.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/install/mysql/data/llx_00_c_country.sql b/htdocs/install/mysql/data/llx_00_c_country.sql index 45cf8622355..5db58817dd2 100644 --- a/htdocs/install/mysql/data/llx_00_c_country.sql +++ b/htdocs/install/mysql/data/llx_00_c_country.sql @@ -232,7 +232,7 @@ INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (20 INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (202,'SI','SVN','Slovénie',1,0); INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (203,'SB','SLB','Iles Salomon',1,0); INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (204,'SO','SOM','Somalie',1,0); -INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (205,'ZA','ZAF','Afrique du Sud',1,0); +INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (205,'ZA','ZAF','South Africa',1,0); INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (206,'GS','SGS','Iles Géorgie du Sud et Sandwich du Sud',1,0); INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (207,'LK','LKA','Sri Lanka',1,0); INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (208,'SD','SDN','Soudan',1,0); From 9aa4a905438e87a47efc24f78534a0b0a7b7cb8c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 19 Mar 2018 10:57:19 +0100 Subject: [PATCH 405/413] NEW Stripe online payments reuse the same stripe customer account --- htdocs/langs/en_US/stripe.lang | 2 +- htdocs/public/payment/newpayment.php | 162 ++++++++++++++++++++------- htdocs/public/stripe/newpayment.php | 4 +- htdocs/societe/card.php | 6 +- 4 files changed, 125 insertions(+), 49 deletions(-) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index dcf94d4a17b..536fb3f940d 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -39,7 +39,7 @@ STRIPE_TEST_WEBHOOK_KEY=Webhook test key STRIPE_LIVE_SECRET_KEY=Secret live key STRIPE_LIVE_PUBLISHABLE_KEY=Publishable live key STRIPE_LIVE_WEBHOOK_KEY=Webhook live key -ONLINE_PAYMENT_WAREHOUSE=Stock to use for stock decrease when payment online payment is done
    (TODO When option to decrease stock is done on an action on invoice and the online payment generate itself the invoice ?) +ONLINE_PAYMENT_WAREHOUSE=Stock to use for stock decrease when online payment is done
    (TODO When option to decrease stock is done on an action on invoice and the online payment generate itself the invoice ?) StripeLiveEnabled=Stripe live enabled (otherwise test/sandbox mode) StripeImportPayment=Import Stripe payments ExampleOfTestCreditCard=Example of credit card for test: %s (valid), %s (error CVC), %s (expired), %s (charge fails) diff --git a/htdocs/public/payment/newpayment.php b/htdocs/public/payment/newpayment.php index 7230170e1aa..96baf02c7d8 100644 --- a/htdocs/public/payment/newpayment.php +++ b/htdocs/public/payment/newpayment.php @@ -41,17 +41,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; // Security check // No check on module enabled. Done later according to $validpaymentmethod -$langs->load("main"); -$langs->load("other"); -$langs->load("dict"); -$langs->load("bills"); -$langs->load("companies"); -$langs->load("errors"); -$langs->load("paybox"); // File with generic data +$langs->loadLangs(array("main","other","dict","bills","companies","errors","paybox")); // File with generic data $action=GETPOST('action','aZ09'); @@ -273,16 +268,17 @@ if ($action == 'dopayment') $PAYPAL_PAYMENT_TYPE='Sale'; $origfulltag=GETPOST("fulltag",'alpha'); - $shipToName=GETPOST("shipToName"); - $shipToStreet=GETPOST("shipToStreet"); - $shipToCity=GETPOST("shipToCity"); - $shipToState=GETPOST("shipToState"); - $shipToCountryCode=GETPOST("shipToCountryCode"); - $shipToZip=GETPOST("shipToZip"); - $shipToStreet2=GETPOST("shipToStreet2"); - $phoneNum=GETPOST("phoneNum"); - $email=GETPOST("email"); + $shipToName=GETPOST("shipToName",'alpha'); + $shipToStreet=GETPOST("shipToStreet",'alpha'); + $shipToCity=GETPOST("shipToCity",'alpha'); + $shipToState=GETPOST("shipToState",'alpha'); + $shipToCountryCode=GETPOST("shipToCountryCode",'alpha'); + $shipToZip=GETPOST("shipToZip",'alpha'); + $shipToStreet2=GETPOST("shipToStreet2",'alpha'); + $phoneNum=GETPOST("phoneNum",'alpha'); + $email=GETPOST("email",'alpha'); $desc=GETPOST("desc",'alpha'); + $thirdparty_id=GETPOST('thirdparty_id', 'int'); $mesg=''; if (empty($PAYPAL_API_PRICE) || ! is_numeric($PAYPAL_API_PRICE)) @@ -347,7 +343,8 @@ if ($action == 'dopayment') if ($paymentmethod == 'paybox') { $PRICE=price2num(GETPOST("newamount"),'MT'); - $email=GETPOST("email"); + $email=GETPOST("email",'alpha'); + $thirdparty_id=GETPOST('thirdparty_id', 'int'); $origfulltag=GETPOST("fulltag",'alpha'); @@ -388,7 +385,7 @@ if ($action == 'dopayment') // Called when choosing Stripe mode, after the 'dopayment' -if ($action == 'charge') +if ($action == 'charge' && ! empty($conf->stripe->enabled)) { $amountstripe = $amount; @@ -401,36 +398,112 @@ if ($action == 'charge') dol_syslog("POST values: ".join(',', $_POST), LOG_DEBUG, 0, '_stripe'); $stripeToken = GETPOST("stripeToken",'alpha'); - $email = GETPOST("stripeEmail",'alpha'); + $email = GETPOST("email",'alpha'); + $thirdparty_id=GETPOST('thirdparty_id', 'int'); $vatnumber = GETPOST('vatnumber','alpha'); dol_syslog("stripeToken = ".$stripeToken, LOG_DEBUG, 0, '_stripe'); dol_syslog("email = ".$email, LOG_DEBUG, 0, '_stripe'); + dol_syslog("thirdparty_id = ".$thirdparty_id, LOG_DEBUG, 0, '_stripe'); dol_syslog("vatnumber = ".$vatnumber, LOG_DEBUG, 0, '_stripe'); $error = 0; try { - dol_syslog("Create customer card profile", LOG_DEBUG, 0, '_stripe'); - $customer = \Stripe\Customer::create(array( - 'email' => $email, - 'description' => ($email?'Customer card profile for '.$email:null), - 'metadata' => array('ipaddress'=>$_SERVER['REMOTE_ADDR']), - 'business_vat_id' => ($vatnumber?$vatnumber:null), - 'source' => $stripeToken // source can be a token OR array('object'=>'card', 'exp_month'=>xx, 'exp_year'=>xxxx, 'number'=>xxxxxxx, 'cvc'=>xxx, 'name'=>'Cardholder's full name', zip ?) - )); - // Return $customer = array('id'=>'cus_XXXX', ...) + $metadata = array( + 'dol_version'=>DOL_VERSION, + 'dol_entity'=>$conf->entity, + 'ipaddress'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR']) + ); + if (! empty($dol_id)) $metadata["dol_id"] = $dol_id; + if (! empty($dol_type)) $metadata["dol_type"] = $dol_type; + if (! empty($thirdparty_id)) $metadata["dol_thirdparty_id"] = $thirdparty_id; - dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe'); - $charge = \Stripe\Charge::create(array( - 'customer' => $customer->id, - 'amount' => price2num($amountstripe, 'MU'), - 'currency' => $currency, - 'description' => 'Stripe payment: '.$FULLTAG, - 'metadata' => array("FULLTAG" => $FULLTAG, 'Recipient' => $mysoc->name), - 'statement_descriptor' => dol_trunc(dol_trunc(dol_string_unaccent($mysoc->name), 6, 'right', 'UTF-8', 1).' '.$FULLTAG, 22, 'right', 'UTF-8', 1) // 22 chars that appears on bank receipt - )); - // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) + if ($thirdparty_id > 0) + { + dol_syslog("Search existing customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_stripe'); + + $service = 'StripeTest'; + $servicestatus = 0; + if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox','alpha')) + { + $service = 'StripeLive'; + $servicestatus = 1; + } + $stripeacc = null; // No Oauth/connect use for public pages + + $thirdparty = new Societe($db); + $thirdparty->fetch($thirdparty_id); + + include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; + $stripe = new Stripe($db); + $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1); + + $card = $customer->sources->create(array("source" => $stripeToken, "metadata" => $metadata)); + + if (empty($card)) + { + $error++; + dol_syslog('Failed to create card record', LOG_WARNING, 0, '_stripe'); + setEventMessages('Failed to create card record', null, 'errors'); + $action=''; + } + else + { + dol_syslog("Create charge on card ".$card->id, LOG_DEBUG, 0, '_stripe'); + $charge = \Stripe\Charge::create(array( + 'amount' => price2num($amountstripe, 'MU'), + 'currency' => $currency, + 'capture' => true, // Charge immediatly + 'description' => 'Stripe payment: '.$FULLTAG, + 'metadata' => array("FULLTAG" => $FULLTAG, 'Recipient' => $mysoc->name, 'dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR'])), + 'customer' => $customer->id, + 'source' => $card, + 'statement_descriptor' => dol_trunc(dol_trunc(dol_string_unaccent($mysoc->name), 6, 'right', 'UTF-8', 1).' '.$FULLTAG, 22, 'right', 'UTF-8', 1) // 22 chars that appears on bank receipt + )); + // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) + if (empty($charge)) + { + $error++; + dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); + setEventMessages('Failed to charge card', null, 'errors'); + $action=''; + } + } + } + else + { + dol_syslog("Create anonymous customer card profile", LOG_DEBUG, 0, '_stripe'); + $customer = \Stripe\Customer::create(array( + 'email' => $email, + 'description' => ($email?'Anonymous customer for '.$email:'Anonymous customer'), + 'metadata' => $metadata, + 'business_vat_id' => ($vatnumber?$vatnumber:null), + 'source' => $stripeToken // source can be a token OR array('object'=>'card', 'exp_month'=>xx, 'exp_year'=>xxxx, 'number'=>xxxxxxx, 'cvc'=>xxx, 'name'=>'Cardholder's full name', zip ?) + )); + // Return $customer = array('id'=>'cus_XXXX', ...) + + // The customer was just created with a source, so we can make a charge + // with no card defined, the source just used for customer creation will be used. + dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe'); + $charge = \Stripe\Charge::create(array( + 'customer' => $customer->id, + 'amount' => price2num($amountstripe, 'MU'), + 'currency' => $currency, + 'capture' => true, // Charge immediatly + 'description' => 'Stripe payment: '.$FULLTAG, + 'metadata' => array("FULLTAG" => $FULLTAG, 'Recipient' => $mysoc->name, 'dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR'])), + 'statement_descriptor' => dol_trunc(dol_trunc(dol_string_unaccent($mysoc->name), 6, 'right', 'UTF-8', 1).' '.$FULLTAG, 22, 'right', 'UTF-8', 1) // 22 chars that appears on bank receipt + )); + // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) + if (empty($charge)) + { + $error++; + dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); + setEventMessages('Failed to charge card', null, 'errors'); + $action=''; + } + } } catch(\Stripe\Error\Card $e) { // Since it's a decline, \Stripe\Error\Card will be caught $body = $e->getJsonBody(); @@ -444,8 +517,8 @@ if ($action == 'charge') print('Message is:' . $err['message'] . "\n"); $error++; - setEventMessages($e->getMessage(), null, 'errors'); dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); $action=''; } catch (\Stripe\Error\RateLimit $e) { // Too many requests made to the API too quickly @@ -794,8 +867,9 @@ if ($source == 'order') { print ''."\n"; } + print ''."\n"; print ''."\n"; - print ''."\n"; + print ''."\n"; $labeldesc=$langs->trans("Order").' '.$order->ref; if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); print ''."\n"; @@ -928,8 +1002,9 @@ if ($source == 'invoice') { print ''."\n"; } + print ''."\n"; print ''."\n"; - print ''."\n"; + print ''."\n"; $labeldesc=$langs->trans("Invoice").' '.$invoice->ref; if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); print ''."\n"; @@ -1135,8 +1210,9 @@ if ($source == 'contractline') { print ''."\n"; } + print ''."\n"; print ''."\n"; - print ''."\n"; + print ''."\n"; $labeldesc=$langs->trans("Contract").' '.$contract->ref; if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); print ''."\n"; @@ -1438,6 +1514,8 @@ if (preg_match('/^dopayment/',$action)) print ''."\n"; print ''."\n"; print ''; + print ''; + print ''; print ' diff --git a/htdocs/public/stripe/newpayment.php b/htdocs/public/stripe/newpayment.php index fc04ef87f1a..9291b2af615 100644 --- a/htdocs/public/stripe/newpayment.php +++ b/htdocs/public/stripe/newpayment.php @@ -219,7 +219,7 @@ if ($action == 'charge') dol_syslog("POST values: ".join(',', $_POST), LOG_DEBUG, 0, '_stripe'); $stripeToken = GETPOST("stripeToken",'alpha'); - $email = GETPOST("stripeEmail",'alpha'); + $email = GETPOST("email",'alpha'); $vatnumber = GETPOST('vatnumber','alpha'); dol_syslog("stripeToken = ".$stripeToken, LOG_DEBUG, 0, '_stripe'); @@ -1149,6 +1149,8 @@ if (preg_match('/^dopayment/',$action)) print ''."\n"; print ''."\n"; print ''; + print ''; + print ''; print '
    diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index e515818cd3d..4a5f3ab87bd 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -46,11 +46,7 @@ require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; if (! empty($conf->adherent->enabled)) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -$langs->load("companies"); -$langs->load("commercial"); -$langs->load("bills"); -$langs->load("banks"); -$langs->load("users"); +$langs->loadLangs(array("companies","commercial","bills","banks","users")); if (! empty($conf->categorie->enabled)) $langs->load("categories"); if (! empty($conf->incoterm->enabled)) $langs->load("incoterm"); if (! empty($conf->notification->enabled)) $langs->load("mails"); From 6ca40bcbd46adfc487910a30019757679d9a46d2 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 19 Mar 2018 11:01:44 +0100 Subject: [PATCH 406/413] Fix translation --- htdocs/langs/en_US/companies.lang | 8 ++++---- htdocs/langs/en_US/mails.lang | 2 +- htdocs/langs/en_US/main.lang | 2 +- htdocs/langs/en_US/margins.lang | 2 +- htdocs/langs/en_US/ticketsup.lang | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index f195da762a8..aec9c1e1a93 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -389,8 +389,8 @@ NoDolibarrAccess=No Dolibarr access ExportDataset_company_1=Third parties (Companies / foundations / physical people) and properties ExportDataset_company_2=Contacts and properties ImportDataset_company_1=Third parties (Companies / foundations / physical people) and properties -ImportDataset_company_2=Contacts/Addresses (of thirdparties or not) and attributes -ImportDataset_company_3=Bank accounts of thirdparties +ImportDataset_company_2=Contacts/Addresses (of third parties or not) and attributes +ImportDataset_company_3=Bank accounts of third parties ImportDataset_company_4=Third parties/Sales representatives (Assign sales representatives users to companies) PriceLevel=Price level DeliveryAddress=Delivery address @@ -425,9 +425,9 @@ ManagingDirectors=Manager(s) name (CEO, director, president...) MergeOriginThirdparty=Duplicate third party (third party you want to delete) MergeThirdparties=Merge third parties ConfirmMergeThirdparties=Are you sure you want to merge this third party into the current one? All linked objects (invoices, orders, ...) will be moved to current third party, then the thirdparty will be deleted. -ThirdpartiesMergeSuccess=Thirdparties have been merged +ThirdpartiesMergeSuccess=Third parties have been merged SaleRepresentativeLogin=Login of sales representative SaleRepresentativeFirstname=First name of sales representative SaleRepresentativeLastname=Last name of sales representative -ErrorThirdpartiesMerge=There was an error when deleting the thirdparties. Please check the log. Changes have been reverted. +ErrorThirdpartiesMerge=There was an error when deleting the third parties. Please check the log. Changes have been reverted. NewCustomerSupplierCodeProposed=New customer or supplier code suggested on duplicate code diff --git a/htdocs/langs/en_US/mails.lang b/htdocs/langs/en_US/mails.lang index 8e2b093fdc2..3c512ca7286 100644 --- a/htdocs/langs/en_US/mails.lang +++ b/htdocs/langs/en_US/mails.lang @@ -135,7 +135,7 @@ NbOfTargetedContacts=Current number of targeted contact emails UseFormatFileEmailToTarget=Imported file must have format email;name;firstname;other UseFormatInputEmailToTarget=Enter a string with format email;name;firstname;other MailAdvTargetRecipients=Recipients (advanced selection) -AdvTgtTitle=Fill input fields to preselect the thirdparties or contacts/addresses to target +AdvTgtTitle=Fill input fields to preselect the third parties or contacts/addresses to target AdvTgtSearchTextHelp=Use %% as magic caracters. For exemple to find all item like jean, joe, jim, you can input j%%, you can also use ; as separator for value, and use ! for except this value. For exemple jean;joe;jim%%;!jimo;!jima% will target all jean, joe, start with jim but not jimo and not everythnig taht start by jima AdvTgtSearchIntHelp=Use interval to select int or float value AdvTgtMinVal=Minimum value diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index c1027e20466..52dd0aba17e 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -904,7 +904,7 @@ Select2MoreCharacters=or more characters Select2MoreCharactersMore=Search syntax:
    | OR (a|b)
    * Any character (a*b)
    ^ Start with (^ab)
    $ End with (ab$)
    Select2LoadingMoreResults=Loading more results... Select2SearchInProgress=Search in progress... -SearchIntoThirdparties=Thirdparties +SearchIntoThirdparties=Third parties SearchIntoContacts=Contacts SearchIntoMembers=Members SearchIntoUsers=Users diff --git a/htdocs/langs/en_US/margins.lang b/htdocs/langs/en_US/margins.lang index 8633d910657..8a8a9f20788 100644 --- a/htdocs/langs/en_US/margins.lang +++ b/htdocs/langs/en_US/margins.lang @@ -41,4 +41,4 @@ rateMustBeNumeric=Rate must be a numeric value markRateShouldBeLesserThan100=Mark rate should be lower than 100 ShowMarginInfos=Show margin infos CheckMargins=Margins detail -MarginPerSaleRepresentativeWarning=The report of margin per user use the link between thirdparties and sale representatives to calculate the margin of each salerepresentaive. Because some thirdparties may not have any ddiated sale representative and some thirdparties may be linked to several, some amounts may not be included into this report (if there is no sale representative) and some may appear on different lines (for each sale representative). +MarginPerSaleRepresentativeWarning=The report of margin per user use the link between third parties and sale representatives to calculate the margin of each salerepresentaive. Because some thirdparties may not have any ddiated sale representative and some thirdparties may be linked to several, some amounts may not be included into this report (if there is no sale representative) and some may appear on different lines (for each sale representative). diff --git a/htdocs/langs/en_US/ticketsup.lang b/htdocs/langs/en_US/ticketsup.lang index 60f98a8e543..cabf1c39ec3 100644 --- a/htdocs/langs/en_US/ticketsup.lang +++ b/htdocs/langs/en_US/ticketsup.lang @@ -25,7 +25,7 @@ Permission56001=See tickets Permission56002=Modify tickets Permission56003=Delete tickets Permission56004=Manage tickets -Permission56005=See tickets of all thirdparties (not effective for external users, always be limited to the thirdparty they depend on) +Permission56005=See tickets of all third parties (not effective for external users, always be limited to the thirdparty they depend on) TicketsupDictType=Tickets type TicketsupDictCategory=Tickets categories From 8899b511fdce6bdea16b73fdf495f2ab0729af61 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 19 Mar 2018 11:28:55 +0100 Subject: [PATCH 407/413] FIX Make a redirect after the remove_file action to avoid deletion done at next action too. --- htdocs/core/actions_builddoc.inc.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/htdocs/core/actions_builddoc.inc.php b/htdocs/core/actions_builddoc.inc.php index ff7a89484fa..9d33def496c 100644 --- a/htdocs/core/actions_builddoc.inc.php +++ b/htdocs/core/actions_builddoc.inc.php @@ -124,5 +124,13 @@ if ($action == 'remove_file' && $permissioncreate) $ret=dol_delete_file($file,0,0,0,$object); if ($ret) setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs'); else setEventMessages($langs->trans("ErrorFailToDeleteFile", $filetodelete), null, 'errors'); + + // Make a redirect to avoid to keep the remove_file into the url that create side effects + $urltoredirect = $_SERVER['REQUEST_URI']; + $urltoredirect = preg_replace('/#builddoc$/', '', $urltoredirect); + $urltoredirect = preg_replace('/action=remove_file&?/', '', $urltoredirect); + + header('Location: '.$urltoredirect); + exit; } From 5db718448f4ad77bb07a28834c99cbdfc35b78ab Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 19 Mar 2018 11:29:06 +0100 Subject: [PATCH 408/413] Delete at end --- htdocs/projet/list.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/projet/list.php b/htdocs/projet/list.php index 90f0fc56755..22887c5e42d 100644 --- a/htdocs/projet/list.php +++ b/htdocs/projet/list.php @@ -435,8 +435,8 @@ $arrayofmassactions = array( // 'builddoc'=>$langs->trans("PDFMerge"), ); //if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); -if ($user->rights->societe->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete"); if ($user->rights->projet->creer) $arrayofmassactions['close']=$langs->trans("Close"); +if ($user->rights->societe->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete"); if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); From f8ca4b1b5cd9cfd1a1079a373421b8904235981a Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 19 Mar 2018 11:34:48 +0100 Subject: [PATCH 409/413] NEW Add option BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD --- htdocs/core/class/commonobject.class.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 0e3719d2427..64e1d05657b 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -4338,8 +4338,10 @@ abstract class CommonObject if ($useonlinesignature) $setsharekey=true; if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; } - if ($this->element == 'commande' && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; - if ($this->element == 'facture' && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($this->element == 'commande' && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($this->element == 'facture' && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($this->element == 'bank_account' && ! empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($setsharekey) { if (empty($ecmfile->share)) // Because object not found or share not set yet From f46df6d8e5003e1dc55880b79d52ecc029cf1db4 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 19 Mar 2018 11:49:05 +0100 Subject: [PATCH 410/413] Can resize and crop images in the ticketsup module --- htdocs/commande/document.php | 1 + htdocs/core/class/html.formfile.class.php | 4 ++-- htdocs/core/photos_resize.php | 23 ++++++++++++++++++++++- htdocs/langs/en_US/main.lang | 1 + htdocs/ticketsup/document.php | 23 +++++++++++------------ 5 files changed, 37 insertions(+), 15 deletions(-) diff --git a/htdocs/commande/document.php b/htdocs/commande/document.php index ee688bed307..5a3f0c1973f 100644 --- a/htdocs/commande/document.php +++ b/htdocs/commande/document.php @@ -69,6 +69,7 @@ $object = new Commande($db); /* * Actions */ + if ($object->fetch($id)) { $object->fetch_thirdparty(); diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index 5eef895bb0c..251a03399d7 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -1226,14 +1226,14 @@ class FormFile if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service'; $disablecrop=1; - if (in_array($modulepart, array('societe','product','produit','service','expensereport','holiday','project','user'))) $disablecrop=0; + if (in_array($modulepart, array('societe','product','produit','service','expensereport','holiday','project','ticketsup','user'))) $disablecrop=0; if (! $disablecrop && image_format_supported($file['name']) > 0) { if ($permtoeditline) { // Link to resize - print ''.img_picto($langs->trans("Resize"),'resize','class="paddingrightonly"').''; + print ''.img_picto($langs->trans("ResizeOrCrop"),'resize','class="paddingrightonly"').''; } } diff --git a/htdocs/core/photos_resize.php b/htdocs/core/photos_resize.php index 9a11523f39b..c40a9b26c66 100644 --- a/htdocs/core/photos_resize.php +++ b/htdocs/core/photos_resize.php @@ -77,6 +77,12 @@ elseif ($modulepart == 'societe') if (! $user->rights->societe->lire) accessforbidden(); $accessallowed=1; } +elseif ($modulepart == 'ticketsup') +{ + $result=restrictedArea($user,'ticketsup',$id,'ticketsup'); + if (! $user->rights->ticketsup->read) accessforbidden(); + $accessallowed=1; +} // Security: // Limit access if permissions are wrong @@ -154,6 +160,20 @@ elseif ($modulepart == 'expensereport') $dir=$conf->expensereport->dir_output; // By default } } +elseif ($modulepart == 'ticketsup') +{ + require_once DOL_DOCUMENT_ROOT.'/ticketsup/class/ticketsup.class.php'; + $object = new Ticketsup($db); + if ($id > 0) + { + $result = $object->fetch($id); + if ($result <= 0) dol_print_error($db,'Failed to load object'); + $dir=$conf->ticketsup->dir_output; // By default + } +} +else { + print 'Action crop for module part '.$modulepart.' is not supported yet.'; +} if (empty($backtourl)) { @@ -161,8 +181,9 @@ if (empty($backtourl)) else if (in_array($modulepart, array('expensereport'))) $backtourl=DOL_URL_ROOT."/expensereport/document.php?id=".$id.'&file='.urldecode($_POST["file"]); else if (in_array($modulepart, array('holiday'))) $backtourl=DOL_URL_ROOT."/holiday/document.php?id=".$id.'&file='.urldecode($_POST["file"]); else if (in_array($modulepart, array('project'))) $backtourl=DOL_URL_ROOT."/projet/document.php?id=".$id.'&file='.urldecode($_POST["file"]); - else if (in_array($modulepart, array('user'))) $backtourl=DOL_URL_ROOT."/user/document.php?id=".$id.'&file='.urldecode($_POST["file"]); else if (in_array($modulepart, array('societe'))) $backtourl=DOL_URL_ROOT."/societe/document.php?id=".$id.'&file='.urldecode($_POST["file"]); + else if (in_array($modulepart, array('ticketsup'))) $backtourl=DOL_URL_ROOT."/ticketsup/document.php?id=".$id.'&file='.urldecode($_POST["file"]); + else if (in_array($modulepart, array('user'))) $backtourl=DOL_URL_ROOT."/user/document.php?id=".$id.'&file='.urldecode($_POST["file"]); } diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index 52dd0aba17e..2066dfa4760 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -185,6 +185,7 @@ ToLink=Link Select=Select Choose=Choose Resize=Resize +ResizeOrCrop=Resize or Crop Recenter=Recenter Author=Author User=User diff --git a/htdocs/ticketsup/document.php b/htdocs/ticketsup/document.php index a19a972c143..94348e1054c 100644 --- a/htdocs/ticketsup/document.php +++ b/htdocs/ticketsup/document.php @@ -33,12 +33,10 @@ require_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php"; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; -$langs->load("companies"); -$langs->load('other'); -$langs->load("ticketsup"); +$langs->loadLangs(array("companies","other","ticketsup")); -$action = GETPOST('action'); -$confirm = GETPOST('confirm'); +$action = GETPOST('action','alpha'); +$confirm = GETPOST('confirm','alpha'); $id = GETPOST('id', 'int'); $track_id = GETPOST('track_id', 'alpha'); $ref = GETPOST('ref', 'alpha'); @@ -61,7 +59,6 @@ $pagenext = $page + 1; if (!$sortorder) { $sortorder = "ASC"; } - if (!$sortfield) { $sortfield = "name"; } @@ -75,22 +72,22 @@ $object->ref = $object->track_id; if ($result < 0) { - setEventMessage($object->error, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else { $upload_dir = $conf->ticketsup->dir_output . "/" . dol_sanitizeFileName($object->track_id); } + /* * Actions */ -// Included file moved into Dolibarr 4, keep it for compatibility -$res=@include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; -if (! $res) { - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_pre_headers.tpl.php'; -} + +include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; $object->ref = $old_ref; + + /* * View */ @@ -155,10 +152,12 @@ if ($object->id) { foreach ($filearray as $key => $file) { $totalsize += $file['size']; } + // For compatibility we use track ID for directory $object->ref = $object->track_id; $modulepart = 'ticketsup'; $permission = $user->rights->ticketsup->write; + $permtoedit = $user->rights->ticketsup->write; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; From e91ffa00eb9add3b7d2c3ea8a5fd0ffb205cc22e Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 19 Mar 2018 11:56:04 +0100 Subject: [PATCH 411/413] NEW Can crop image files attached in "document" tabs of a member --- htdocs/core/class/html.formfile.class.php | 2 +- htdocs/core/photos_resize.php | 34 +++++++++++++++++------ 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index 251a03399d7..df6f389180f 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -1226,7 +1226,7 @@ class FormFile if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service'; $disablecrop=1; - if (in_array($modulepart, array('societe','product','produit','service','expensereport','holiday','project','ticketsup','user'))) $disablecrop=0; + if (in_array($modulepart, array('societe','product','produit','service','expensereport','holiday','member','project','ticketsup','user'))) $disablecrop=0; if (! $disablecrop && image_format_supported($file['name']) > 0) { diff --git a/htdocs/core/photos_resize.php b/htdocs/core/photos_resize.php index c40a9b26c66..e51e7ee660b 100644 --- a/htdocs/core/photos_resize.php +++ b/htdocs/core/photos_resize.php @@ -53,16 +53,22 @@ elseif ($modulepart == 'project') if (! $user->rights->projet->lire) accessforbidden(); $accessallowed=1; } +elseif ($modulepart == 'expensereport') +{ + $result=restrictedArea($user,'expensereport',$id,'expensereport'); + if (! $user->rights->expensereport->lire) accessforbidden(); + $accessallowed=1; +} elseif ($modulepart == 'holiday') { $result=restrictedArea($user,'holiday',$id,'holiday'); if (! $user->rights->holiday->read) accessforbidden(); $accessallowed=1; } -elseif ($modulepart == 'expensereport') +elseif ($modulepart == 'member') { - $result=restrictedArea($user,'expensereport',$id,'expensereport'); - if (! $user->rights->expensereport->lire) accessforbidden(); + $result=restrictedArea($user, 'adherent', $id, '', '', 'fk_soc', 'rowid'); + if (! $user->rights->adherent->lire) accessforbidden(); $accessallowed=1; } elseif ($modulepart == 'user') @@ -127,6 +133,17 @@ elseif ($modulepart == 'holiday') $dir=$conf->holiday->dir_output; // By default } } +elseif ($modulepart == 'member') +{ + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + $object = new Adherent($db); + if ($id > 0) + { + $result = $object->fetch($id); + if ($result <= 0) dol_print_error($db,'Failed to load object'); + $dir=$conf->adherent->dir_output; // By default + } +} elseif ($modulepart == 'societe') { require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; @@ -179,11 +196,12 @@ if (empty($backtourl)) { if (in_array($modulepart, array('product','produit','service','produit|service'))) $backtourl=DOL_URL_ROOT."/product/document.php?id=".$id.'&file='.urldecode($_POST["file"]); else if (in_array($modulepart, array('expensereport'))) $backtourl=DOL_URL_ROOT."/expensereport/document.php?id=".$id.'&file='.urldecode($_POST["file"]); - else if (in_array($modulepart, array('holiday'))) $backtourl=DOL_URL_ROOT."/holiday/document.php?id=".$id.'&file='.urldecode($_POST["file"]); - else if (in_array($modulepart, array('project'))) $backtourl=DOL_URL_ROOT."/projet/document.php?id=".$id.'&file='.urldecode($_POST["file"]); - else if (in_array($modulepart, array('societe'))) $backtourl=DOL_URL_ROOT."/societe/document.php?id=".$id.'&file='.urldecode($_POST["file"]); - else if (in_array($modulepart, array('ticketsup'))) $backtourl=DOL_URL_ROOT."/ticketsup/document.php?id=".$id.'&file='.urldecode($_POST["file"]); - else if (in_array($modulepart, array('user'))) $backtourl=DOL_URL_ROOT."/user/document.php?id=".$id.'&file='.urldecode($_POST["file"]); + else if (in_array($modulepart, array('holiday'))) $backtourl=DOL_URL_ROOT."/holiday/document.php?id=".$id.'&file='.urldecode($_POST["file"]); + else if (in_array($modulepart, array('member'))) $backtourl=DOL_URL_ROOT."/adherents/document.php?id=".$id.'&file='.urldecode($_POST["file"]); + else if (in_array($modulepart, array('project'))) $backtourl=DOL_URL_ROOT."/projet/document.php?id=".$id.'&file='.urldecode($_POST["file"]); + else if (in_array($modulepart, array('societe'))) $backtourl=DOL_URL_ROOT."/societe/document.php?id=".$id.'&file='.urldecode($_POST["file"]); + else if (in_array($modulepart, array('ticketsup'))) $backtourl=DOL_URL_ROOT."/ticketsup/document.php?id=".$id.'&file='.urldecode($_POST["file"]); + else if (in_array($modulepart, array('user'))) $backtourl=DOL_URL_ROOT."/user/document.php?id=".$id.'&file='.urldecode($_POST["file"]); } From ce3975377d1a1df2a32fa9d80f6dc2a8eff24366 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 19 Mar 2018 12:02:49 +0100 Subject: [PATCH 412/413] Link to unlink is unlink and not remove --- htdocs/core/tpl/contacts.tpl.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/tpl/contacts.tpl.php b/htdocs/core/tpl/contacts.tpl.php index 493a6c88ec7..0ecf01f9dd1 100644 --- a/htdocs/core/tpl/contacts.tpl.php +++ b/htdocs/core/tpl/contacts.tpl.php @@ -229,7 +229,7 @@ if ($permission) { From 5a98958280cce71f618803c60a3abd4bc236f33b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 19 Mar 2018 12:07:08 +0100 Subject: [PATCH 413/413] Update adherent.class.php --- htdocs/adherents/class/adherent.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index d9bca123000..cf120f3871f 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -1614,7 +1614,7 @@ class Adherent extends CommonObject // Generate PDF (whatever is option MAIN_DISABLE_PDF_AUTOUPDATE) so we can include it into email //if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - $invoice->generateDocument($invoice->modelpdf, $outputlangs, 0, 0, 0); + $invoice->generateDocument($invoice->modelpdf, $outputlangs); } }