diff --git a/htdocs/admin/emailcollector_card.php b/htdocs/admin/emailcollector_card.php index 6d1b640f45b..64e784ece9d 100644 --- a/htdocs/admin/emailcollector_card.php +++ b/htdocs/admin/emailcollector_card.php @@ -116,7 +116,7 @@ if (empty($reshook)) if (GETPOST('addfilter', 'alpha')) { $emailcollectorfilter = new EmailCollectorFilter($db); - $emailcollectorfilter->type = GETPOST('filtertype', 'az09'); + $emailcollectorfilter->type = GETPOST('filtertype', 'aZ09'); $emailcollectorfilter->rulevalue = GETPOST('rulevalue', 'alpha'); $emailcollectorfilter->fk_emailcollector = $object->id; $emailcollectorfilter->status = 1; @@ -150,7 +150,7 @@ if ($action == 'deletefilter') if (GETPOST('addoperation', 'alpha')) { $emailcollectoroperation = new EmailCollectorAction($db); - $emailcollectoroperation->type = GETPOST('operationtype', 'az09'); + $emailcollectoroperation->type = GETPOST('operationtype', 'aZ09'); $emailcollectoroperation->actionparam = GETPOST('operationparam', 'none'); $emailcollectoroperation->fk_emailcollector = $object->id; $emailcollectoroperation->status = 1; diff --git a/htdocs/admin/expensereport_extrafields.php b/htdocs/admin/expensereport_extrafields.php index 8d102bc8328..013db3d36f1 100644 --- a/htdocs/admin/expensereport_extrafields.php +++ b/htdocs/admin/expensereport_extrafields.php @@ -63,8 +63,6 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; * View */ -$textobject=$langs->transnoentitiesnoconv("expensereports"); - llxHeader('', $langs->trans("ExpenseReportsSetup")); $linkback=''.$langs->trans("BackToModuleList").''; diff --git a/htdocs/admin/holiday_extrafields.php b/htdocs/admin/holiday_extrafields.php new file mode 100644 index 00000000000..b9c32a8b9c9 --- /dev/null +++ b/htdocs/admin/holiday_extrafields.php @@ -0,0 +1,118 @@ + + * Copyright (C) 2003 Jean-Louis Bergamo + * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2012 Florian Henry + * Copyright (C) 2013 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, see . + */ + +/** + * \file htdocs/admin/holiday_extrafields.php + * \ingroup holiday + * \brief Page to setup extra fields of holiday + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/holiday.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + +if (!$user->admin) + accessforbidden(); + +// Load translation files required by the page +$langs->loadLangs(array('admin', 'errors', 'holiday', 'other')); + +$extrafields = new ExtraFields($db); +$form = new Form($db); + +// List of supported format +$tmptype2label=ExtraFields::$type2label; +$type2label=array(''); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); + +$action=GETPOST('action', 'alpha'); +$attrname=GETPOST('attrname', 'alpha'); +$elementtype='holiday'; //Must be the $table_element of the class that manage extrafield + +if (!$user->admin) accessforbidden(); + + +/* + * Actions + */ + +require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; + + + +/* + * View + */ + +llxHeader('', $langs->trans("HolidaySetup")); + +$linkback=''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans("HolidaySetup"), $linkback, 'title_setup'); + +$head = holiday_admin_prepare_head(); + +dol_fiche_head($head, 'attributes', $langs->trans("Holidays"), -1, 'holiday'); + +require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; + +dol_fiche_end(); + + +// Buttons +if ($action != 'create' && $action != 'edit') +{ + print '
'; + print "".$langs->trans("NewAttribute").""; + print "
"; +} + + +/* ************************************************************************** */ +/* */ +/* Creation of an optional field */ +/* */ +/* ************************************************************************** */ + +if ($action == 'create') +{ + print '
'; + print load_fiche_titre($langs->trans('NewAttribute')); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; +} + +/* ************************************************************************** */ +/* */ +/* Edition of an optional field */ +/* */ +/* ************************************************************************** */ +if ($action == 'edit' && ! empty($attrname)) +{ + print "
"; + print load_fiche_titre($langs->trans("FieldEdition", $attrname)); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php index b62009c2ba6..b5f22376c16 100644 --- a/htdocs/admin/mails_templates.php +++ b/htdocs/admin/mails_templates.php @@ -50,7 +50,7 @@ $confirm = GETPOST('confirm', 'alpha'); // Result of a confirmatio $id = GETPOST('id', 'int'); $rowid = GETPOST('rowid', 'alpha'); -$search_label=GETPOST('search_label', 'alpha'); +$search_label=GETPOST('search_label', 'alphanohtml'); // Must allow value like 'Abc Def' or '(MyTemplateName)' $search_type_template=GETPOST('search_type_template', 'alpha'); $search_lang=GETPOST('search_lang', 'alpha'); $search_fk_user=GETPOST('search_fk_user', 'intcomma'); @@ -263,6 +263,7 @@ if (empty($reshook)) { //var_dump($i.' - '.$listfieldvalue[$i].' - '.$_POST[$listfieldvalue[$i]].' - '.$value); $keycode=$listfieldvalue[$i]; + if ($value == 'label') $_POST[$keycode] = dol_escape_htmltag($_POST[$keycode]); if ($value == 'lang') $keycode='langcode'; if ($value == 'entity') $_POST[$keycode] = $conf->entity; if ($i) $sql.=","; @@ -667,8 +668,6 @@ if ($resql) print ''; foreach ($fieldlist as $field => $value) { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees $showfield=1; // By defaut $align="left"; $sortable=1; @@ -695,7 +694,7 @@ if ($resql) if ($fieldlist[$field]=='content') { $valuetoshow=$langs->trans("Content"); $showfield=0;} if ($fieldlist[$field]=='content_lines') { $valuetoshow=$langs->trans("ContentLines"); $showfield=0; } - // Affiche nom du champ + // Show fields if ($showfield) { if (! empty($tabhelp[$id][$value])) @@ -813,6 +812,10 @@ if ($resql) $showfield=1; $align="left"; $valuetoshow=$obj->{$fieldlist[$field]}; + if ($value == 'label' || $value == 'topic') + { + $valuetoshow = dol_escape_htmltag($valuetoshow); + } if ($value == 'type_template') { $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index 67ef7905235..787e158670f 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -36,7 +36,7 @@ $langs->load("categories"); $id = GETPOST('id', 'int'); $label = GETPOST('label', 'alpha'); -$type = GETPOST('type', 'az09'); +$type = GETPOST('type', 'aZ09'); $removeelem = GETPOST('removeelem', 'int'); $elemid = GETPOST('elemid', 'int'); diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 4da7686b0a2..4bba10a939a 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -657,7 +657,7 @@ class ActionComm extends CommonObject $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working $this->contactid = $obj->fk_contact; // To have fetch_contact method working - $this->fk_project = $obj->fk_project; // To have fetch_project method working + $this->fk_project = $obj->fk_project; // To have fetch_projet method working //$this->societe->id = $obj->fk_soc; // deprecated //$this->contact->id = $obj->fk_contact; // deprecated diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index d42b1b7d134..a2328dd9ca4 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -87,7 +87,7 @@ $week=GETPOST("week", "int")?GETPOST("week", "int"):date("W"); $day=GETPOST("day", "int")?GETPOST("day", "int"):date("d"); $pid=GETPOST("search_projectid", "int", 3)?GETPOST("search_projectid", "int", 3):GETPOST("projectid", "int", 3); $status=GETPOST("search_status", 'aZ09')?GETPOST("search_status", 'aZ09'):GETPOST("status", 'aZ09'); // status may be 0, 50, 100, 'todo' -$type=GETPOST("search_type", 'az09')?GETPOST("search_type", 'az09'):GETPOST("type", 'az09'); +$type=GETPOST("search_type", 'aZ09')?GETPOST("search_type", 'aZ09'):GETPOST("type", 'aZ09'); $maxprint=(isset($_GET["maxprint"])?GETPOST("maxprint"):$conf->global->AGENDA_MAX_EVENTS_DAY_VIEW); // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) if (GETPOST('search_actioncode', 'array')) diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index d54d2dd02ff..6cd98f00e48 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -384,6 +384,10 @@ if (! $error && $massaction == 'confirm_presend') foreach ($looparray as $objectid => $objecttmp) // $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per object { // Make substitution in email content + if (! empty($conf->projet->enabled) && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project)) + { + $objecttmp->fetch_projet(); + } $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp); $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ', array_keys($listofqualifiedobj)) : $objecttmp->id); $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ', $listofqualifiedref) : $objecttmp->ref); diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index 836652ea819..de3a43d9ce6 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -113,8 +113,8 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO { $result=$object->fetch($id); - $sendtosocid=0; // Thirdparty on object - if (method_exists($object, "fetch_thirdparty") && ! in_array($object->element, array('societe','member','user','expensereport', 'contact'))) + $sendtosocid=0; // Id of related thirdparty + if (method_exists($object, "fetch_thirdparty") && ! in_array($object->element, array('societe', 'member', 'user', 'expensereport', 'contact'))) { $result=$object->fetch_thirdparty(); if ($object->element == 'user' && $result == 0) $result=1; // Even if not found, we consider ok @@ -124,7 +124,14 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO elseif ($object->element == 'member' || $object->element == 'user') { $thirdparty=$object; - if ($thirdparty->id > 0) $sendtosocid=$thirdparty->id; + if ($object->socid > 0) $sendtosocid=$object->socid; + } + elseif ($object->element == 'expensereport') + { + $tmpuser=new User($db); + $tmpuser->fetch($object->fk_user_author); + $thirdparty=$tmpuser; + if ($object->socid > 0) $sendtosocid=$object->socid; } elseif ($object->element == 'societe') { @@ -136,7 +143,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $contact=$object; if ($contact->id > 0) $sendtosocid=$contact->fetch_thirdparty()->id; } - else dol_print_error('', 'Use actions_sendmails.in.php for an element/object that is not supported'); + else dol_print_error('', "Use actions_sendmails.in.php for an element/object '".$object->element."' that is not supported"); if (is_object($hookmanager)) { @@ -162,6 +169,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO if ($receiver == '-1') $receiver=array(); else $receiver=array($receiver); } + $tmparray=array(); if (trim($_POST['sendto'])) { @@ -173,22 +181,23 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO foreach($receiver as $key=>$val) { // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party + if ($val == 'thirdparty') // Key selected means currentthird party (may be usd for current member or current user too) { - $tmparray[] = dol_string_nospecial($thirdparty->name, ' ', array(",")).' <'.$thirdparty->email.'>'; + $tmparray[] = dol_string_nospecial($thirdparty->getFullName($langs), ' ', array(",")).' <'.$thirdparty->email.'>'; } // Recipient was provided from combo list - elseif ($val == 'contact') // Id of contact + elseif ($val == 'contact') // Key selected means current contact { - $tmparray[] = dol_string_nospecial($contact->name, ' ', array(",")).' <'.$contact->email.'>'; + $tmparray[] = dol_string_nospecial($contact->getFullName($langs), ' ', array(",")).' <'.$contact->email.'>'; } - elseif ($val) // Id du contact + elseif ($val) // $val is the Id of a contact { $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email'); $sendtoid[] = $val; } } } + if (!empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) { $receiveruser=$_POST['receiveruser']; @@ -222,16 +231,16 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO foreach($receivercc as $key=>$val) { // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party + if ($val == 'thirdparty') // Key selected means currentthird party (may be usd for current member or current user too) { $tmparray[] = dol_string_nospecial($thirdparty->name, ' ', array(",")).' <'.$thirdparty->email.'>'; } // Recipient was provided from combo list - elseif ($val == 'contact') // Id of contact + elseif ($val == 'contact') // Key selected means current contact { $tmparray[] = dol_string_nospecial($contact->name, ' ', array(",")).' <'.$contact->email.'>'; } - elseif ($val) // Id du contact + elseif ($val) // $val is the Id of a contact { $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email'); //$sendtoid[] = $val; TODO Add also id of contact in CC ? @@ -414,27 +423,6 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $result=$mailfile->sendfile(); if ($result) { - // Two hooks are available into method $mailfile->sendfile, so dedicated code is no more required - /* - if (! empty($conf->dolimail->enabled)) - { - $mid = (GETPOST('mid','int') ? GETPOST('mid','int') : 0); // Original mail id is set ? - if ($mid) - { - // set imap flag answered if it is an answered mail - $dolimail=new DoliMail($db); - $dolimail->id = $mid; - $res=$dolimail->set_prop($user, 'answered',1); - } - if ($imap==1) - { - // write mail to IMAP Server - $movemail = $mailboxconfig->putMail($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$folder,$deliveryreceipt,$mailfile); - if ($movemail) setEventMessages($langs->trans("MailMovedToImapFolder",$folder), null, 'mesgs'); - else setEventMessages($langs->trans("MailMovedToImapFolder_Warning",$folder), null, 'warnings'); - } - }*/ - // Initialisation of datas of object to call trigger if (is_object($object)) { diff --git a/htdocs/core/class/events.class.php b/htdocs/core/class/events.class.php index 57a076963fd..160e22f4c50 100644 --- a/htdocs/core/class/events.class.php +++ b/htdocs/core/class/events.class.php @@ -87,33 +87,9 @@ class Events // extends CommonObject array('id'=>'USER_NEW_PASSWORD', 'test'=>1), array('id'=>'USER_ENABLEDISABLE', 'test'=>1), array('id'=>'USER_DELETE', 'test'=>1), - /* array('id'=>'USER_SETINGROUP', 'test'=>1), deprecated. Replace with USER_MODIFY - array('id'=>'USER_REMOVEFROMGROUP', 'test'=>1), deprecated. Replace with USER_MODIFY */ array('id'=>'GROUP_CREATE', 'test'=>1), array('id'=>'GROUP_MODIFY', 'test'=>1), array('id'=>'GROUP_DELETE', 'test'=>1), - /* array('id'=>'ACTION_CREATE', 'test'=>$conf->societe->enabled), - array('id'=>'COMPANY_CREATE', 'test'=>$conf->societe->enabled), - array('id'=>'CONTRACT_VALIDATE', 'test'=>$conf->contrat->enabled), - array('id'=>'PROPAL_VALIDATE', 'test'=>$conf->propal->enabled), - array('id'=>'PROPAL_CLOSE_SIGNED', 'test'=>$conf->propal->enabled), - array('id'=>'PROPAL_CLOSE_REFUSED', 'test'=>$conf->propal->enabled), - array('id'=>'PROPAL_SENTBYMAIL', 'test'=>$conf->propal->enabled), - array('id'=>'ORDER_VALIDATE', 'test'=>$conf->commande->enabled), - array('id'=>'ORDER_SENTBYMAIL', 'test'=>$conf->commande->enabled), - array('id'=>'BILL_VALIDATE', 'test'=>$conf->facture->enabled), - array('id'=>'BILL_PAYED', 'test'=>$conf->facture->enabled), - array('id'=>'BILL_CANCEL', 'test'=>$conf->facture->enabled), - array('id'=>'BILL_SENTBYMAIL', 'test'=>$conf->facture->enabled), - array('id'=>'PAYMENT_CUSTOMER_CREATE','test'=>$conf->facture->enabled), - array('id'=>'PAYMENT_SUPPLIER_CREATE','test'=>$conf->fournisseur->enabled), - array('id'=>'MEMBER_CREATE', 'test'=>$conf->adherent->enabled), - array('id'=>'MEMBER_VALIDATE', 'test'=>$conf->adherent->enabled), - array('id'=>'MEMBER_SUBSCRIPTION', 'test'=>$conf->adherent->enabled), - array('id'=>'MEMBER_MODIFY', 'test'=>$conf->adherent->enabled), - array('id'=>'MEMBER_RESILIATE', 'test'=>$conf->adherent->enabled), - array('id'=>'MEMBER_DELETE', 'test'=>$conf->adherent->enabled), - */ ); diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 0a9f98b4afd..5f26365c2a8 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -959,9 +959,10 @@ class ExtraFields * @param string $morecss More css (to defined size of field. Old behaviour: may also be a numeric) * @param int $objectid Current object id * @param string $extrafieldsobjectkey If defined (for example $object->table_element), use the new method to get extrafields data + * @param string $mode 1=Used for search filters * @return string */ - public function showInputField($key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '', $objectid = 0, $extrafieldsobjectkey = '') + public function showInputField($key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '', $objectid = 0, $extrafieldsobjectkey = '', $mode = 0) { global $conf,$langs,$form; @@ -1116,13 +1117,20 @@ class ExtraFields } elseif ($type == 'boolean') { - $checked=''; - if (!empty($value)) { - $checked=' checked value="1" '; - } else { - $checked=' value="1" '; + if (empty($mode)) + { + $checked=''; + if (!empty($value)) { + $checked=' checked value="1" '; + } else { + $checked=' value="1" '; + } + $out=''; + } + else + { + $out.=$form->selectyesno($keyprefix.$key.$keysuffix, $value, 1, false, 1); } - $out=''; } elseif ($type == 'price') { diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php index fe00f803a6b..eca41a55301 100644 --- a/htdocs/core/class/translate.class.php +++ b/htdocs/core/class/translate.class.php @@ -88,11 +88,12 @@ class Translate if (empty($srclang) || $srclang == 'auto') { + // $_SERVER['HTTP_ACCEPT_LANGUAGE'] can be 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7,it;q=0.6' but can contains also malicious content $langpref=empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])?'':$_SERVER['HTTP_ACCEPT_LANGUAGE']; - $langpref=preg_replace("/;([^,]*)/i", "", $langpref); + $langpref=preg_replace("/;([^,]*)/i", "", $langpref); // Remove the 'q=x.y,' part $langpref=str_replace("-", "_", $langpref); $langlist=preg_split("/[;,]/", $langpref); - $codetouse=$langlist[0]; + $codetouse=preg_replace('/[^_a-zA-Z]/', '', $langlist[0]); } else $codetouse=$srclang; diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 86d02bcf22c..d234195d8cd 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -4473,7 +4473,9 @@ function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $ * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK) * Numeric = Nb of digits for rounding * @param int $alreadysqlnb Put 1 if you know that content is already universal format number - * @return string Amount with universal numeric format (Example: '99.99999') or unchanged text if conversion fails. If amount is null or '', it returns ''. + * @return string Amount with universal numeric format (Example: '99.99999'). + * If conversion fails, it return text unchanged if $rounding = '' or '0' if $rounding is defined. + * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.. * * @see price() Opposite function of price2num */ @@ -5895,11 +5897,13 @@ $substitutionarray=array_merge($substitutionarray, array( $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__'; $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__'; - $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__'; - $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__'; - $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__'; - $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__'; - + if (! empty($conf->societe->enabled)) + { + $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__'; + $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__'; + $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__'; + $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__'; + } if (! empty($conf->adherent->enabled)) { $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__'; @@ -5907,15 +5911,19 @@ $substitutionarray=array_merge($substitutionarray, array( $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__'; $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__'; } - $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__'; - $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__'; - $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__'; - - $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start'; - $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start'; - $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service'; - $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service'; - + if (! empty($conf->projet->enabled)) + { + $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__'; + $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__'; + $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__'; + } + if (! empty($conf->contrat->enabled)) + { + $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start'; + $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start'; + $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service'; + $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service'; + } $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable'; $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable'; $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)'; @@ -5993,7 +6001,13 @@ $substitutionarray=array_merge($substitutionarray, array( $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty)?$object->thirdparty->email:''); } - if (is_object($object->projet) && $object->projet->id > 0) + if (is_object($object->project) && $object->project->id > 0) + { + $substitutionarray['__PROJECT_ID__'] = (is_object($object->project)?$object->project->id:''); + $substitutionarray['__PROJECT_REF__'] = (is_object($object->project)?$object->project->ref:''); + $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project)?$object->project->title:''); + } + if (is_object($object->projet) && $object->projet->id > 0) // Deprecated, for backward compatibility { $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet)?$object->projet->id:''); $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet)?$object->projet->ref:''); diff --git a/htdocs/core/lib/holiday.lib.php b/htdocs/core/lib/holiday.lib.php index 492766192b4..960acfa3aa7 100644 --- a/htdocs/core/lib/holiday.lib.php +++ b/htdocs/core/lib/holiday.lib.php @@ -86,6 +86,11 @@ function holiday_admin_prepare_head() // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, null, $head, $h, 'holiday_admin'); + $head[$h][0] = DOL_URL_ROOT.'/admin/holiday_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFields"); + $head[$h][2] = 'attributes'; + $h++; + complete_head_from_modules($conf, $langs, null, $head, $h, 'holiday_admin', 'remove'); return $head; diff --git a/htdocs/core/menus/standard/auguria.lib.php b/htdocs/core/menus/standard/auguria.lib.php index 438ff8246ea..2aaeb967675 100644 --- a/htdocs/core/menus/standard/auguria.lib.php +++ b/htdocs/core/menus/standard/auguria.lib.php @@ -271,14 +271,19 @@ function print_left_auguria_menu($db, $menu_array_before, $menu_array_after, &$t // Show logo company if (empty($noout) && ! empty($conf->global->MAIN_SHOW_LOGO) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $mysoc->logo_mini=$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI; - if (! empty($mysoc->logo_mini) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_mini)) + $mysoc->logo_mini=(empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI); + $mysoc->logo_squarred_mini=(empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI); + if (! empty($mysoc->logo_squarred_mini) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_squarred_mini)) + { + $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini); + } + elseif (! empty($mysoc->logo_mini) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_mini)) { $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_mini); } else { - $urllogo=DOL_URL_ROOT.'/theme/dolibarr_logo.png'; + $urllogo=DOL_URL_ROOT.'/theme/dolibarr_logo_squarred.png'; } $title=$langs->trans("GoIntoSetupToChangeLogo"); print "\n".''."\n"; diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index 2eead6da81d..d62cd1993fd 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -43,7 +43,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php'; */ function print_eldy_menu($db, $atarget, $type_user, &$tabMenu, &$menu, $noout = 0, $mode = '') { - global $user,$conf,$langs,$dolibarr_main_db_name; + global $user,$conf,$langs,$mysoc; + global $dolibarr_main_db_name; $mainmenu=(empty($_SESSION["mainmenu"])?'':$_SESSION["mainmenu"]); $leftmenu=(empty($_SESSION["leftmenu"])?'':$_SESSION["leftmenu"]); @@ -477,8 +478,8 @@ function print_eldy_menu($db, $atarget, $type_user, &$tabMenu, &$menu, $noout = // Show logo company if (empty($conf->global->MAIN_MENU_INVERT) && empty($noout) && ! empty($conf->global->MAIN_SHOW_LOGO) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $mysoc->logo_mini=$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI; - $mysoc->logo_squarred_mini=$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI; + $mysoc->logo_mini=(empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI); + $mysoc->logo_squarred_mini=(empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI); if (! empty($mysoc->logo_squarred_mini) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_squarred_mini)) { $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini); diff --git a/htdocs/core/modules/modHoliday.class.php b/htdocs/core/modules/modHoliday.class.php index ba792ad28ad..61217d91686 100644 --- a/htdocs/core/modules/modHoliday.class.php +++ b/htdocs/core/modules/modHoliday.class.php @@ -202,13 +202,13 @@ class modHoliday extends DolibarrModules $this->export_permission[$r]=array(array("holiday","read_all")); $this->export_fields_array[$r]=array( 'd.rowid'=>"LeaveId",'d.fk_type'=>'TypeOfLeaveId','t.code'=>'TypeOfLeaveCode','t.label'=>'TypeOfLeaveLabel','d.fk_user'=>'UserID', - 'u.lastname'=>'Lastname','u.firstname'=>'Firstname','u.login'=>"Login",'d.date_debut'=>'DateStart','d.date_fin'=>'DateEnd','d.halfday'=>'HalfDay', + 'u.lastname'=>'Lastname','u.firstname'=>'Firstname','u.login'=>"Login",'d.date_debut'=>'DateStart','d.date_fin'=>'DateEnd','d.halfday'=>'HalfDay','none.num_open_days'=>'NbUseDaysCP', 'd.date_valid'=>'DateApprove','d.fk_validator'=>"UserForApprovalID",'ua.lastname'=>"UserForApprovalLastname",'ua.firstname'=>"UserForApprovalFirstname", 'ua.login'=>"UserForApprovalLogin",'d.description'=>'Description','d.statut'=>'Status' ); $this->export_TypeFields_array[$r]=array( 'd.rowid'=>"Numeric",'t.code'=>'Text', 't.label'=>'Text','d.fk_user'=>'Numeric', - 'u.lastname'=>'Text','u.firstname'=>'Text','u.login'=>"Text",'d.date_debut'=>'Date','d.date_fin'=>'Date', + 'u.lastname'=>'Text','u.firstname'=>'Text','u.login'=>"Text",'d.date_debut'=>'Date','d.date_fin'=>'Date','none.num_open_days'=>'NumericCompute', 'd.date_valid'=>'Date','d.fk_validator'=>"Numeric",'ua.lastname'=>"Text",'ua.firstname'=>"Text", 'ua.login'=>"Text",'d.description'=>'Text','d.statut'=>'Numeric' ); @@ -216,6 +216,7 @@ class modHoliday extends DolibarrModules 'u.lastname'=>'user','u.firstname'=>'user','u.login'=>'user','ua.lastname'=>'user','ua.firstname'=>'user','ua.login'=>'user' ); $this->export_alias_array[$r]=array('d.rowid'=>"idholiday"); + $this->export_special_array[$r] = array('none.num_open_days'=>'getNumOpenDays'); $this->export_dependencies_array[$r]=array(); // To add unique key if we ask a field of a child to avoid the DISTINCT to discard them $this->export_sql_start[$r]='SELECT DISTINCT '; diff --git a/htdocs/core/tpl/extrafields_list_search_input.tpl.php b/htdocs/core/tpl/extrafields_list_search_input.tpl.php index b4a98946f94..0b9a048f28a 100644 --- a/htdocs/core/tpl/extrafields_list_search_input.tpl.php +++ b/htdocs/core/tpl/extrafields_list_search_input.tpl.php @@ -22,28 +22,28 @@ if (! empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_ if (! empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) { $align=$extrafields->getAlignFlag($key); $typeofextrafield=$extrafields->attributes[$extrafieldsobjectkey]['type'][$key]; + print ''; $tmpkey=preg_replace('/'.$search_options_pattern.'/', '', $key); if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key])) { - $crit=$val; $searchclass=''; if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; print ''; } - elseif (! in_array($typeofextrafield, array('datetime','timestamp'))) - { - // for the type as 'checkbox', 'chkbxlst', 'sellist' we should use code instead of id (example: I declare a 'chkbxlst' to have a link with dictionnairy, I have to extend it with the 'code' instead 'rowid') - $morecss=''; - if ($typeofextrafield == 'sellist') $morecss='maxwidth200'; - echo $extrafields->showInputField($key, $search_array_options[$search_options_pattern.$tmpkey], '', '', $search_options_pattern, $morecss); - } elseif (in_array($typeofextrafield, array('datetime','timestamp'))) { // TODO // Use showInputField in a particular manner to have input with a comparison operator, not input for a specific value date-hour-minutes } + else + { + // for the type as 'checkbox', 'chkbxlst', 'sellist' we should use code instead of id (example: I declare a 'chkbxlst' to have a link with dictionnairy, I have to extend it with the 'code' instead 'rowid') + $morecss=''; + if ($typeofextrafield == 'sellist') $morecss='maxwidth200'; + echo $extrafields->showInputField($key, $search_array_options[$search_options_pattern.$tmpkey], '', '', $search_options_pattern, $morecss, 0, $extrafieldsobjectkey, 1); + } print ''; } } diff --git a/htdocs/core/tpl/extrafields_list_search_sql.tpl.php b/htdocs/core/tpl/extrafields_list_search_sql.tpl.php index c2c4934c832..29c67094975 100644 --- a/htdocs/core/tpl/extrafields_list_search_sql.tpl.php +++ b/htdocs/core/tpl/extrafields_list_search_sql.tpl.php @@ -25,10 +25,18 @@ if (! empty($extrafieldsobjectkey) && ! empty($search_array_options) && is_array { $sql .= " AND ".$extrafieldsobjectprefix.$tmpkey." = '".$db->idate($crit)."'"; } + elseif (in_array($typ, array('boolean'))) + { + if ($crit !== '-1' && $crit !== '') { + $sql .= " AND (".$extrafieldsobjectprefix.$tmpkey." = '".$db->escape($crit)."'"; + if ($crit == '0') $sql.=" OR ".$extrafieldsobjectprefix.$tmpkey." IS NULL"; + $sql.= ")"; + } + } elseif ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0') && (! in_array($typ, array('link')) || $crit != '-1')) { $mode_search=0; - if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric + if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric if (in_array($typ, array('sellist','link')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int if (in_array($typ, array('chkbxlst','checkbox'))) $mode_search=4; // Search on a multiselect field with sql type = text if (is_array($crit)) $crit = implode(' ', $crit); // natural_search() expects a string diff --git a/htdocs/document.php b/htdocs/document.php index 8e86d6c3e6f..84fb0492554 100644 --- a/htdocs/document.php +++ b/htdocs/document.php @@ -161,6 +161,8 @@ if (! empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) $attachment=false; $type = 'application/octet-stream'; if (GETPOST('type', 'alpha')) $type=GETPOST('type', 'alpha'); else $type=dol_mimetype($original_file); +// Security: Force to octet-stream if file is a dangerous file +if (preg_match('/\.noexe$/i', $original_file)) $type = 'application/octet-stream'; // Security: Delete string ../ into $original_file $original_file = str_replace("../", "/", $original_file); @@ -217,7 +219,7 @@ if (! $accessallowed) } // Security: -// On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers. +// We refuse directory transversal change and pipes in file names if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) { dol_syslog("Refused to deliver file ".$fullpath_original_file); @@ -229,6 +231,7 @@ if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $full clearstatcache(); $filename = basename($fullpath_original_file); +$filename = preg_replace('/\.noexe$/i', '', $filename); // Output file on browser dol_syslog("document.php download $fullpath_original_file filename=$filename content-type=$type"); diff --git a/htdocs/expensereport/list.php b/htdocs/expensereport/list.php index 666403a7412..fd53e8af1d1 100644 --- a/htdocs/expensereport/list.php +++ b/htdocs/expensereport/list.php @@ -40,12 +40,13 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php' // Load translation files required by the page $langs->loadLangs(array('companies', 'users', 'trips')); -$action=GETPOST('action', 'aZ09'); -$massaction=GETPOST('massaction', 'alpha'); -$show_files=GETPOST('show_files', 'int'); -$confirm=GETPOST('confirm', 'alpha'); -$toselect = GETPOST('toselect', 'array'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'expensereportlist'; +$action = GETPOST('action', 'aZ09'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); +$contextpage = GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'expensereportlist'; $childids = $user->getAllChildIds(1); @@ -136,17 +137,17 @@ $arrayfields=array( 'd.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields -if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { - 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])); - } + foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) + { + if (! empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key]=array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + } } $canedituser=(! empty($user->admin) || $user->rights->user->user->creer); -$object = new ExpenseReport($db); $objectuser = new User($db); @@ -161,12 +162,13 @@ $parameters=array('socid'=>$socid); $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'); -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - 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')) // Both test must be present to be compatible with all browsers + 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 { $search_ref=""; $search_user=""; @@ -176,7 +178,6 @@ if (empty($reshook)) $search_status=""; $month_start=""; $year_start=""; - $day =""; $month_end=""; $year_end=""; $day_end = ""; @@ -258,9 +259,9 @@ $title = $langs->trans("ListOfTrips"); llxHeader('', $title); $max_year = 5; -$min_year = 5; +$min_year = 10; -// Récupération de l'ID de l'utilisateur +// Get current user id $user_id = $user->id; if ($id > 0) @@ -340,15 +341,15 @@ if ($resql) $arrayofselected=is_array($toselect)?$toselect:array(); $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($sall) $param.="&sall=".$sall; - if ($search_ref) $param.="&search_ref=".$search_ref; - if ($search_user) $param.="&search_user=".$search_user; - if ($search_amount_ht) $param.="&search_amount_ht=".$search_amount_ht; - if ($search_amount_ttc) $param.="&search_amount_ttc=".$search_amount_ttc; - if ($search_status >= 0) $param.="&search_status=".$search_status; - if ($optioncss != '') $param.='&optioncss='.$optioncss; + 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 ($search_ref) $param.="&search_ref=".urlencode($search_ref); + if ($search_user) $param.="&search_user=".urlencode($search_user); + if ($search_amount_ht) $param.="&search_amount_ht=".urlencode($search_amount_ht); + if ($search_amount_ttc) $param.="&search_amount_ttc=".urlencode($search_amount_ttc); + if ($search_status >= 0) $param.="&search_status=".urlencode($search_status); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -503,7 +504,7 @@ if ($resql) $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); print '
'; print ''."\n"; @@ -606,7 +607,7 @@ if ($resql) print ''; } // Action column - print ''; @@ -757,6 +758,7 @@ if ($resql) $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; + // Date creation if (! empty($arrayfields['d.date_create']['checked'])) { @@ -801,10 +803,9 @@ if ($resql) } else { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } - - print ''.''; + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print ''; } // Show total line diff --git a/htdocs/exports/class/export.class.php b/htdocs/exports/class/export.class.php index 51a16f717b2..da184f27574 100644 --- a/htdocs/exports/class/export.class.php +++ b/htdocs/exports/class/export.class.php @@ -540,7 +540,7 @@ class Export public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '') { // phpcs:enable - global $conf,$langs; + global $conf,$langs,$mysoc; $indice=0; asort($array_selected); @@ -634,6 +634,14 @@ class Export $alias=str_replace(array('.', '-','(',')'), '_', $key); if ($obj->$alias < 0) $obj->$alias='0'; } + // Operation GETNUMOPENDAYS (for Holiday module) + elseif ($this->array_export_special[$indice][$key]=='getNumOpenDays') + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + //$alias=$this->array_export_alias[$indice][$key]; + $alias=str_replace(array('.', '-','(',')'), '_', $key); + $obj->$alias=num_open_day(dol_stringtotime($obj->d_date_debut, 1), dol_stringtotime($obj->d_date_fin, 1), 0, 1, $obj->d_halfday, $mysoc->country_code); + } // Operation INVOICEREMAINTOPAY elseif ($this->array_export_special[$indice][$key]=='getRemainToPay') { diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index 6847af5edf1..febfda0a419 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -207,7 +207,7 @@ class ProductFournisseur extends Product /** * Modify the purchase price for a supplier * - * @param int $qty Min quantity for which price is valid + * @param float $qty Min quantity for which price is valid * @param float $buyprice Purchase price for the quantity min * @param User $user Object user user made changes * @param string $price_base_type HT or TTC @@ -230,7 +230,7 @@ class ProductFournisseur extends Product * @param string $desc_fourn Custom description for product_fourn_price * @param string $barcode Barcode * @param int $fk_barcode_type Barcode type - * @return int <0 if KO, >=0 if OK + * @return int <0 if KO, >=0 if OK */ public function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges = 0, $remise_percent = 0, $remise = 0, $newnpr = 0, $delivery_time_days = 0, $supplier_reputation = '', $localtaxes_array = array(), $newdefaultvatcode = '', $multicurrency_buyprice = 0, $multicurrency_price_base_type = 'HT', $multicurrency_tx = 1, $multicurrency_code = '', $desc_fourn = '', $barcode = '', $fk_barcode_type = '') { @@ -272,11 +272,10 @@ class ProductFournisseur extends Product $buyprice=price2num($buyprice, 'MU'); $charges=price2num($charges, 'MU'); - $qty=price2num($qty); - $error=0; - + $qty=price2num($qty, 'MS'); $unitBuyPrice = price2num($buyprice/$qty, 'MU'); + $error=0; $now=dol_now(); $newvat = $tva_tx; @@ -298,6 +297,12 @@ class ProductFournisseur extends Product if (empty($localtax1)) $localtax1=0; // If = '' then = 0 if (empty($localtax2)) $localtax2=0; // If = '' then = 0 + // Check parameters + if ($buyprice != '' && ! is_numeric($buyprice)) + { + + } + $this->db->begin(); if ($this->product_fourn_price_id > 0) @@ -331,7 +336,7 @@ class ProductFournisseur extends Product $sql.= " SET fk_user = " . $user->id." ,"; $sql.= " ref_fourn = '" . $this->db->escape($ref_fourn) . "',"; $sql.= " desc_fourn = '" . $this->db->escape($desc_fourn) . "',"; - $sql.= " price = ".price2num($buyprice).","; + $sql.= " price = ".$buyprice.","; $sql.= " quantity = ".$qty.","; $sql.= " remise_percent = ".$remise_percent.","; $sql.= " remise = ".$remise.","; diff --git a/htdocs/holiday/card.php b/htdocs/holiday/card.php index 204d832a94c..bc9c10045a8 100644 --- a/htdocs/holiday/card.php +++ b/htdocs/holiday/card.php @@ -37,9 +37,13 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/holiday.lib.php'; require_once DOL_DOCUMENT_ROOT.'/holiday/common.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Get parameters -$action=GETPOST('action', 'alpha'); +$action=GETPOST('action', 'aZ09'); +$cancel=GETPOST('cancel', 'alpha'); +$confirm = GETPOST('confirm', 'alpha'); + $id=GETPOST('id', 'int'); $ref=GETPOST('ref', 'alpha'); $fuserid = (GETPOST('fuserid', 'int')?GETPOST('fuserid', 'int'):$user->id); @@ -48,10 +52,10 @@ $fuserid = (GETPOST('fuserid', 'int')?GETPOST('fuserid', 'int'):$user->id); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'holiday', $id, 'holiday'); -$now=dol_now(); - // Load translation files required by the page -$langs->load("holiday"); +$langs->loadLangs(array("holiday","mails")); + +$now=dol_now(); $childids = $user->getAllChildIds(1); @@ -61,6 +65,11 @@ if (! empty($conf->global->HOLIDAY_FOR_NON_SALARIES_TOO)) $morefilter = ''; $error = 0; $object = new Holiday($db); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + if ($id > 0) { $object->fetch($id); @@ -83,745 +92,798 @@ $candelete = 0; if (! empty($user->rights->holiday->delete)) $candelete=1; if ($object->statut == Holiday::STATUS_DRAFT && $user->rights->holiday->write && in_array($object->fk_user, $childids)) $candelete=1; + /* * Actions */ -if (GETPOST('cancel', 'alpha')) -{ - $action = ''; -} +$parameters = array('socid' => $socid); +$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 create a request -if ($action == 'create') +if (empty($reshook)) { - // If no right to create a request - if (! $cancreate) - { - $error++; - setEventMessages($langs->trans('CantCreateCP'), null, 'errors'); - $action='request'; - } + if ($cancel) + { + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + $action = ''; + } - if (! $error) - { - $object = new Holiday($db); + // If create a request + if ($action == 'create') + { - $db->begin(); - - $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year')); - $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year')); - $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1); - $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1); - $starthalfday=GETPOST('starthalfday'); - $endhalfday=GETPOST('endhalfday'); - $type=GETPOST('type'); - $halfday=0; - if ($starthalfday == 'afternoon' && $endhalfday == 'morning') $halfday=2; - elseif ($starthalfday == 'afternoon') $halfday=-1; - elseif ($endhalfday == 'morning') $halfday=1; - - $valideur = GETPOST('valideur', 'int'); - $description = trim(GETPOST('description')); - - // If no type - if ($type <= 0) + // If no right to create a request + if (! $cancreate) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error++; - $action='create'; + $error++; + setEventMessages($langs->trans('CantCreateCP'), null, 'errors'); + $action='request'; } - // If no start date - if (empty($date_debut)) - { - setEventMessages($langs->trans("NoDateDebut"), null, 'errors'); - $error++; - $action='create'; - } - // If no end date - if (empty($date_fin)) - { - setEventMessages($langs->trans("NoDateFin"), null, 'errors'); - $error++; - $action='create'; - } - // If start date after end date - if ($date_debut > $date_fin) - { - setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors'); - $error++; - $action='create'; - } - - // Check if there is already holiday for this period - $verifCP = $object->verifDateHolidayCP($fuserid, $date_debut, $date_fin, $halfday); - if (! $verifCP) - { - setEventMessages($langs->trans("alreadyCPexist"), null, 'errors'); - $error++; - $action='create'; - } - - // If there is no Business Days within request - $nbopenedday=num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); - if($nbopenedday < 0.5) - { - setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); - $error++; - $action='create'; - } - - // If no validator designated - if ($valideur < 1) - { - setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors'); - $error++; - } - - $result = 0; - if (! $error) { - $object->fk_user = $fuserid; - $object->description = $description; - $object->fk_validator = $valideur; - $object->fk_type = $type; - $object->date_debut = $date_debut; - $object->date_fin = $date_fin; - $object->halfday = $halfday; + $object = new Holiday($db); - $result = $object->create($user); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } + $db->begin(); + + $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year')); + $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year')); + $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1); + $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1); + $starthalfday=GETPOST('starthalfday'); + $endhalfday=GETPOST('endhalfday'); + $type=GETPOST('type'); + $halfday=0; + if ($starthalfday == 'afternoon' && $endhalfday == 'morning') $halfday=2; + elseif ($starthalfday == 'afternoon') $halfday=-1; + elseif ($endhalfday == 'morning') $halfday=1; + + $valideur = GETPOST('valideur', 'int'); + $description = trim(GETPOST('description')); + + // If no type + if ($type <= 0) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $error++; + $action='create'; + } + + // If no start date + if (empty($date_debut)) + { + setEventMessages($langs->trans("NoDateDebut"), null, 'errors'); + $error++; + $action='create'; + } + // If no end date + if (empty($date_fin)) + { + setEventMessages($langs->trans("NoDateFin"), null, 'errors'); + $error++; + $action='create'; + } + // If start date after end date + if ($date_debut > $date_fin) + { + setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors'); + $error++; + $action='create'; + } + + // Check if there is already holiday for this period + $verifCP = $object->verifDateHolidayCP($fuserid, $date_debut, $date_fin, $halfday); + if (! $verifCP) + { + setEventMessages($langs->trans("alreadyCPexist"), null, 'errors'); + $error++; + $action='create'; + } + + // If there is no Business Days within request + $nbopenedday=num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); + if($nbopenedday < 0.5) + { + setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); + $error++; + $action='create'; + } + + // If no validator designated + if ($valideur < 1) + { + setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors'); + $error++; + } + + $result = 0; + + if (! $error) + { + $object->fk_user = $fuserid; + $object->description = $description; + $object->fk_validator = $valideur; + $object->fk_type = $type; + $object->date_debut = $date_debut; + $object->date_fin = $date_fin; + $object->halfday = $halfday; + + $result = $object->create($user); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } + + // If no SQL error we redirect to the request card + if (! $error) + { + $db->commit(); + + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + else + { + $db->rollback(); + } + } + } + + if ($action == 'update' && GETPOSTISSET('savevalidator') && ! empty($user->rights->holiday->approve)) + { + $object->fetch($id); + + $object->oldcopy = dol_clone($object); + + $object->fk_validator = GETPOST('valideur', 'int'); + + if ($object->fk_validator != $object->oldcopy->fk_validator) + { + $verif = $object->update($user); + + if ($verif <= 0) + { + setEventMessages($object->error, $object->errors, 'warnings'); + $action='editvalidator'; + } + else + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } } - // If no SQL error we redirect to the request card - if (! $error) - { - $db->commit(); + $action = ''; + } - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + if ($action == 'update' && ! GETPOSTISSET('savevalidator')) + { + $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year')); + $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year')); + $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1); + $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1); + $starthalfday=GETPOST('starthalfday'); + $endhalfday=GETPOST('endhalfday'); + $halfday=0; + if ($starthalfday == 'afternoon' && $endhalfday == 'morning') $halfday=2; + elseif ($starthalfday == 'afternoon') $halfday=-1; + elseif ($endhalfday == 'morning') $halfday=1; + + // If no right to modify a request + if (! $user->rights->holiday->write) + { + header('Location: '.$_SERVER["PHP_SELF"].'?action=request&error=CantUpdate'); exit; } - else - { - $db->rollback(); + + $object->fetch($id); + + // If under validation + if ($object->statut == Holiday::STATUS_DRAFT) + { + // If this is the requestor or has read/write rights + if ($cancreate) + { + $valideur = GETPOST('valideur', 'int'); + $description = trim(GETPOST('description', 'none')); + + // If no start date + if (empty($_POST['date_debut_'])) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=nodatedebut'); + exit; + } + + // If no end date + if (empty($_POST['date_fin_'])) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=nodatefin'); + exit; + } + + // If start date after end date + if ($date_debut > $date_fin) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=datefin'); + exit; + } + + // If no validator designated + if ($valideur < 1) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=Valideur'); + exit; + } + + // If there is no Business Days within request + $nbopenedday=num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); + if ($nbopenedday < 0.5) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=DureeHoliday'); + exit; + } + + $object->description = $description; + $object->date_debut = $date_debut; + $object->date_fin = $date_fin; + $object->fk_validator = $valideur; + $object->halfday = $halfday; + + // Update + $verif = $object->update($user); + + if ($verif <= 0) + { + setEventMessages($object->error, $object->errors, 'warnings'); + $action='edit'; + } + else + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + } + else + { + setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); + $action=''; + } } - } -} + else + { + setEventMessages($langs->trans("ErrorBadStatus"), null, 'errors'); + $action=''; + } + } -if ($action == 'update' && GETPOSTISSET('savevalidator') && ! empty($user->rights->holiday->approve)) -{ - $object->fetch($id); + // If delete of request + if ($action == 'confirm_delete' && GETPOST('confirm') == 'yes' && $user->rights->holiday->delete) + { + $error=0; - $object->oldcopy = dol_clone($object); + $db->begin(); - $object->fk_validator = GETPOST('valideur', 'int'); + $object->fetch($id); - if ($object->fk_validator != $object->oldcopy->fk_validator) - { - $verif = $object->update($user); - - if ($verif <= 0) - { - setEventMessages($object->error, $object->errors, 'warnings'); - $action='editvalidator'; - } - else - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - } - - $action = ''; -} - -if ($action == 'update' && ! GETPOSTISSET('savevalidator')) -{ - $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year')); - $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year')); - $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1); - $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1); - $starthalfday=GETPOST('starthalfday'); - $endhalfday=GETPOST('endhalfday'); - $halfday=0; - if ($starthalfday == 'afternoon' && $endhalfday == 'morning') $halfday=2; - elseif ($starthalfday == 'afternoon') $halfday=-1; - elseif ($endhalfday == 'morning') $halfday=1; - - // If no right to modify a request - if (! $user->rights->holiday->write) - { - header('Location: '.$_SERVER["PHP_SELF"].'?action=request&error=CantUpdate'); - exit; - } - - $object->fetch($id); - - // If under validation - if ($object->statut == Holiday::STATUS_DRAFT) - { - // If this is the requestor or has read/write rights - if ($cancreate) - { - $valideur = GETPOST('valideur', 'int'); - $description = trim(GETPOST('description', 'none')); - - // If no start date - if (empty($_POST['date_debut_'])) { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=nodatedebut'); - exit; - } - - // If no end date - if (empty($_POST['date_fin_'])) { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=nodatefin'); - exit; - } - - // If start date after end date - if ($date_debut > $date_fin) { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=datefin'); - exit; - } - - // If no validator designated - if ($valideur < 1) { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=Valideur'); - exit; - } - - // If there is no Business Days within request - $nbopenedday=num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); - if ($nbopenedday < 0.5) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=DureeHoliday'); - exit; - } - - $object->description = $description; - $object->date_debut = $date_debut; - $object->date_fin = $date_fin; - $object->fk_validator = $valideur; - $object->halfday = $halfday; - - // Update - $verif = $object->update($user); - - if ($verif <= 0) + // If this is a rough draft, approved, canceled or refused + if ($object->statut == Holiday::STATUS_DRAFT || $object->statut == Holiday::STATUS_CANCELED || $object->statut == Holiday::STATUS_REFUSED) + { + // Si l'utilisateur à le droit de lire cette demande, il peut la supprimer + if ($candelete) { - setEventMessages($object->error, $object->errors, 'warnings'); - $action='edit'; + $result=$object->delete($user); } else { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; + $error++; + setEventMessages($langs->trans('ErrorCantDeleteCP'), null, 'errors'); + $action=''; } - } - else - { - setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); - $action=''; - } - } - else - { - setEventMessages($langs->trans("ErrorBadStatus"), null, 'errors'); - $action=''; - } -} + } -// If delete of request -if ($action == 'confirm_delete' && GETPOST('confirm') == 'yes' && $user->rights->holiday->delete) -{ - $error=0; - - $db->begin(); - - $object->fetch($id); - - // If this is a rough draft, approved, canceled or refused - if ($object->statut == Holiday::STATUS_DRAFT || $object->statut == Holiday::STATUS_CANCELED || $object->statut == Holiday::STATUS_REFUSED) - { - // Si l'utilisateur à le droit de lire cette demande, il peut la supprimer - if ($candelete) + if (! $error) { - $result=$object->delete($user); + $db->commit(); + header('Location: list.php?restore_lastsearch_values=1'); + exit; } else { - $error++; - setEventMessages($langs->trans('ErrorCantDeleteCP'), null, 'errors'); - $action=''; + $db->rollback(); } } - if (! $error) + // Action validate (+ send email for approval) + if ($action == 'confirm_send') { - $db->commit(); - header('Location: list.php?restore_lastsearch_values=1'); - exit; + $object->fetch($id); + + // Si brouillon et créateur + if ($object->statut == Holiday::STATUS_DRAFT && $cancreate) + { + $object->oldcopy = dol_clone($object); + + $object->statut = Holiday::STATUS_VALIDATED; + + $verif = $object->validate($user); + + // Si pas d'erreur SQL on redirige vers la fiche de la demande + if ($verif > 0) + { + // To + $destinataire = new User($db); + $destinataire->fetch($object->fk_validator); + $emailTo = $destinataire->email; + + if (!$emailTo) + { + dol_syslog("Expected validator has no email, so we redirect directly to finished page without sending email"); + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + + // From + $expediteur = new User($db); + $expediteur->fetch($object->fk_user); + $emailFrom = $expediteur->email; + + // Subject + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + + $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysToValidate"); + + // Content + $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; + $message.= "\n"; + $message.= $langs->transnoentities("HolidaysToValidateBody")."\n"; + + $delayForRequest = $object->getConfCP('delayForRequest'); + //$delayForRequest = $delayForRequest * (60*60*24); + + $nextMonth = dol_time_plus_duree($now, $delayForRequest, 'd'); + + // Si l'option pour avertir le valideur en cas de délai trop court + if ($object->getConfCP('AlertValidatorDelay')) + { + if($object->date_debut < $nextMonth) + { + $message.= "\n"; + $message.= $langs->transnoentities("HolidaysToValidateDelay", $object->getConfCP('delayForRequest'))."\n"; + } + } + + // Si l'option pour avertir le valideur en cas de solde inférieur à la demande + if ($object->getConfCP('AlertValidatorSolde')) + { + $nbopenedday=num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); + if ($nbopenedday > $object->getCPforUser($object->fk_user, $object->fk_type)) + { + $message.= "\n"; + $message.= $langs->transnoentities("HolidaysToValidateAlertSolde")."\n"; + } + } + + $message.= "\n"; + $message.= "- ".$langs->transnoentitiesnoconv("Name")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; + $message.= "- ".$langs->transnoentitiesnoconv("Period")." : ".dol_print_date($object->date_debut, 'day')." ".$langs->transnoentitiesnoconv("To")." ".dol_print_date($object->date_fin, 'day')."\n"; + $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; + $message.= "\n"; + + $trackid='leav'.$object->id; + + $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); + + // Envoi du mail + $result=$mail->sendfile(); + + if (!$result) + { + setEventMessages($mail->error, $mail->errors, 'warnings'); + $action=''; + } + else + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $action=''; + } + } } - else + + if ($action == 'update_extras') { - $db->rollback(); + $object->oldcopy = dol_clone($object); + + // Fill array 'array_options' with data from update form + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute', 'none')); + if ($ret < 0) $error++; + + if (! $error) + { + // Actions on extra fields + $result = $object->insertExtraFields('HOLIDAY_MODIFY'); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } + + if ($error) + $action = 'edit_extras'; } -} - -// Action validate (+ send email for approval) -if ($action == 'confirm_send') -{ - $object->fetch($id); - - // Si brouillon et créateur - if ($object->statut == Holiday::STATUS_DRAFT && $cancreate) - { - $object->oldcopy = dol_clone($object); - - $object->statut = Holiday::STATUS_VALIDATED; - - $verif = $object->validate($user); - - // Si pas d'erreur SQL on redirige vers la fiche de la demande - if ($verif > 0) - { - // To - $destinataire = new User($db); - $destinataire->fetch($object->fk_validator); - $emailTo = $destinataire->email; - - if (!$emailTo) - { - dol_syslog("Expected validator has no email, so we redirect directly to finished page without sending email"); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - - // From - $expediteur = new User($db); - $expediteur->fetch($object->fk_user); - $emailFrom = $expediteur->email; - - // Subject - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - - $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysToValidate"); - - // Content - $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; - $message.= "\n"; - $message.= $langs->transnoentities("HolidaysToValidateBody")."\n"; - - $delayForRequest = $object->getConfCP('delayForRequest'); - //$delayForRequest = $delayForRequest * (60*60*24); - - $nextMonth = dol_time_plus_duree($now, $delayForRequest, 'd'); - - // Si l'option pour avertir le valideur en cas de délai trop court - if ($object->getConfCP('AlertValidatorDelay')) - { - if($object->date_debut < $nextMonth) - { - $message.= "\n"; - $message.= $langs->transnoentities("HolidaysToValidateDelay", $object->getConfCP('delayForRequest'))."\n"; - } - } - - // Si l'option pour avertir le valideur en cas de solde inférieur à la demande - if ($object->getConfCP('AlertValidatorSolde')) - { - $nbopenedday=num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); - if ($nbopenedday > $object->getCPforUser($object->fk_user, $object->fk_type)) - { - $message.= "\n"; - $message.= $langs->transnoentities("HolidaysToValidateAlertSolde")."\n"; - } - } - - $message.= "\n"; - $message.= "- ".$langs->transnoentitiesnoconv("Name")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - $message.= "- ".$langs->transnoentitiesnoconv("Period")." : ".dol_print_date($object->date_debut, 'day')." ".$langs->transnoentitiesnoconv("To")." ".dol_print_date($object->date_fin, 'day')."\n"; - $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; - $message.= "\n"; - - $trackid='leav'.$object->id; - - $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - - // Envoi du mail - $result=$mail->sendfile(); - - if (!$result) - { - setEventMessages($mail->error, $mail->errors, 'warnings'); - $action=''; - } - else - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - $action=''; - } - } -} - - -// Approve leave request -if ($action == 'confirm_valid') -{ - $object->fetch($id); - - // Si statut en attente de validation et valideur = utilisateur - if ($object->statut == Holiday::STATUS_VALIDATED && $user->id == $object->fk_validator) - { - $object->oldcopy = dol_clone($object); - - $object->date_valid = dol_now(); - $object->fk_user_valid = $user->id; - $object->statut = Holiday::STATUS_APPROVED; - - $db->begin(); - - $verif = $object->approve($user); - if ($verif <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - - // Si pas d'erreur SQL on redirige vers la fiche de la demande - if (! $error) - { - // Calculcate number of days consummed - $nbopenedday=num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); - $soldeActuel = $object->getCpforUser($object->fk_user, $object->fk_type); - $newSolde = ($soldeActuel - $nbopenedday); - - // On ajoute la modification dans le LOG - $result=$object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $object->fk_type); - if ($result < 0) - { - $error++; - setEventMessages(null, $object->errors, 'errors'); - } - - //Update balance - $result=$object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type); - if ($result < 0) - { - $error++; - setEventMessages(null, $object->errors, 'errors'); - } - } - - if (! $error) - { - // To - $destinataire = new User($db); - $destinataire->fetch($object->fk_user); - $emailTo = $destinataire->email; - - if (!$emailTo) - { - dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email"); - } - else - { - // From - $expediteur = new User($db); - $expediteur->fetch($object->fk_validator); - $emailFrom = $expediteur->email; - - // Subject - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - - $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated"); - - // Content - $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; - $message.= "\n"; - $message.= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; - - $message.= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - - $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; - $message.= "\n"; - - $trackid='leav'.$object->id; - - $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - - // Envoi du mail - $result=$mail->sendfile(); - - if (!$result) - { - setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1 - $action=''; - } - } - } - - if (! $error) - { - $db->commit(); - - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - else - { - $db->rollback(); - $action=''; - } - } -} - -if ($action == 'confirm_refuse' && GETPOST('confirm', 'alpha') == 'yes') -{ - if (! empty($_POST['detail_refuse'])) - { - $object->fetch($id); - - // Si statut en attente de validation et valideur = utilisateur - if ($object->statut == Holiday::STATUS_VALIDATED && $user->id == $object->fk_validator) - { - $object->date_refuse = dol_print_date('dayhour', dol_now()); - $object->fk_user_refuse = $user->id; - $object->statut = Holiday::STATUS_REFUSED; - $object->detail_refuse = GETPOST('detail_refuse', 'alphanohtml'); - - $db->begin(); - - $verif = $object->update($user); - if ($verif <= 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - } - - // Si pas d'erreur SQL on redirige vers la fiche de la demande - if (! $error) - { - // To - $destinataire = new User($db); - $destinataire->fetch($object->fk_user); - $emailTo = $destinataire->email; - - if (!$emailTo) - { - dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email"); - } - else - { - // From - $expediteur = new User($db); - $expediteur->fetch($object->fk_validator); - $emailFrom = $expediteur->email; - - // Subject - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - - $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysRefused"); - - // Content - $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; - $message.= "\n"; - $message.= $langs->transnoentities("HolidaysRefusedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; - $message.= GETPOST('detail_refuse', 'alpha')."\n\n"; - - $message.= "- ".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - - $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; - $message.= "\n"; - - $trackid='leav'.$object->id; - - $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - - // Envoi du mail - $result=$mail->sendfile(); - - if (! $result) - { - setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1 - $action=''; - } - } - } - else - { - $action=''; - } - - if (! $error) - { - $db->commit(); - - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - else - { - $db->rollback(); - $action=''; - } - } - } else { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DetailRefusCP")), null, 'errors'); - $action='refuse'; - } -} - - -// Si Validation de la demande -if ($action == 'confirm_draft' && GETPOST('confirm') == 'yes') -{ - $error = 0; - - $object->fetch($id); - - $oldstatus = $object->statut; - $object->statut = Holiday::STATUS_DRAFT; - - $result = $object->update($user); - if ($result < 0) - { - $error++; - setEventMessages($langs->trans('ErrorBackToDraft').' '.$object->error, $object->errors, 'errors'); - } - - if (! $error) - { - $db->commit(); - - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - else - { - $db->rollback(); - } -} - -// Si confirmation of cancellation -if ($action == 'confirm_cancel' && GETPOST('confirm') == 'yes') -{ - $error = 0; - - $object->fetch($id); - - // Si statut en attente de validation et valideur = valideur ou utilisateur, ou droits de faire pour les autres - if (($object->statut == Holiday::STATUS_VALIDATED || $object->statut == Holiday::STATUS_APPROVED) && ($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || ! empty($user->rights->holiday->write_all))) - { - $db->begin(); - - $oldstatus = $object->statut; - $object->date_cancel = dol_now(); - $object->fk_user_cancel = $user->id; - $object->statut = Holiday::STATUS_CANCELED; - - $result = $object->update($user); - - if ($result >= 0 && $oldstatus == Holiday::STATUS_APPROVED) // holiday was already validated, status 3, so we must increase back the balance - { - // Calculcate number of days consummed - $nbopenedday=num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); - - $soldeActuel = $object->getCpforUser($object->fk_user, $object->fk_type); - $newSolde = ($soldeActuel + $nbopenedday); - - // On ajoute la modification dans le LOG - $result1=$object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("HolidaysCancelation"), $newSolde, $object->fk_type); - - // Mise à jour du solde - $result2=$object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type); - - if ($result1 < 0 || $result2 < 0) - { - $error++; - setEventMessages($langs->trans('ErrorCantDeleteCP').' '.$object->error, $object->errors, 'errors'); - } - } - - if (! $error) - { - $db->commit(); - } - else - { - $db->rollback(); - } - - // Si pas d'erreur SQL on redirige vers la fiche de la demande - if (! $error && $result > 0) - { - // To - $destinataire = new User($db); - $destinataire->fetch($object->fk_user); - $emailTo = $destinataire->email; - - if (!$emailTo) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - - // From - $expediteur = new User($db); - $expediteur->fetch($object->fk_user_cancel); - $emailFrom = $expediteur->email; - - // Subject - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - - $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysCanceled"); - - // Content - $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; - $message.= "\n"; - - $message.= $langs->transnoentities("HolidaysCanceledBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; - $message.= "- ".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - - $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; - $message.= "\n"; - - $trackid='leav'.$object->id; - - $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - - // Envoi du mail - $result=$mail->sendfile(); - - if (!$result) - { - setEventMessages($mail->error, $mail->errors, 'warnings'); - $action=''; - } - else - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - } - } + + // Approve leave request + if ($action == 'confirm_valid') + { + $object->fetch($id); + + // Si statut en attente de validation et valideur = utilisateur + if ($object->statut == Holiday::STATUS_VALIDATED && $user->id == $object->fk_validator) + { + $object->oldcopy = dol_clone($object); + + $object->date_valid = dol_now(); + $object->fk_user_valid = $user->id; + $object->statut = Holiday::STATUS_APPROVED; + + $db->begin(); + + $verif = $object->approve($user); + if ($verif <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + + // Si pas d'erreur SQL on redirige vers la fiche de la demande + if (! $error) + { + // Calculcate number of days consummed + $nbopenedday=num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); + $soldeActuel = $object->getCpforUser($object->fk_user, $object->fk_type); + $newSolde = ($soldeActuel - $nbopenedday); + + // On ajoute la modification dans le LOG + $result=$object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $object->fk_type); + if ($result < 0) + { + $error++; + setEventMessages(null, $object->errors, 'errors'); + } + + //Update balance + $result=$object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type); + if ($result < 0) + { + $error++; + setEventMessages(null, $object->errors, 'errors'); + } + } + + if (! $error) + { + // To + $destinataire = new User($db); + $destinataire->fetch($object->fk_user); + $emailTo = $destinataire->email; + + if (!$emailTo) + { + dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email"); + } + else + { + // From + $expediteur = new User($db); + $expediteur->fetch($object->fk_validator); + $emailFrom = $expediteur->email; + + // Subject + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + + $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated"); + + // Content + $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; + $message.= "\n"; + $message.= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; + + $message.= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; + + $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; + $message.= "\n"; + + $trackid='leav'.$object->id; + + $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); + + // Envoi du mail + $result=$mail->sendfile(); + + if (!$result) + { + setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1 + $action=''; + } + } + } + + if (! $error) + { + $db->commit(); + + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + else + { + $db->rollback(); + $action=''; + } + } + } + + if ($action == 'confirm_refuse' && GETPOST('confirm', 'alpha') == 'yes') + { + if (! empty($_POST['detail_refuse'])) + { + $object->fetch($id); + + // Si statut en attente de validation et valideur = utilisateur + if ($object->statut == Holiday::STATUS_VALIDATED && $user->id == $object->fk_validator) + { + $object->date_refuse = dol_print_date('dayhour', dol_now()); + $object->fk_user_refuse = $user->id; + $object->statut = Holiday::STATUS_REFUSED; + $object->detail_refuse = GETPOST('detail_refuse', 'alphanohtml'); + + $db->begin(); + + $verif = $object->update($user); + if ($verif <= 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } + + // Si pas d'erreur SQL on redirige vers la fiche de la demande + if (! $error) + { + // To + $destinataire = new User($db); + $destinataire->fetch($object->fk_user); + $emailTo = $destinataire->email; + + if (!$emailTo) + { + dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email"); + } + else + { + // From + $expediteur = new User($db); + $expediteur->fetch($object->fk_validator); + $emailFrom = $expediteur->email; + + // Subject + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + + $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysRefused"); + + // Content + $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; + $message.= "\n"; + $message.= $langs->transnoentities("HolidaysRefusedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; + $message.= GETPOST('detail_refuse', 'alpha')."\n\n"; + + $message.= "- ".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; + + $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; + $message.= "\n"; + + $trackid='leav'.$object->id; + + $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); + + // Envoi du mail + $result=$mail->sendfile(); + + if (! $result) + { + setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1 + $action=''; + } + } + } + else + { + $action=''; + } + + if (! $error) + { + $db->commit(); + + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + else + { + $db->rollback(); + $action=''; + } + } + } else { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DetailRefusCP")), null, 'errors'); + $action='refuse'; + } + } + + + // Si Validation de la demande + if ($action == 'confirm_draft' && GETPOST('confirm') == 'yes') + { + $error = 0; + + $object->fetch($id); + + $oldstatus = $object->statut; + $object->statut = Holiday::STATUS_DRAFT; + + $result = $object->update($user); + if ($result < 0) + { + $error++; + setEventMessages($langs->trans('ErrorBackToDraft').' '.$object->error, $object->errors, 'errors'); + } + + if (! $error) + { + $db->commit(); + + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + else + { + $db->rollback(); + } + } + + // Si confirmation of cancellation + if ($action == 'confirm_cancel' && GETPOST('confirm') == 'yes') + { + $error = 0; + + $object->fetch($id); + + // Si statut en attente de validation et valideur = valideur ou utilisateur, ou droits de faire pour les autres + if (($object->statut == Holiday::STATUS_VALIDATED || $object->statut == Holiday::STATUS_APPROVED) && ($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || ! empty($user->rights->holiday->write_all))) + { + $db->begin(); + + $oldstatus = $object->statut; + $object->date_cancel = dol_now(); + $object->fk_user_cancel = $user->id; + $object->statut = Holiday::STATUS_CANCELED; + + $result = $object->update($user); + + if ($result >= 0 && $oldstatus == Holiday::STATUS_APPROVED) // holiday was already validated, status 3, so we must increase back the balance + { + // Calculcate number of days consummed + $nbopenedday=num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); + + $soldeActuel = $object->getCpforUser($object->fk_user, $object->fk_type); + $newSolde = ($soldeActuel + $nbopenedday); + + // On ajoute la modification dans le LOG + $result1=$object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("HolidaysCancelation"), $newSolde, $object->fk_type); + + // Mise à jour du solde + $result2=$object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type); + + if ($result1 < 0 || $result2 < 0) + { + $error++; + setEventMessages($langs->trans('ErrorCantDeleteCP').' '.$object->error, $object->errors, 'errors'); + } + } + + if (! $error) + { + $db->commit(); + } + else + { + $db->rollback(); + } + + // Si pas d'erreur SQL on redirige vers la fiche de la demande + if (! $error && $result > 0) + { + // To + $destinataire = new User($db); + $destinataire->fetch($object->fk_user); + $emailTo = $destinataire->email; + + if (!$emailTo) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + + // From + $expediteur = new User($db); + $expediteur->fetch($object->fk_user_cancel); + $emailFrom = $expediteur->email; + + // Subject + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + + $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysCanceled"); + + // Content + $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; + $message.= "\n"; + + $message.= $langs->transnoentities("HolidaysCanceledBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; + $message.= "- ".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; + + $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; + $message.= "\n"; + + $trackid='leav'.$object->id; + + $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); + + // Envoi du mail + $result=$mail->sendfile(); + + if (!$result) + { + setEventMessages($mail->error, $mail->errors, 'warnings'); + $action=''; + } + else + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + } + } + } + + /* + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + + // Actions to send emails + $trigger_name='HOLIDAY_SENTBYMAIL'; + $autocopy='MAIN_MAIL_AUTOCOPY_HOLIDAY_TO'; + $trackid='leav'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + + // Actions to build doc + $upload_dir = $conf->holiday->dir_output; + $permissioncreate = $user->rights->holiday->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + */ } @@ -1049,6 +1111,9 @@ if ((empty($id) && empty($ref)) || $action == 'add' || $action == 'request' || $ print $doleditor->Create(1); print ''; + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + print ''; print '
'; + print ''; $searchpicto=$form->showFilterButtons(); print $searchpicto; print '
'.$langs->trans("NoRecordFound").'
'.$langs->trans("NoRecordFound").'
'; @@ -1134,6 +1199,7 @@ else if ($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) $edit = true; print '
'."\n"; + print ''."\n"; print ''."\n"; print ''."\n"; } @@ -1247,6 +1313,9 @@ else print ''; } + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + print ''; print ''."\n"; @@ -1311,7 +1380,7 @@ else } print ''; - print ''.$langs->trans('DateCreateCP').''; + print ''.$langs->trans('DateCreation').''; print ''.dol_print_date($object->date_create, 'dayhour').''; print ''; if ($object->statut == Holiday::STATUS_APPROVED || $object->statut == Holiday::STATUS_CANCELED) { diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php index d767bcdc691..25d1c1d5a2d 100644 --- a/htdocs/holiday/class/holiday.class.php +++ b/htdocs/holiday/class/holiday.class.php @@ -402,6 +402,8 @@ class Holiday extends CommonObject } $this->db->free($resql); + $this->fetch_optionals(); + return 1; } else @@ -558,6 +560,7 @@ class Holiday extends CommonObject $sql.= " cp.fk_user,"; $sql.= " cp.fk_type,"; $sql.= " cp.date_create,"; + $sql.= " cp.tms as date_update,"; $sql.= " cp.description,"; $sql.= " cp.date_debut,"; $sql.= " cp.date_fin,"; @@ -623,6 +626,7 @@ class Holiday extends CommonObject $tab_result[$i]['fk_user'] = $obj->fk_user; $tab_result[$i]['fk_type'] = $obj->fk_type; $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create); + $tab_result[$i]['date_update'] = $this->db->jdate($obj->date_update); $tab_result[$i]['description'] = $obj->description; $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut); $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin); diff --git a/htdocs/holiday/document.php b/htdocs/holiday/document.php index a594a920e74..6ade6a13e17 100644 --- a/htdocs/holiday/document.php +++ b/htdocs/holiday/document.php @@ -251,7 +251,7 @@ if ($object->id) } print ''; - print ''.$langs->trans('DateCreateCP').''; + print ''.$langs->trans('DateCreation').''; print ''.dol_print_date($object->date_create,'dayhour').''; print ''; if ($object->statut == 3) { diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php index f74d731e8bd..072a6aacc45 100644 --- a/htdocs/holiday/list.php +++ b/htdocs/holiday/list.php @@ -27,6 +27,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; @@ -40,16 +41,19 @@ $langs->loadLangs(array('users', 'holidays', 'hrm')); // Protection if external user if ($user->societe_id > 0) accessforbidden(); -$action = GETPOST('action', 'alpha'); // The action 'add', 'create', 'edit', 'update', 'view', ... +$action = GETPOST('action', 'aZ09'); // 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'):'myobjectlist'; // To manage different context of search +$contextpage= GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'holidaylist'; // 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'); + $childids = $user->getAllChildIds(1); // Security check @@ -59,8 +63,7 @@ if ($user->societe_id > 0) // Protection if external user //$socid = $user->societe_id; accessforbidden(); } -$result = restrictedArea($user, 'holiday', $id, ''); -$id = GETPOST('id', 'int'); +$result = restrictedArea($user, 'holiday', '', ''); // If we are on the view of a specific user if ($id > 0) { @@ -74,6 +77,9 @@ if ($id > 0) } } +$diroutputmassaction=$conf->holiday->dir_output . '/temp/massgeneration/'.$user->id; + + // Load variable for pagination $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); @@ -83,20 +89,8 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; - -// Initialize technical objects -$object=new Holiday($db); -$extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->holiday->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('holidaylist')); // Note that conf->hooks_modules contains array -// Fetch optionals attributes and labels -$extralabels = $extrafields->fetch_name_optionals_label('holiday'); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); - -// Default sort order (if not yet defined by previous GETPOST) -if (! $sortfield) $sortfield="cp.rowid"; -if (! $sortorder) $sortorder="DESC"; - +if (!$sortorder) $sortorder="DESC"; +if (!$sortfield) $sortfield="cp.rowid"; $sall = trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); $search_ref = GETPOST('search_ref', 'alphanohtml'); @@ -114,13 +108,47 @@ $search_valideur = GETPOST('search_valideur', 'int'); $search_statut = GETPOST('search_statut', 'int'); $search_type = GETPOST('search_type', 'int'); +// Initialize technical objects +$object=new Holiday($db); +$extrafields = new ExtraFields($db); +$hookmanager->initHooks(array('holidaylist')); // Note that conf->hooks_modules contains array + +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('holiday'); +$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + // List of fields to search into when doing a "search in all" $fieldstosearchall = array( 'cp.description'=>'Description', 'uu.lastname'=>'EmployeeLastname', - 'uu.firstname'=>'EmployeeFirstname' + 'uu.firstname'=>'EmployeeFirstname', + 'uu.login'=>'Login' ); +$arrayfields=array( + 'cp.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'cp.fk_user'=>array('label'=>$langs->trans("Employee"), 'checked'=>1, 'position'=>20), + 'cp.fk_validator'=>array('label'=>$langs->trans("ValidatorCP"), 'checked'=>1, 'position'=>30), + 'cp.fk_type'=>array('label'=>$langs->trans("Type"), 'checked'=>1, 'position'=>35), + 'duration'=>array('label'=>$langs->trans("NbUseDaysCPShort"), 'checked'=>1, 'position'=>38), + 'cp.date_debut'=>array('label'=>$langs->trans("DateStart"), 'checked'=>1, 'position'=>40), + 'cp.date_fin'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1, 'position'=>42), + 'cp.date_valid'=>array('label'=>$langs->trans("DateValidation"), 'checked'=>1, 'position'=>60), + 'cp.date_approve'=>array('label'=>$langs->trans("DateApprove"), 'checked'=>1, 'position'=>70), + 'cp.date_create'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'cp.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>501), + 'cp.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), +); +// Extra fields +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) +{ + foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) + { + if (! empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key]=array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + } +} + /* @@ -130,7 +158,7 @@ $fieldstosearchall = array( if (GETPOST('cancel', 'alpha')) { $action='list'; $massaction=''; } if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } -$parameters=array(); +$parameters=array('socid'=>$socid); $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'); @@ -180,59 +208,21 @@ if (empty($reshook)) $form = new Form($db); $formother = new FormOther($db); +$formfile = new FormFile($db); -$holiday = new Holiday($db); -$holidaystatic=new Holiday($db); $fuser = new User($db); +$holidaystatic=new Holiday($db); // Update sold -$result = $holiday->updateBalance(); +$result = $object->updateBalance(); + +$title = $langs->trans('CPTitreMenu'); +llxHeader('', $title); $max_year = 5; $min_year = 10; -$filter=''; -llxHeader('', $langs->trans('CPTitreMenu')); - -$order = $db->order($sortfield, $sortorder).$db->plimit($limit + 1, $offset); - -// Ref -if(!empty($search_ref)) -{ - $filter.= " AND cp.rowid = ".(int) $db->escape($search_ref); -} -// Start date -$filter.= dolSqlDateFilter("cp.date_debut", $search_day_start, $search_month_start, $search_year_start); -// End date -$filter.= dolSqlDateFilter("cp.date_fin", $search_day_end, $search_month_end, $search_year_end); -// Create date -$filter.= dolSqlDateFilter("cp.date_create", $search_day_create, $search_month_create, $search_year_create); -// Employee -if(!empty($search_employee) && $search_employee != -1) { - $filter.= " AND cp.fk_user = '".$db->escape($search_employee)."'\n"; -} -// Validator -if(!empty($search_valideur) && $search_valideur != -1) { - $filter.= " AND cp.fk_validator = '".$db->escape($search_valideur)."'\n"; -} -// Type -if (!empty($search_type) && $search_type != -1) { - $filter.= ' AND cp.fk_type IN ('.$db->escape($search_type).')'; -} -// Status -if(!empty($search_statut) && $search_statut != -1) { - $filter.= " AND cp.statut = '".$db->escape($search_statut)."'\n"; -} -// Search all -if (!empty($sall)) -{ - $filter.= natural_search(array_keys($fieldstosearchall), $sall); -} - -if (empty($user->rights->holiday->read_all)) $filter.=' AND cp.fk_user IN ('.join(',', $childids).')'; - - -// Récupération de l'ID de l'utilisateur +// Get current user id $user_id = $user->id; if ($id > 0) @@ -246,356 +236,559 @@ if ($id > 0) } // Récupération des congés payés de l'utilisateur ou de tous les users de sa hierarchy -// Load array $holiday->holiday -if (empty($user->rights->holiday->read_all) || $id > 0) -{ - if ($id > 0) $result = $holiday->fetchByUser($id, $order, $filter); - else $result = $holiday->fetchByUser(join(',', $childids), $order, $filter); -} -else -{ - $result = $holiday->fetchAll($order, $filter); -} -// Si erreur SQL -if ($result == '-1') -{ - print load_fiche_titre($langs->trans('CPTitreMenu'), '', 'title_hrm.png'); +// Load array $object->holiday - dol_print_error($db, $langs->trans('Error').' '.$holiday->error); - exit(); +$sql = "SELECT"; +$sql.= " cp.rowid,"; +$sql.= " cp.ref,"; + +$sql.= " cp.fk_user,"; +$sql.= " cp.fk_type,"; +$sql.= " cp.date_create,"; +$sql.= " cp.tms as date_update,"; +$sql.= " cp.description,"; +$sql.= " cp.date_debut,"; +$sql.= " cp.date_fin,"; +$sql.= " cp.halfday,"; +$sql.= " cp.statut,"; +$sql.= " cp.fk_validator,"; +$sql.= " cp.date_valid,"; +$sql.= " cp.fk_user_valid,"; +$sql.= " cp.date_refuse,"; +$sql.= " cp.fk_user_refuse,"; +$sql.= " cp.date_cancel,"; +$sql.= " cp.fk_user_cancel,"; +$sql.= " cp.detail_refuse,"; + +$sql.= " uu.lastname as user_lastname,"; +$sql.= " uu.firstname as user_firstname,"; +$sql.= " uu.login as user_login,"; +$sql.= " uu.statut as user_statut,"; +$sql.= " uu.photo as user_photo,"; + +$sql.= " ua.lastname as validator_lastname,"; +$sql.= " ua.firstname as validator_firstname,"; +$sql.= " ua.login as validator_login,"; +$sql.= " ua.statut as validator_statut,"; +$sql.= " ua.photo as validator_photo"; +// 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); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +$sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp"; +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."holiday_extrafields as ef on (cp.rowid = ef.fk_object)"; +$sql.= ", ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua"; +$sql.= " WHERE cp.entity IN (".getEntity('holiday').")"; +$sql.= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack pour la recherche sur le tableau +// Search all +if (!empty($sall)) $sql.= natural_search(array_keys($fieldstosearchall), $sall); +// Ref +if(!empty($search_ref)) +{ + $sql.= " AND cp.rowid = ".(int) $db->escape($search_ref); +} +// Start date +$sql.= dolSqlDateFilter("cp.date_debut", $search_day_start, $search_month_start, $search_year_start); +// End date +$sql.= dolSqlDateFilter("cp.date_fin", $search_day_end, $search_month_end, $search_year_end); +// Create date +$sql.= dolSqlDateFilter("cp.date_create", $search_day_create, $search_month_create, $search_year_create); +// Employee +if(!empty($search_employee) && $search_employee != -1) { + $sql.= " AND cp.fk_user = '".$db->escape($search_employee)."'\n"; +} +// Validator +if(!empty($search_valideur) && $search_valideur != -1) { + $sql.= " AND cp.fk_validator = '".$db->escape($search_valideur)."'\n"; +} +// Type +if (!empty($search_type) && $search_type != -1) { + $sql.= ' AND cp.fk_type IN ('.$db->escape($search_type).')'; +} +// Status +if(!empty($search_statut) && $search_statut != -1) { + $sql.= " AND cp.statut = '".$db->escape($search_statut)."'\n"; } +if (empty($user->rights->holiday->read_all)) $sql.=' AND cp.fk_user IN ('.join(',', $childids).')'; +if ($id > 0) $sql.= " AND cp.fk_user IN (".$id.")"; -// Show table of vacations +// 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); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; -$num = count($holiday->holiday); +$sql.= $db->order($sortfield, $sortorder); -$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); -if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); -if ($search_ref) $param.='&search_ref='.urlencode($search_ref); -if ($search_day_create) $param.='&search_day_create='.urlencode($search_day_create); -if ($search_month_create) $param.='&search_month_create='.urlencode($search_month_create); -if ($search_year_create) $param.='&search_year_create='.urlencode($search_year_create); -if ($search_search_day_start) $param.='&search_day_start='.urlencode($search_day_start); -if ($search_month_start) $param.='&search_month_start='.urlencode($search_month_start); -if ($search_year_start) $param.='&search_year_start='.urlencode($search_year_start); -if ($search_day_end) $param.='&search_day_end='.urlencode($search_day_end); -if ($search_month_end) $param.='&search_month_end='.urlencode($search_month_end); -if ($search_year_end) $param.='&search_year_end='.urlencode($search_year_end); -if ($search_employee > 0) $param.='&search_employee='.urlencode($search_employee); -if ($search_valideur > 0) $param.='&search_valideur='.urlencode($search_valideur); -if ($search_type > 0) $param.='&search_type='.urlencode($search_type); -if ($search_statut > 0) $param.='&search_statut='.urlencode($search_statut); - -// List of mass actions available -$arrayofmassactions = array( -//'presend'=>$langs->trans("SendByMail"), -//'builddoc'=>$langs->trans("PDFMerge"), -); -if ($user->rights->holiday->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 ''; -if ($id > 0) print ''; - -if ($id > 0) // For user tab +// Count total nb of records +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $title = $langs->trans("User"); - $linkback = ''.$langs->trans("BackToList").''; - $head = user_prepare_head($fuser); - - dol_fiche_head($head, 'paidholidays', $title, -1, 'user'); - - dol_banner_tab($fuser, 'id', $linkback, $user->rights->user->user->lire || $user->admin); - - if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 { - print '
'; - - print '
'; - - showMyBalance($holiday, $user_id); + $page = 0; + $offset = 0; } - - dol_fiche_end(); - - // Buttons for actions - - print '
'; - - $canedit=(($user->id == $user_id && $user->rights->holiday->write) || ($user->id != $user_id && $user->rights->holiday->write_all)); - - if ($canedit) - { - print ''.$langs->trans("AddCP").''; - } - - print '
'; } -else + +$sql.= $db->plimit($limit+1, $offset); + + +//print $sql; +$resql = $db->query($sql); +if ($resql) { - $nbtotalofrecords = count($holiday->holiday); - //print $num; - //print count($holiday->holiday); + $num = $db->num_rows($resql); - $newcardbutton=''; - if ($user->rights->holiday->write) + $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); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + if ($search_ref) $param.='&search_ref='.urlencode($search_ref); + if ($search_day_create) $param.='&search_day_create='.urlencode($search_day_create); + if ($search_month_create) $param.='&search_month_create='.urlencode($search_month_create); + if ($search_year_create) $param.='&search_year_create='.urlencode($search_year_create); + if ($search_day_start) $param.='&search_day_start='.urlencode($search_day_start); + if ($search_month_start) $param.='&search_month_start='.urlencode($search_month_start); + if ($search_year_start) $param.='&search_year_start='.urlencode($search_year_start); + if ($search_day_end) $param.='&search_day_end='.urlencode($search_day_end); + if ($search_month_end) $param.='&search_month_end='.urlencode($search_month_end); + if ($search_year_end) $param.='&search_year_end='.urlencode($search_year_end); + if ($search_employee > 0) $param.='&search_employee='.urlencode($search_employee); + if ($search_valideur > 0) $param.='&search_valideur='.urlencode($search_valideur); + if ($search_type > 0) $param.='&search_type='.urlencode($search_type); + if ($search_statut > 0) $param.='&search_statut='.urlencode($search_statut); + // Add $param from extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + + // List of mass actions available + $arrayofmassactions = array( + //'generate_doc'=>$langs->trans("ReGeneratePDF"), + //'builddoc'=>$langs->trans("PDFMerge"), + //'presend'=>$langs->trans("SendByMail"), + ); + if ($user->rights->holiday->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); + if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + + // Lines of title fields + print ''."\n"; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if ($id > 0) print ''; + + if ($id > 0) // For user tab { - $newcardbutton.= dolGetButtonTitle($langs->trans('MenuAddCP'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/holiday/card.php?action=request'); - } + $title = $langs->trans("User"); + $linkback = ''.$langs->trans("BackToList").''; + $head = user_prepare_head($fuser); - print_barre_liste($langs->trans("ListeCP"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_hrm.png', 0, $newcardbutton, '', $limit); + dol_fiche_head($head, 'paidholidays', $title, -1, 'user'); + + dol_banner_tab($fuser, 'id', $linkback, $user->rights->user->user->lire || $user->admin); + + if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) + { + print '
'; + + print '
'; + + showMyBalance($object, $user_id); + } + + dol_fiche_end(); + + // Buttons for actions + + print '
'; + + $canedit=(($user->id == $user_id && $user->rights->holiday->write) || ($user->id != $user_id && $user->rights->holiday->write_all)); + + if ($canedit) + { + print ''.$langs->trans("AddCP").''; + } + + print '
'; + } + else + { + $title = $langs->trans("ListeCP"); + + $newcardbutton=''; + if ($user->rights->holiday->write) + { + $newcardbutton.= dolGetButtonTitle($langs->trans('MenuAddCP'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/holiday/card.php?action=request'); + } + + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_hrm.png', 0, $newcardbutton, '', $limit); + } $topicmail="Information"; $modelmail="leaverequest"; $objecttmp=new Holiday($db); $trackid='leav'.$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).'
'; -} - -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=''; // $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - -print '
'; -print ''."\n"; - -// Filters -print ''; -print ''; - -// Create date -print ''; - - -$morefilter = 'AND employee = 1'; -if (! empty($conf->global->HOLIDAY_FOR_NON_SALARIES_TOO)) $morefilter = ''; - -// User -$disabled=0; -// If into the tab holiday of a user ($id is set in such a case) -if ($id && ! GETPOSTISSET('search_employee')) -{ - $search_employee=$id; - $disabled=1; -} -if (! empty($user->rights->holiday->read_all)) // Can see all -{ - if (GETPOSTISSET('search_employee')) $search_employee=GETPOST('search_employee', 'int'); - print ''; -} -else -{ - if (GETPOSTISSET('search_employee')) $search_employee=GETPOST('search_employee', 'int'); - print ''; -} - -// Approve -if ($user->rights->holiday->read_all) -{ - print ''; -} -else -{ - print ''; -} - -// Type -print ''; -// Duration -print ''; + $moreforfilter=''; -// Start date -print ''; + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; + else $moreforfilter = $hookmanager->resPrint; -// End date -print ''; - -// Status -print ''; - -// Actions -print ''; - -print "\n"; - -print ''; -print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "cp.ref", "", $param, '', $sortfield, $sortorder); -print_liste_field_titre("DateCreateCP", $_SERVER["PHP_SELF"], "cp.date_create", "", $param, '', $sortfield, $sortorder, 'center '); -print_liste_field_titre("Employee", $_SERVER["PHP_SELF"], "cp.fk_user", "", $param, '', $sortfield, $sortorder); -print_liste_field_titre("ValidatorCP", $_SERVER["PHP_SELF"], "cp.fk_validator", "", $param, '', $sortfield, $sortorder); -print_liste_field_titre("Type", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); -print_liste_field_titre("NbUseDaysCPShort", $_SERVER["PHP_SELF"], '', '', $pram, '', $sortfield, $sortorder, 'right '); -print_liste_field_titre("DateDebCP", $_SERVER["PHP_SELF"], "cp.date_debut", "", $param, '', $sortfield, $sortorder, 'center '); -print_liste_field_titre("DateFinCP", $_SERVER["PHP_SELF"], "cp.date_fin", "", $param, '', $sortfield, $sortorder, 'center '); -print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "cp.statut", "", $param, '', $sortfield, $sortorder, 'right '); -print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; -print "\n"; - -$listhalfday=array('morning'=>$langs->trans("Morning"),"afternoon"=>$langs->trans("Afternoon")); - - -// If we ask a dedicated card and not allow to see it, we forc on user. -if ($id && empty($user->rights->holiday->read_all) && ! in_array($id, $childids)) { - $langs->load("errors"); - print ''; - $result = 0; -} -elseif (! empty($holiday->holiday) && !empty($mysoc->country_id)) -{ - // Lines - $userstatic = new User($db); - $approbatorstatic = new User($db); - - $typeleaves=$holiday->getTypes(1, -1); - - foreach($holiday->holiday as $infos_CP) + if (! empty($moreforfilter)) { - // Leave request - $holidaystatic->id=$infos_CP['rowid']; - $holidaystatic->ref=($infos_CP['ref']?$infos_CP['ref']:$infos_CP['rowid']); + 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) : ''); + + + $include = ''; + if (! empty($user->rights->holiday->read_all)) $include = 'hierarchyme'; // Can see all + + print '
'; + print '
'; -print ''; -print ''; -print ''; -$formother->select_year($search_year_create, 'search_year_create', 1, $min_year, 0); -print ''; - print $form->select_dolusers($search_employee, "search_employee", 1, "", $disabled, '', '', 0, 0, 0, $morefilter, 0, '', 'maxwidth200'); - print ''; - print $form->select_dolusers($search_employee, "search_employee", 1, "", $disabled, 'hierarchyme', '', 0, 0, 0, $morefilter, 0, '', 'maxwidth200'); - print ''; - - $validator = new UserGroup($db); - $excludefilter=$user->admin?'':'u.rowid <> '.$user->id; - $valideurobjects = $validator->listUsersForGroup($excludefilter); - $valideurarray = array(); - foreach($valideurobjects as $val) $valideurarray[$val->id]=$val->id; - print $form->select_dolusers($search_valideur, "search_valideur", 1, "", 0, $valideurarray, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth200'); - print ' '; -if (empty($mysoc->country_id)) { - setEventMessages(null, array($langs->trans("ErrorSetACountryFirst"),$langs->trans("CompanyFoundation")), 'errors'); -} else { - $typeleaves=$holidaystatic->getTypes(1, -1); - $arraytypeleaves=array(); - foreach($typeleaves as $key => $val) + if ($sall) { - $labeltoshow = ($langs->trans($val['code'])!=$val['code'] ? $langs->trans($val['code']) : $val['label']); - //$labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')':''); - $arraytypeleaves[$val['rowid']]=$labeltoshow; + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
'; } - print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1); -} -print '
 '; -print ''; -$formother->select_year($search_year_start, 'search_year_start', 1, $min_year, $max_year); -print ''; -print ''; -$formother->select_year($search_year_end, 'search_year_end', 1, $min_year, $max_year); -print ''; -$holiday->selectStatutCP($search_statut, 'search_statut'); -print ''; -$searchpicto=$form->showFilterAndCheckAddButtons(0); -print $searchpicto; -print '
'.$langs->trans("NotEnoughPermissions").'
'."\n"; + + + // Filters + print ''; + + if (! empty($arrayfields['cp.ref']['checked'])) + { + print ''; + } + + if (! empty($arrayfields['cp.fk_user']['checked'])) + { + $morefilter = 'AND employee = 1'; + if (! empty($conf->global->HOLIDAY_FOR_NON_SALARIES_TOO)) $morefilter = ''; // User - $userstatic->id=$infos_CP['fk_user']; - $userstatic->lastname=$infos_CP['user_lastname']; - $userstatic->firstname=$infos_CP['user_firstname']; - $userstatic->login=$infos_CP['user_login']; - $userstatic->statut=$infos_CP['user_statut']; - $userstatic->photo=$infos_CP['user_photo']; + $disabled=0; + // If into the tab holiday of a user ($id is set in such a case) + if ($id && ! GETPOSTISSET('search_employee')) + { + $search_employee=$id; + $disabled=1; + } - // Validator - $approbatorstatic->id=$infos_CP['fk_validator']; - $approbatorstatic->lastname=$infos_CP['validator_lastname']; - $approbatorstatic->firstname=$infos_CP['validator_firstname']; - $approbatorstatic->login=$infos_CP['validator_login']; - $approbatorstatic->statut=$infos_CP['validator_statut']; - $approbatorstatic->photo=$infos_CP['validator_photo']; - - $date = $infos_CP['date_create']; - - $starthalfday=($infos_CP['halfday'] == -1 || $infos_CP['halfday'] == 2)?'afternoon':'morning'; - $endhalfday=($infos_CP['halfday'] == 1 || $infos_CP['halfday'] == 2)?'morning':'afternoon'; - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - // Action column - print ''; - - print ''."\n"; } -} -// Si il n'y a pas d'enregistrement suite à une recherche -if ($result == '2') -{ - print ''; - print ''; - print ''; -} + // Approver + if (! empty($arrayfields['cp.fk_validator']['checked'])) + { + if ($user->rights->holiday->read_all) + { + print ''; + } + else + { + print ''; + } + } -print '
'; + print ''; + print '
'; - print $holidaystatic->getNomUrl(1, 1); + print ''; + print $form->select_dolusers($search_employee, "search_employee", 1, "", $disabled, $include, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth200'); print ''.dol_print_date($date, 'day').''.$userstatic->getNomUrl(-1, 'leave').''.$approbatorstatic->getNomUrl(-1).''; - $labeltypeleavetoshow = ($langs->trans($typeleaves[$infos_CP['fk_type']]['code'])!=$typeleaves[$infos_CP['fk_type']]['code'] ? $langs->trans($typeleaves[$infos_CP['fk_type']]['code']) : $typeleaves[$infos_CP['fk_type']]['label']); - print empty($typeleaves[$infos_CP['fk_type']]['label']) ? $langs->trans("TypeWasDisabledOrRemoved", $infos_CP['fk_type']) : $labeltypeleavetoshow; - print ''; - $nbopenedday=num_open_day($infos_CP['date_debut_gmt'], $infos_CP['date_fin_gmt'], 0, 1, $infos_CP['halfday']); - print $nbopenedday.' '.$langs->trans('DurationDays'); - print ''; - print dol_print_date($infos_CP['date_debut'], 'day'); - print ' ('.$langs->trans($listhalfday[$starthalfday]).')'; - print ''; - print dol_print_date($infos_CP['date_fin'], 'day'); - print ' ('.$langs->trans($listhalfday[$endhalfday]).')'; - print ''.$holidaystatic->LibStatut($infos_CP['statut'], 5).''; - 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($infos_CP['rowid'], $arrayofselected)) $selected=1; - print ''; - } - print '
'.$langs->trans('NoRecordFound').'
'; + $validator = new UserGroup($db); + $excludefilter=$user->admin?'':'u.rowid <> '.$user->id; + $valideurobjects = $validator->listUsersForGroup($excludefilter); + $valideurarray = array(); + foreach($valideurobjects as $val) $valideurarray[$val->id]=$val->id; + print $form->select_dolusers($search_valideur, "search_valideur", 1, "", 0, $valideurarray, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth200'); + print ' 
'; -print '
'; + // Type + if (! empty($arrayfields['cp.fk_type']['checked'])) + { + print ''; + if (empty($mysoc->country_id)) { + setEventMessages(null, array($langs->trans("ErrorSetACountryFirst"),$langs->trans("CompanyFoundation")), 'errors'); + } else { + $typeleaves=$holidaystatic->getTypes(1, -1); + $arraytypeleaves=array(); + foreach($typeleaves as $key => $val) + { + $labeltoshow = ($langs->trans($val['code'])!=$val['code'] ? $langs->trans($val['code']) : $val['label']); + //$labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')':''); + $arraytypeleaves[$val['rowid']]=$labeltoshow; + } + print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1); + } + print ''; + } -print '
'; + // Duration + if (! empty($arrayfields['duration']['checked'])) + { + print ' '; + } -/*if ($user_id == $user->id) -{ - print '
'; - print '
'; - print ''.$langs->trans('AddCP').''; + // Start date + if (! empty($arrayfields['cp.date_debut']['checked'])) + { + print ''; + print ''; + $formother->select_year($search_year_start, 'search_year_start', 1, $min_year, $max_year); + print ''; + } + + // End date + if (! empty($arrayfields['cp.date_fin']['checked'])) + { + print ''; + print ''; + $formother->select_year($search_year_end, 'search_year_end', 1, $min_year, $max_year); + 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); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + + // Create date + if (! empty($arrayfields['cp.date_create']['checked'])) + { + print ''; + print ''; + $formother->select_year($search_year_create, 'search_year_create', 1, $min_year, 0); + print ''; + } + + // Create date + if (! empty($arrayfields['cp.tms']['checked'])) + { + print ''; + print ''; + $formother->select_year($search_year_update, 'search_year_update', 1, $min_year, 0); + print ''; + } + + // Status + if (! empty($arrayfields['cp.statut']['checked'])) + { + print ''; + $object->selectStatutCP($search_statut, 'search_statut'); + print ''; + } + + // Action column + print ''; + $searchpicto=$form->showFilterButtons(); + print $searchpicto; + print ''; + + print "\n"; + + print ''; + if (! empty($arrayfields['cp.ref']['checked'])) print_liste_field_titre($arrayfields['cp.ref']['label'], $_SERVER["PHP_SELF"], "cp.ref", "", $param, '', $sortfield, $sortorder); + if (! empty($arrayfields['cp.fk_user']['checked'])) print_liste_field_titre($arrayfields['cp.fk_user']['label'], $_SERVER["PHP_SELF"], "cp.fk_user", "", $param, '', $sortfield, $sortorder); + if (! empty($arrayfields['cp.fk_validator']['checked'])) print_liste_field_titre($arrayfields['cp.fk_validator']['label'], $_SERVER["PHP_SELF"], "cp.fk_validator", "", $param, '', $sortfield, $sortorder); + if (! empty($arrayfields['cp.fk_type']['checked'])) print_liste_field_titre($arrayfields['cp.fk_type']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); + if (! empty($arrayfields['duration']['checked'])) print_liste_field_titre($arrayfields['duration']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['cp.date_debut']['checked'])) print_liste_field_titre($arrayfields['cp.date_debut']['label'], $_SERVER["PHP_SELF"], "cp.date_debut", "", $param, '', $sortfield, $sortorder, 'center '); + if (! empty($arrayfields['cp.date_fin']['checked'])) print_liste_field_titre($arrayfields['cp.date_fin']['label'], $_SERVER["PHP_SELF"], "cp.date_fin", "", $param, '', $sortfield, $sortorder, 'center '); + // 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); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['cp.date_create']['checked'])) print_liste_field_titre($arrayfields['cp.date_create']['label'], $_SERVER["PHP_SELF"], "cp.date_create", "", $param, '', $sortfield, $sortorder, 'center '); + if (! empty($arrayfields['cp.tms']['checked'])) print_liste_field_titre($arrayfields['cp.tms']['label'], $_SERVER["PHP_SELF"], "cp.tms", "", $param, '', $sortfield, $sortorder, 'center '); + if (! empty($arrayfields['cp.statut']['checked'])) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "cp.statut", "", $param, '', $sortfield, $sortorder, 'right '); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); + print "\n"; + + $listhalfday=array('morning'=>$langs->trans("Morning"),"afternoon"=>$langs->trans("Afternoon")); + + + // If we ask a dedicated card and not allow to see it, we force on user. + if ($id && empty($user->rights->holiday->read_all) && ! in_array($id, $childids)) { + $langs->load("errors"); + print ''.$langs->trans("NotEnoughPermissions").''; + $result = 0; + } + elseif ($num > 0 && !empty($mysoc->country_id)) + { + // Lines + $userstatic = new User($db); + $approbatorstatic = new User($db); + + $typeleaves=$object->getTypes(1, -1); + + $i = 0; + $totalarray=array(); + while ($i < min($num, $limit)) + { + $obj = $db->fetch_object($resql); + + // Leave request + $holidaystatic->id=$obj->rowid; + $holidaystatic->ref=($obj->ref?$obj->ref:$obj->rowid); + + // User + $userstatic->id=$obj->fk_user; + $userstatic->lastname=$obj->user_lastname; + $userstatic->firstname=$obj->user_firstname; + $userstatic->login=$obj->user_login; + $userstatic->statut=$obj->user_statut; + $userstatic->photo=$obj->user_photo; + + // Validator + $approbatorstatic->id=$obj->fk_validator; + $approbatorstatic->lastname=$obj->validator_lastname; + $approbatorstatic->firstname=$obj->validator_firstname; + $approbatorstatic->login=$obj->validator_login; + $approbatorstatic->statut=$obj->validator_statut; + $approbatorstatic->photo=$obj->validator_photo; + + $date = $obj->date_create; + $date_modif = $obj->date_update; + + $starthalfday=($obj->halfday == -1 || $obj->halfday == 2)?'afternoon':'morning'; + $endhalfday=($obj->halfday == 1 || $obj->halfday == 2)?'morning':'afternoon'; + + print ''; + + if (! empty($arrayfields['cp.ref']['checked'])) + { + print ''; + print $holidaystatic->getNomUrl(1, 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['cp.fk_user']['checked'])) + { + print ''.$userstatic->getNomUrl(-1, 'leave').''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['cp.fk_validator']['checked'])) + { + print ''.$approbatorstatic->getNomUrl(-1).''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['cp.fk_type']['checked'])) + { + print ''; + $labeltypeleavetoshow = ($langs->trans($typeleaves[$obj->fk_type]['code'])!=$typeleaves[$obj->fk_type]['code'] ? $langs->trans($typeleaves[$obj->fk_type]['code']) : $typeleaves[$obj->fk_type]['label']); + print empty($typeleaves[$obj->fk_type]['label']) ? $langs->trans("TypeWasDisabledOrRemoved", $obj->fk_type) : $labeltypeleavetoshow; + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['duration']['checked'])) + { + print ''; + $nbopenedday=num_open_day($db->jdate($obj->date_debut, 1), $db->jdate($obj->date_fin, 1), 0, 1, $obj->halfday); + print $nbopenedday.' '.$langs->trans('DurationDays'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['cp.date_debut']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->date_debut), 'day'); + print ' ('.$langs->trans($listhalfday[$starthalfday]).')'; + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['cp.date_fin']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->date_fin), 'day'); + print ' ('.$langs->trans($listhalfday[$endhalfday]).')'; + print ''; + if (! $i) $totalarray['nbfield']++; + } + + // 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); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + + // Date creation + if (! empty($arrayfields['cp.date_create']['checked'])) + { + print ''.dol_print_date($date, 'dayhour').''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['cp.tms']['checked'])) + { + print ''.dol_print_date($date_modif, 'dayhour').''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['cp.statut']['checked'])) + { + print ''.$holidaystatic->LibStatut($obj->statut, 5).''; + if (! $i) $totalarray['nbfield']++; + } + + // Action column + 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 ''; + if (! $i) $totalarray['nbfield']++; + + print ''."\n"; + + $i++; + } + } + + // Si il n'y a pas d'enregistrement suite à une recherche + if ($num == 0) + { + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print ''.$langs->trans("NoRecordFound").''; + } + + print ''; print '
'; -}*/ + + print ''; +} +else +{ + dol_print_error($db); +} // End of page llxFooter(); diff --git a/htdocs/install/check.php b/htdocs/install/check.php index c4d580bf99f..1e248071135 100644 --- a/htdocs/install/check.php +++ b/htdocs/install/check.php @@ -35,7 +35,7 @@ $allowinstall = 0; $allowupgrade = false; $checksok = 1; -$setuplang=GETPOST("selectlang", 'az09', 3)?GETPOST("selectlang", 'az09', 3):$langs->getDefaultLang(); +$setuplang=GETPOST("selectlang", 'aZ09', 3)?GETPOST("selectlang", 'aZ09', 3):$langs->getDefaultLang(); $langs->setDefaultLang($setuplang); $langs->load("install"); diff --git a/htdocs/install/mysql/data/llx_c_action_trigger.sql b/htdocs/install/mysql/data/llx_c_action_trigger.sql index aaa96e3136a..0e2a1875e21 100644 --- a/htdocs/install/mysql/data/llx_c_action_trigger.sql +++ b/htdocs/install/mysql/data/llx_c_action_trigger.sql @@ -113,12 +113,13 @@ insert into llx_c_action_trigger (code,label,description,elementtype,rang) value insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('TICKET_CLOSE','Ticket closed','Executed when a ticket is closed','ticket',165); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('TICKET_SENTBYMAIL','Ticket message sent by email','Executed when a message is sent from the ticket record','ticket',166); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('TICKET_DELETE','Ticket deleted','Executed when a ticket is deleted','ticket',167); --- actions not enabled by default (no constant created for that) when we enable module agenda +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('USER_SENTBYMAIL','Email sent','Executed when an email is sent from user card','user',300); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PRODUCT_MODIFY','Product or service modified','Executed when a product or sevice is modified','product',41); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MEMBER_MODIFY','Member modified','Executed when a member is modified','member',23); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('FICHINTER_MODIFY','Intervention modified','Executed when a intervention is modified','ficheinter',19); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PROJECT_CREATE','Project creation','Executed when a project is created','project',140); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PROJECT_MODIFY','Project modified','Executed when a project is modified','project',142); +-- actions not enabled by default : they are excluded when we enable the module Agenda (except TASK_...) insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('TASK_CREATE','Task created','Executed when a project task is created','project',150); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('TASK_MODIFY','Task modified','Executed when a project task is modified','project',151); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('TASK_DELETE','Task deleted','Executed when a project task is deleted','project',152); diff --git a/htdocs/install/mysql/migration/10.0.0-11.0.0.sql b/htdocs/install/mysql/migration/10.0.0-11.0.0.sql index 92dcdce1128..45bd666abb0 100644 --- a/htdocs/install/mysql/migration/10.0.0-11.0.0.sql +++ b/htdocs/install/mysql/migration/10.0.0-11.0.0.sql @@ -33,6 +33,23 @@ ALTER TABLE llx_account_bookkeeping ADD COLUMN date_export datetime DEFAULT NULL ALTER TABLE llx_expensereport ADD COLUMN paid smallint default 0 NOT NULL; UPDATE llx_expensereport set paid = 1 WHERE fk_statut = 6 and paid = 0; + +-- For v11 + +create table llx_holiday_extrafields +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp, + fk_object integer NOT NULL, + import_key varchar(14) -- import key +) ENGINE=innodb; + +ALTER TABLE llx_holiday_extrafields ADD INDEX idx_holiday_extrafields (fk_object); + +ALTER TABLE llx_societe_rib MODIFY label varchar(200); + +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('USER_SENTBYMAIL','Email sent','Executed when an email is sent from user card','user',300); + create table llx_entrepot_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, diff --git a/htdocs/install/mysql/tables/llx_holiday_extrafields.key.sql b/htdocs/install/mysql/tables/llx_holiday_extrafields.key.sql new file mode 100644 index 00000000000..6558fdef503 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_holiday_extrafields.key.sql @@ -0,0 +1,21 @@ +-- =================================================================== +-- 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 . +-- +-- =================================================================== + + +ALTER TABLE llx_holiday_extrafields ADD INDEX idx_holiday_extrafields (fk_object); + diff --git a/htdocs/install/mysql/tables/llx_holiday_extrafields.sql b/htdocs/install/mysql/tables/llx_holiday_extrafields.sql new file mode 100644 index 00000000000..29881bbb0cb --- /dev/null +++ b/htdocs/install/mysql/tables/llx_holiday_extrafields.sql @@ -0,0 +1,26 @@ +-- ======================================================================== +-- 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 . +-- +-- ======================================================================== + +create table llx_holiday_extrafields +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp, + fk_object integer NOT NULL, + import_key varchar(14) -- import key +) ENGINE=innodb; + diff --git a/htdocs/install/mysql/tables/llx_societe_rib.sql b/htdocs/install/mysql/tables/llx_societe_rib.sql index 5bfc6d10fd6..adabd0ab35f 100644 --- a/htdocs/install/mysql/tables/llx_societe_rib.sql +++ b/htdocs/install/mysql/tables/llx_societe_rib.sql @@ -24,7 +24,7 @@ create table llx_societe_rib ( rowid integer AUTO_INCREMENT PRIMARY KEY, type varchar(32) DEFAULT 'ban' NOT NULL, -- 'ban' or 'paypal' or 'card' or 'stripe' - label varchar(30), + label varchar(200), fk_soc integer NOT NULL, datec datetime, tms timestamp, diff --git a/htdocs/install/repair.php b/htdocs/install/repair.php index d34d43384d0..95ad4d2d563 100644 --- a/htdocs/install/repair.php +++ b/htdocs/install/repair.php @@ -42,7 +42,7 @@ error_reporting(0); @set_time_limit(120); error_reporting($err); -$setuplang=GETPOST("selectlang", 'az09', 3)?GETPOST("selectlang", 'az09', 3):'auto'; +$setuplang=GETPOST("selectlang", 'aZ09', 3)?GETPOST("selectlang", 'aZ09', 3):'auto'; $langs->setDefaultLang($setuplang); $langs->loadLangs(array("admin","install","other")); diff --git a/htdocs/langs/en_US/holiday.lang b/htdocs/langs/en_US/holiday.lang index 145f996c4f2..9e31180f3ea 100644 --- a/htdocs/langs/en_US/holiday.lang +++ b/htdocs/langs/en_US/holiday.lang @@ -8,7 +8,6 @@ NotActiveModCP=You must enable the module Leave to view this page. AddCP=Make a leave request DateDebCP=Start date DateFinCP=End date -DateCreateCP=Creation date DraftCP=Draft ToReviewCP=Awaiting approval ApprovedCP=Approved diff --git a/htdocs/langs/fr_NC/admin.lang b/htdocs/langs/fr_NC/admin.lang index d86b324fdc5..f7c25610e3f 100644 --- a/htdocs/langs/fr_NC/admin.lang +++ b/htdocs/langs/fr_NC/admin.lang @@ -1,4 +1,4 @@ # Dolibarr language file - Source file is en_US - admin -VATManagement=Gestion TSS -VATIsUsedDesc=Le taux de TSS proposé par défaut lors de la création de proposition commerciale, facture, commande, etc... répond à la règle standard suivante :
Si vendeur non assujetti à TSS, TSS par défaut=0. Fin de règle.
Si le (pays vendeur= pays acheteur) alors TSS par défaut=TSS du produit vendu. Fin de règle.
Si vendeur et acheteur dans Communauté européenne et bien vendu= moyen de transport neuf (auto, bateau, avion), TSS par défaut=0 (La TSS doit être payée par acheteur au centre d'impôts de son pays et non au vendeur). Fin de règle.
Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TSS par défaut=TSS du produit vendu. Fin de règle.
Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TSS par défaut=0. Fin de règle.
Sinon TSS proposée par défaut=0. Fin de règle.
-VATIsNotUsedDesc=Le taux de TSS proposé par défaut est 0. C'est le cas d'associations, particuliers ou certaines petites sociétés. +VATManagement=Gestion TGC +VATIsUsedDesc=Le taux de TGC proposé par défaut lors de la création de proposition commerciale, facture, commande, etc... répond à la règle standard suivante :
Si vendeur non assujetti à TGC, TGC par défaut=0. Fin de règle.
Si le (pays vendeur= pays acheteur) alors TGC par défaut=TGC du produit vendu. Fin de règle.
Si vendeur et acheteur dans Communauté européenne et bien vendu= moyen de transport neuf (auto, bateau, avion), TGC par défaut=0 (La TGC doit être payée par acheteur au centre d'impôts de son pays et non au vendeur). Fin de règle.
Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TGC par défaut=TGC du produit vendu. Fin de règle.
Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TGC par défaut=0. Fin de règle.
Sinon TGC proposée par défaut=0. Fin de règle.
+VATIsNotUsedDesc=Le taux de TGC proposé par défaut est 0. C'est le cas d'associations, particuliers ou certaines petites sociétés. diff --git a/htdocs/langs/fr_NC/companies.lang b/htdocs/langs/fr_NC/companies.lang index 9853f7e7e21..c3520226e42 100644 --- a/htdocs/langs/fr_NC/companies.lang +++ b/htdocs/langs/fr_NC/companies.lang @@ -1,3 +1,3 @@ # Dolibarr language file - Source file is en_US - companies -VATIsUsed=Assujetti à la TSS -VATIsNotUsed=Non assujetti à la TSS +VATIsUsed=Assujetti à la TGC +VATIsNotUsed=Non assujetti à la TGC diff --git a/htdocs/langs/fr_NC/compta.lang b/htdocs/langs/fr_NC/compta.lang index f22e834c4a5..2d7a5468f84 100644 --- a/htdocs/langs/fr_NC/compta.lang +++ b/htdocs/langs/fr_NC/compta.lang @@ -1,21 +1,21 @@ # Dolibarr language file - Source file is en_US - compta -VATToPay=TSS ventes -VATReceived=TSS collectée -VATToCollect=TSS achats -VATSummary=Balance de TSS -VATPaid=TSS payée -VATCollected=TSS récupérée -PaymentVat=Règlement TSS -VATPayment=Règlement TSS -VATPayments=Règlements TSS -ShowVatPayment=Affiche paiement TSS -RulesResultInOut=- Il inclut les règlements effectivement réalisés pour les factures, les charges et la TSS.
- Il se base sur la date de règlement de ces factures, charges et TSS. -VATReportByCustomersInInputOutputMode=Rapport par client des TSS collectées et payées (TSS sur encaissement) -VATReportByQuartersInInputOutputMode=Rapport par taux des TSS collectées et payées (TSS sur encaissement) -SeeVATReportInInputOutputMode=Voir le rapport %sTSS encaissement%s pour mode de calcul standard -SeeVATReportInDueDebtMode=Voir le rapport %sTSS sur débit%s pour mode de calcul avec option sur les débits -RulesVATInServices=- Pour les services, le rapport inclut les TSS des règlements effectivement reçus ou émis en se basant sur la date du règlement. -RulesVATInProducts=- Pour les biens matériels, il inclut les TSS des factures en se basant sur la date de facture. -RulesVATDueServices=- Pour les services, le rapport inclut les TSS des factures dues, payées ou non en se basant sur la date de facture. -RulesVATDueProducts=- Pour les biens matériels, il inclut les TSS des factures en se basant sur la date de facture. -CalculationRuleDesc=Pour calculer le total de TSS, il existe 2 modes:
Le mode 1 consiste à arrondir la TSS de chaque ligne et à sommer cet arrondi.
Le mode 2 consiste à sommer la tva de chaque ligne puis à l'arrondir.
Les résultats peuvent différer de quelques centimes. Le mode par défaut est le mode %s. +VATToPay=TGC ventes +VATReceived=TGC collectée +VATToCollect=TGC achats +VATSummary=Balance de TGC +VATPaid=TGC payée +VATCollected=TGC récupérée +PaymentVat=Règlement TGC +VATPayment=Règlement TGC +VATPayments=Règlements TGC +ShowVatPayment=Affiche paiement TGC +RulesResultInOut=- Il inclut les règlements effectivement réalisés pour les factures, les charges et la TGC.
- Il se base sur la date de règlement de ces factures, charges et TGC. +VATReportByCustomersInInputOutputMode=Rapport par client des TGC collectées et payées (TGC sur encaissement) +VATReportByQuartersInInputOutputMode=Rapport par taux des TGC collectées et payées (TGC sur encaissement) +SeeVATReportInInputOutputMode=Voir le rapport %sTGC encaissement%s pour mode de calcul standard +SeeVATReportInDueDebtMode=Voir le rapport %sTGC sur débit%s pour mode de calcul avec option sur les débits +RulesVATInServices=- Pour les services, le rapport inclut les TGC des règlements effectivement reçus ou émis en se basant sur la date du règlement. +RulesVATInProducts=- Pour les biens matériels, il inclut les TGC des factures en se basant sur la date de facture. +RulesVATDueServices=- Pour les services, le rapport inclut les TGC des factures dues, payées ou non en se basant sur la date de facture. +RulesVATDueProducts=- Pour les biens matériels, il inclut les TGC des factures en se basant sur la date de facture. +CalculationRuleDesc=Pour calculer le total de TGC, il existe 2 modes:
Le mode 1 consiste à arrondir la TGC de chaque ligne et à sommer cet arrondi.
Le mode 2 consiste à sommer la tva de chaque ligne puis à l'arrondir.
Les résultats peuvent différer de quelques centimes. Le mode par défaut est le mode %s. diff --git a/htdocs/langs/fr_NC/main.lang b/htdocs/langs/fr_NC/main.lang index 82c7a4ee746..c2d48114259 100644 --- a/htdocs/langs/fr_NC/main.lang +++ b/htdocs/langs/fr_NC/main.lang @@ -3,7 +3,7 @@ DIRECTION=ltr FONTFORPDF=helvetica FONTSIZEFORPDF=10 SeparatorDecimal=, -SeparatorThousand=None +SeparatorThousand=Space FormatDateShort=%d/%m/%Y FormatDateShortInput=%d/%m/%Y FormatDateShortJava=dd/MM/yyyy @@ -20,7 +20,7 @@ FormatDateHourSecShort=%d/%m/%Y %H:%M:%S FormatDateHourTextShort=%d %b %Y %H:%M FormatDateHourText=%d %B %Y %H:%M ErrorNoVATRateDefinedForSellerCountry=Erreur, aucun taux de taxe défini pour le pays '%s'. -AmountVAT=Montant TSS -TotalVAT=Total TSS -VAT=TSS -VATRate=Taux TSS +AmountVAT=Montant TGC +TotalVAT=Total TGC +VAT=TGC +VATRate=Taux TGC diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index 014ca843236..5fd79e96c23 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -79,6 +79,8 @@ function testSqlAndScriptInject($val, $type) $inj += preg_match('/union.+select/i', $val); $inj += preg_match('/(\.\.%2f)+/i', $val); } + // For XSS Injection done by closing textarea to exucute content into a textarea field + $inj += preg_match('/<\/textarea/i', $val); // For XSS Injection done by adding javascript with script // This is all cases a browser consider text is javascript: // When it found ''.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST)); diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index dd88c3dfa8a..647ffda194d 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -3487,7 +3487,7 @@ class Product extends CommonObject * @param int $id_fourn Supplier id * @param string $ref_fourn Supplier ref * @param float $quantity Quantity minimum for price - * @return int < 0 if KO, 0 if link already exists for this product, > 0 if OK + * @return int < 0 if KO, 0 if link already exists for this product, > 0 if OK */ public function add_fournisseur($user, $id_fourn, $ref_fourn, $quantity) { @@ -3498,6 +3498,9 @@ class Product extends CommonObject dol_syslog(get_class($this)."::add_fournisseur id_fourn = ".$id_fourn." ref_fourn=".$ref_fourn." quantity=".$quantity, LOG_DEBUG); + // Clean parameters + $quantity = price2num($quantity, 'MS'); + if ($ref_fourn) { $sql = "SELECT rowid, fk_product"; $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; @@ -3524,7 +3527,7 @@ class Product extends CommonObject if ($ref_fourn) { $sql.= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'"; } else { $sql.= " AND (ref_fourn = '' OR ref_fourn IS NULL)"; } - $sql.= " AND quantity = '".$quantity."'"; + $sql.= " AND quantity = ".$quantity; $sql.= " AND fk_product = ".$this->id; $sql.= " AND entity IN (".getEntity('productsupplierprice').")"; diff --git a/htdocs/product/fournisseurs.php b/htdocs/product/fournisseurs.php index cb56ff63cfc..42644f24098 100644 --- a/htdocs/product/fournisseurs.php +++ b/htdocs/product/fournisseurs.php @@ -154,7 +154,7 @@ if (empty($reshook)) if (empty($ref_fourn)) $ref_fourn=GETPOST("search_ref_fourn"); $ref_fourn_old=GETPOST("ref_fourn_old"); if (empty($ref_fourn_old)) $ref_fourn_old = $ref_fourn; - $quantity=GETPOST("qty"); + $quantity=price2num(GETPOST("qty", 'nohtml'), 'MS'); $remise_percent=price2num(GETPOST('remise_percent', 'alpha')); $npr = preg_match('/\*/', $_POST['tva_tx']) ? 1 : 0 ; $tva_tx = str_replace('*', '', GETPOST('tva_tx', 'alpha')); @@ -481,7 +481,7 @@ if ($id > 0 || $ref) print ''; print ''.$langs->trans("QtyMin").''; print ''; - $quantity = GETPOST('qty') ? GETPOST('qty') : "1"; + $quantity = GETPOSTISSET('qty') ? price2num(GETPOST('qty', 'nohtml'), 'MS') : "1"; if ($rowid) { print ''; diff --git a/htdocs/public/paybox/index.php b/htdocs/public/paybox/index.php deleted file mode 100644 index 58d748aba72..00000000000 --- a/htdocs/public/paybox/index.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * 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/public/paybox/index.php - * \ingroup core - * \brief A redirect page to an error - * \author Laurent Destailleur - */ - -require '../../master.inc.php'; - -header("Location: ".DOL_URL_ROOT.'/public/error-404.php'); diff --git a/htdocs/public/paybox/newpayment.php b/htdocs/public/paybox/newpayment.php deleted file mode 100644 index 319c40f2c18..00000000000 --- a/htdocs/public/paybox/newpayment.php +++ /dev/null @@ -1,49 +0,0 @@ - - * Copyright (C) 2006-2012 Laurent Destailleur - * Copyright (C) 2009 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 . - */ - -/** - * \file htdocs/public/paybox/newpayment.php - * \ingroup paybox - * \brief File to offer a way to make a payment for a particular Dolibarr entity - * \author Laurent Destailleur - */ - -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. - -// For MultiCompany module. -// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php -// TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/paybox/lib/paybox.lib.php'; -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'; - -// Security check -if (empty($conf->paybox->enabled)) accessforbidden('', 0, 0, 1); - -$newurl = $_SERVER['REQUEST_URI']; -$newurl = preg_replace('/\/paybox\/newpayment/', '/payment/newpayment', $newurl); -header("Location: ".$newurl.(preg_match('/\?/', $newurl)?'&':'?').'paymentmethod=paybox'); -exit; diff --git a/htdocs/public/paybox/paymentko.php b/htdocs/public/paybox/paymentko.php deleted file mode 100644 index a2f9f52e9e5..00000000000 --- a/htdocs/public/paybox/paymentko.php +++ /dev/null @@ -1,162 +0,0 @@ - - * Copyright (C) 2006-2013 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 . - */ - -/** - * \file htdocs/public/paybox/paymentko.php - * \ingroup paybox - * \brief File to show page after a failed payment - */ - -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. - -// For MultiCompany module. -// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php -// TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/paybox/lib/paybox.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - -// Security check -if (empty($conf->paybox->enabled)) accessforbidden('', 0, 0, 1); - -$langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal", "stripe")); - -$object = new stdClass(); // For triggers - -$paymentmethod='paybox'; - - -/* - * Actions - */ - - - - - -/* - * View - */ - -dol_syslog("Callback url when a PayBox payment was canceled. query_string=".(dol_escape_htmltag($_SERVER["QUERY_STRING"])?dol_escape_htmltag($_SERVER["QUERY_STRING"]):'')." script_uri=".(dol_escape_htmltag($_SERVER["SCRIPT_URI"])?dol_escape_htmltag($_SERVER["SCRIPT_URI"]):''), LOG_DEBUG, 0, '_paybox'); - -$tracepost = ""; -foreach($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; -dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_paybox'); - - -if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice -{ - // Get on url call - $fulltag = $FULLTAG; - $onlinetoken = empty($PAYPALTOKEN)?$_SESSION['onlinetoken']:$PAYPALTOKEN; - $payerID = empty($PAYPALPAYERID)?$_SESSION['payerID']:$PAYPALPAYERID; - // Set by newpayment.php - $paymentType = $_SESSION['PaymentType']; - $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; - // From env - $ipaddress = $_SESSION['ipaddress']; - - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result=$interface->run_triggers('PAYBOX_PAYMENT_OK', $object, $user, $langs, $conf); - if ($result < 0) { $error++; $errors=$interface->errors; } - // Fin appel triggers - - // Send an email - $sendemail = ''; - if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) $sendemail=$conf->global->ONLINE_PAYMENT_SENDEMAIL; - - if ($sendemail) - { - $sendto=$sendemail; - $from=$conf->global->MAILING_EMAIL_FROM; - - // Define link to login card - $appli=constant('DOL_APPLICATION_TITLE'); - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) - { - $appli=$conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")"; // If new title contains a version that is different than core - } - else $appli.=" ".DOL_VERSION; - } - else $appli.=" ".DOL_VERSION; - - $urlback=$_SERVER["REQUEST_URI"]; - $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentFailed"); - $content=""; - $content.=$langs->transnoentitiesnoconv("ValidationOfOnlinePaymentFailed")."\n"; - $content.="\n"; - $content.=$langs->transnoentitiesnoconv("TechnicalInformation").":\n"; - $content.=$langs->transnoentitiesnoconv("OnlinePaymentSystem").': '.$paymentmethod."
\n"; - $content.=$langs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."\n"; - $content.="tag=".$fulltag."\npaymentType=".$paymentType." currencycodeType=".$currencyCodeType." payerId=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt; - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($topic, $sendto, $from, $content); - - $result=$mailfile->sendfile(); - if ($result) - { - dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_paybox'); - } - else - { - dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_paybox'); - } - } - - unset($_SESSION['ipaddress']); -} - -$head=''; -if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; - -$conf->dol_hide_topmenu=1; -$conf->dol_hide_leftmenu=1; - -llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); - - -// Show message -print ''."\n"; -print '
'."\n"; - -print $langs->trans("YourPaymentHasNotBeenRecorded")."

\n"; - -$key='ONLINE_PAYMENT_MESSAGE_KO'; -if (! empty($conf->global->$key)) print $conf->global->$key; - -print "\n
\n"; - - -htmlPrintOnlinePaymentFooter($mysoc, $langs, 0, $suffix); - - -llxFooter('', 'public'); - -$db->close(); diff --git a/htdocs/public/paybox/paymentok.php b/htdocs/public/paybox/paymentok.php deleted file mode 100644 index efa49ce84fc..00000000000 --- a/htdocs/public/paybox/paymentok.php +++ /dev/null @@ -1,194 +0,0 @@ - - * Copyright (C) 2006-2013 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 . - */ - -/** - * \file htdocs/public/paybox/paymentok.php - * \ingroup paybox - * \brief File to show page after a successful payment - */ - -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. - -// For MultiCompany module. -// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php -// TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/paybox/lib/paybox.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - -// Security check -if (empty($conf->paybox->enabled)) accessforbidden('', 0, 0, 1); - -$langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal", "stripe")); - -/*$source=GETPOST('source'); -$ref=GETPOST('ref'); -$PAYBOXTOKEN=GETPOST('TOKEN'); -if (empty($PAYBOXTOKEN)) $PAYBOXTOKEN=GETPOST('token'); -$PAYBOXPAYERID=GETPOST('PAYERID'); -if (empty($PAYBOXPAYERID)) $PAYBOXPAYERID=GETPOST('PayerID'); -*/ -$FULLTAG=GETPOST('FULLTAG'); -if (empty($FULLTAG)) $FULLTAG=GETPOST('fulltag'); - - -$object = new stdClass(); // For triggers - -$paymentmethod='paybox'; - - -/* - * Actions - */ - - - - - -/* - * View - */ - -dol_syslog("Callback url when a PayBox payment was done. query_string=".(dol_escape_htmltag($_SERVER["QUERY_STRING"])?dol_escape_htmltag($_SERVER["QUERY_STRING"]):'')." script_uri=".(dol_escape_htmltag($_SERVER["SCRIPT_URI"])?dol_escape_htmltag($_SERVER["SCRIPT_URI"]):''), LOG_DEBUG, 0, '_paybox'); - -$tracepost = ""; -foreach($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; -dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_paybox'); - - -$head=''; -if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; - -$conf->dol_hide_topmenu=1; -$conf->dol_hide_leftmenu=1; - -llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); - - -// Show message -print ''."\n"; -print '
'."\n"; - -// Get on url call -/* -$onlinetoken = $PAYBOXTOKEN; -*/ -$fulltag = $FULLTAG; -/*$payerID = $PAYBOXPAYERID; -// Set by newpayment.php -$paymentType = $_SESSION['PaymentType']; -$currencyCodeType = $_SESSION['currencyCodeType']; -$FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; -// From env -$ipaddress = $_SESSION['ipaddress']; - -dol_syslog("Call newpaymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag); -*/ - - -print $langs->trans("YourPaymentHasBeenRecorded")."

\n"; - -$key='ONLINE_PAYMENT_MESSAGE_OK'; -if (! empty($conf->global->$key)) print $conf->global->$key; - - -// Appel des triggers -include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; -$interface=new Interfaces($db); -$result=$interface->run_triggers('PAYBOX_PAYMENT_OK', $object, $user, $langs, $conf); -if ($result < 0) { $error++; $errors=$interface->errors; } -// Fin appel triggers - -$tmptag=dolExplodeIntoArray($fulltag, '.', '='); - -// Send an email -if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) -{ - $sendto=$conf->global->ONLINE_PAYMENT_SENDEMAIL; - $from=$conf->global->MAILING_EMAIL_FROM; - // 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 - - // Define link to login card - $appli=constant('DOL_APPLICATION_TITLE'); - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) - { - $appli=$conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")"; // If new title contains a version that is different than core - } - else $appli.=" ".DOL_VERSION; - } - else $appli.=" ".DOL_VERSION; - - $urlback=$_SERVER["REQUEST_URI"]; - $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentReceived"); - $content=""; - if (! empty($tmptag['MEM'])) - { - $langs->load("members"); - $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"; - } - else - { - $content.=$langs->transnoentitiesnoconv("NewOnlinePaymentReceived")."
\n"; - } - $content.="
\n"; - $content.=$langs->transnoentitiesnoconv("TechnicalInformation").":
\n"; - $content.=$langs->transnoentitiesnoconv("OnlinePaymentSystem").': '.$paymentmethod."
\n"; - $content.=$langs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."
\n"; - $content.="tag=".$fulltag."
\n"; - - $ishtml=dol_textishtml($content); // May contain urls - - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml); - - // Send an email - $result=$mailfile->sendfile(); - if ($result) - { - dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_paybox'); - } - else - { - dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_paybox'); - } -} - - - -print "\n
\n"; - -htmlPrintOnlinePaymentFooter($mysoc, $langs, 0, $suffix); - - -llxFooter('', 'public'); - -$db->close(); diff --git a/htdocs/public/paypal/index.php b/htdocs/public/paypal/index.php deleted file mode 100644 index 0cba12e6aa2..00000000000 --- a/htdocs/public/paypal/index.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * 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/public/paypal/index.php - * \ingroup core - * \brief A redirect page to an error - * \author Laurent Destailleur - */ - -require '../../master.inc.php'; - -header("Location: ".DOL_URL_ROOT.'/public/error-404.php'); diff --git a/htdocs/public/paypal/newpayment.php b/htdocs/public/paypal/newpayment.php deleted file mode 100644 index ce6bb62500b..00000000000 --- a/htdocs/public/paypal/newpayment.php +++ /dev/null @@ -1,52 +0,0 @@ - - * Copyright (C) 2006-2017 Laurent Destailleur - * Copyright (C) 2009-2012 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 . - * - * For paypal test: https://developer.paypal.com/ - * For paybox test: ??? - */ - -/** - * \file htdocs/public/paypal/newpayment.php - * \ingroup paypal - * \brief File to offer a way to make a payment for a particular Dolibarr entity - */ - -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. - -// For MultiCompany module. -// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php -// TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php'; -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'; - -// Security check -if (empty($conf->paypal->enabled)) accessforbidden('', 0, 0, 1); - -$newurl = $_SERVER['REQUEST_URI']; -$newurl = preg_replace('/\/paypal\/newpayment/', '/payment/newpayment', $newurl); -header("Location: ".$newurl.(preg_match('/\?/', $newurl)?'&':'?').'paymentmethod=paypal'); -exit; diff --git a/htdocs/public/paypal/paymentko.php b/htdocs/public/paypal/paymentko.php deleted file mode 100644 index 2a80f5e5ba4..00000000000 --- a/htdocs/public/paypal/paymentko.php +++ /dev/null @@ -1,173 +0,0 @@ - - * Copyright (C) 2006-2013 Laurent Destailleur - * Copyright (C) 2012 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 . - */ - -/** - * \file htdocs/public/paypal/paymentko.php - * \ingroup paypal - * \brief File to show page after a failed payment. - * This page is called by paypal with url provided to payal competed with parameter TOKEN=xxx - * This token can be used to get more informations. - */ - -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. - -// For MultiCompany module. -// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php -// TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - -// Security check -if (empty($conf->paypal->enabled)) accessforbidden('', 0, 0, 1); - -$langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal", "stripe")); - -$PAYPALTOKEN=GETPOST('TOKEN'); -if (empty($PAYPALTOKEN)) $PAYPALTOKEN=GETPOST('token'); -$PAYPALPAYERID=GETPOST('PAYERID'); -if (empty($PAYPALPAYERID)) $PAYPALPAYERID=GETPOST('PayerID'); -$FULLTAG=GETPOST('FULLTAG'); -if (empty($FULLTAG)) $FULLTAG=GETPOST('fulltag'); - - -$object = new stdClass(); // For triggers - -$paymentmethod='paypal'; - - -/* - * Actions - */ - - - - -/* - * View - */ - -dol_syslog("Callback url when a PayPal payment was canceled. query_string=".(dol_escape_htmltag($_SERVER["QUERY_STRING"])?dol_escape_htmltag($_SERVER["QUERY_STRING"]):'')." script_uri=".(dol_escape_htmltag($_SERVER["SCRIPT_URI"])?dol_escape_htmltag($_SERVER["SCRIPT_URI"]):''), LOG_DEBUG, 0, '_paypal'); - -$tracepost = ""; -foreach($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; -dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_paypal'); - -if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice -{ - // Get on url call - $fulltag = $FULLTAG; - $onlinetoken = empty($PAYPALTOKEN)?$_SESSION['onlinetoken']:$PAYPALTOKEN; - $payerID = empty($PAYPALPAYERID)?$_SESSION['payerID']:$PAYPALPAYERID; - // Set by newpayment.php - $paymentType = $_SESSION['PaymentType']; - $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; - // From env - $ipaddress = $_SESSION['ipaddress']; - - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result=$interface->run_triggers('PAYPAL_PAYMENT_KO', $object, $user, $langs, $conf); - if ($result < 0) { $error++; $errors=$interface->errors; } - // Fin appel triggers - - // Send an email - $sendemail = ''; - if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) $sendemail=$conf->global->ONLINE_PAYMENT_SENDEMAIL; - - if ($sendemail) - { - $sendto=$sendemail; - $from=$conf->global->MAILING_EMAIL_FROM; - - // Define link to login card - $appli=constant('DOL_APPLICATION_TITLE'); - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) - { - $appli=$conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")"; // If new title contains a version that is different than core - } - else $appli.=" ".DOL_VERSION; - } - else $appli.=" ".DOL_VERSION; - - $urlback=$_SERVER["REQUEST_URI"]; - $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentFailed"); - $content=""; - $content.=$langs->transnoentitiesnoconv("ValidationOfOnlinePaymentFailed")."\n"; - $content.="\n"; - $content.=$langs->transnoentitiesnoconv("TechnicalInformation").":\n"; - $content.=$langs->transnoentitiesnoconv("OnlinePaymentSystem").': '.$paymentmethod."
\n"; - $content.=$langs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."\n"; - $content.="tag=".$fulltag."\ntoken=".$onlinetoken." paymentType=".$paymentType." currencycodeType=".$currencyCodeType." payerId=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt; - - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($topic, $sendto, $from, $content); - - $result=$mailfile->sendfile(); - if ($result) - { - dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_paypal'); - } - else - { - dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_paypal'); - } - } - - unset($_SESSION['ipaddress']); -} - - -$head=''; -if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; - -$conf->dol_hide_topmenu=1; -$conf->dol_hide_leftmenu=1; - -llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); - - -// Show ko message -print ''."\n"; -print '
'."\n"; -print $langs->trans("YourPaymentHasNotBeenRecorded")."

"; - -$key='ONLINE_PAYMENT_MESSAGE_KO'; -if (! empty($conf->global->$key)) print $conf->global->$key; - -print "\n
\n"; - - -htmlPrintOnlinePaymentFooter($mysoc, $langs, 0, $suffix); - - -llxFooter('', 'public'); - -$db->close(); diff --git a/htdocs/public/paypal/paymentok.php b/htdocs/public/paypal/paymentok.php deleted file mode 100644 index 6319945ce00..00000000000 --- a/htdocs/public/paypal/paymentok.php +++ /dev/null @@ -1,332 +0,0 @@ - - * Copyright (C) 2006-2013 Laurent Destailleur - * Copyright (C) 2012 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 . - */ - -/** - * \file htdocs/public/paypal/paymentok.php - * \ingroup paypal - * \brief File to show page after a successful payment - * This page is called by paypal with url provided to payal completed with parameter TOKEN=xxx - * This token can be used to get more informations. - */ - -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. - -// For MultiCompany module. -// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php -// TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - -// Security check -if (empty($conf->paypal->enabled)) accessforbidden('', 0, 0, 1); - -$langs->loadLangs(array("main","other","dict","bills","companies","paybox","paypal","stripe")); - -// Clean parameters -$PAYPAL_API_USER=""; -if (! empty($conf->global->PAYPAL_API_USER)) $PAYPAL_API_USER=$conf->global->PAYPAL_API_USER; -$PAYPAL_API_PASSWORD=""; -if (! empty($conf->global->PAYPAL_API_PASSWORD)) $PAYPAL_API_PASSWORD=$conf->global->PAYPAL_API_PASSWORD; -$PAYPAL_API_SIGNATURE=""; -if (! empty($conf->global->PAYPAL_API_SIGNATURE)) $PAYPAL_API_SIGNATURE=$conf->global->PAYPAL_API_SIGNATURE; -$PAYPAL_API_SANDBOX=""; -if (! empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX=$conf->global->PAYPAL_API_SANDBOX; -$PAYPAL_API_OK=""; -if ($urlok) $PAYPAL_API_OK=$urlok; -$PAYPAL_API_KO=""; -if ($urlko) $PAYPAL_API_KO=$urlko; -if (empty($PAYPAL_API_USER)) -{ - dol_print_error('', "Paypal setup param PAYPAL_API_USER not defined"); - return -1; -} -if (empty($PAYPAL_API_PASSWORD)) -{ - dol_print_error('', "Paypal setup param PAYPAL_API_PASSWORD not defined"); - return -1; -} -if (empty($PAYPAL_API_SIGNATURE)) -{ - dol_print_error('', "Paypal setup param PAYPAL_API_SIGNATURE not defined"); - return -1; -} - -$source=GETPOST('source'); -$ref=GETPOST('ref'); -$PAYPALTOKEN=GETPOST('TOKEN'); -if (empty($PAYPALTOKEN)) $PAYPALTOKEN=GETPOST('token'); -$PAYPALPAYERID=GETPOST('PAYERID'); -if (empty($PAYPALPAYERID)) $PAYPALPAYERID=GETPOST('PayerID'); -$FULLTAG=GETPOST('FULLTAG'); -if (empty($FULLTAG)) $FULLTAG=GETPOST('fulltag'); - - -$object = new stdClass(); // For triggers - -$paymentmethod='paypal'; - - -/* - * Actions - */ - - - -/* - * View - */ - -dol_syslog("Callback url when a PayPal payment was done. query_string=".(dol_escape_htmltag($_SERVER["QUERY_STRING"])?dol_escape_htmltag($_SERVER["QUERY_STRING"]):'')." script_uri=".(dol_escape_htmltag($_SERVER["SCRIPT_URI"])?dol_escape_htmltag($_SERVER["SCRIPT_URI"]):''), LOG_DEBUG, 0, '_paypal'); - -$tracepost = ""; -foreach($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; -dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_paypal'); - - -$head=''; -if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; - -$conf->dol_hide_topmenu=1; -$conf->dol_hide_leftmenu=1; - -llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); - - -// Show message -print ''."\n"; -print '
'."\n"; - -if ($PAYPALTOKEN) -{ - // Get on url call - $onlinetoken = $PAYPALTOKEN; - $fulltag = $FULLTAG; - $payerID = $PAYPALPAYERID; - // Set by newpayment.php - $paymentType = $_SESSION['PaymentType']; - $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; - // From env - $ipaddress = $_SESSION['ipaddress']; - - dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_paypal'); - - - // Validate record - if (! empty($paymentType)) - { - dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_paypal'); - $resArray=getDetails($onlinetoken); - //var_dump($resarray); - - dol_syslog("We call DoExpressCheckoutPayment token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_paypal'); - $resArray=confirmPayment($onlinetoken, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $fulltag); - - $ack = strtoupper($resArray["ACK"]); - if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING") - { - $object->source = $source; - $object->ref = $ref; - $object->payerID = $payerID; - $object->fulltag = $fulltag; - $object->resArray = $resArray; - - // resArray was built from a string like that - // TOKEN=EC%2d1NJ057703V9359028&TIMESTAMP=2010%2d11%2d01T11%3a40%3a13Z&CORRELATIONID=1efa8c6a36bd8&ACK=Success&VERSION=56&BUILD=1553277&TRANSACTIONID=9B994597K9921420R&TRANSACTIONTYPE=expresscheckout&PAYMENTTYPE=instant&ORDERTIME=2010%2d11%2d01T11%3a40%3a12Z&AMT=155%2e57&FEEAMT=5%2e54&TAXAMT=0%2e00&CURRENCYCODE=EUR&PAYMENTSTATUS=Completed&PENDINGREASON=None&REASONCODE=None - $PAYMENTSTATUS=urldecode($resArray["PAYMENTSTATUS"]); // Should contains 'Completed' - $TRANSACTIONID=urldecode($resArray["TRANSACTIONID"]); - $TAXAMT=urldecode($resArray["TAXAMT"]); - $NOTE=urldecode($resArray["NOTE"]); - - print $langs->trans("YourPaymentHasBeenRecorded")."
\n"; - print $langs->trans("ThisIsTransactionId", $TRANSACTIONID)."

\n"; - - $key='ONLINE_PAYMENT_MESSAGE_OK'; - if (! empty($conf->global->$key)) print $conf->global->$key; - - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result=$interface->run_triggers('PAYPAL_PAYMENT_OK', $object, $user, $langs, $conf); - if ($result < 0) { $error++; $errors=$interface->errors; } - // Fin appel triggers - - $tmptag=dolExplodeIntoArray($fulltag, '.', '='); - - // Send an email - if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) - { - $sendto=$conf->global->ONLINE_PAYMENT_SENDEMAIL; - $from=$conf->global->MAILING_EMAIL_FROM; - // 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 - - // Define link to login card - $appli=constant('DOL_APPLICATION_TITLE'); - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) - { - $appli=$conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")"; // If new title contains a version that is different than core - } - else $appli.=" ".DOL_VERSION; - } - else $appli.=" ".DOL_VERSION; - - $urlback=$_SERVER["REQUEST_URI"]; - $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentReceived"); - $content=""; - if (! empty($tmptag['MEM'])) - { - $langs->load("members"); - $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"; - } - else - { - $content.=$langs->transnoentitiesnoconv("NewOnlinePaymentReceived")."
\n"; - } - $content.="
\n"; - $content.=$langs->transnoentitiesnoconv("TechnicalInformation").":
\n"; - $content.=$langs->transnoentitiesnoconv("OnlinePaymentSystem").': '.$paymentmethod."
\n"; - $content.=$langs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."
\n"; - $content.="tag=".$fulltag."\ntoken=".$onlinetoken." paymentType=".$paymentType." currencycodeType=".$currencyCodeType." payerId=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt; - - $ishtml=dol_textishtml($content); // May contain urls - - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml); - - $result=$mailfile->sendfile(); - if ($result) - { - dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_paypal'); - } - else - { - dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_paypal'); - } - } - } - else - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result=$interface->run_triggers('PAYPAL_PAYMENT_KO', $object, $user, $langs, $conf); - if ($result < 0) { $error++; $errors=$interface->errors; } - // Fin appel triggers - - //Display a user friendly Error on the page using any of the following error information returned by PayPal - $ErrorCode = urldecode($resArray["L_ERRORCODE0"]); - $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]); - $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]); - $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]); - - echo $langs->trans('DoExpressCheckoutPaymentAPICallFailed') . "
\n"; - echo $langs->trans('DetailedErrorMessage') . ": " . $ErrorLongMsg."
\n"; - echo $langs->trans('ShortErrorMessage') . ": " . $ErrorShortMsg."
\n"; - echo $langs->trans('ErrorCode') . ": " . $ErrorCode."
\n"; - echo $langs->trans('ErrorSeverityCode') . ": " . $ErrorSeverityCode."
\n"; - - if ($mysoc->email) echo "\nPlease, send a screenshot of this page to ".$mysoc->email."
\n"; - - $tmptag=dolExplodeIntoArray($fulltag, '.', '='); - - // Send an email - if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) - { - $sendto=$conf->global->ONLINE_PAYMENT_SENDEMAIL; - $from=$conf->global->MAILING_EMAIL_FROM; - // 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 - - // Define link to login card - $appli=constant('DOL_APPLICATION_TITLE'); - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) - { - $appli=$conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")"; // If new title contains a version that is different than core - } - else $appli.=" ".DOL_VERSION; - } - else $appli.=" ".DOL_VERSION; - - $urlback=$_SERVER["REQUEST_URI"]; - $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("ValidationOfPaymentFailed"); - $content=""; - $content.=$langs->transnoentitiesnoconv("PaymentSystemConfirmPaymentPageWasCalledButFailed")."\n"; - $content.="\n"; - $content.=$langs->transnoentitiesnoconv("TechnicalInformation").":\n"; - $content.=$langs->transnoentitiesnoconv("OnlinePaymentSystem").': '.$paymentmethod."\n"; - $content.=$langs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."\n"; - $content.="tag=".$fulltag."\ntoken=".$onlinetoken." paymentType=".$paymentType." currencycodeType=".$currencyCodeType." payerId=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt; - - $ishtml=dol_textishtml($content); // May contain urls - - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml); - - $result=$mailfile->sendfile(); - if ($result) - { - dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_paypal'); - } - else - { - dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_paypal'); - } - } - } - } - else - { - dol_print_error('', 'Session expired'); - } -} -else -{ - // No TOKEN parameter in URL - dol_print_error('', 'No TOKEN parameter in URL'); -} - -print "\n
\n"; - -htmlPrintOnlinePaymentFooter($mysoc, $langs, 0, $suffix); - - -llxFooter('', 'public'); - -$db->close(); diff --git a/htdocs/public/stripe/ipn.php b/htdocs/public/stripe/ipn.php index 2f44c6390ff..7b57c315e34 100644 --- a/htdocs/public/stripe/ipn.php +++ b/htdocs/public/stripe/ipn.php @@ -146,7 +146,7 @@ $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; -dol_syslog("Stripe IPN was called with event->type = ".$event->type); +dol_syslog("***** Stripe IPN was called with event->type = ".$event->type); if ($event->type == 'payout.created') { @@ -404,18 +404,7 @@ elseif ($event->type == 'charge.failed') { // TODO: Redirect to paymentko.php } elseif (($event->type == 'source.chargeable') && ($event->data->object->type == 'three_d_secure') && ($event->data->object->three_d_secure->authenticated==true)) { - - $fulltag=$event->data->object->metadata->FULLTAG; - dol_syslog("fulltag=".$fulltag); - // Save into $tmptag all metadata - $tmptag=dolExplodeIntoArray($fulltag, '.', '='); - - $stripe=new Stripe($db); - /* - $stripeacc = $stripe->getStripeAccount($service); // Stripe OAuth connect account of dolibarr user (no network access here) - $stripecu = $stripe->getStripeCustomerAccount($tmptag['CUS'], $servicestatus); // Get thirdparty cu_... - $charge=$stripe->createPaymentStripe($event->data->object->amount/100, $event->data->object->currency, $origin, $item, $event->data->object->id, $stripecu, $stripeacc, $servicestatus); - */ + // This event is deprecated. } http_response_code(200); // PHP 5.4 or greater diff --git a/htdocs/public/stripe/newpayment.php b/htdocs/public/stripe/newpayment.php deleted file mode 100644 index 38f76865cb7..00000000000 --- a/htdocs/public/stripe/newpayment.php +++ /dev/null @@ -1,51 +0,0 @@ - - * Copyright (C) 2017 Saasprov - * Copyright (C) 2017 Laurent Destailleur - * 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 . - * - * Page is called with payment parameters then called with action='dopayment', then called with action='charge' then redirect is done on urlok/jo - */ - -/** - * \file htdocs/public/stripe/newpayment.php - * \ingroup Stripe - * \brief Page to do payment with Stripe - */ - -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. - -// For MultiCompany module. -// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php -// TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; -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'; - -// Security check -if (empty($conf->stripe->enabled)) accessforbidden('', 0, 0, 1); - -$newurl = $_SERVER['REQUEST_URI']; -$newurl = preg_replace('/\/stripe\/newpayment/', '/stripe/newpayment', $newurl); -header("Location: ".$newurl.(preg_match('/\?/', $newurl)?'&':'?').'paymentmethod=stripe'); -exit; diff --git a/htdocs/public/stripe/paymentko.php b/htdocs/public/stripe/paymentko.php deleted file mode 100644 index fa4eb5730eb..00000000000 --- a/htdocs/public/stripe/paymentko.php +++ /dev/null @@ -1,160 +0,0 @@ - - * - * 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/public/stripe/paymentko.php - * \ingroup core - * \brief File to show page after a failed payment. - * This page is called by payment system with url provided to it competed with parameter FULLTAG=xxx - * More data like token are saved into session. This token can be used to get more informations. - */ - -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. - -// For MultiCompany module. -// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php -// TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - -$langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal", "stripe")); - -$FULLTAG=GETPOST('FULLTAG'); -if (empty($FULLTAG)) $FULLTAG=GETPOST('fulltag'); - -// Security check -if (empty($conf->stripe->enabled)) accessforbidden('', 0, 0, 1); - -$object = new stdClass(); // For triggers - -$paymentmethod='stripe'; - - -/* - * Actions - */ - - - - -/* - * View - */ - -dol_syslog("Callback url when a PayPal payment was canceled. query_string=".(empty($_SERVER["QUERY_STRING"])?'':$_SERVER["QUERY_STRING"])." script_uri=".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG, 0, '_stripe'); - -$tracepost = ""; -foreach($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; -dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_stripe'); - -if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice -{ - $fulltag = $FULLTAG; - $onlinetoken = empty($PAYPALTOKEN)?$_SESSION['onlinetoken']:$PAYPALTOKEN; - $payerID = empty($PAYPALPAYERID)?$_SESSION['payerID']:$PAYPALPAYERID; - $currencyCodeType = $_SESSION['currencyCodeType']; - $paymentType = $_SESSION['paymentType']; - $FinalPaymentAmt = $_SESSION['FinalPaymentAmt']; - $ipaddress = $_SESSION['ipaddress']; - - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result=$interface->run_triggers('STRIPE_PAYMENT_KO', $object, $user, $langs, $conf); - if ($result < 0) { $error++; $errors=$interface->errors; } - // Fin appel triggers - - // Send an email - $sendemail = ''; - if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) $sendemail=$conf->global->ONLINE_PAYMENT_SENDEMAIL; - - if ($sendemail) - { - // Get on url call - $sendto=$sendemail; - $from=$conf->global->MAILING_EMAIL_FROM; - - // Define link to login card - $appli=constant('DOL_APPLICATION_TITLE'); - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) - { - $appli=$conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")"; // If new title contains a version that is different than core - } - else $appli.=" ".DOL_VERSION; - } - else $appli.=" ".DOL_VERSION; - - $urlback=$_SERVER["REQUEST_URI"]; - $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentFailed"); - $content=""; - $content.=$langs->transnoentitiesnoconv("ValidationOfOnlinePaymentFailed")."\n"; - $content.="\n"; - $content.=$langs->transnoentitiesnoconv("TechnicalInformation").":\n"; - $content.=$langs->transnoentitiesnoconv("OnlinePaymentSystem").': '.$paymentmethod."\n"; - $content.=$langs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."\n"; - $content.="tag=".$fulltag."\ntoken=".$onlinetoken." paymentType=".$paymentType." currencycodeType=".$currencyCodeType." payerId=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt; - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($topic, $sendto, $from, $content); - - $result=$mailfile->sendfile(); - if ($result) - { - dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_stripe'); - } - else - { - dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_stripe'); - } - } - - unset($_SESSION['ipaddress']); -} - -$head=''; -if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; - -$conf->dol_hide_topmenu=1; -$conf->dol_hide_leftmenu=1; - -llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); - - -// Show ko message -print ''."\n"; -print '
'."\n"; -print $langs->trans("YourPaymentHasNotBeenRecorded")."

"; - -$key='ONLINE_PAYMENT_MESSAGE_KO'; -if (! empty($conf->global->$key)) print $conf->global->$key; - -print "\n
\n"; - - -htmlPrintOnlinePaymentFooter($mysoc, $langs, 0, $suffix); - - -llxFooter('', 'public'); - -$db->close(); diff --git a/htdocs/public/stripe/paymentok.php b/htdocs/public/stripe/paymentok.php deleted file mode 100644 index 76df44be576..00000000000 --- a/htdocs/public/stripe/paymentok.php +++ /dev/null @@ -1,196 +0,0 @@ - - * - * 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/public/stripe/paymentok.php - * \ingroup core - * \brief File to show page after a successful payment - * This page is called by payment system with url provided to it completed with parameter FULLTAG=xxx - * More data like token are saved into session. This token can be used to get more informations. - */ - -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. - -// For MultiCompany module. -// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php -// TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); -if (is_numeric($entity)) define("DOLENTITY", $entity); - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - -$langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal")); - -$FULLTAG=GETPOST('FULLTAG'); -if (empty($FULLTAG)) $FULLTAG=GETPOST('fulltag'); -$source=GETPOST('source'); -$ref=GETPOST('ref'); - -// Security check -if (empty($conf->stripe->enabled)) accessforbidden('', 0, 0, 1); - - -$ispaymentok = false; -// If payment is ok -$PAYMENTSTATUS=$TRANSACTIONID=$TAXAMT=$NOTE=''; -// If payment is ko -$ErrorCode=$ErrorShortMsg=$ErrorLongMsg=$ErrorSeverityCode=''; - - -$object = new stdClass(); // For triggers - -$paymentmethod='stripe'; - - -/* - * Actions - */ - - - -/* - * View - */ - -dol_syslog("Callback url when a payment was done. query_string=".(empty($_SERVER["QUERY_STRING"])?'':$_SERVER["QUERY_STRING"])." script_uri=".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG, 0, '_stripe'); - -$tracepost = ""; -foreach($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; -dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_stripe'); - -$head=''; -if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; - -$conf->dol_hide_topmenu=1; -$conf->dol_hide_leftmenu=1; - -llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); - - - -// Show message -print ''."\n"; -print '
'."\n"; - -$ispaymentok = true; // We call this page if payment is ok -if ($ispaymentok) -{ - // Get on url call - $fulltag = $FULLTAG; - $onlinetoken = empty($PAYPALTOKEN)?$_SESSION['onlinetoken']:$PAYPALTOKEN; - $payerID = empty($PAYPALPAYERID)?$_SESSION['payerID']:$PAYPALPAYERID; - // Set by newpayment.php - $paymentType = $_SESSION['PaymentType']; - $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; - // From env - $ipaddress = $_SESSION['ipaddress']; - $TRANSACTIONID = $_SESSION['TRANSACTIONID']; - - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result=$interface->run_triggers('STRIPE_PAYMENT_OK', $object, $user, $langs, $conf); - if ($result < 0) { $error++; $errors=$interface->errors; } - // Fin appel triggers - - - print $langs->trans("YourPaymentHasBeenRecorded")."
\n"; - print $langs->trans("ThisIsTransactionId", $TRANSACTIONID)."

\n"; - - $key='ONLINE_PAYMENT_MESSAGE_OK'; - if (! empty($conf->global->$key)) print $conf->global->$key; - - $sendemail = ''; - if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) $sendemail=$conf->global->ONLINE_PAYMENT_SENDEMAIL; - - $tmptag=dolExplodeIntoArray($fulltag, '.', '='); - - // Send an email - if ($sendemail) - { - $sendto=$sendemail; - $from=$conf->global->MAILING_EMAIL_FROM; - // 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 - - // Define link to login card - $appli=constant('DOL_APPLICATION_TITLE'); - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) - { - $appli=$conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")"; // If new title contains a version that is different than core - } - else $appli.=" ".DOL_VERSION; - } - else $appli.=" ".DOL_VERSION; - - $urlback=$_SERVER["REQUEST_URI"]; - $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentReceived"); - $content=""; - if (! empty($tmptag['MEM'])) - { - $langs->load("members"); - $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"; - } - else - { - $content.=$langs->transnoentitiesnoconv("NewOnlinePaymentReceived")."
\n"; - } - $content.="
\n"; - $content.=$langs->transnoentitiesnoconv("TechnicalInformation").":
\n"; - $content.=$langs->transnoentitiesnoconv("OnlinePaymentSystem").': '.$paymentmethod."
\n"; - $content.=$langs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."
\n"; - $content.="tag=".$fulltag."\ntoken=".$onlinetoken." paymentType=".$paymentType." currencycodeType=".$currencyCodeType." payerId=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt; - - $ishtml=dol_textishtml($content); // May contain urls - - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml); - - $result=$mailfile->sendfile(); - if ($result) - { - dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_stripe'); - } - else - { - dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_stripe'); - } - } -} - - -print "\n
\n"; - - -htmlPrintOnlinePaymentFooter($mysoc, $langs, 0, $suffix); - - -llxFooter('', 'public'); - -$db->close(); diff --git a/htdocs/public/ticket/create_ticket.php b/htdocs/public/ticket/create_ticket.php index b7d17244c2a..b2434e7d826 100644 --- a/htdocs/public/ticket/create_ticket.php +++ b/htdocs/public/ticket/create_ticket.php @@ -138,9 +138,9 @@ if ($action == 'create_ticket' && GETPOST('add', 'alpha')) { $object->message = GETPOST("message", "none"); $object->origin_email = $origin_email; - $object->type_code = GETPOST("type_code", 'az09'); - $object->category_code = GETPOST("category_code", 'az09'); - $object->severity_code = GETPOST("severity_code", 'az09'); + $object->type_code = GETPOST("type_code", 'aZ09'); + $object->category_code = GETPOST("category_code", 'aZ09'); + $object->severity_code = GETPOST("severity_code", 'aZ09'); if (is_array($searched_companies)) { $object->fk_soc = $searched_companies[0]->id; } diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 6379aa36746..cff5f17494b 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -60,6 +60,7 @@ class Stripe extends CommonObject public $type; public $code; + public $declinecode; public $message; @@ -305,16 +306,18 @@ class Stripe extends CommonObject * @param string $currency_code Currency code * @param string $tag Tag * @param string $description Description - * @param Societe $object Object to pay with Stripe + * @param mixed $object Object to pay with Stripe * @param string $customer Stripe customer ref 'cus_xxxxxxxxxxxxx' via customerStripe() * @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 $usethirdpartyemailforreceiptemail 1=use thirdparty email for receipt * @param int $mode automatic=automatic confirmation/payment when conditions are ok, manual=need to call confirm() on intent * @param boolean $confirmnow false=default, true=try to confirm immediatly after create (if conditions are ok) + * @param string $payment_method 'pm_....' (if known) + * @param string $off_session If we use an already known payment method to pay off line. * @return \Stripe\PaymentIntent|null Stripe PaymentIntent or null if not found and failed to create */ - public function getPaymentIntent($amount, $currency_code, $tag, $description = '', $object = null, $customer = null, $key = null, $status = 0, $usethirdpartyemailforreceiptemail = 0, $mode = 'automatic', $confirmnow = false) + public function getPaymentIntent($amount, $currency_code, $tag, $description = '', $object = null, $customer = null, $key = null, $status = 0, $usethirdpartyemailforreceiptemail = 0, $mode = 'automatic', $confirmnow = false, $payment_method = null, $off_session = 0) { global $conf; @@ -335,7 +338,7 @@ class Stripe extends CommonObject } elseif ($fee < $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) { $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL; } - if (! in_array($currency, $arrayzerounitcurrency)) $stripefee = round($fee * 100); + if (! in_array($currency_code, $arrayzerounitcurrency)) $stripefee = round($fee * 100); else $stripefee = round($fee); $paymentintent = null; @@ -411,6 +414,16 @@ class Stripe extends CommonObject // payment_method = // payment_method_types = array('card') //var_dump($dataforintent); + if ($off_session) + { + unset($dataforintent['setup_future_usage']); + $dataforintent["off_session"] = true; + } + if (! is_null($payment_method)) + { + $dataforintent["payment_method"] = $payment_method; + $description.=' - '.$payment_method; + } if ($conf->entity!=$conf->global->STRIPECONNECT_PRINCIPAL && $stripefee > 0) { @@ -434,7 +447,6 @@ class Stripe extends CommonObject $paymentintent = \Stripe\PaymentIntent::create($dataforintent, array("idempotency_key" => "$description", "stripe_account" => $key)); //$paymentintent = \Stripe\PaymentIntent::create($dataforintent, array("stripe_account" => $key)); } - //var_dump($paymentintent->id); // Store the payment intent if (is_object($object)) @@ -479,19 +491,29 @@ class Stripe extends CommonObject $_SESSION["stripe_payment_intent"] = $paymentintent; } } + catch(Stripe\Error\Card $e) + { + $error++; + $this->error = $e->getMessage(); + $this->code = $e->getStripeCode(); + $this->declinecode = $e->getDeclineCode(); + } catch(Exception $e) { /*var_dump($dataforintent); var_dump($description); var_dump($key); var_dump($paymentintent); - var_dump($e->getMessage());*/ - $error++; + var_dump($e->getMessage()); + var_dump($e);*/ + $error++; $this->error = $e->getMessage(); + $this->code = ''; + $this->declinecode = ''; } } - dol_syslog("getPaymentIntent return error=".$error, LOG_INFO, -1); + dol_syslog("getPaymentIntent return error=".$error." this->error=".$this->error, LOG_INFO, -1); if (! $error) { @@ -782,13 +804,12 @@ class Stripe extends CommonObject /** * Create charge with public/payment/newpayment.php, stripe/card.php, cronjobs or REST API - * This is using old Stripe API charge. * * @param int $amount Amount to pay * @param string $currency EUR, GPB... * @param string $origin Object type to pay (order, invoice, contract...) * @param int $item Object id to pay - * @param string $source src_xxxxx or card_xxxxx + * @param string $source src_xxxxx or card_xxxxx or pm_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) diff --git a/htdocs/stripe/payment.php b/htdocs/stripe/payment.php index 6811df8d589..41f802062a2 100644 --- a/htdocs/stripe/payment.php +++ b/htdocs/stripe/payment.php @@ -28,7 +28,7 @@ /** * \file htdocs/stripe/payment.php * \ingroup stripe - * \brief Payment page for customers invoices + * \brief Payment page for customers invoices. TODO Seems deprecated and bugged ! */ // Load Dolibarr environment @@ -71,6 +71,7 @@ if ($user->societe_id > 0) } $object=new Facture($db); +$stripe=new Stripe($db); // Load object if ($facid > 0) @@ -78,9 +79,9 @@ if ($facid > 0) $ret=$object->fetch($facid); } -if (! empty($conf->stripe->enabled)) +if (empty($conf->stripe->enabled)) { - access_forbidden(); + accessforbidden(); } if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha')) @@ -306,7 +307,7 @@ if (empty($reshook)) elseif (preg_match('/src_/i', $source)) { - $customer2 = $customerstripe=$stripe->customerStripe($facture->thirdparty, $stripeacc, $servicestatus); + $customer2 = $customerstripe=$stripe->customerStripe($facture->thirdparty, $stripeacc, $servicestatus); $src = $customer2->sources->retrieve("$source"); if ($src->type=='card') { @@ -1082,7 +1083,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie if (! GETPOST('action')) { - if ($page == -1) $page = 0 ; + if ($page == -1 || empty($page)) $page = 0 ; $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $offset = $limit * $page ; diff --git a/htdocs/takepos/invoice.php b/htdocs/takepos/invoice.php index 672f17ca81b..f23f71552c3 100644 --- a/htdocs/takepos/invoice.php +++ b/htdocs/takepos/invoice.php @@ -137,6 +137,7 @@ if ($action == 'valid' && $user->rights->facture->creer) $bankaccount=$conf->global->$accountname; } $now=dol_now(); + $res = 0; $invoice = new Facture($db); $invoice->fetch($placeid); @@ -179,41 +180,42 @@ if ($action == 'valid' && $user->rights->facture->creer) $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"]; dol_syslog("Validate invoice with stock change into warehouse defined into constant ".$constantforkey." = ".$conf->global->$constantforkey); - $invoice->validate($user, '', $conf->global->$constantforkey); + $res = $invoice->validate($user, '', $conf->global->$constantforkey); $conf->global->STOCK_CALCULATE_ON_BILL = $savconst; } else { - $invoice->validate($user); + $res = $invoice->validate($user); } // Add the payment - $payment=new Paiement($db); - $payment->datepaye = $now; - $payment->fk_account = $bankaccount; - $payment->amounts[$invoice->id] = $amountofpayment; + if ($res > 0) { + $payment = new Paiement($db); + $payment->datepaye = $now; + $payment->fk_account = $bankaccount; + $payment->amounts[$invoice->id] = $amountofpayment; - // If user has not used change control, add total invoice payment - if ($amountofpayment == 0) $payment->amounts[$invoice->id] = $invoice->total_ttc; + // If user has not used change control, add total invoice payment + if ($amountofpayment == 0) $payment->amounts[$invoice->id] = $invoice->total_ttc; - $payment->paiementid=$paiementid; - $payment->num_payment=$invoice->ref; + $payment->paiementid=$paiementid; + $payment->num_payment=$invoice->ref; - $payment->create($user); - $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccount, '', ''); + $payment->create($user); + $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccount, '', ''); - $remaintopay = $invoice->getRemainToPay(); - if ($remaintopay == 0) - { - dol_syslog("Invoice is paid, so we set it to pay"); - $result = $invoice->set_paid($user); - if ($result > 0) $invoice->paye = 1; - } - else - { - dol_syslog("Invoice is not paid, remain to pay = ".$remaintopay); - } + $remaintopay = $invoice->getRemainToPay(); + if ($remaintopay == 0) { + dol_syslog("Invoice is paid, so we set it to pay"); + $result = $invoice->set_paid($user); + if ($result > 0) $invoice->paye = 1; + } else { + dol_syslog("Invoice is not paid, remain to pay = " . $remaintopay); + } + } else { + dol_htmloutput_errors($invoice->error, $invoice->errors, 1); + } } if ($action == 'history') diff --git a/htdocs/takepos/pay.php b/htdocs/takepos/pay.php index 83f4aefb5f5..9fd19b7378f 100644 --- a/htdocs/takepos/pay.php +++ b/htdocs/takepos/pay.php @@ -190,7 +190,7 @@ else print "var received=0;";
-
trans("Received"); ?>:
+
trans("Received"); ?>:
trans("Change"); ?>:
@@ -225,7 +225,7 @@ $numpad=$conf->global->TAKEPOS_NUMPAD; if ($paycode == 'CB') $paycode = 'card'; if ($paycode == 'CHQ') $paycode = 'cheque'; ?> - + @@ -238,7 +238,7 @@ $numpad=$conf->global->TAKEPOS_NUMPAD; if ($paycode == 'CB') $paycode = 'card'; if ($paycode == 'CHQ') $paycode = 'cheque'; ?> - + @@ -253,7 +253,7 @@ $button = array_pop($action_buttons); if ($paycode == 'CB') $paycode = 'card'; if ($paycode == 'CHQ') $paycode = 'cheque'; ?> - + - + fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')); - $object->type_code = GETPOST('update_value_type', 'az09'); - $object->severity_code = GETPOST('update_value_severity', 'az09'); - $object->category_code = GETPOST('update_value_category', 'az09'); + $object->type_code = GETPOST('update_value_type', 'aZ09'); + $object->severity_code = GETPOST('update_value_severity', 'aZ09'); + $object->category_code = GETPOST('update_value_category', 'aZ09'); $ret = $object->update($user); if ($ret > 0) { diff --git a/htdocs/user/card.php b/htdocs/user/card.php index 13035d1fb0e..90cc0a142cb 100644 --- a/htdocs/user/card.php +++ b/htdocs/user/card.php @@ -54,7 +54,6 @@ $id = GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); $mode = GETPOST('mode', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); -$subaction = GETPOST('subaction', 'alpha'); $group = GETPOST("group", "int", 3); $cancel = GETPOST('cancel', 'alpha'); $contextpage= GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'useracard'; // To manage different context of search @@ -195,14 +194,14 @@ if (empty($reshook)) { } if (!$error) { - $object->lastname = GETPOST("lastname", 'alpha'); - $object->firstname = GETPOST("firstname", 'alpha'); - $object->login = GETPOST("login", 'alpha'); - $object->api_key = GETPOST("api_key", 'alpha'); - $object->gender = GETPOST("gender", 'alpha'); - $birth = dol_mktime(0, 0, 0, GETPOST('birthmonth'), GETPOST('birthday'), GETPOST('birthyear')); + $object->lastname = GETPOST("lastname", 'alphanohtml'); + $object->firstname = GETPOST("firstname", 'alphanohtml'); + $object->login = GETPOST("login", 'alphanohtml'); + $object->api_key = GETPOST("api_key", 'alphanohtml'); + $object->gender = GETPOST("gender", 'aZ09'); + $birth = dol_mktime(0, 0, 0, GETPOST('birthmonth', 'int'), GETPOST('birthday', 'int'), GETPOST('birthyear', 'int')); $object->birth = $birth; - $object->admin = GETPOST("admin", 'alpha'); + $object->admin = GETPOST("admin", 'int'); $object->address = GETPOST('address', 'alphanohtml'); $object->zip = GETPOST('zipcode', 'alphanohtml'); $object->town = GETPOST('town', 'alphanohtml'); @@ -217,8 +216,8 @@ if (empty($reshook)) { $object->facebook = GETPOST("facebook", 'alphanohtml'); $object->linkedin = GETPOST("linkedin", 'alphanohtml'); - $object->email = preg_replace('/\s+/', '', GETPOST("email", 'alpha')); - $object->job = GETPOST("job", 'alpha'); + $object->email = preg_replace('/\s+/', '', GETPOST("email", 'alphanohtml')); + $object->job = GETPOST("job", 'nohtml'); $object->signature = GETPOST("signature", 'none'); $object->accountancy_code = GETPOST("accountancy_code", 'alphanohtml'); $object->note = GETPOST("note", 'none'); @@ -233,10 +232,10 @@ if (empty($reshook)) { $object->weeklyhours = GETPOST("weeklyhours", 'alphanohtml') != '' ? GETPOST("weeklyhours", 'alphanohtml') : ''; $object->color = GETPOST("color", 'alphanohtml') != '' ? GETPOST("color", 'alphanohtml') : ''; - $dateemployment = dol_mktime(0, 0, 0, GETPOST('dateemploymentmonth'), GETPOST('dateemploymentday'), GETPOST('dateemploymentyear')); + $dateemployment = dol_mktime(0, 0, 0, GETPOST('dateemploymentmonth', 'int'), GETPOST('dateemploymentday', 'int'), GETPOST('dateemploymentyear', 'int')); $object->dateemployment = $dateemployment; - $dateemploymentend = dol_mktime(0, 0, 0, GETPOST('dateemploymentendmonth'), GETPOST('dateemploymentendday'), GETPOST('dateemploymentendyear')); + $dateemploymentend = dol_mktime(0, 0, 0, GETPOST('dateemploymentendmonth', 'int'), GETPOST('dateemploymentendday', 'int'), GETPOST('dateemploymentendyear', 'int')); $object->dateemploymentend = $dateemploymentend; $object->fk_warehouse = GETPOST('fk_warehouse', 'int'); @@ -348,15 +347,15 @@ if (empty($reshook)) { $db->begin(); - $object->lastname = GETPOST("lastname", 'alpha'); - $object->firstname = GETPOST("firstname", 'alpha'); - $object->login = GETPOST("login", 'alpha'); - $object->gender = GETPOST("gender", 'alpha'); - $birth = dol_mktime(0, 0, 0, GETPOST('birthmonth'), GETPOST('birthday'), GETPOST('birthyear')); + $object->lastname = GETPOST("lastname", 'alphanohtml'); + $object->firstname = GETPOST("firstname", 'alphanohtml'); + $object->login = GETPOST("login", 'alphanohtml'); + $object->gender = GETPOST("gender", 'aZ09'); + $birth = dol_mktime(0, 0, 0, GETPOST('birthmonth', 'int'), GETPOST('birthday', 'int'), GETPOST('birthyear', 'int')); $object->birth = $birth; $object->pass = GETPOST("password", 'none'); - $object->api_key = (GETPOST("api_key", 'alpha')) ? GETPOST("api_key", 'alpha') : $object->api_key; - if (! empty($user->admin)) $object->admin = GETPOST("admin"); // admin flag can only be set/unset by an admin user. A test is also done later when forging sql request + $object->api_key = (GETPOST("api_key", 'alphanohtml')) ? GETPOST("api_key", 'alphanohtml') : $object->api_key; + if (! empty($user->admin)) $object->admin = GETPOST("admin", "int"); // admin flag can only be set/unset by an admin user. A test is also done later when forging sql request $object->address = GETPOST('address', 'alphanohtml'); $object->zip = GETPOST('zipcode', 'alphanohtml'); $object->town = GETPOST('town', 'alphanohtml'); @@ -365,15 +364,17 @@ if (empty($reshook)) { $object->office_phone = GETPOST("office_phone", 'alphanohtml'); $object->office_fax = GETPOST("office_fax", 'alphanohtml'); $object->user_mobile = GETPOST("user_mobile", 'alphanohtml'); - $object->skype = GETPOST("skype", 'alpha'); - $object->twitter = GETPOST("twitter", 'alpha'); - $object->facebook = GETPOST("facebook", 'alpha'); - $object->linkedin = GETPOST("linkedin", 'alpha'); - $object->email = preg_replace('/\s+/', '', GETPOST("email", 'alpha')); - $object->job = GETPOST("job", 'alpha'); + + $object->skype = GETPOST("skype", 'alphanohtml'); + $object->twitter = GETPOST("twitter", 'alphanohtml'); + $object->facebook = GETPOST("facebook", 'alphanohtml'); + $object->linkedin = GETPOST("linkedin", 'alphanohtml'); + + $object->email = preg_replace('/\s+/', '', GETPOST("email", 'alphanohtml')); + $object->job = GETPOST("job", 'nohtml'); $object->signature = GETPOST("signature", 'none'); - $object->accountancy_code = GETPOST("accountancy_code", 'alpha'); - $object->openid = GETPOST("openid", 'alpha'); + $object->accountancy_code = GETPOST("accountancy_code", 'alphanohtml'); + $object->openid = GETPOST("openid", 'alphanohtml'); $object->fk_user = GETPOST("fk_user", 'int') > 0 ? GETPOST("fk_user", 'int') : 0; $object->employee = GETPOST('employee', 'int'); @@ -383,7 +384,7 @@ if (empty($reshook)) { $object->salaryextra = GETPOST("salaryextra", 'alphanohtml') != '' ? GETPOST("salaryextra", 'alphanohtml') : ''; $object->weeklyhours = GETPOST("weeklyhours", 'alphanohtml') != '' ? GETPOST("weeklyhours", 'alphanohtml') : ''; - $object->color = GETPOST("color", 'alpha') != '' ? GETPOST("color", 'alpha') : ''; + $object->color = GETPOST("color", 'alphanohtml') != '' ? GETPOST("color", 'alphanohtml') : ''; $dateemployment = dol_mktime(0, 0, 0, GETPOST('dateemploymentmonth', 'int'), GETPOST('dateemploymentday', 'int'), GETPOST('dateemploymentyear', 'int')); $object->dateemployment = $dateemployment; $dateemploymentend = dol_mktime(0, 0, 0, GETPOST('dateemploymentendmonth', 'int'), GETPOST('dateemploymentendday', 'int'), GETPOST('dateemploymentendyear', 'int')); @@ -1203,7 +1204,7 @@ if ($action == 'create' || $action == 'adduserldap') // Position/Job print ''.$langs->trans("PostOrFunction").''; print ''; - print ''; + print ''; print ''; // Default warehouse diff --git a/htdocs/website/index.php b/htdocs/website/index.php index 6394428bd42..db5ecd2ca7a 100644 --- a/htdocs/website/index.php +++ b/htdocs/website/index.php @@ -2237,7 +2237,7 @@ if (! GETPOST('hide_websitemenu')) $formquestion = array( array('type' => 'checkbox', 'name' => 'delete_also_js', 'label' => $langs->trans("DeleteAlsoJs"), 'value' => 0), array('type' => 'checkbox', 'name' => 'delete_also_medias', 'label' => $langs->trans("DeleteAlsoMedias"), 'value' => 0), - //array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'az09')?GETPOST('newlang', 'az09'):$langs->defaultlang, 'newlang', 0, null, '', 0, 0, 'minwidth200')), + //array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'aZ09')?GETPOST('newlang', 'aZ09'):$langs->defaultlang, 'newlang', 0, null, '', 0, 0, 'minwidth200')), //array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("WebSite"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)) ); @@ -2252,7 +2252,7 @@ if (! GETPOST('hide_websitemenu')) $formquestion = array( array('type' => 'text', 'name' => 'siteref', 'label'=> $langs->trans("WebSite") ,'value'=> 'copy_of_'.$object->ref), //array('type' => 'checkbox', 'name' => 'is_a_translation', 'label' => $langs->trans("SiteIsANewTranslation"), 'value' => 0), - //array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'az09')?GETPOST('newlang', 'az09'):$langs->defaultlang, 'newlang', 0, null, '', 0, 0, 'minwidth200')), + //array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'aZ09')?GETPOST('newlang', 'aZ09'):$langs->defaultlang, 'newlang', 0, null, '', 0, 0, 'minwidth200')), //array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("WebSite"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)) ); @@ -2266,7 +2266,7 @@ if (! GETPOST('hide_websitemenu')) // Confirmation to clone if ($action == 'createpagefromclone') { // Create an array for form - $preselectedlanguage = GETPOST('newlang', 'az09') ? GETPOST('newlang', 'az09') : ($objectpage->lang ? $objectpage->lang : $langs->defaultlang); + $preselectedlanguage = GETPOST('newlang', 'aZ09') ? GETPOST('newlang', 'aZ09') : ($objectpage->lang ? $objectpage->lang : $langs->defaultlang); $formquestion = array( array('type' => 'hidden', 'name' => 'sourcepageurl', 'value'=> $objectpage->pageurl), array('type' => 'checkbox', 'tdclass'=>'maxwidth200', 'name' => 'is_a_translation', 'label' => $langs->trans("PageIsANewTranslation"), 'value' => 0), @@ -3319,7 +3319,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm') print ''; print ''.$answerrecord['type'].''; print ''; - $backtopageurl = $_SERVER["PHP_SELF"].'?action=replacesiteconfirm&searchstring='.urlencode($searchkey).'&optioncontent='.GETPOST('optioncontent', 'az09').'&optionmeta='.GETPOST('optionmeta', 'az09').'&optionsitefiles='.GETPOST('optionsitefiles', 'az09'); + $backtopageurl = $_SERVER["PHP_SELF"].'?action=replacesiteconfirm&searchstring='.urlencode($searchkey).'&optioncontent='.GETPOST('optioncontent', 'aZ09').'&optionmeta='.GETPOST('optionmeta', 'aZ09').'&optionsitefiles='.GETPOST('optionsitefiles', 'aZ09'); print 'ref.'&backtopage='.urlencode($backtopageurl).'">'.$langs->trans("EditCss").''; print ''; print ''; diff --git a/test/phpunit/SecurityTest.php b/test/phpunit/SecurityTest.php index b457c4c0fa7..68b93c6ec88 100644 --- a/test/phpunit/SecurityTest.php +++ b/test/phpunit/SecurityTest.php @@ -130,6 +130,24 @@ class SecurityTest extends PHPUnit\Framework\TestCase print __METHOD__."\n"; } + /** + * testSetLang + * + * @return string + */ + public function testSetLang() + { + global $conf; + $conf=$this->savconf; + + $tmplangs = new Translate('', $conf); + + $_SERVER['HTTP_ACCEPT_LANGUAGE'] = "' malicious text with quote"; + $tmplangs->setDefaultLang('auto'); + print __METHOD__.' $tmplangs->defaultlang='.$tmplangs->defaultlang."\n"; + $this->assertEquals($tmplangs->defaultlang, 'malicioustextwithquote_MALICIOUSTEXTWITHQUOTE'); + } + /** * testGETPOST *