diff --git a/htdocs/adherents/list.php b/htdocs/adherents/list.php index 85c22a535bd6287aa2663ce238ea0dd0d42a73cf..d5b856ce5dd40a801138090e4db195963aa7e6c8 100644 --- a/htdocs/adherents/list.php +++ b/htdocs/adherents/list.php @@ -87,50 +87,50 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'd.rowid'=>'Ref', - 'd.login'=>'Login', - 'd.lastname'=>'Lastname', - 'd.firstname'=>'Firstname', - 'd.login'=>'Login', + 'd.rowid'=>'Ref', + 'd.login'=>'Login', + 'd.lastname'=>'Lastname', + 'd.firstname'=>'Firstname', + 'd.login'=>'Login', 'd.societe'=>"Company", - 'd.email'=>'EMail', - 'd.address'=>'Address', - 'd.zip'=>'Zip', - 'd.town'=>'Town', - 'd.note_public'=>'NotePublic', - 'd.note_private'=>'NotePrivate', + 'd.email'=>'EMail', + 'd.address'=>'Address', + 'd.zip'=>'Zip', + 'd.town'=>'Town', + 'd.note_public'=>'NotePublic', + 'd.note_private'=>'NotePrivate', ); $arrayfields=array( - 'd.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'd.lastname'=>array('label'=>$langs->trans("Lastname"), 'checked'=>1), - 'd.firstname'=>array('label'=>$langs->trans("Firstname"), 'checked'=>1), + 'd.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'd.lastname'=>array('label'=>$langs->trans("Lastname"), 'checked'=>1), + 'd.firstname'=>array('label'=>$langs->trans("Firstname"), 'checked'=>1), 'd.company'=>array('label'=>$langs->trans("Company"), 'checked'=>1), 'd.login'=>array('label'=>$langs->trans("Login"), 'checked'=>1), - 'd.morphy'=>array('label'=>$langs->trans("MorPhy"), 'checked'=>1), - 't.libelle'=>array('label'=>$langs->trans("Type"), 'checked'=>1), + 'd.morphy'=>array('label'=>$langs->trans("MorPhy"), 'checked'=>1), + 't.libelle'=>array('label'=>$langs->trans("Type"), 'checked'=>1), 'd.email'=>array('label'=>$langs->trans("Email"), 'checked'=>1), - 'd.address'=>array('label'=>$langs->trans("Address"), 'checked'=>0), - 'd.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0), - 'd.town'=>array('label'=>$langs->trans("Town"), 'checked'=>0), + 'd.address'=>array('label'=>$langs->trans("Address"), 'checked'=>0), + 'd.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0), + 'd.town'=>array('label'=>$langs->trans("Town"), 'checked'=>0), 'd.phone'=>array('label'=>$langs->trans("Phone"), 'checked'=>0), 'd.phone_perso'=>array('label'=>$langs->trans("PhonePerso"), 'checked'=>0), 'd.phone_mobile'=>array('label'=>$langs->trans("PhoneMobile"), 'checked'=>0), - 'state.nom'=>array('label'=>$langs->trans("State"), 'checked'=>0), + 'state.nom'=>array('label'=>$langs->trans("State"), 'checked'=>0), 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - /*'d.note_public'=>array('label'=>$langs->trans("NotePublic"), 'checked'=>0), + /*'d.note_public'=>array('label'=>$langs->trans("NotePublic"), 'checked'=>0), 'd.note_private'=>array('label'=>$langs->trans("NotePrivate"), 'checked'=>0),*/ 'd.datefin'=>array('label'=>$langs->trans("EndSubscription"), 'checked'=>1, 'position'=>500), 'd.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'd.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000) + 'd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'd.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! 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'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } @@ -147,44 +147,44 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $search=""; - $search_ref=""; - $search_lastname=""; - $search_firstname=""; - $search_login=""; - $search_company=""; - $search_type=""; - $search_email=""; - $search_address=""; - $search_zip=""; - $search_town=""; - $search_state=""; - $search_country=''; - $search_phone=''; - $search_phone_perso=''; - $search_phone_mobile=''; - $search_morphy=""; - $search_categ=""; - $catid=""; - $sall=""; - $statut=''; - $toselect=''; - $search_array_options=array(); - } - - // Mass actions - $objectclass='Adherent'; - $objectlabel='Members'; - $permtoread = $user->rights->adherent->lire; - $permtodelete = $user->rights->adherent->supprimer; - $uploaddir = $conf->adherent->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search=""; + $search_ref=""; + $search_lastname=""; + $search_firstname=""; + $search_login=""; + $search_company=""; + $search_type=""; + $search_email=""; + $search_address=""; + $search_zip=""; + $search_town=""; + $search_state=""; + $search_country=''; + $search_phone=''; + $search_phone_perso=''; + $search_phone_mobile=''; + $search_morphy=""; + $search_categ=""; + $catid=""; + $sall=""; + $statut=''; + $toselect=''; + $search_array_options=array(); + } + + // Mass actions + $objectclass='Adherent'; + $objectlabel='Members'; + $permtoread = $user->rights->adherent->lire; + $permtodelete = $user->rights->adherent->supprimer; + $uploaddir = $conf->adherent->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -245,16 +245,16 @@ if ($filter == 'outofdate') $sql.=" AND (datefin IS NULL OR datefin < '".$db->id // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -278,8 +278,8 @@ dol_syslog("get list", LOG_DEBUG); $resql = $db->query($sql); if (! $resql) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($resql); @@ -288,10 +288,10 @@ $arrayofselected=is_array($toselect)?$toselect:array(); if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/adherents/card.php?id='.$id); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/adherents/card.php?id='.$id); + exit; } llxHeader('',$langs->trans("Member"),'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros'); @@ -344,9 +344,9 @@ if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available @@ -373,8 +373,8 @@ print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . implode(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . implode(', ',$fieldstosearchall); } // Filter on categories @@ -382,7 +382,7 @@ $moreforfilter=''; if (! empty($conf->categorie->enabled)) { require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='<div class="divsearchfield">'; + $moreforfilter.='<div class="divsearchfield">'; $moreforfilter.=$langs->trans('Categories'). ': '; $moreforfilter.=$formother->select_categories(Categorie::TYPE_MEMBER,$search_categ,'search_categ',1); $moreforfilter.='</div>'; @@ -418,9 +418,9 @@ if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) // Ref if (! empty($arrayfields['d.ref']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input class="flat maxwidth50" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; - print '</td>'; + print '</td>'; } if (! empty($arrayfields['d.firstname']['checked'])) @@ -449,8 +449,8 @@ if (! empty($arrayfields['d.login']['checked'])) if (! empty($arrayfields['d.morphy']['checked'])) { - print '<td class="liste_titre" align="left">'; - print '</td>'; + print '<td class="liste_titre" align="left">'; + print '</td>'; } if (! empty($arrayfields['t.libelle']['checked'])) @@ -480,16 +480,16 @@ if (! empty($arrayfields['d.town']['checked'])) // State if (! empty($arrayfields['state.nom']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat searchstring maxwidth50" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat searchstring maxwidth50" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; + print '</td>'; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print '<td class="liste_titre" align="center">'; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print '</td>'; + print '<td class="liste_titre" align="center">'; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print '</td>'; } // Phone pro if (! empty($arrayfields['d.phone']['checked'])) @@ -524,25 +524,25 @@ if (! empty($arrayfields['d.datefin']['checked'])) // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } - print '</td>'; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -551,26 +551,26 @@ print $hookmanager->resPrint; // Date creation if (! empty($arrayfields['d.datec']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Date modification if (! empty($arrayfields['d.tms']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Status if (! empty($arrayfields['d.statut']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="right">'; - $liststatus=array( - '-1'=>$langs->trans("Draft"), - '1'=>$langs->trans("Validated"), - '0'=>$langs->trans("Resiliated") - ); - print $form->selectarray('statut', $liststatus, $statut, -2); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="right">'; + $liststatus=array( + '-1'=>$langs->trans("Draft"), + '1'=>$langs->trans("Validated"), + '0'=>$langs->trans("Resiliated") + ); + print $form->selectarray('statut', $liststatus, $statut, -2); + print '</td>'; } // Action column print '<td class="liste_titre" align="middle">'; @@ -583,7 +583,7 @@ print "</tr>\n"; print '<tr class="liste_titre">'; if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { - print '<td colspan="1" align="center">'.$langs->trans("NumberingShort").'</td>'; + print '<td colspan="1" align="center">'.$langs->trans("NumberingShort").'</td>'; } if (! empty($arrayfields['d.ref']['checked'])) print_liste_field_titre($arrayfields['d.ref']['label'],$_SERVER["PHP_SELF"],'d.rowid','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['d.firstname']['checked'])) print_liste_field_titre($arrayfields['d.firstname']['label'],$_SERVER["PHP_SELF"],'d.firstname','',$param,'',$sortfield,$sortorder); @@ -605,16 +605,16 @@ if (! empty($arrayfields['d.datefin']['checked'])) print_liste_field_titr // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -643,7 +643,7 @@ while ($i < min($num, $limit)) $memberstatic->photo = $obj->photo; if (! empty($obj->fk_soc)) { - $memberstatic->fetch_thirdparty(); + $memberstatic->fetch_thirdparty(); $companyname=$memberstatic->thirdparty->name; } else { $companyname=$obj->company; @@ -666,22 +666,22 @@ while ($i < min($num, $limit)) // Firstname if (! empty($arrayfields['d.firstname']['checked'])) { - print "<td>"; + print "<td>"; print $obj->firstname; print "</td>\n"; } // Lastname if (! empty($arrayfields['d.lastname']['checked'])) { - print "<td>"; + print "<td>"; print $obj->lastname; print "</td>\n"; } // Company if (! empty($arrayfields['d.company']['checked'])) { - print "<td>"; - print $companyname; + print "<td>"; + print $companyname; print "</td>\n"; } // Login @@ -697,7 +697,7 @@ while ($i < min($num, $limit)) // Type label if (! empty($arrayfields['t.libelle']['checked'])) { - $membertypestatic->id=$obj->type_id; + $membertypestatic->id=$obj->type_id; $membertypestatic->label=$obj->type; print '<td class="nowrap">'; print $membertypestatic->getNomUrl(1,32); @@ -706,69 +706,69 @@ while ($i < min($num, $limit)) // Address if (! empty($arrayfields['d.address']['checked'])) { - print '<td class="nocellnopadd">'; - print $obj->address; - print '</td>'; + print '<td class="nocellnopadd">'; + print $obj->address; + print '</td>'; } // Zip if (! empty($arrayfields['d.zip']['checked'])) { - print '<td class="nocellnopadd">'; - print $obj->zip; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="nocellnopadd">'; + print $obj->zip; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Town if (! empty($arrayfields['d.town']['checked'])) { - print '<td class="nocellnopadd">'; - print $obj->town; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="nocellnopadd">'; + print $obj->town; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // State if (! empty($arrayfields['state.nom']['checked'])) { - print "<td>".$obj->state_name."</td>\n"; - if (! $i) $totalarray['nbfield']++; + print "<td>".$obj->state_name."</td>\n"; + if (! $i) $totalarray['nbfield']++; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print '<td align="center">'; - $tmparray=getCountry($obj->country,'all'); - print $tmparray['label']; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + $tmparray=getCountry($obj->country,'all'); + print $tmparray['label']; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Phone pro if (! empty($arrayfields['d.phone']['checked'])) { print '<td class="nocellnopadd">'; - print $obj->phone; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print $obj->phone; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Phone perso if (! empty($arrayfields['d.phone_perso']['checked'])) { print '<td class="nocellnopadd">'; - print $obj->phone_perso; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print $obj->phone_perso; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Phone mobile if (! empty($arrayfields['d.phone_mobile']['checked'])) { print '<td class="nocellnopadd">'; - print $obj->phone_mobile; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print $obj->phone_mobile; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // EMail if (! empty($arrayfields['d.email']['checked'])) { - print "<td>".dol_print_email($obj->email,0,0,1)."</td>\n"; + print "<td>".dol_print_email($obj->email,0,0,1)."</td>\n"; } // End of subscription date $datefin=$db->jdate($obj->datefin); @@ -779,7 +779,7 @@ while ($i < min($num, $limit)) print '<td align="center" class="nowrap">'; print dol_print_date($datefin,'day'); if ($memberstatic->hasDelay()) { - $textlate .= ' ('.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($conf->adherent->subscription->warning_delay/60/60/24) >= 0 ? '+' : '').ceil($conf->adherent->subscription->warning_delay/60/60/24).' '.$langs->trans("days").')'; + $textlate .= ' ('.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($conf->adherent->subscription->warning_delay/60/60/24) >= 0 ? '+' : '').ceil($conf->adherent->subscription->warning_delay/60/60/24).' '.$langs->trans("days").')'; print " ".img_warning($langs->trans("SubscriptionLate").$textlate); } print '</td>'; @@ -802,20 +802,20 @@ while ($i < min($num, $limit)) // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); @@ -824,37 +824,37 @@ while ($i < min($num, $limit)) // Date creation if (! empty($arrayfields['d.datec']['checked'])) { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['d.tms']['checked'])) { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Status if (! empty($arrayfields['d.statut']['checked'])) { - print '<td align="right" class="nowrap">'; - print $memberstatic->LibStatut($obj->statut,$obj->subscription,$datefin,5); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="right" class="nowrap">'; + print $memberstatic->LibStatut($obj->statut,$obj->subscription,$datefin,5); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Action column print '<td align="center">'; - 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 ($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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; print "</tr>\n"; $i++; diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index ac06a30294706c0514a2f3d62a5dc83a9c0a9bea..d77f448f811346af44b5b36907949c68eb7d1c36 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -70,7 +70,7 @@ complete_substitutions_array($substitutionarrayfortest, $langs); if ($action == 'update' && empty($_POST["cancel"])) { dolibarr_set_const($db, "MAIN_DISABLE_ALL_MAILS", GETPOST("MAIN_DISABLE_ALL_MAILS"),'chaine',0,'',$conf->entity); - // Send mode parameters + // Send mode parameters dolibarr_set_const($db, "MAIN_MAIL_SENDMODE", GETPOST("MAIN_MAIL_SENDMODE"),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_SMTP_PORT", GETPOST("MAIN_MAIL_SMTP_PORT"),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_SMTP_SERVER", GETPOST("MAIN_MAIL_SMTP_SERVER"),'chaine',0,'',$conf->entity); @@ -78,11 +78,11 @@ if ($action == 'update' && empty($_POST["cancel"])) dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW", GETPOST("MAIN_MAIL_SMTPS_PW"), 'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS", GETPOST("MAIN_MAIL_EMAIL_TLS"),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS", GETPOST("MAIN_MAIL_EMAIL_STARTTLS"),'chaine',0,'',$conf->entity); - // Content parameters + // Content parameters dolibarr_set_const($db, "MAIN_MAIL_EMAIL_FROM", GETPOST("MAIN_MAIL_EMAIL_FROM"), 'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_ERRORS_TO", GETPOST("MAIN_MAIL_ERRORS_TO"), 'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_AUTOCOPY_TO", GETPOST("MAIN_MAIL_AUTOCOPY_TO"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, 'MAIN_MAIL_DEFAULT_FROMTYPE', GETPOST('MAIN_MAIL_DEFAULT_FROMTYPE'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, 'MAIN_MAIL_DEFAULT_FROMTYPE', GETPOST('MAIN_MAIL_DEFAULT_FROMTYPE'),'chaine',0,'',$conf->entity); header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); exit; @@ -406,7 +406,7 @@ if ($action == 'edit') print '<td><input class="flat" name="MAIN_MAIL_EMAIL_FROM" size="32" value="' . (! empty($conf->global->MAIN_MAIL_EMAIL_FROM)?$conf->global->MAIN_MAIL_EMAIL_FROM:''); print '"></td></tr>'; - // Default from type + // Default from type $liste = array(); $liste['user'] = $langs->trans('UserEmail'); $liste['company'] = $langs->trans('CompanyEmail').' ('.(empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?$langs->trans("NotDefined"):$conf->global->MAIN_INFO_SOCIETE_MAIL).')'; @@ -429,13 +429,13 @@ if ($action == 'edit') } else dol_print_error($db);*/ - print '<tr '.$bc[$var?1:0].'><td>'.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').'</td><td>'; - print $form->selectarray('MAIN_MAIL_DEFAULT_FROMTYPE', $liste, $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE, 0); - print '</td></tr>'; + print '<tr '.$bc[$var?1:0].'><td>'.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').'</td><td>'; + print $form->selectarray('MAIN_MAIL_DEFAULT_FROMTYPE', $liste, $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE, 0); + print '</td></tr>'; - // Separator + // Separator - print '<tr class="oddeven"><td colspan="2"> </td></tr>'; + print '<tr class="oddeven"><td colspan="2"> </td></tr>'; // From @@ -449,24 +449,24 @@ if ($action == 'edit') print '<td><input class="flat" name="MAIN_MAIL_AUTOCOPY_TO" size="32" value="' . (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)?$conf->global->MAIN_MAIL_AUTOCOPY_TO:''); print '"></td></tr>'; - print '</table>'; + print '</table>'; - dol_fiche_end(); + dol_fiche_end(); - print '<br><div class="center">'; - print '<input class="button" type="submit" name="save" value="'.$langs->trans("Save").'">'; - print ' '; - print '<input class="button" type="submit" name="cancel" value="'.$langs->trans("Cancel").'">'; - print '</div>'; + print '<br><div class="center">'; + print '<input class="button" type="submit" name="save" value="'.$langs->trans("Save").'">'; + print ' '; + print '<input class="button" type="submit" name="cancel" value="'.$langs->trans("Cancel").'">'; + print '</div>'; print '</form>'; } else { - dol_fiche_head($head, 'common', '', -1); + dol_fiche_head($head, 'common', '', -1); - print $langs->trans("EMailsDesc")."<br>\n"; - print "<br>\n"; + print $langs->trans("EMailsDesc")."<br>\n"; + print "<br>\n"; $var=true; @@ -587,33 +587,33 @@ else } else dol_print_error($db); - print '<tr '.$bc[$var?1:0].'><td>'.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').'</td>'; - print '<td>'; - if ($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'user') - { - print $langs->trans('UserEmail'); - } - else if ($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'company') - { - print $langs->trans('CompanyEmail').' '.dol_escape_htmltag('<'.$mysoc->email.'>'); - } - else { - $id = preg_replace('/senderprofile_/', '', $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE); - if ($id > 0) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/emailsenderprofile.class.php'; - $emailsenderprofile = new EmailSenderProfile($db); - $emailsenderprofile->fetch($id); - print $emailsenderprofile->label.' '.dol_escape_htmltag('<'.$emailsenderprofile->email.'>'); - } - } - print '</td></tr>'; + print '<tr '.$bc[$var?1:0].'><td>'.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').'</td>'; + print '<td>'; + if ($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'user') + { + print $langs->trans('UserEmail'); + } + else if ($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'company') + { + print $langs->trans('CompanyEmail').' '.dol_escape_htmltag('<'.$mysoc->email.'>'); + } + else { + $id = preg_replace('/senderprofile_/', '', $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE); + if ($id > 0) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/emailsenderprofile.class.php'; + $emailsenderprofile = new EmailSenderProfile($db); + $emailsenderprofile->fetch($id); + print $emailsenderprofile->label.' '.dol_escape_htmltag('<'.$emailsenderprofile->email.'>'); + } + } + print '</td></tr>'; // Separator print '<tr class="oddeven"><td colspan="2"> </td></tr>'; - // Errors To + // Errors To print '<tr class="oddeven"><td>'.$langs->trans("MAIN_MAIL_ERRORS_TO").'</td>'; print '<td>'.$conf->global->MAIN_MAIL_ERRORS_TO; @@ -640,10 +640,10 @@ else dol_fiche_end(); - if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) - { - print '<br>'; - /* + if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) + { + print '<br>'; + /* // Warning 1 if ($linuxlike) { @@ -653,9 +653,9 @@ else print info_admin($langs->trans("SendmailOptionNotComplete")); } }*/ - // Warning 2 - print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); - } + // Warning 2 + print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); + } // Boutons actions @@ -687,8 +687,8 @@ else if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && ! in_array($action, array('testconnect', 'test', 'testhtml'))) { - $text = $langs->trans("WarningPHPMail"); - print info_admin($text); + $text = $langs->trans("WarningPHPMail"); + print info_admin($text); } // Run the test to connect @@ -716,7 +716,7 @@ else // Show email send test form if ($action == 'test' || $action == 'testhtml') { - print '<div id="formmailbeforetitle" name="formmailbeforetitle"></div>'; + print '<div id="formmailbeforetitle" name="formmailbeforetitle"></div>'; print load_fiche_titre($action == 'testhtml'?$langs->trans("DoTestSendHTML"):$langs->trans("DoTestSend")); dol_fiche_head(''); @@ -752,7 +752,7 @@ else $formmail->param["returnurl"]=$_SERVER["PHP_SELF"]; // Init list of files - if (GETPOST("mode")=='init') + if (GETPOST("mode")=='init') { $formmail->clear_attached_files(); } diff --git a/htdocs/bookmarks/list.php b/htdocs/bookmarks/list.php index 0e22e2112cd3f86d14deb9014977c6fc87083027..0e642bdcc14ab7cf39852f5d81d308fb08750959 100644 --- a/htdocs/bookmarks/list.php +++ b/htdocs/bookmarks/list.php @@ -35,7 +35,7 @@ $toselect = GETPOST('toselect', 'array'); // Security check if (! $user->rights->bookmark->lire) { - restrictedArea($user, 'bookmarks'); + restrictedArea($user, 'bookmarks'); } $optioncss = GETPOST('optioncss','alpha'); @@ -59,17 +59,17 @@ $id = GETPOST("id",'int'); if ($action == 'delete') { - $bookmark=new Bookmark($db); - $res=$bookmark->remove($id); - if ($res > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } - else - { - setEventMessages($bookmark->error, $bookmark->errors, 'errors'); - } + $bookmark=new Bookmark($db); + $res=$bookmark->remove($id); + if ($res > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } + else + { + setEventMessages($bookmark->error, $bookmark->errors, 'errors'); + } } @@ -95,112 +95,112 @@ $sql.= $db->plimit($limit, $offset); $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - $param = ""; - if ($optioncss != '') $param ='&optioncss='.$optioncss; - - $moreforfilter=''; - - print '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; - - print "<tr class=\"liste_titre\">"; - //print "<td> </td>"; - print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"rowid","", $param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Title",$_SERVER["PHP_SELF"],"title","", $param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Link",'',''); - print_liste_field_titre("Target",'','','','','align="center"'); - print_liste_field_titre("Owner",$_SERVER["PHP_SELF"],"u.lastname","", $param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre("Date",$_SERVER["PHP_SELF"],"b.dateb","", $param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre("Position",$_SERVER["PHP_SELF"],"b.position","", $param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre(''); - print "</tr>\n"; - - $var=True; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - - - print '<tr class="oddeven">'; - - // Id - print '<td align="left">'; - print "<a href=\"card.php?id=".$obj->rowid."\">".img_object($langs->trans("ShowBookmark"),"bookmark").' '.$obj->rowid."</a>"; - print '</td>'; - - $linkintern=0; - $title=$obj->title; - $link=$obj->url; - - // Title - print "<td>"; - $linkintern=1; - if ($linkintern) print "<a href=\"".$obj->url."\">"; - print $title; - if ($linkintern) print "</a>"; - print "</td>\n"; - - // Url - print '<td class="tdoverflowmax200">'; - if (! $linkintern) print '<a href="'.$obj->url.'"'.($obj->target?' target="newlink"':'').'>'; - print $link; - if (! $linkintern) print '</a>'; - print "</td>\n"; - - // Target - print '<td align="center">'; - if ($obj->target == 0) print $langs->trans("BookmarkTargetReplaceWindowShort"); - if ($obj->target == 1) print $langs->trans("BookmarkTargetNewWindowShort"); - print "</td>\n"; - - // Author - print '<td align="center">'; + $num = $db->num_rows($resql); + $i = 0; + $param = ""; + if ($optioncss != '') $param ='&optioncss='.$optioncss; + + $moreforfilter=''; + + print '<div class="div-table-responsive">'; + print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; + + print "<tr class=\"liste_titre\">"; + //print "<td> </td>"; + print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"rowid","", $param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre("Title",$_SERVER["PHP_SELF"],"title","", $param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre("Link",'',''); + print_liste_field_titre("Target",'','','','','align="center"'); + print_liste_field_titre("Owner",$_SERVER["PHP_SELF"],"u.lastname","", $param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre("Date",$_SERVER["PHP_SELF"],"b.dateb","", $param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre("Position",$_SERVER["PHP_SELF"],"b.position","", $param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre(''); + print "</tr>\n"; + + $var=True; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + + print '<tr class="oddeven">'; + + // Id + print '<td align="left">'; + print "<a href=\"card.php?id=".$obj->rowid."\">".img_object($langs->trans("ShowBookmark"),"bookmark").' '.$obj->rowid."</a>"; + print '</td>'; + + $linkintern=0; + $title=$obj->title; + $link=$obj->url; + + // Title + print "<td>"; + $linkintern=1; + if ($linkintern) print "<a href=\"".$obj->url."\">"; + print $title; + if ($linkintern) print "</a>"; + print "</td>\n"; + + // Url + print '<td class="tdoverflowmax200">'; + if (! $linkintern) print '<a href="'.$obj->url.'"'.($obj->target?' target="newlink"':'').'>'; + print $link; + if (! $linkintern) print '</a>'; + print "</td>\n"; + + // Target + print '<td align="center">'; + if ($obj->target == 0) print $langs->trans("BookmarkTargetReplaceWindowShort"); + if ($obj->target == 1) print $langs->trans("BookmarkTargetNewWindowShort"); + print "</td>\n"; + + // Author + print '<td align="center">'; if ($obj->fk_user) { - $userstatic->id=$obj->fk_user; - $userstatic->lastname=$obj->login; + $userstatic->id=$obj->fk_user; + $userstatic->lastname=$obj->login; print $userstatic->getNomUrl(1); } else { print $langs->trans("Public"); } - print "</td>\n"; - - // Date creation - print '<td align="center">'.dol_print_date($db->jdate($obj->dateb),'day')."</td>"; - - // Position - print '<td align="right">'.$obj->position."</td>"; - - // Actions - print '<td align="right" class="nowrap">'; - if ($user->rights->bookmark->creer) - { - print "<a href=\"".DOL_URL_ROOT."/bookmarks/card.php?action=edit&id=".$obj->rowid."&backtopage=".urlencode($_SERVER["PHP_SELF"])."\">".img_edit()."</a> "; - } - if ($user->rights->bookmark->supprimer) - { - print "<a href=\"".$_SERVER["PHP_SELF"]."?action=delete&id=$obj->rowid\">".img_delete()."</a>"; - } - else - { - print " "; - } - print "</td>"; - print "</tr>\n"; - $i++; - } - print "</table>"; - print '</div>'; - - $db->free($resql); + print "</td>\n"; + + // Date creation + print '<td align="center">'.dol_print_date($db->jdate($obj->dateb),'day')."</td>"; + + // Position + print '<td align="right">'.$obj->position."</td>"; + + // Actions + print '<td align="right" class="nowrap">'; + if ($user->rights->bookmark->creer) + { + print "<a href=\"".DOL_URL_ROOT."/bookmarks/card.php?action=edit&id=".$obj->rowid."&backtopage=".urlencode($_SERVER["PHP_SELF"])."\">".img_edit()."</a> "; + } + if ($user->rights->bookmark->supprimer) + { + print "<a href=\"".$_SERVER["PHP_SELF"]."?action=delete&id=$obj->rowid\">".img_delete()."</a>"; + } + else + { + print " "; + } + print "</td>"; + print "</tr>\n"; + $i++; + } + print "</table>"; + print '</div>'; + + $db->free($resql); } else { - dol_print_error($db); + dol_print_error($db); } @@ -209,7 +209,7 @@ print "<div class=\"tabsAction\">\n"; if ($user->rights->bookmark->creer) { - print '<a class="butAction" href="'.DOL_URL_ROOT.'/bookmarks/card.php?action=create">'.$langs->trans("NewBookmark").'</a>'; + print '<a class="butAction" href="'.DOL_URL_ROOT.'/bookmarks/card.php?action=create">'.$langs->trans("NewBookmark").'</a>'; } print '</div>'; diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index 5e893a3ab44614663011d6790f618cb24357e604..bb8e0d880b9e355886e2929057eee7881fe3365e 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -124,42 +124,42 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'p.ref'=>'Ref', - 'p.ref_client'=>'CustomerRef', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'p.note_public'=>'NotePublic', + 'p.ref'=>'Ref', + 'p.ref_client'=>'CustomerRef', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'p.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["p.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'p.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'p.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1), - 'p.fin_validite'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), - 'p.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'p.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'p.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'u.login'=>array('label'=>$langs->trans("Author"), 'checked'=>1, 'position'=>10), - 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'p.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'p.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'p.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1), + 'p.fin_validite'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), + 'p.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'p.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'p.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'u.login'=>array('label'=>$langs->trans("Author"), 'checked'=>1, 'position'=>10), + 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'p.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! 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'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } $object = new Propal($db); // To be passed as parameter of executeHooks that need @@ -181,40 +181,40 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_ref=''; - $search_refcustomer=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_login=''; - $search_product_category=''; - $search_town=''; + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_ref=''; + $search_refcustomer=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $search_login=''; + $search_product_category=''; + $search_town=''; $search_zip=""; - $search_state=""; + $search_state=""; $search_type=''; $search_country=''; $search_type_thirdparty=''; $search_year=''; - $search_month=''; - $search_day=''; + $search_month=''; + $search_day=''; $viewstatut=''; $object_statut=''; $toselect=''; - $search_array_options=array(); + $search_array_options=array(); } if ($object_statut != '') $viewstatut=$object_statut; if (empty($reshook)) { - $objectclass='Propal'; - $objectlabel='Proposals'; - $permtoread = $user->rights->propal->lire; - $permtodelete = $user->rights->propal->supprimer; - $uploaddir = $conf->propal->dir_output; + $objectclass='Propal'; + $objectlabel='Proposals'; + $permtoread = $user->rights->propal->lire; + $permtodelete = $user->rights->propal->supprimer; + $uploaddir = $conf->propal->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -266,8 +266,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr ON pr.rowid = p.fk_projet"; if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as c"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as c"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE p.fk_soc = s.rowid'; $sql.= ' AND p.entity IN ('.getEntity('propal').')'; @@ -288,7 +288,7 @@ if ($search_montant_ht != '') $sql.= natural_search("p.total_ht", $search_monta if ($search_montant_vat != '') $sql.= natural_search("p.tva", $search_montant_vat, 1); if ($search_montant_ttc != '') $sql.= natural_search("p.total", $search_montant_ttc, 1); if ($sall) { - $sql .= natural_search(array_keys($fieldstosearchall), $sall); + $sql .= natural_search(array_keys($fieldstosearchall), $sall); } if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$db->escape($search_product_category); if ($socid > 0) $sql.= ' AND s.rowid = '.$socid; @@ -298,12 +298,12 @@ if ($viewstatut != '' && $viewstatut != '-1') } if ($search_month > 0) { - if ($search_year > 0 && empty($search_day)) - $sql.= " AND p.datep BETWEEN '".$db->idate(dol_get_first_day($search_year,$search_month,false))."' AND '".$db->idate(dol_get_last_day($search_year,$search_month,false))."'"; - else if ($search_year > 0 && ! empty($search_day)) - $sql.= " AND p.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month, $search_day, $search_year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month, $search_day, $search_year))."'"; - else - $sql.= " AND date_format(p.datep, '%m') = '".$db->escape($search_month)."'"; + if ($search_year > 0 && empty($search_day)) + $sql.= " AND p.datep BETWEEN '".$db->idate(dol_get_first_day($search_year,$search_month,false))."' AND '".$db->idate(dol_get_last_day($search_year,$search_month,false))."'"; + else if ($search_year > 0 && ! empty($search_day)) + $sql.= " AND p.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month, $search_day, $search_year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month, $search_day, $search_year))."'"; + else + $sql.= " AND date_format(p.datep, '%m') = '".$db->escape($search_month)."'"; } else if ($search_year > 0) { @@ -312,21 +312,21 @@ else if ($search_year > 0) if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$db->escape($search_sale); if ($search_user > 0) { - $sql.= " AND c.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal' AND c.element_id = p.rowid AND c.fk_socpeople = ".$db->escape($search_user); + $sql.= " AND c.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal' AND c.element_id = p.rowid AND c.fk_socpeople = ".$db->escape($search_user); } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -340,8 +340,8 @@ $sql.=', p.ref DESC'; $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1, $offset); @@ -361,7 +361,7 @@ if ($resql) } else { - $title = $langs->trans('ListOfProposals'); + $title = $langs->trans('ListOfProposals'); } $num = $db->num_rows($resql); @@ -369,15 +369,15 @@ if ($resql) $arrayofselected=is_array($toselect)?$toselect:array(); $param='&viewstatut='.urlencode($viewstatut); - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + 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_day) $param.='&search_day='.urlencode($search_day); if ($search_month) $param.='&search_month='.urlencode($search_month); if ($search_year) $param.='&search_year='.urlencode($search_year); if ($search_ref) $param.='&search_ref='.urlencode($search_ref); - if ($search_refcustomer) $param.='&search_refcustomer='.urlencode($search_refcustomer); - if ($search_societe) $param.='&search_societe='.urlencode($search_societe); + if ($search_refcustomer) $param.='&search_refcustomer='.urlencode($search_refcustomer); + if ($search_societe) $param.='&search_societe='.urlencode($search_societe); if ($search_user > 0) $param.='&search_user='.urlencode($search_user); if ($search_sale > 0) $param.='&search_sale='.urlencode($search_sale); if ($search_montant_ht) $param.='&search_montant_ht='.urlencode($search_montant_ht); @@ -390,15 +390,15 @@ if ($resql) // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->propal->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); if ($massaction == 'presend') $arrayofmassactions=array(); @@ -406,7 +406,7 @@ if ($resql) // Lignes des champs de filtre print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -419,19 +419,19 @@ if ($resql) if ($massaction == 'presend') { - $topicmail="SendSupplierProposalRef"; - $modelmail="supplier_proposal_send"; - $objecttmp=new Propal($db); - $trackid='ord'.$object->id; + $topicmail="SendSupplierProposalRef"; + $modelmail="supplier_proposal_send"; + $objecttmp=new Propal($db); + $trackid='ord'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; } if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } $i = 0; @@ -451,8 +451,8 @@ if ($resql) { $moreforfilter.='<div class="divsearchfield">'; $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter.='</div>'; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.='</div>'; } // If the user can view products if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) @@ -471,70 +471,70 @@ if ($resql) if (! empty($moreforfilter)) { - print '<div class="liste_titre liste_titre_bydiv centpercent">'; - print $moreforfilter; - print '</div>'; + print '<div class="liste_titre liste_titre_bydiv centpercent">'; + print $moreforfilter; + print '</div>'; } - $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); + $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); - print '<div class="div-table-responsive">'; + print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; print '<tr class="liste_titre_filter">'; if (! empty($arrayfields['p.ref']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" size="6" type="text" name="search_ref" value="'.$search_ref.'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" size="6" type="text" name="search_ref" value="'.$search_ref.'">'; + print '</td>'; } if (! empty($arrayfields['p.ref_client']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input class="flat" size="6" type="text" name="search_refcustomer" value="'.$search_refcustomer.'">'; print '</td>'; } if (! empty($arrayfields['s.nom']['checked'])) { - print '<td class="liste_titre" align="left">'; - print '<input class="flat" type="text" size="10" name="search_societe" value="'.$search_societe.'">'; + print '<td class="liste_titre" align="left">'; + print '<input class="flat" type="text" size="10" name="search_societe" value="'.$search_societe.'">'; print '</td>'; } if (! empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; if (! empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="4" name="search_zip" value="'.$search_zip.'"></td>'; // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print '<td class="liste_titre">'; - print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; - print '</td>'; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print '<td class="liste_titre" align="center">'; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print '</td>'; - } + if (! empty($arrayfields['state.nom']['checked'])) + { + print '<td class="liste_titre">'; + print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; + print '</td>'; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print '<td class="liste_titre" align="center">'; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print '</td>'; + } // Company type - if (! empty($arrayfields['typent.code']['checked'])) - { - print '<td class="liste_titre maxwidthonsmartphone" align="center">'; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print '</td>'; - } + if (! empty($arrayfields['typent.code']['checked'])) + { + print '<td class="liste_titre maxwidthonsmartphone" align="center">'; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print '</td>'; + } // Date if (! empty($arrayfields['p.date']['checked'])) { - print '<td class="liste_titre" align="center">'; - //print $langs->trans('Month').': '; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_day" value="'.$search_day.'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="search_month" value="'.$search_month.'">'; - //print ' '.$langs->trans('Year').': '; - $formother->select_year($search_year,'search_year',1, 20, 5); - print '</td>'; + print '<td class="liste_titre" align="center">'; + //print $langs->trans('Month').': '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_day" value="'.$search_day.'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="search_month" value="'.$search_month.'">'; + //print ' '.$langs->trans('Year').': '; + $formother->select_year($search_year,'search_year',1, 20, 5); + print '</td>'; } // Date end if (! empty($arrayfields['p.fin_validite']['checked'])) @@ -543,54 +543,54 @@ if ($resql) } if (! empty($arrayfields['p.total_ht']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.$search_montant_ht.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.$search_montant_ht.'">'; + print '</td>'; } if (! empty($arrayfields['p.total_vat']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.$search_montant_vat.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.$search_montant_vat.'">'; + print '</td>'; } if (! empty($arrayfields['p.total_ttc']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.$search_montant_ttc.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.$search_montant_ttc.'">'; + print '</td>'; } if (! empty($arrayfields['u.login']['checked'])) { - // Author - print '<td class="liste_titre" align="center">'; - print '<input class="flat" size="4" type="text" name="search_login" value="'.$search_login.'">'; - print '</td>'; + // Author + print '<td class="liste_titre" align="center">'; + print '<input class="flat" size="4" type="text" name="search_login" value="'.$search_login.'">'; + print '</td>'; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; } - print '</td>'; - } - } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -599,21 +599,21 @@ if ($resql) // Date creation if (! empty($arrayfields['p.datec']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Date modification if (! empty($arrayfields['p.tms']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Status if (! empty($arrayfields['p.fk_statut']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="right">'; - $formpropal->selectProposalStatus($viewstatut,1); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="right">'; + $formpropal->selectProposalStatus($viewstatut,1); + print '</td>'; } // Action column print '<td class="liste_titre" align="middle">'; @@ -645,19 +645,19 @@ if ($resql) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'],$_SERVER["PHP_SELF"],"p.fk_statut","",$param,'align="right"',$sortfield,$sortorder); @@ -671,55 +671,55 @@ if ($resql) { $obj = $db->fetch_object($resql); - $objectstatic->id=$obj->rowid; - $objectstatic->ref=$obj->ref; + $objectstatic->id=$obj->rowid; + $objectstatic->ref=$obj->ref; print '<tr class="oddeven">'; if (! empty($arrayfields['p.ref']['checked'])) { - print '<td class="nowrap">'; - - print '<table class="nobordernopadding"><tr class="nocellnopadd">'; - // Picto + Ref - print '<td class="nobordernopadding nowrap">'; - print $objectstatic->getNomUrl(1, '', '', 0, 1); - print '</td>'; - // Warning - $warnornote=''; - if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); - if (! empty($obj->note_private)) - { - $warnornote.=($warnornote?' ':''); - $warnornote.= '<span class="note">'; - $warnornote.= '<a href="note.php?id='.$obj->rowid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>'; - $warnornote.= '</span>'; - } - if ($warnornote) - { - print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; - print $warnornote; - print '</td>'; - } - // Other picto tool - print '<td width="16" align="right" class="nobordernopadding">'; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); - print '</td></tr></table>'; - - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; + print '<td class="nowrap">'; + + print '<table class="nobordernopadding"><tr class="nocellnopadd">'; + // Picto + Ref + print '<td class="nobordernopadding nowrap">'; + print $objectstatic->getNomUrl(1, '', '', 0, 1); + print '</td>'; + // Warning + $warnornote=''; + if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); + if (! empty($obj->note_private)) + { + $warnornote.=($warnornote?' ':''); + $warnornote.= '<span class="note">'; + $warnornote.= '<a href="note.php?id='.$obj->rowid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>'; + $warnornote.= '</span>'; + } + if ($warnornote) + { + print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; + print $warnornote; + print '</td>'; + } + // Other picto tool + print '<td width="16" align="right" class="nobordernopadding">'; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); + print '</td></tr></table>'; + + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['p.ref_client']['checked'])) { - // Customer ref - print '<td class="nocellnopadd nowrap">'; - print $obj->ref_client; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + // Customer ref + print '<td class="nocellnopadd nowrap">'; + print $obj->ref_client; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } $companystatic->id=$obj->socid; @@ -731,169 +731,169 @@ if ($resql) // Thirdparty if (! empty($arrayfields['s.nom']['checked'])) { - print '<td class="tdoverflowmax200">'; - print $companystatic->getNomUrl(1,'customer'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="tdoverflowmax200">'; + print $companystatic->getNomUrl(1,'customer'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->town; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->zip; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "<td>".$obj->state_name."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print '<td align="center">'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print '<td align="center">'; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['s.town']['checked'])) + { + print '<td class="nocellnopadd">'; + print $obj->town; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print '<td class="nocellnopadd">'; + print $obj->zip; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "<td>".$obj->state_name."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print '<td align="center">'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print '<td align="center">'; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } // Date proposal - if (! empty($arrayfields['p.date']['checked'])) - { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->dp), 'day'); - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.date']['checked'])) + { + print '<td align="center">'; + print dol_print_date($db->jdate($obj->dp), 'day'); + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; + } // Date end validity - if (! empty($arrayfields['p.fin_validite']['checked'])) - { - if ($obj->dfv) - { - print '<td align="center">'.dol_print_date($db->jdate($obj->dfv),'day'); - print '</td>'; - } - else - { - print '<td> </td>'; - } - if (! $i) $totalarray['nbfield']++; - } - - // Amount HT - if (! empty($arrayfields['p.total_ht']['checked'])) - { - print '<td align="right">'.price($obj->total_ht)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['p.total_vat']['checked'])) - { - print '<td align="right">'.price($obj->total_vat)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_vat; - } - // Amount TTC - if (! empty($arrayfields['p.total_ttc']['checked'])) - { - print '<td align="right">'.price($obj->total_ttc)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } - - $userstatic->id=$obj->fk_user_author; + if (! empty($arrayfields['p.fin_validite']['checked'])) + { + if ($obj->dfv) + { + print '<td align="center">'.dol_print_date($db->jdate($obj->dfv),'day'); + print '</td>'; + } + else + { + print '<td> </td>'; + } + if (! $i) $totalarray['nbfield']++; + } + + // Amount HT + if (! empty($arrayfields['p.total_ht']['checked'])) + { + print '<td align="right">'.price($obj->total_ht)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['p.total_vat']['checked'])) + { + print '<td align="right">'.price($obj->total_vat)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_vat; + } + // Amount TTC + if (! empty($arrayfields['p.total_ttc']['checked'])) + { + print '<td align="right">'.price($obj->total_ttc)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } + + $userstatic->id=$obj->fk_user_author; $userstatic->login=$obj->login; - // Author - if (! empty($arrayfields['u.login']['checked'])) - { - print '<td align="center">'; - if ($userstatic->id) print $userstatic->getLoginUrl(1); - else print ' '; - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } - } - // 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['p.datec']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['p.fk_statut']['checked'])) - { - print '<td align="right" class="nowrap">'.$objectstatic->LibStatut($obj->fk_statut,5).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Action column - print '<td class="nowrap" align="center">'; - 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + // Author + if (! empty($arrayfields['u.login']['checked'])) + { + print '<td align="center">'; + if ($userstatic->id) print $userstatic->getLoginUrl(1); + else print ' '; + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } + } + // 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['p.datec']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['p.fk_statut']['checked'])) + { + print '<td align="right" class="nowrap">'.$objectstatic->LibStatut($obj->fk_statut,5).'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Action column + print '<td class="nowrap" align="center">'; + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; print "</tr>\n"; @@ -901,7 +901,7 @@ if ($resql) } // Show total line - if (isset($totalarray['totalhtfield']) + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totalttcfield']) || isset($totalarray['totalamfield']) @@ -914,10 +914,10 @@ if ($resql) { $i++; if ($i == 1) - { - if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; - else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; - } + { + if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; + else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; + } elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; @@ -933,27 +933,27 @@ if ($resql) print $hookmanager->resPrint; print '</table>'."\n"; - print '</div>'."\n"; + print '</div>'."\n"; print '</form>'."\n"; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->propal->lire; - $delallowed=$user->rights->propal->lire; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->propal->lire; + $delallowed=$user->rights->propal->lire; - print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); + print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); } else { - print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; + print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; } } diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 49386538468feb539a0c7b5b789850c56874f857..10c1459a08779dbc2c0264201b78fbd909072036 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -108,42 +108,42 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'c.ref'=>'Ref', - 'c.ref_client'=>'RefCustomerOrder', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'c.note_public'=>'NotePublic', + 'c.ref'=>'Ref', + 'c.ref_client'=>'RefCustomerOrder', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'c.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["c.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'c.ref_client'=>array('label'=>$langs->trans("RefCustomerOrder"), 'checked'=>1), - 'p.project_ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>0, 'enabled'=>1), + 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'c.ref_client'=>array('label'=>$langs->trans("RefCustomerOrder"), 'checked'=>1), + 'p.project_ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>0, 'enabled'=>1), 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'c.date_commande'=>array('label'=>$langs->trans("OrderDateShort"), 'checked'=>1), - 'c.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)), - 'c.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'c.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'c.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'c.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), - 'c.facture'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>(empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'c.date_commande'=>array('label'=>$langs->trans("OrderDateShort"), 'checked'=>1), + 'c.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)), + 'c.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'c.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'c.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'c.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'c.facture'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>(empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } @@ -161,272 +161,272 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=''; - $search_ref_customer=''; - $search_company=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $search_total_ht=''; - $search_total_vat=''; - $search_total_ttc=''; - $search_orderyear=''; - $search_ordermonth=''; - $search_orderday=''; - $search_deliveryday=''; - $search_deliverymonth=''; - $search_deliveryyear=''; - $search_project_ref=''; - $viewstatut=''; - $billed=''; - $toselect=''; - $search_array_options=array(); - } - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') - || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) - { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation - } - - // Mass actions - $objectclass='Commande'; - $objectlabel='Orders'; - $permtoread = $user->rights->commande->lire; - $permtodelete = $user->rights->commande->supprimer; - $uploaddir = $conf->commande->dir_output; - $trigger_name='ORDER_SENTBYMAIL'; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_product_category=''; + $search_ref=''; + $search_ref_customer=''; + $search_company=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $search_total_ht=''; + $search_total_vat=''; + $search_total_ttc=''; + $search_orderyear=''; + $search_ordermonth=''; + $search_orderday=''; + $search_deliveryday=''; + $search_deliverymonth=''; + $search_deliveryyear=''; + $search_project_ref=''; + $viewstatut=''; + $billed=''; + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass='Commande'; + $objectlabel='Orders'; + $permtoread = $user->rights->commande->lire; + $permtodelete = $user->rights->commande->supprimer; + $uploaddir = $conf->commande->dir_output; + $trigger_name='ORDER_SENTBYMAIL'; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; // TODO Move this into mass action include - if ($massaction == 'confirm_createbills') { - - $orders = GETPOST('toselect','array'); - $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); - $validate_invoices = GETPOST('valdate_invoices', 'int'); - - $TFact = array(); - $TFactThird = array(); - - $nb_bills_created = 0; - - $db->begin(); - - foreach($orders as $id_order) - { - $cmd = new Commande($db); - if ($cmd->fetch($id_order) <= 0) continue; - - $object = new Facture($db); - if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. - else { - - $object->socid = $cmd->socid; - $object->type = Facture::TYPE_STANDARD; - $object->cond_reglement_id = $cmd->cond_reglement_id; - $object->mode_reglement_id = $cmd->mode_reglement_id; - $object->fk_project = $cmd->fk_project; - - $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); - if (empty($datefacture)) - { - $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); - } - - $object->date = $datefacture; - $object->origin = 'commande'; - $object->origin_id = $id_order; - - $res = $object->create($user); - - if($res > 0) $nb_bills_created++; - } - - if ($object->id > 0) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql.= "fk_source"; - $sql.= ", sourcetype"; - $sql.= ", fk_target"; - $sql.= ", targettype"; - $sql.= ") VALUES ("; - $sql.= $id_order; - $sql.= ", '".$object->origin."'"; - $sql.= ", ".$object->id; - $sql.= ", '".$object->element."'"; - $sql.= ")"; - - if (! $db->query($sql)) - { - $error++; - } - - if (! $error) - { - $lines = $cmd->lines; - if (empty($lines) && method_exists($cmd, 'fetch_lines')) - { - $cmd->fetch_lines(); - $lines = $cmd->lines; - } - - $fk_parent_line=0; - $num=count($lines); - - for ($i=0;$i<$num;$i++) - { - $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); - if ($lines[$i]->subprice < 0) - { - // Negative line, we create a discount line - $discount = new DiscountAbsolute($db); - $discount->fk_soc=$object->socid; - $discount->amount_ht=abs($lines[$i]->total_ht); - $discount->amount_tva=abs($lines[$i]->total_tva); - $discount->amount_ttc=abs($lines[$i]->total_ttc); - $discount->tva_tx=$lines[$i]->tva_tx; - $discount->fk_user=$user->id; - $discount->description=$desc; - $discountid=$discount->create($user); - if ($discountid > 0) - { - $result=$object->insert_discount($discountid); - //$result=$discount->link_to_invoice($lineid,$id); - } - else - { - setEventMessages($discount->error, $discount->errors, 'errors'); - $error++; - break; - } - } - else - { - // Positive line - $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); - // Date start - $date_start=false; - if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; - //Date end - $date_end=false; - if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; - // Reset fk_parent_line for no child products and special product - if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) - { - $fk_parent_line = 0; - } - $result = $object->addline( - $desc, - $lines[$i]->subprice, - $lines[$i]->qty, - $lines[$i]->tva_tx, - $lines[$i]->localtax1_tx, - $lines[$i]->localtax2_tx, - $lines[$i]->fk_product, - $lines[$i]->remise_percent, - $date_start, - $date_end, - 0, - $lines[$i]->info_bits, - $lines[$i]->fk_remise_except, - 'HT', - 0, - $product_type, - $ii, - $lines[$i]->special_code, - $object->origin, - $lines[$i]->rowid, - $fk_parent_line, - $lines[$i]->fk_fournprice, - $lines[$i]->pa_ht, - $lines[$i]->label - ); - if ($result > 0) - { - $lineid=$result; - } - else - { - $lineid=0; - $error++; - break; - } - // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) - { - $fk_parent_line = $result; - } - } - } - } - } - - //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. - - if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; - else $TFact[$object->id] = $object; - } - - // Build doc with all invoices - $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; - $toselect = array(); - - if (! $error && $validate_invoices) - { - $massaction = $action = 'builddoc'; - foreach($TAllFact as &$object) - { - $result = $object->validate($user); - if ($result <= 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - break; - } - - $id = $object->id; // For builddoc action - - // Fac builddoc - $donotredirect = 1; - $upload_dir = $conf->facture->dir_output; - $permissioncreate=$user->rights->facture->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - } - - $massaction = $action = 'confirm_createbills'; - } - - if (! $error) - { - $db->commit(); - setEventMessage($langs->trans('BillCreated', $nb_bills_created)); - } - else - { - $db->rollback(); - $action='create'; - $_GET["origin"]=$_POST["origin"]; - $_GET["originid"]=$_POST["originid"]; - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } + if ($massaction == 'confirm_createbills') { + + $orders = GETPOST('toselect','array'); + $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); + $validate_invoices = GETPOST('valdate_invoices', 'int'); + + $TFact = array(); + $TFactThird = array(); + + $nb_bills_created = 0; + + $db->begin(); + + foreach($orders as $id_order) + { + $cmd = new Commande($db); + if ($cmd->fetch($id_order) <= 0) continue; + + $object = new Facture($db); + if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. + else { + + $object->socid = $cmd->socid; + $object->type = Facture::TYPE_STANDARD; + $object->cond_reglement_id = $cmd->cond_reglement_id; + $object->mode_reglement_id = $cmd->mode_reglement_id; + $object->fk_project = $cmd->fk_project; + + $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); + if (empty($datefacture)) + { + $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); + } + + $object->date = $datefacture; + $object->origin = 'commande'; + $object->origin_id = $id_order; + + $res = $object->create($user); + + if($res > 0) $nb_bills_created++; + } + + if ($object->id > 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; + $sql.= "fk_source"; + $sql.= ", sourcetype"; + $sql.= ", fk_target"; + $sql.= ", targettype"; + $sql.= ") VALUES ("; + $sql.= $id_order; + $sql.= ", '".$object->origin."'"; + $sql.= ", ".$object->id; + $sql.= ", '".$object->element."'"; + $sql.= ")"; + + if (! $db->query($sql)) + { + $error++; + } + + if (! $error) + { + $lines = $cmd->lines; + if (empty($lines) && method_exists($cmd, 'fetch_lines')) + { + $cmd->fetch_lines(); + $lines = $cmd->lines; + } + + $fk_parent_line=0; + $num=count($lines); + + for ($i=0;$i<$num;$i++) + { + $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); + if ($lines[$i]->subprice < 0) + { + // Negative line, we create a discount line + $discount = new DiscountAbsolute($db); + $discount->fk_soc=$object->socid; + $discount->amount_ht=abs($lines[$i]->total_ht); + $discount->amount_tva=abs($lines[$i]->total_tva); + $discount->amount_ttc=abs($lines[$i]->total_ttc); + $discount->tva_tx=$lines[$i]->tva_tx; + $discount->fk_user=$user->id; + $discount->description=$desc; + $discountid=$discount->create($user); + if ($discountid > 0) + { + $result=$object->insert_discount($discountid); + //$result=$discount->link_to_invoice($lineid,$id); + } + else + { + setEventMessages($discount->error, $discount->errors, 'errors'); + $error++; + break; + } + } + else + { + // Positive line + $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + // Date start + $date_start=false; + if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue; + if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; + if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; + //Date end + $date_end=false; + if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue; + if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; + if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; + // Reset fk_parent_line for no child products and special product + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) + { + $fk_parent_line = 0; + } + $result = $object->addline( + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $lines[$i]->tva_tx, + $lines[$i]->localtax1_tx, + $lines[$i]->localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $date_start, + $date_end, + 0, + $lines[$i]->info_bits, + $lines[$i]->fk_remise_except, + 'HT', + 0, + $product_type, + $ii, + $lines[$i]->special_code, + $object->origin, + $lines[$i]->rowid, + $fk_parent_line, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + $lines[$i]->label + ); + if ($result > 0) + { + $lineid=$result; + } + else + { + $lineid=0; + $error++; + break; + } + // Defined the new fk_parent_line + if ($result > 0 && $lines[$i]->product_type == 9) + { + $fk_parent_line = $result; + } + } + } + } + } + + //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. + + if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; + else $TFact[$object->id] = $object; + } + + // Build doc with all invoices + $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; + $toselect = array(); + + if (! $error && $validate_invoices) + { + $massaction = $action = 'builddoc'; + foreach($TAllFact as &$object) + { + $result = $object->validate($user); + if ($result <= 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + break; + } + + $id = $object->id; // For builddoc action + + // Fac builddoc + $donotredirect = 1; + $upload_dir = $conf->facture->dir_output; + $permissioncreate=$user->rights->facture->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + } + + $massaction = $action = 'confirm_createbills'; + } + + if (! $error) + { + $db->commit(); + setEventMessage($langs->trans('BillCreated', $nb_bills_created)); + } + else + { + $db->rollback(); + $action='create'; + $_GET["origin"]=$_POST["origin"]; + $_GET["originid"]=$_POST["originid"]; + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } } @@ -475,8 +475,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = c.fk_projet"; if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE c.fk_soc = s.rowid'; $sql.= ' AND c.entity IN ('.getEntity('commande').')'; @@ -512,29 +512,29 @@ if ($viewstatut <> '') } if ($search_ordermonth > 0) { - if ($search_orderyear > 0 && empty($search_orderday)) - $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,$search_ordermonth,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,$search_ordermonth,false))."'"; - else if ($search_orderyear > 0 && ! empty($search_orderday)) - $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_ordermonth, $search_orderday, $search_orderyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_ordermonth, $search_orderday, $search_orderyear))."'"; - else - $sql.= " AND date_format(c.date_commande, '%m') = '".$search_ordermonth."'"; + if ($search_orderyear > 0 && empty($search_orderday)) + $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,$search_ordermonth,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,$search_ordermonth,false))."'"; + else if ($search_orderyear > 0 && ! empty($search_orderday)) + $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_ordermonth, $search_orderday, $search_orderyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_ordermonth, $search_orderday, $search_orderyear))."'"; + else + $sql.= " AND date_format(c.date_commande, '%m') = '".$search_ordermonth."'"; } else if ($search_orderyear > 0) { - $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,12,false))."'"; + $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,12,false))."'"; } if ($search_deliverymonth > 0) { - if ($search_deliveryyear > 0 && empty($search_deliveryday)) - $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,$search_deliverymonth,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,$search_deliverymonth,false))."'"; - else if ($search_deliveryyear > 0 && ! empty($search_deliveryday)) - $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."'"; - else - $sql.= " AND date_format(c.date_livraison, '%m') = '".$search_deliverymonth."'"; + if ($search_deliveryyear > 0 && empty($search_deliveryday)) + $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,$search_deliverymonth,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,$search_deliverymonth,false))."'"; + else if ($search_deliveryyear > 0 && ! empty($search_deliveryday)) + $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."'"; + else + $sql.= " AND date_format(c.date_livraison, '%m') = '".$search_deliverymonth."'"; } else if ($search_deliveryyear > 0) { - $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,12,false))."'"; + $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,12,false))."'"; } if ($search_town) $sql.= natural_search('s.town', $search_town); if ($search_zip) $sql.= natural_search("s.zip",$search_zip); @@ -549,16 +549,16 @@ if ($search_project_ref != '') $sql.= natural_search("p.ref",$search_project_ref // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -614,7 +614,7 @@ if ($resql) $arrayofselected=is_array($toselect)?$toselect:array(); $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + 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 ($socid > 0) $param.='&socid='.$socid; @@ -635,20 +635,20 @@ if ($resql) if ($search_total_ttc != '') $param.='&search_total_ttc='.$search_total_ttc; if ($search_project_ref >= 0) $param.="&search_project_ref=".$search_project_ref; if ($show_files) $param.='&show_files=' .$show_files; - if ($optioncss != '') $param.='&optioncss='.$optioncss; + if ($optioncss != '') $param.='&optioncss='.$optioncss; if ($billed != '') $param.='&billed='.$billed; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if ($user->rights->commande->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); @@ -657,13 +657,13 @@ if ($resql) // Lines of title fields print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; - print '<input type="hidden" name="page" value="'.$page.'">'; + print '<input type="hidden" name="page" value="'.$page.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print '<input type="hidden" name="viewstatut" value="'.$viewstatut.'">'; @@ -708,12 +708,12 @@ if ($resql) print '<td>'; if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL)) { - print $form->selectyesno('valdate_invoices', 0, 1, 1); - print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; + print $form->selectyesno('valdate_invoices', 0, 1, 1); + print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; } else { - print $form->selectyesno('valdate_invoices', 0, 1); + print $form->selectyesno('valdate_invoices', 0, 1); } print '</td>'; print '</tr>'; @@ -728,10 +728,10 @@ if ($resql) } if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } $moreforfilter=''; @@ -749,7 +749,7 @@ if ($resql) { $moreforfilter.='<div class="divsearchfield">'; $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='</div>'; } // If the user can view prospects other than his' @@ -771,30 +771,30 @@ if ($resql) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; - print '</div>'; + print '</div>'; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $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 '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; + print '<div class="div-table-responsive">'; + print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; print '<tr class="liste_titre_filter">'; // Ref if (! empty($arrayfields['c.ref']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" size="6" type="text" name="search_ref" value="'.$search_ref.'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" size="6" type="text" name="search_ref" value="'.$search_ref.'">'; + print '</td>'; } // Ref customer if (! empty($arrayfields['c.ref_client']['checked'])) { - print '<td class="liste_titre" align="left">'; - print '<input class="flat" type="text" size="6" name="search_ref_customer" value="'.$search_ref_customer.'">'; - print '</td>'; + print '<td class="liste_titre" align="left">'; + print '<input class="flat" type="text" size="6" name="search_ref_customer" value="'.$search_ref_customer.'">'; + print '</td>'; } // Project ref if (! empty($arrayfields['p.project_ref']['checked'])) @@ -804,9 +804,9 @@ if ($resql) // Thirpdarty if (! empty($arrayfields['s.nom']['checked'])) { - print '<td class="liste_titre" align="left">'; - print '<input class="flat" type="text" name="search_company" value="'.$search_company.'">'; - print '</td>'; + print '<td class="liste_titre" align="left">'; + print '<input class="flat" type="text" name="search_company" value="'.$search_company.'">'; + print '</td>'; } // Town if (! empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="4" name="search_town" value="'.$search_town.'"></td>'; @@ -815,84 +815,84 @@ if ($resql) // State if (! empty($arrayfields['state.nom']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; + print '</td>'; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print '<td class="liste_titre" align="center">'; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print '</td>'; + print '<td class="liste_titre" align="center">'; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print '</td>'; } // Company type if (! empty($arrayfields['typent.code']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="center">'; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="center">'; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print '</td>'; } // Date order if (! empty($arrayfields['c.date_commande']['checked'])) { - print '<td class="liste_titre" align="center">'; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_orderday" value="'.$search_orderday.'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="search_ordermonth" value="'.$search_ordermonth.'">'; - $formother->select_year($search_orderyear?$search_orderyear:-1,'search_orderyear',1, 20, 5); - print '</td>'; + print '<td class="liste_titre" align="center">'; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_orderday" value="'.$search_orderday.'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="search_ordermonth" value="'.$search_ordermonth.'">'; + $formother->select_year($search_orderyear?$search_orderyear:-1,'search_orderyear',1, 20, 5); + print '</td>'; } if (! empty($arrayfields['c.date_delivery']['checked'])) { - print '<td class="liste_titre" align="center">'; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_deliveryday" value="'.$search_deliveryday.'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="search_deliverymonth" value="'.$search_deliverymonth.'">'; - $formother->select_year($search_deliveryyear?$search_deliveryyear:-1,'search_deliveryyear',1, 20, 5); - print '</td>'; + print '<td class="liste_titre" align="center">'; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_deliveryday" value="'.$search_deliveryday.'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="search_deliverymonth" value="'.$search_deliverymonth.'">'; + $formother->select_year($search_deliveryyear?$search_deliveryyear:-1,'search_deliveryyear',1, 20, 5); + print '</td>'; } if (! empty($arrayfields['c.total_ht']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="4" name="search_total_ht" value="'.$search_total_ht.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="4" name="search_total_ht" value="'.$search_total_ht.'">'; + print '</td>'; } if (! empty($arrayfields['c.total_vat']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="4" name="search_total_vat" value="'.$search_total_vat.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="4" name="search_total_vat" value="'.$search_total_vat.'">'; + print '</td>'; } if (! empty($arrayfields['c.total_ttc']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_total_ttc" value="'.$search_total_ttc.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_total_ttc" value="'.$search_total_ttc.'">'; + print '</td>'; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } - print '</td>'; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -901,36 +901,36 @@ if ($resql) // Date creation if (! empty($arrayfields['c.datec']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Date modification if (! empty($arrayfields['c.tms']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Status if (! empty($arrayfields['c.fk_statut']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="right">'; - $liststatus=array( - Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"), - Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), - Commande::STATUS_SHIPMENTONPROCESS=>$langs->trans("StatusOrderSentShort"), - Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"), - -3=>$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort").'+'.$langs->trans("StatusOrderDelivered"), - Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceledShort") - ); - print $form->selectarray('viewstatut', $liststatus, $viewstatut, -4); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="right">'; + $liststatus=array( + Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"), + Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), + Commande::STATUS_SHIPMENTONPROCESS=>$langs->trans("StatusOrderSentShort"), + Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"), + -3=>$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort").'+'.$langs->trans("StatusOrderDelivered"), + Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceledShort") + ); + print $form->selectarray('viewstatut', $liststatus, $viewstatut, -4); + print '</td>'; } // Status billed if (! empty($arrayfields['c.facture']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="right">'; - print $form->selectyesno('billed', $billed, 1, 0, 1); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="right">'; + print $form->selectyesno('billed', $billed, 1, 0, 1); + print '</td>'; } // Action column print '<td class="liste_titre" align="middle">'; @@ -938,7 +938,7 @@ if ($resql) print $searchpicto; print '</td>'; - print "</tr>\n"; + print "</tr>\n"; // Fields title print '<tr class="liste_titre">'; @@ -961,19 +961,19 @@ if ($resql) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'],$_SERVER["PHP_SELF"],"c.date_creation","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'],$_SERVER["PHP_SELF"],"c.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['c.fk_statut']['checked'])) print_liste_field_titre($arrayfields['c.fk_statut']['label'],$_SERVER["PHP_SELF"],"c.fk_statut","",$param,'align="right"',$sortfield,$sortorder); @@ -983,188 +983,188 @@ if ($resql) $total=0; $subtotal=0; - $productstat_cache=array(); + $productstat_cache=array(); - $generic_commande = new Commande($db); - $generic_product = new Product($db); + $generic_commande = new Commande($db); + $generic_product = new Product($db); - $i=0; + $i=0; $totalarray=array(); - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); - - $notshippable=0; - $warning = 0; - $text_info=''; - $text_warning=''; - $nbprod=0; - - $companystatic->id=$obj->socid; - $companystatic->code_client = $obj->code_client; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; - $companystatic->email=$obj->email; - - $generic_commande->id=$obj->rowid; - $generic_commande->ref=$obj->ref; - $generic_commande->statut = $obj->fk_statut; - $generic_commande->date_commande = $db->jdate($obj->date_commande); - $generic_commande->date_livraison = $db->jdate($obj->date_delivery); - $generic_commande->ref_client = $obj->ref_client; - $generic_commande->total_ht = $obj->total_ht; - $generic_commande->total_tva = $obj->total_tva; - $generic_commande->total_ttc = $obj->total_ttc; - - print '<tr class="oddeven">'; - - // Ref - if (! empty($arrayfields['c.ref']['checked'])) - { - print '<td class="nowrap">'; - - $generic_commande->lines=array(); - $generic_commande->getLinesArray(); - - print '<table class="nobordernopadding"><tr class="nocellnopadd">'; - print '<td class="nobordernopadding nowrap">'; - print $generic_commande->getNomUrl(1, ($viewstatut != 2?0:$obj->fk_statut), 0, 0, 0, 1); - print '</td>'; - - // Show shippable Icon (create subloop, so may be slow) - if ($conf->stock->enabled) - { - $langs->load("stocks"); - if (($obj->fk_statut > 0) && ($obj->fk_statut < 3)) - { - $numlines = count($generic_commande->lines); // Loop on each line of order - for ($lig=0; $lig < $numlines; $lig++) - { - if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0) // If line is a product and not a service - { - $nbprod++; // order contains real products - $generic_product->id = $generic_commande->lines[$lig]->fk_product; - - // Get local and virtual stock and store it into cache - if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product])) { - $generic_product->load_stock('nobatch'); - //$generic_product->load_virtual_stock(); Already included into load_stock - $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_reel; - $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; - } else { - $generic_product->stock_reel = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel']; - $generic_product->stock_theorique = $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; - } - - if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) // Default code. Default is when this option is not set, setting it create strange result - { - $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); - $text_info .= ' - '.$langs->trans("Stock").': '.$generic_product->stock_reel; - $text_info .= ' - '.$langs->trans("VirtualStock").': '.$generic_product->stock_theorique; - $text_info .= '<br>'; - - if ($generic_commande->lines[$lig]->qty > $generic_product->stock_reel) - { - $notshippable++; - } - } - else { // Detailed code, looks bugged - // stock order and stock order_supplier - $stock_order=0; - $stock_order_supplier=0; - if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) // What about other options ? - { - if (! empty($conf->commande->enabled)) - { - if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'])) { - $generic_product->load_stats_commande(0,'1,2'); - $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'] = $generic_product->stats_commande['qty']; - } else { - $generic_product->stats_commande['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer']; - } - $stock_order=$generic_product->stats_commande['qty']; - } - if (! empty($conf->fournisseur->enabled)) - { - if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'])) { - $generic_product->load_stats_commande_fournisseur(0,'3'); - $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'] = $generic_product->stats_commande_fournisseur['qty']; - } else { - $generic_product->stats_commande_fournisseur['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier']; - } - $stock_order_supplier=$generic_product->stats_commande_fournisseur['qty']; - } - } - $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); - $text_stock_reel = $generic_product->stock_reel.'/'.$stock_order; - if ($stock_order > $generic_product->stock_reel && ! ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty)) { - $warning++; - $text_warning.='<span class="warning">'.$langs->trans('Available').' : '.$text_stock_reel.'</span>'; - } - if ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty) { - $notshippable++; - $text_info.='<span class="warning">'.$langs->trans('Available').' : '.$text_stock_reel.'</span>'; - } else { - $text_info.='<span class="ok">'.$langs->trans('Available').' : '.$text_stock_reel.'</span>'; - } - if (! empty($conf->fournisseur->enabled)) { - $text_info.= ' '.$langs->trans('SupplierOrder').' : '.$stock_order_supplier.'<br>'; - } else { - $text_info.= '<br>'; - } - } - } - } - if ($notshippable==0) { - $text_icon = img_picto('', 'object_sending'); - $text_info = $langs->trans('Shippable').'<br>'.$text_info; - } else { - $text_icon = img_picto('', 'error'); - $text_info = $langs->trans('NonShippable').'<br>'.$text_info; - } - } - - print '<td>'; - if ($nbprod) - { - print $form->textwithtooltip('',$text_info,2,1,$text_icon,'',2); - } - if ($warning) { // Always false in default mode - print $form->textwithtooltip('', $langs->trans('NotEnoughForAllOrders').'<br>'.$text_warning, 2, 1, img_picto('', 'error'),'',2); - } - print '</td>'; - } - - // Warning late icon and note - print '<td class="nobordernopadding nowrap">'; - if ($generic_commande->hasDelay()) { - print img_picto($langs->trans("Late").' : '.$generic_commande->showDelay(), "warning"); - } - if (!empty($obj->note_private) || !empty($obj->note_public)) - { - print ' <span class="note">'; - print '<a href="'.DOL_URL_ROOT.'/commande/note.php?id='.$obj->rowid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>'; - print '</span>'; - } - print '</td>'; - - print '<td width="16" align="right" class="nobordernopadding hideonsmartphone">'; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); - print '</td>'; - print '</tr></table>'; - - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); + + $notshippable=0; + $warning = 0; + $text_info=''; + $text_warning=''; + $nbprod=0; + + $companystatic->id=$obj->socid; + $companystatic->code_client = $obj->code_client; + $companystatic->name=$obj->name; + $companystatic->client=$obj->client; + $companystatic->email=$obj->email; + + $generic_commande->id=$obj->rowid; + $generic_commande->ref=$obj->ref; + $generic_commande->statut = $obj->fk_statut; + $generic_commande->date_commande = $db->jdate($obj->date_commande); + $generic_commande->date_livraison = $db->jdate($obj->date_delivery); + $generic_commande->ref_client = $obj->ref_client; + $generic_commande->total_ht = $obj->total_ht; + $generic_commande->total_tva = $obj->total_tva; + $generic_commande->total_ttc = $obj->total_ttc; + + print '<tr class="oddeven">'; + + // Ref + if (! empty($arrayfields['c.ref']['checked'])) + { + print '<td class="nowrap">'; + + $generic_commande->lines=array(); + $generic_commande->getLinesArray(); + + print '<table class="nobordernopadding"><tr class="nocellnopadd">'; + print '<td class="nobordernopadding nowrap">'; + print $generic_commande->getNomUrl(1, ($viewstatut != 2?0:$obj->fk_statut), 0, 0, 0, 1); + print '</td>'; + + // Show shippable Icon (create subloop, so may be slow) + if ($conf->stock->enabled) + { + $langs->load("stocks"); + if (($obj->fk_statut > 0) && ($obj->fk_statut < 3)) + { + $numlines = count($generic_commande->lines); // Loop on each line of order + for ($lig=0; $lig < $numlines; $lig++) + { + if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0) // If line is a product and not a service + { + $nbprod++; // order contains real products + $generic_product->id = $generic_commande->lines[$lig]->fk_product; + + // Get local and virtual stock and store it into cache + if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product])) { + $generic_product->load_stock('nobatch'); + //$generic_product->load_virtual_stock(); Already included into load_stock + $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_reel; + $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; + } else { + $generic_product->stock_reel = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel']; + $generic_product->stock_theorique = $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; + } + + if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) // Default code. Default is when this option is not set, setting it create strange result + { + $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); + $text_info .= ' - '.$langs->trans("Stock").': '.$generic_product->stock_reel; + $text_info .= ' - '.$langs->trans("VirtualStock").': '.$generic_product->stock_theorique; + $text_info .= '<br>'; + + if ($generic_commande->lines[$lig]->qty > $generic_product->stock_reel) + { + $notshippable++; + } + } + else { // Detailed code, looks bugged + // stock order and stock order_supplier + $stock_order=0; + $stock_order_supplier=0; + if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) // What about other options ? + { + if (! empty($conf->commande->enabled)) + { + if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'])) { + $generic_product->load_stats_commande(0,'1,2'); + $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'] = $generic_product->stats_commande['qty']; + } else { + $generic_product->stats_commande['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer']; + } + $stock_order=$generic_product->stats_commande['qty']; + } + if (! empty($conf->fournisseur->enabled)) + { + if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'])) { + $generic_product->load_stats_commande_fournisseur(0,'3'); + $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'] = $generic_product->stats_commande_fournisseur['qty']; + } else { + $generic_product->stats_commande_fournisseur['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier']; + } + $stock_order_supplier=$generic_product->stats_commande_fournisseur['qty']; + } + } + $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); + $text_stock_reel = $generic_product->stock_reel.'/'.$stock_order; + if ($stock_order > $generic_product->stock_reel && ! ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty)) { + $warning++; + $text_warning.='<span class="warning">'.$langs->trans('Available').' : '.$text_stock_reel.'</span>'; + } + if ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty) { + $notshippable++; + $text_info.='<span class="warning">'.$langs->trans('Available').' : '.$text_stock_reel.'</span>'; + } else { + $text_info.='<span class="ok">'.$langs->trans('Available').' : '.$text_stock_reel.'</span>'; + } + if (! empty($conf->fournisseur->enabled)) { + $text_info.= ' '.$langs->trans('SupplierOrder').' : '.$stock_order_supplier.'<br>'; + } else { + $text_info.= '<br>'; + } + } + } + } + if ($notshippable==0) { + $text_icon = img_picto('', 'object_sending'); + $text_info = $langs->trans('Shippable').'<br>'.$text_info; + } else { + $text_icon = img_picto('', 'error'); + $text_info = $langs->trans('NonShippable').'<br>'.$text_info; + } + } + + print '<td>'; + if ($nbprod) + { + print $form->textwithtooltip('',$text_info,2,1,$text_icon,'',2); + } + if ($warning) { // Always false in default mode + print $form->textwithtooltip('', $langs->trans('NotEnoughForAllOrders').'<br>'.$text_warning, 2, 1, img_picto('', 'error'),'',2); + } + print '</td>'; + } + + // Warning late icon and note + print '<td class="nobordernopadding nowrap">'; + if ($generic_commande->hasDelay()) { + print img_picto($langs->trans("Late").' : '.$generic_commande->showDelay(), "warning"); + } + if (!empty($obj->note_private) || !empty($obj->note_public)) + { + print ' <span class="note">'; + print '<a href="'.DOL_URL_ROOT.'/commande/note.php?id='.$obj->rowid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>'; + print '</span>'; + } + print '</td>'; + + print '<td width="16" align="right" class="nobordernopadding hideonsmartphone">'; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); + print '</td>'; + print '</tr></table>'; + + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } // Ref customer if (! empty($arrayfields['c.ref_client']['checked'])) { - print '<td>'.$obj->ref_client.'</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td>'.$obj->ref_client.'</td>'; + if (! $i) $totalarray['nbfield']++; } // Project @@ -1181,167 +1181,167 @@ if ($resql) // Third party if (! empty($arrayfields['s.nom']['checked'])) { - print '<td class="tdoverflowmax200">'; - print $companystatic->getNomUrl(1,'customer'); - - // If module invoices enabled and user with invoice creation permissions - if (! empty($conf->facture->enabled) && ! empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) - { - if ($user->rights->facture->creer) - { - if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) - { - print ' <a href="'.DOL_URL_ROOT.'/commande/orderstoinvoice.php?socid='.$companystatic->id.'">'; - print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').'</a>'; - } - } - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="tdoverflowmax200">'; + print $companystatic->getNomUrl(1,'customer'); + + // If module invoices enabled and user with invoice creation permissions + if (! empty($conf->facture->enabled) && ! empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) + { + if ($user->rights->facture->creer) + { + if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) + { + print ' <a href="'.DOL_URL_ROOT.'/commande/orderstoinvoice.php?socid='.$companystatic->id.'">'; + print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').'</a>'; + } + } + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Town if (! empty($arrayfields['s.town']['checked'])) { - print '<td class="nocellnopadd">'; - print $obj->town; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="nocellnopadd">'; + print $obj->town; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Zip if (! empty($arrayfields['s.zip']['checked'])) { - print '<td class="nocellnopadd">'; - print $obj->zip; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="nocellnopadd">'; + print $obj->zip; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // State if (! empty($arrayfields['state.nom']['checked'])) { - print "<td>".$obj->state_name."</td>\n"; - if (! $i) $totalarray['nbfield']++; + print "<td>".$obj->state_name."</td>\n"; + if (! $i) $totalarray['nbfield']++; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print '<td align="center">'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Type ent if (! empty($arrayfields['typent.code']['checked'])) { - print '<td align="center">'; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Order date if (! empty($arrayfields['c.date_commande']['checked'])) { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_commande), 'day'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_commande), 'day'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Plannned date of delivery if (! empty($arrayfields['c.date_delivery']['checked'])) { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_delivery), 'day'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_delivery), 'day'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Amount HT + if (! empty($arrayfields['c.total_ht']['checked'])) + { + print '<td align="right">'.price($obj->total_ht)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['c.total_vat']['checked'])) + { + print '<td align="right">'.price($obj->total_tva)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_tva; + } + // Amount TTC + if (! empty($arrayfields['c.total_ttc']['checked'])) + { + print '<td align="right">'.price($obj->total_ttc)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } + + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } + } + // 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['c.datec']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['c.tms']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['c.fk_statut']['checked'])) + { + print '<td align="right" class="nowrap">'.$generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1).'</td>'; + if (! $i) $totalarray['nbfield']++; } - // Amount HT - if (! empty($arrayfields['c.total_ht']['checked'])) - { - print '<td align="right">'.price($obj->total_ht)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['c.total_vat']['checked'])) - { - print '<td align="right">'.price($obj->total_tva)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_tva; - } - // Amount TTC - if (! empty($arrayfields['c.total_ttc']['checked'])) - { - print '<td align="right">'.price($obj->total_ttc)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } - - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } - } - // 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['c.datec']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['c.tms']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['c.fk_statut']['checked'])) - { - print '<td align="right" class="nowrap">'.$generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1).'</td>'; - if (! $i) $totalarray['nbfield']++; - } // Billed - if (! empty($arrayfields['c.facture']['checked'])) - { - print '<td align="center">'.yn($obj->billed).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Action column - print '<td class="nowrap" align="center">'; - 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! empty($arrayfields['c.facture']['checked'])) + { + print '<td align="center">'.yn($obj->billed).'</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Action column + print '<td class="nowrap" align="center">'; + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; print "</tr>\n"; @@ -1351,29 +1351,29 @@ if ($resql) } // Show total line - if (isset($totalarray['totalhtfield']) + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totalttcfield']) || isset($totalarray['totalamfield']) || isset($totalarray['totalrtpfield']) ) { - print '<tr class="liste_total">'; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; - else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; - } - elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; - elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; - elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; - else print '<td></td>'; - } - print '</tr>'; + print '<tr class="liste_total">'; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; + else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; + } + elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; + elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; + elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; + else print '<td></td>'; + } + print '</tr>'; } $db->free($resql); @@ -1389,21 +1389,21 @@ if ($resql) if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->commande->lire; - $delallowed=$user->rights->commande->supprimer; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->commande->lire; + $delallowed=$user->rights->commande->supprimer; - print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } else { - print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; + print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; } } diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index a9ad95d26d59123fd95c5035f2994ec51a7dd510..8ad1ccd2ecfc39344aaec8f9609620db1be58ba1 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -36,117 +36,117 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; */ class Account extends CommonObject { - public $element = 'bank_account'; - public $table_element = 'bank_account'; - public $picto = 'account'; - - /** - * @var int Use id instead of rowid - * @deprecated - * @see id - */ - public $rowid; - - /** - * Label - * @var string - */ - public $label; - - /** - * Bank account type. Check TYPE_ constants - * @var int - */ - public $courant; - - /** - * Bank account type. Check TYPE_ constants - * @var int - */ - public $type; - - /** - * Bank name - * @var string - */ - public $bank; - - /** - * Status - * @var int - */ - public $clos = self::STATUS_OPEN; - - /** - * Does it need to be conciliated? - * @var int - */ - public $rappro=1; - - /** - * Webpage - * @var string - */ - public $url; - - /** - * Bank number. If in SEPA area, you should move to IBAN field - * @var string - */ - public $code_banque; - - /** - * Branch number. If in SEPA area, you should move to IBAN field - * @var string - */ - public $code_guichet; - - /** - * Account number. If in SEPA area, you should move to IBAN field - * @var string - */ - public $number; - - /** - * Bank account number control digit. If in SEPA area, you should move to IBAN field - * @var string - */ - public $cle_rib; - - /** - * BIC/Swift code - * @var string - */ - public $bic; - - /** - * IBAN number (International Bank Account Number). Stored into iban_prefix field into database - * @var - */ - public $iban; - - /** - * Name of account holder - * @var string - */ - public $proprio; - - /** - * Address of account holder - * @var string - */ - public $owner_address; - - public $state_id; - public $state_code; - public $state; + public $element = 'bank_account'; + public $table_element = 'bank_account'; + public $picto = 'account'; + + /** + * @var int Use id instead of rowid + * @deprecated + * @see id + */ + public $rowid; + + /** + * Label + * @var string + */ + public $label; + + /** + * Bank account type. Check TYPE_ constants + * @var int + */ + public $courant; + + /** + * Bank account type. Check TYPE_ constants + * @var int + */ + public $type; + + /** + * Bank name + * @var string + */ + public $bank; + + /** + * Status + * @var int + */ + public $clos = self::STATUS_OPEN; + + /** + * Does it need to be conciliated? + * @var int + */ + public $rappro=1; + + /** + * Webpage + * @var string + */ + public $url; + + /** + * Bank number. If in SEPA area, you should move to IBAN field + * @var string + */ + public $code_banque; + + /** + * Branch number. If in SEPA area, you should move to IBAN field + * @var string + */ + public $code_guichet; + + /** + * Account number. If in SEPA area, you should move to IBAN field + * @var string + */ + public $number; + + /** + * Bank account number control digit. If in SEPA area, you should move to IBAN field + * @var string + */ + public $cle_rib; + + /** + * BIC/Swift code + * @var string + */ + public $bic; + + /** + * IBAN number (International Bank Account Number). Stored into iban_prefix field into database + * @var + */ + public $iban; + + /** + * Name of account holder + * @var string + */ + public $proprio; + + /** + * Address of account holder + * @var string + */ + public $owner_address; + + public $state_id; + public $state_code; + public $state; /** * Variable containing all account types with their respective translated label. * Defined in __construct * @var array */ - public $type_lib = array(); + public $type_lib = array(); /** * Variable containing all account statuses with their respective translated label. @@ -155,90 +155,90 @@ class Account extends CommonObject */ public $status = array(); - /** - * Accountancy code - * @var string - */ - public $account_number; + /** + * Accountancy code + * @var string + */ + public $account_number; public $fk_accountancy_journal; - /** - * Currency code - * @var string - */ - public $currency_code; - - /** - * Currency code - * @var string - * @deprecated Use currency_code instead - */ - public $account_currency_code; - - /** - * Authorized minimum balance - * @var float - */ - public $min_allowed; - - /** - * Desired minimum balance - * @var float - */ - public $min_desired; - - /** - * Notes - * @var string - */ - public $comment; - - /** - * Date of the initial balance. Used in Account::create - * @var int - */ - public $date_solde; - - /** - * Current account - */ - const TYPE_CURRENT = 1; - /** - * Cash account - */ - const TYPE_CASH = 2; - /** - * Savings account - */ - const TYPE_SAVINGS = 0; - - const STATUS_OPEN = 0; - const STATUS_CLOSED = 1; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct(DoliDB $db) - { - global $langs; - - $this->db = $db; - - $this->solde = 0; - - $this->type_lib = array( - self::TYPE_SAVINGS => $langs->trans("BankType0"), - self::TYPE_CURRENT => $langs->trans("BankType1"), - self::TYPE_CASH => $langs->trans("BankType2"), - ); - - $this->status = array( - self::STATUS_OPEN => $langs->trans("StatusAccountOpened"), - self::STATUS_CLOSED => $langs->trans("StatusAccountClosed") - ); - } + /** + * Currency code + * @var string + */ + public $currency_code; + + /** + * Currency code + * @var string + * @deprecated Use currency_code instead + */ + public $account_currency_code; + + /** + * Authorized minimum balance + * @var float + */ + public $min_allowed; + + /** + * Desired minimum balance + * @var float + */ + public $min_desired; + + /** + * Notes + * @var string + */ + public $comment; + + /** + * Date of the initial balance. Used in Account::create + * @var int + */ + public $date_solde; + + /** + * Current account + */ + const TYPE_CURRENT = 1; + /** + * Cash account + */ + const TYPE_CASH = 2; + /** + * Savings account + */ + const TYPE_SAVINGS = 0; + + const STATUS_OPEN = 0; + const STATUS_CLOSED = 1; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct(DoliDB $db) + { + global $langs; + + $this->db = $db; + + $this->solde = 0; + + $this->type_lib = array( + self::TYPE_SAVINGS => $langs->trans("BankType0"), + self::TYPE_CURRENT => $langs->trans("BankType1"), + self::TYPE_CASH => $langs->trans("BankType2"), + ); + + $this->status = array( + self::STATUS_OPEN => $langs->trans("StatusAccountOpened"), + self::STATUS_CLOSED => $langs->trans("StatusAccountClosed") + ); + } /** * Shows the account number in the appropiate format @@ -270,184 +270,184 @@ class Account extends CommonObject } - /** - * Return if a bank account need to be conciliated - * - * @return int 1 if need to be concialiated, < 0 otherwise. - */ - function canBeConciliated() - { - global $conf; - - if (empty($this->rappro)) return -1; - if ($this->courant == Account::TYPE_CASH && empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) return -2; - if ($this->clos) return -3; - return 1; - } - - - /** - * Add a link between bank line record and its source - * - * @param int $line_id Id ecriture bancaire - * @param int $url_id Id parametre url - * @param string $url Url - * @param string $label Link label - * @param string $type Type of link ('payment', 'company', 'member', ...) - * @return int <0 if KO, id line if OK - */ - function add_url_line($line_id, $url_id, $url, $label, $type) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url ("; - $sql.= "fk_bank"; - $sql.= ", url_id"; - $sql.= ", url"; - $sql.= ", label"; - $sql.= ", type"; - $sql.= ") VALUES ("; - $sql.= "'".$line_id."'"; - $sql.= ", '".$url_id."'"; - $sql.= ", '".$url."'"; - $sql.= ", '".$this->db->escape($label)."'"; - $sql.= ", '".$type."'"; - $sql.= ")"; - - dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG); - if ($this->db->query($sql)) - { - $rowid = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_url"); - return $rowid; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } - - /** - * TODO Move this into AccountLine - * Return array with links from llx_bank_url - * - * @param int $fk_bank To search using bank transaction id - * @param int $url_id To search using link to - * @param string $type To search using type - * @return array|-1 Array of links or -1 on error - */ - function get_url($fk_bank='', $url_id='', $type='') - { - $lines = array(); - - // Check parameters - if (! empty($fk_bank) && (! empty($url_id) || ! empty($type))) - { - $this->error="ErrorBadParameter"; - return -1; - } + /** + * Return if a bank account need to be conciliated + * + * @return int 1 if need to be concialiated, < 0 otherwise. + */ + function canBeConciliated() + { + global $conf; - $sql = "SELECT fk_bank, url_id, url, label, type"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_url"; - if ($fk_bank > 0) { - $sql.= " WHERE fk_bank = ".$fk_bank; - } - else { $sql.= " WHERE url_id = ".$url_id." AND type = '".$type."'"; - } - $sql.= " ORDER BY type, label"; + if (empty($this->rappro)) return -1; + if ($this->courant == Account::TYPE_CASH && empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) return -2; + if ($this->clos) return -3; + return 1; + } - dol_syslog(get_class($this)."::get_url", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $i = 0; - $num = $this->db->num_rows($result); - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - // Anciens liens (pour compatibilite) - $lines[$i][0] = $obj->url; - $lines[$i][1] = $obj->url_id; - $lines[$i][2] = $obj->label; - $lines[$i][3] = $obj->type; - // Nouveaux liens - $lines[$i]['url'] = $obj->url; - $lines[$i]['url_id'] = $obj->url_id; - $lines[$i]['label'] = $obj->label; - $lines[$i]['type'] = $obj->type; - $lines[$i]['fk_bank'] = $obj->fk_bank; - $i++; - } - } - else dol_print_error($this->db); - - return $lines; - } - - /** - * Add an entry into table ".MAIN_DB_PREFIX."bank - * - * @param int $date Date operation - * @param string $oper 1,2,3,4... (deprecated) or TYP,VIR,PRE,LIQ,VAD,CB,CHQ... - * @param string $label Descripton - * @param float $amount Amount - * @param string $num_chq Numero cheque ou virement - * @param int $categorie Category id (optionnal) - * @param User $user User that create - * @param string $emetteur Name of cheque writer - * @param string $banque Bank of cheque writer - * @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on. - * @return int Rowid of added entry, <0 if KO - */ - function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='') - { - // Deprecatîon warning - if (is_numeric($oper)) { - dol_syslog(__METHOD__ . ": using numeric operations is deprecated", LOG_WARNING); - } - - // Clean parameters - $emetteur=trim($emetteur); - $banque=trim($banque); - - $now=dol_now(); - - if (is_numeric($oper)) // Clean oper to have a code instead of a rowid - { - $sql = "SELECT code FROM ".MAIN_DB_PREFIX."c_paiement"; - $sql.= " WHERE id=".$oper; - $sql.= " AND entity IN (" . getEntity('c_paiement') . ")"; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - $oper=$obj->code; - } - else - { - dol_print_error($this->db,'Failed to get payment type code'); - return -1; - } - } - // Check parameters - if (! $oper) - { - $this->error="oper not defined"; - return -1; - } - if (! $this->rowid) - { - $this->error="this->rowid not defined"; - return -2; - } - if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ') - { - $this->error="ErrorCashAccountAcceptsOnlyCashMoney"; - return -3; - } + /** + * Add a link between bank line record and its source + * + * @param int $line_id Id ecriture bancaire + * @param int $url_id Id parametre url + * @param string $url Url + * @param string $label Link label + * @param string $type Type of link ('payment', 'company', 'member', ...) + * @return int <0 if KO, id line if OK + */ + function add_url_line($line_id, $url_id, $url, $label, $type) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url ("; + $sql.= "fk_bank"; + $sql.= ", url_id"; + $sql.= ", url"; + $sql.= ", label"; + $sql.= ", type"; + $sql.= ") VALUES ("; + $sql.= "'".$line_id."'"; + $sql.= ", '".$url_id."'"; + $sql.= ", '".$url."'"; + $sql.= ", '".$this->db->escape($label)."'"; + $sql.= ", '".$type."'"; + $sql.= ")"; + + dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG); + if ($this->db->query($sql)) + { + $rowid = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_url"); + return $rowid; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + + /** + * TODO Move this into AccountLine + * Return array with links from llx_bank_url + * + * @param int $fk_bank To search using bank transaction id + * @param int $url_id To search using link to + * @param string $type To search using type + * @return array|-1 Array of links or -1 on error + */ + function get_url($fk_bank='', $url_id='', $type='') + { + $lines = array(); + + // Check parameters + if (! empty($fk_bank) && (! empty($url_id) || ! empty($type))) + { + $this->error="ErrorBadParameter"; + return -1; + } + + $sql = "SELECT fk_bank, url_id, url, label, type"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_url"; + if ($fk_bank > 0) { + $sql.= " WHERE fk_bank = ".$fk_bank; + } + else { $sql.= " WHERE url_id = ".$url_id." AND type = '".$type."'"; + } + $sql.= " ORDER BY type, label"; + + dol_syslog(get_class($this)."::get_url", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $i = 0; + $num = $this->db->num_rows($result); + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + // Anciens liens (pour compatibilite) + $lines[$i][0] = $obj->url; + $lines[$i][1] = $obj->url_id; + $lines[$i][2] = $obj->label; + $lines[$i][3] = $obj->type; + // Nouveaux liens + $lines[$i]['url'] = $obj->url; + $lines[$i]['url_id'] = $obj->url_id; + $lines[$i]['label'] = $obj->label; + $lines[$i]['type'] = $obj->type; + $lines[$i]['fk_bank'] = $obj->fk_bank; + $i++; + } + } + else dol_print_error($this->db); + + return $lines; + } + + /** + * Add an entry into table ".MAIN_DB_PREFIX."bank + * + * @param int $date Date operation + * @param string $oper 1,2,3,4... (deprecated) or TYP,VIR,PRE,LIQ,VAD,CB,CHQ... + * @param string $label Descripton + * @param float $amount Amount + * @param string $num_chq Numero cheque ou virement + * @param int $categorie Category id (optionnal) + * @param User $user User that create + * @param string $emetteur Name of cheque writer + * @param string $banque Bank of cheque writer + * @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on. + * @return int Rowid of added entry, <0 if KO + */ + function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='') + { + // Deprecatîon warning + if (is_numeric($oper)) { + dol_syslog(__METHOD__ . ": using numeric operations is deprecated", LOG_WARNING); + } + + // Clean parameters + $emetteur=trim($emetteur); + $banque=trim($banque); + + $now=dol_now(); + + if (is_numeric($oper)) // Clean oper to have a code instead of a rowid + { + $sql = "SELECT code FROM ".MAIN_DB_PREFIX."c_paiement"; + $sql.= " WHERE id=".$oper; + $sql.= " AND entity IN (" . getEntity('c_paiement') . ")"; + $resql=$this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + $oper=$obj->code; + } + else + { + dol_print_error($this->db,'Failed to get payment type code'); + return -1; + } + } + + // Check parameters + if (! $oper) + { + $this->error="oper not defined"; + return -1; + } + if (! $this->rowid) + { + $this->error="this->rowid not defined"; + return -2; + } + if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ') + { + $this->error="ErrorCashAccountAcceptsOnlyCashMoney"; + return -3; + } - $this->db->begin(); + $this->db->begin(); - $datev = $date; + $datev = $date; $accline = new AccountLine($this->db); $accline->datec = $now; @@ -498,109 +498,109 @@ class Account extends CommonObject } } - /** - * Create bank account into database - * - * @param User $user Object user making creation - * @param int $notrigger 1=Disable triggers - * @return int < 0 if KO, > 0 if OK - */ - function create(User $user = null, $notrigger=0) - { - global $langs,$conf, $hookmanager; - - // Clean parameters - if (! $this->min_allowed) $this->min_allowed=0; - if (! $this->min_desired) $this->min_desired=0; - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); - - // Check parameters - if (empty($this->country_id)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } - if (empty($this->ref)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } - if (empty($this->date_solde)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateInitialBalance")); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } + /** + * Create bank account into database + * + * @param User $user Object user making creation + * @param int $notrigger 1=Disable triggers + * @return int < 0 if KO, > 0 if OK + */ + function create(User $user = null, $notrigger=0) + { + global $langs,$conf, $hookmanager; + + // Clean parameters + if (! $this->min_allowed) $this->min_allowed=0; + if (! $this->min_desired) $this->min_desired=0; + $this->state_id = ($this->state_id?$this->state_id:$this->state_id); + $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + + // Check parameters + if (empty($this->country_id)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } + if (empty($this->ref)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } + if (empty($this->date_solde)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateInitialBalance")); + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } - // Chargement librairie pour acces fonction controle RIB - require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; + // Chargement librairie pour acces fonction controle RIB + require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; - $now=dol_now(); + $now=dol_now(); - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account ("; - $sql.= "datec"; - $sql.= ", ref"; - $sql.= ", label"; - $sql.= ", entity"; - $sql.= ", account_number"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account ("; + $sql.= "datec"; + $sql.= ", ref"; + $sql.= ", label"; + $sql.= ", entity"; + $sql.= ", account_number"; $sql.= ", fk_accountancy_journal"; $sql.= ", bank"; - $sql.= ", code_banque"; - $sql.= ", code_guichet"; - $sql.= ", number"; - $sql.= ", cle_rib"; - $sql.= ", bic"; - $sql.= ", iban_prefix"; - $sql.= ", domiciliation"; - $sql.= ", proprio"; - $sql.= ", owner_address"; + $sql.= ", code_banque"; + $sql.= ", code_guichet"; + $sql.= ", number"; + $sql.= ", cle_rib"; + $sql.= ", bic"; + $sql.= ", iban_prefix"; + $sql.= ", domiciliation"; + $sql.= ", proprio"; + $sql.= ", owner_address"; $sql.= ", currency_code"; - $sql.= ", rappro"; - $sql.= ", min_allowed"; - $sql.= ", min_desired"; - $sql.= ", comment"; - $sql.= ", state_id"; - $sql.= ", fk_pays"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->idate($now)."'"; - $sql.= ", '".$this->db->escape($this->ref)."'"; - $sql.= ", '".$this->db->escape($this->label)."'"; - $sql.= ", ".$conf->entity; - $sql.= ", '".$this->db->escape($this->account_number)."'"; + $sql.= ", rappro"; + $sql.= ", min_allowed"; + $sql.= ", min_desired"; + $sql.= ", comment"; + $sql.= ", state_id"; + $sql.= ", fk_pays"; + $sql.= ") VALUES ("; + $sql.= "'".$this->db->idate($now)."'"; + $sql.= ", '".$this->db->escape($this->ref)."'"; + $sql.= ", '".$this->db->escape($this->label)."'"; + $sql.= ", ".$conf->entity; + $sql.= ", '".$this->db->escape($this->account_number)."'"; $sql.= ", ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); $sql.= ", '".$this->db->escape($this->bank)."'"; - $sql.= ", '".$this->db->escape($this->code_banque)."'"; - $sql.= ", '".$this->db->escape($this->code_guichet)."'"; - $sql.= ", '".$this->db->escape($this->number)."'"; - $sql.= ", '".$this->db->escape($this->cle_rib)."'"; - $sql.= ", '".$this->db->escape($this->bic)."'"; - $sql.= ", '".$this->db->escape($this->iban)."'"; - $sql.= ", '".$this->db->escape($this->domiciliation)."'"; - $sql.= ", '".$this->db->escape($this->proprio)."'"; - $sql.= ", '".$this->db->escape($this->owner_address)."'"; - $sql.= ", '".$this->db->escape($this->currency_code)."'"; - $sql.= ", ".$this->rappro; - $sql.= ", ".price2num($this->min_allowed); - $sql.= ", ".price2num($this->min_desired); - $sql.= ", '".$this->db->escape($this->comment)."'"; - $sql.= ", ".($this->state_id>0?$this->state_id:"null"); - $sql.= ", ".$this->country_id; - $sql.= ")"; - - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account"); + $sql.= ", '".$this->db->escape($this->code_banque)."'"; + $sql.= ", '".$this->db->escape($this->code_guichet)."'"; + $sql.= ", '".$this->db->escape($this->number)."'"; + $sql.= ", '".$this->db->escape($this->cle_rib)."'"; + $sql.= ", '".$this->db->escape($this->bic)."'"; + $sql.= ", '".$this->db->escape($this->iban)."'"; + $sql.= ", '".$this->db->escape($this->domiciliation)."'"; + $sql.= ", '".$this->db->escape($this->proprio)."'"; + $sql.= ", '".$this->db->escape($this->owner_address)."'"; + $sql.= ", '".$this->db->escape($this->currency_code)."'"; + $sql.= ", ".$this->rappro; + $sql.= ", ".price2num($this->min_allowed); + $sql.= ", ".price2num($this->min_desired); + $sql.= ", '".$this->db->escape($this->comment)."'"; + $sql.= ", ".($this->state_id>0?$this->state_id:"null"); + $sql.= ", ".$this->country_id; + $sql.= ")"; + + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account"); - $result=$this->update($user, 1); - if ($result > 0) - { + $result=$this->update($user, 1); + if ($result > 0) + { $accline = new AccountLine($this->db); $accline->datec = $this->db->idate($now); $accline->label = '('.$langs->trans("InitialBankBalance").')'; @@ -613,455 +613,455 @@ class Account extends CommonObject if ($accline->insert() < 0) { $error++; - $this->error = $accline->error; - $this->errors = $accline->errors; + $this->error = $accline->error; + $this->errors = $accline->errors; } if (! $error) { - $result=$this->insertExtraFields(); - if ($result < 0) $error++; + $result=$this->insertExtraFields(); + if ($result < 0) $error++; } - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('BANKACCOUNT_CREATE',$user); - if ($result < 0) $error++; - // End call triggers - } - } - else - { - $error++; - } - } - else - { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $this->error=$langs->trans("ErrorBankLabelAlreadyExists"); - $error++; - } - else { - $this->error=$this->db->error()." sql=".$sql; - $error++; - } - } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('BANKACCOUNT_CREATE',$user); + if ($result < 0) $error++; + // End call triggers + } + } + else + { + $error++; + } + } + else + { + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $this->error=$langs->trans("ErrorBankLabelAlreadyExists"); + $error++; + } + else { + $this->error=$this->db->error()." sql=".$sql; + $error++; + } + } - if (! $error) - { - $this->db->commit(); - return $this->id; - } - else - { - $this->db->rollback(); - return -1*$error; - } - } + if (! $error) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1*$error; + } + } - /** - * Update bank account card - * - * @param User $user Object user making action - * @param int $notrigger 1=Disable triggers - * @return int <0 if KO, >0 if OK - */ - function update(User $user = null, $notrigger = 0) - { - global $langs,$conf, $hookmanager; + /** + * Update bank account card + * + * @param User $user Object user making action + * @param int $notrigger 1=Disable triggers + * @return int <0 if KO, >0 if OK + */ + function update(User $user = null, $notrigger = 0) + { + global $langs,$conf, $hookmanager; - $error=0; + $error=0; - $this->db->begin(); + $this->db->begin(); - // Clean parameters - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + // Clean parameters + $this->state_id = ($this->state_id?$this->state_id:$this->state_id); + $this->country_id = ($this->country_id?$this->country_id:$this->country_id); - // Check parameters - if (empty($this->country_id)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); - return -1; - } - if (empty($this->ref)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); - return -1; - } - if (! $this->label) $this->label = "???"; + // Check parameters + if (empty($this->country_id)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); + dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); + return -1; + } + if (empty($this->ref)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); + dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); + return -1; + } + if (! $this->label) $this->label = "???"; - $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; - $sql.= " ref = '".$this->db->escape($this->ref)."'"; - $sql.= ",label = '".$this->db->escape($this->label)."'"; + $sql.= " ref = '".$this->db->escape($this->ref)."'"; + $sql.= ",label = '".$this->db->escape($this->label)."'"; - $sql.= ",courant = ".$this->courant; - $sql.= ",clos = ".$this->clos; - $sql.= ",rappro = ".$this->rappro; - $sql.= ",url = ".($this->url?"'".$this->db->escape($this->url)."'":"null"); - $sql.= ",account_number = '".$this->db->escape($this->account_number)."'"; + $sql.= ",courant = ".$this->courant; + $sql.= ",clos = ".$this->clos; + $sql.= ",rappro = ".$this->rappro; + $sql.= ",url = ".($this->url?"'".$this->db->escape($this->url)."'":"null"); + $sql.= ",account_number = '".$this->db->escape($this->account_number)."'"; $sql.= ",fk_accountancy_journal = ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); $sql.= ",bank = '".$this->db->escape($this->bank)."'"; - $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; - $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; - $sql.= ",number='".$this->db->escape($this->number)."'"; - $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; - $sql.= ",bic='".$this->db->escape($this->bic)."'"; - $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; - $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; - $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; - $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; - - $sql.= ",currency_code = '".$this->db->escape($this->currency_code)."'"; - - $sql.= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null"); - $sql.= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null"); - $sql.= ",comment = '".$this->db->escape($this->comment)."'"; - - $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); - $sql.= ",fk_pays = ".$this->country_id; - - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - // Actions on extra fields (by external module or standard code) - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - if (! $error) - { - $result=$this->insertExtraFields(); - if ($result < 0) $error++; - } - } - - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('BANKACCOUNT_UPDATE',$user); - if ($result < 0) $error++; - // End call triggers - } - } - else - { - $error++; - $this->error=$this->db->lasterror(); - dol_print_error($this->db); - } + $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; + $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; + $sql.= ",number='".$this->db->escape($this->number)."'"; + $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; + $sql.= ",bic='".$this->db->escape($this->bic)."'"; + $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; + $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; + $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; + $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; + + $sql.= ",currency_code = '".$this->db->escape($this->currency_code)."'"; + + $sql.= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null"); + $sql.= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null"); + $sql.= ",comment = '".$this->db->escape($this->comment)."'"; + + $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); + $sql.= ",fk_pays = ".$this->country_id; + + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + // Actions on extra fields (by external module or standard code) + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + if (! $error) + { + $result=$this->insertExtraFields(); + if ($result < 0) $error++; + } + } + + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('BANKACCOUNT_UPDATE',$user); + if ($result < 0) $error++; + // End call triggers + } + } + else + { + $error++; + $this->error=$this->db->lasterror(); + dol_print_error($this->db); + } if (! $error) { - $this->db->commit(); - return $this->id; + $this->db->commit(); + return $this->id; } else { - $this->db->rollback(); - return -1*$error; + $this->db->rollback(); + return -1*$error; } - } - - - /** - * Update BBAN (RIB) account fields - * - * @param User $user Object user making update - * @return int <0 if KO, >0 if OK - */ - function update_bban(User $user = null) - { - global $conf,$langs; - - // Clean parameters - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + } - // Chargement librairie pour acces fonction controle RIB - require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; - dol_syslog(get_class($this)."::update_bban $this->code_banque,$this->code_guichet,$this->number,$this->cle_rib,$this->iban"); + /** + * Update BBAN (RIB) account fields + * + * @param User $user Object user making update + * @return int <0 if KO, >0 if OK + */ + function update_bban(User $user = null) + { + global $conf,$langs; - // Check parameters - if (! $this->ref) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->trans("Ref")); - return -2; - } + // Clean parameters + $this->state_id = ($this->state_id?$this->state_id:$this->state_id); + $this->country_id = ($this->country_id?$this->country_id:$this->country_id); - $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; - $sql.= " bank = '".$this->db->escape($this->bank)."'"; - $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; - $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; - $sql.= ",number='".$this->db->escape($this->number)."'"; - $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; - $sql.= ",bic='".$this->db->escape($this->bic)."'"; - $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; - $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; - $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; - $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; - $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); - $sql.= ",fk_pays = ".$this->country_id; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this)."::update_bban", LOG_DEBUG); - - $result = $this->db->query($sql); - if ($result) - { - return 1; - } - else - { - $this->error=$this->db->lasterror(); - dol_print_error($this->db); - return -1; - } - } + // Chargement librairie pour acces fonction controle RIB + require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; + dol_syslog(get_class($this)."::update_bban $this->code_banque,$this->code_guichet,$this->number,$this->cle_rib,$this->iban"); - /** - * Load a bank account into memory from database - * - * @param int $id Id of bank account to get - * @param string $ref Ref of bank account to get - * @return int <0 if KO, >0 if OK - */ - function fetch($id, $ref='') - { - global $conf; + // Check parameters + if (! $this->ref) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->trans("Ref")); + return -2; + } - if (empty($id) && empty($ref)) - { - $this->error="ErrorBadParameters"; - return -1; - } + $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; + $sql.= " bank = '".$this->db->escape($this->bank)."'"; + $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; + $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; + $sql.= ",number='".$this->db->escape($this->number)."'"; + $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; + $sql.= ",bic='".$this->db->escape($this->bic)."'"; + $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; + $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; + $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; + $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; + $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); + $sql.= ",fk_pays = ".$this->country_id; + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this)."::update_bban", LOG_DEBUG); + + $result = $this->db->query($sql); + if ($result) + { + return 1; + } + else + { + $this->error=$this->db->lasterror(); + dol_print_error($this->db); + return -1; + } + } - $sql = "SELECT ba.rowid, ba.ref, ba.label, ba.bank, ba.number, ba.courant, ba.clos, ba.rappro, ba.url,"; - $sql.= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,"; - $sql.= " ba.domiciliation, ba.proprio, ba.owner_address, ba.state_id, ba.fk_pays as country_id,"; - $sql.= " ba.account_number, ba.fk_accountancy_journal, ba.currency_code,"; - $sql.= " ba.min_allowed, ba.min_desired, ba.comment,"; - $sql.= " ba.datec as date_creation, ba.tms as date_update,"; - $sql.= ' c.code as country_code, c.label as country,'; - $sql.= ' d.code_departement as state_code, d.nom as state'; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid'; - $sql.= " WHERE entity IN (".getEntity($this->element, 1).")"; - if ($id) $sql.= " AND ba.rowid = ".$id; - if ($ref) $sql.= " AND ba.ref = '".$this->db->escape($ref)."'"; - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - - $this->id = $obj->rowid; - $this->rowid = $obj->rowid; - $this->ref = $obj->ref; - $this->label = $obj->label; - $this->type = $obj->courant; - $this->courant = $obj->courant; - $this->bank = $obj->bank; - $this->clos = $obj->clos; - $this->rappro = $obj->rappro; - $this->url = $obj->url; - - $this->code_banque = $obj->code_banque; - $this->code_guichet = $obj->code_guichet; - $this->number = $obj->number; - $this->cle_rib = $obj->cle_rib; - $this->bic = $obj->bic; - $this->iban = $obj->iban; - $this->domiciliation = $obj->domiciliation; - $this->proprio = $obj->proprio; - $this->owner_address = $obj->owner_address; - - $this->state_id = $obj->state_id; - $this->state_code = $obj->state_code; - $this->state = $obj->state; - - $this->country_id = $obj->country_id; - $this->country_code = $obj->country_code; - $this->country = $obj->country; - - $this->account_number = $obj->account_number; + + /** + * Load a bank account into memory from database + * + * @param int $id Id of bank account to get + * @param string $ref Ref of bank account to get + * @return int <0 if KO, >0 if OK + */ + function fetch($id, $ref='') + { + global $conf; + + if (empty($id) && empty($ref)) + { + $this->error="ErrorBadParameters"; + return -1; + } + + $sql = "SELECT ba.rowid, ba.ref, ba.label, ba.bank, ba.number, ba.courant, ba.clos, ba.rappro, ba.url,"; + $sql.= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,"; + $sql.= " ba.domiciliation, ba.proprio, ba.owner_address, ba.state_id, ba.fk_pays as country_id,"; + $sql.= " ba.account_number, ba.fk_accountancy_journal, ba.currency_code,"; + $sql.= " ba.min_allowed, ba.min_desired, ba.comment,"; + $sql.= " ba.datec as date_creation, ba.tms as date_update,"; + $sql.= ' c.code as country_code, c.label as country,'; + $sql.= ' d.code_departement as state_code, d.nom as state'; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid'; + $sql.= " WHERE entity IN (".getEntity($this->element, 1).")"; + if ($id) $sql.= " AND ba.rowid = ".$id; + if ($ref) $sql.= " AND ba.ref = '".$this->db->escape($ref)."'"; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + + $this->id = $obj->rowid; + $this->rowid = $obj->rowid; + $this->ref = $obj->ref; + $this->label = $obj->label; + $this->type = $obj->courant; + $this->courant = $obj->courant; + $this->bank = $obj->bank; + $this->clos = $obj->clos; + $this->rappro = $obj->rappro; + $this->url = $obj->url; + + $this->code_banque = $obj->code_banque; + $this->code_guichet = $obj->code_guichet; + $this->number = $obj->number; + $this->cle_rib = $obj->cle_rib; + $this->bic = $obj->bic; + $this->iban = $obj->iban; + $this->domiciliation = $obj->domiciliation; + $this->proprio = $obj->proprio; + $this->owner_address = $obj->owner_address; + + $this->state_id = $obj->state_id; + $this->state_code = $obj->state_code; + $this->state = $obj->state; + + $this->country_id = $obj->country_id; + $this->country_code = $obj->country_code; + $this->country = $obj->country; + + $this->account_number = $obj->account_number; $this->fk_accountancy_journal = $obj->fk_accountancy_journal; - $this->currency_code = $obj->currency_code; - $this->account_currency_code = $obj->currency_code; - $this->min_allowed = $obj->min_allowed; - $this->min_desired = $obj->min_desired; - $this->comment = $obj->comment; - - $this->date_creation = $this->db->jdate($obj->date_creation); - $this->date_update = $this->db->jdate($obj->date_update); - - // Retreive all extrafield for thirdparty - // fetch optionals attributes and labels - require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); - - return 1; - } - else + $this->currency_code = $obj->currency_code; + $this->account_currency_code = $obj->currency_code; + $this->min_allowed = $obj->min_allowed; + $this->min_desired = $obj->min_desired; + $this->comment = $obj->comment; + + $this->date_creation = $this->db->jdate($obj->date_creation); + $this->date_update = $this->db->jdate($obj->date_update); + + // Retreive all extrafield for thirdparty + // fetch optionals attributes and labels + require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); + $extrafields=new ExtraFields($this->db); + $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); + $this->fetch_optionals($this->id,$extralabels); + + return 1; + } + else { - return 0; - } - } - else - { - $this->error=$this->db->lasterror; - $this->errors[]=$this->error; - return -1; - } - } - - /** - * Sets object to supplied categories. - * - * Deletes object from existing categories not supplied. - * Adds it to non existing supplied categories. - * Existing categories are left untouch. - * - * @param int[]|int $categories Category or categories IDs - */ - public function setCategories($categories) { - // Handle single category - if (! is_array($categories)) { - $categories = array($categories); - } + return 0; + } + } + else + { + $this->error=$this->db->lasterror; + $this->errors[]=$this->error; + return -1; + } + } - // Get current categories - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $c = new Categorie($this->db); - $existing = $c->containing($this->id, Categorie::TYPE_ACCOUNT, 'id'); - - // Diff - if (is_array($existing)) { - $to_del = array_diff($existing, $categories); - $to_add = array_diff($categories, $existing); - } else { - $to_del = array(); // Nothing to delete - $to_add = $categories; - } + /** + * Sets object to supplied categories. + * + * Deletes object from existing categories not supplied. + * Adds it to non existing supplied categories. + * Existing categories are left untouch. + * + * @param int[]|int $categories Category or categories IDs + */ + public function setCategories($categories) { + // Handle single category + if (! is_array($categories)) { + $categories = array($categories); + } - // Process - foreach($to_del as $del) { - if ($c->fetch($del) > 0) { - $c->del_type($this, 'account'); - } - } - foreach ($to_add as $add) { - if ($c->fetch($add) > 0) { - $c->add_type($this, 'account'); - } - } + // Get current categories + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $c = new Categorie($this->db); + $existing = $c->containing($this->id, Categorie::TYPE_ACCOUNT, 'id'); - return; - } + // Diff + if (is_array($existing)) { + $to_del = array_diff($existing, $categories); + $to_add = array_diff($categories, $existing); + } else { + $to_del = array(); // Nothing to delete + $to_add = $categories; + } - /** - * Delete bank account from database - * - * @param User $user User deleting - * @return int <0 if KO, >0 if OK - */ - function delete(User $user = null) - { - global $conf; + // Process + foreach($to_del as $del) { + if ($c->fetch($del) > 0) { + $c->del_type($this, 'account'); + } + } + foreach ($to_add as $add) { + if ($c->fetch($add) > 0) { + $c->add_type($this, 'account'); + } + } - $error=0; + return; + } - $this->db->begin(); + /** + * Delete bank account from database + * + * @param User $user User deleting + * @return int <0 if KO, >0 if OK + */ + function delete(User $user = null) + { + global $conf; - // Delete link between tag and bank account - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_account"; - $sql.= " WHERE fk_account = ".$this->id; - - $resql = $this->db->query($sql); - if (!$resql) - { - $error++; - $this->error = "Error ".$this->db->lasterror(); - } - } + $error=0; - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_account"; - $sql.= " WHERE rowid = ".$this->rowid; - - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - // Remove extrafields - if ((empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used - { - $result=$this->deleteExtraFields(); - if ($result < 0) - { - $error++; - dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); - } - } - } - else - { - $error++; - $this->error = "Error ".$this->db->lasterror(); - } - } + $this->db->begin(); - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } + // Delete link between tag and bank account + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_account"; + $sql.= " WHERE fk_account = ".$this->id; + + $resql = $this->db->query($sql); + if (!$resql) + { + $error++; + $this->error = "Error ".$this->db->lasterror(); + } + } + + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_account"; + $sql.= " WHERE rowid = ".$this->rowid; + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + // Remove extrafields + if ((empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + { + $result=$this->deleteExtraFields(); + if ($result < 0) + { + $error++; + dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); + } + } + } + else + { + $error++; + $this->error = "Error ".$this->db->lasterror(); + } + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } - /** + /** * Return label of object status - * + * * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto - * @return string Label - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->clos,$mode); - } - - /** - * Return label of given object status - * - * @param int $statut Id statut + * @return string Label + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->clos,$mode); + } + + /** + * Return label of given object status + * + * @param int $statut Id statut * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto - * @return string Label - */ + * @return string Label + */ function LibStatut($statut, $mode = 0) { global $langs; @@ -1084,7 +1084,7 @@ class Account extends CommonObject } elseif ($mode == 5) { return $label.' '.$picto; } elseif ($mode == 6) { - return $label.' '.$picto; + return $label.' '.$picto; } //There is no short mode for this label @@ -1092,394 +1092,394 @@ class Account extends CommonObject } - /** - * Renvoi si un compte peut etre supprimer ou non (sans mouvements) - * - * @return boolean vrai si peut etre supprime, faux sinon - */ - function can_be_deleted() - { - $can_be_deleted=false; + /** + * Renvoi si un compte peut etre supprimer ou non (sans mouvements) + * + * @return boolean vrai si peut etre supprime, faux sinon + */ + function can_be_deleted() + { + $can_be_deleted=false; - $sql = "SELECT COUNT(rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account=".$this->id; + $sql = "SELECT COUNT(rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank"; + $sql.= " WHERE fk_account=".$this->id; - $resql = $this->db->query($sql); - if ($resql) { - $obj=$this->db->fetch_object($resql); - if ($obj->nb <= 1) $can_be_deleted=true; // Juste le solde - } - else { - dol_print_error($this->db); - } - return $can_be_deleted; - } - - - /** - * Return error - * - * @return string Error string - */ - function error() - { - return $this->error; - } - - /** - * Return current sold - * - * @param int $option 1=Exclude future operation date (this is to exclude input made in advance and have real account sold) - * @return int Current sold (value date <= today) - */ - function solde($option=0) - { - $sql = "SELECT sum(amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account = ".$this->id; - if ($option == 1) $sql.= " AND dateo <= '".$this->db->idate(dol_now())."'"; - - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj=$this->db->fetch_object($resql); - $solde = $obj->amount; - } - $this->db->free($resql); - return $solde; - } - } - - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Objet user - * @param int $filteraccountid To get info for a particular account id - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - function load_board(User $user, $filteraccountid = 0) - { - global $conf, $langs; - - if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe - - $sql = "SELECT b.rowid, b.datev as datefin"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; - $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.rappro=0"; - $sql.= " AND b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable - $sql.= " AND clos = 0"; - if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid; - - $resql=$this->db->query($sql); - if ($resql) - { - $langs->load("banks"); - $now=dol_now(); - - require_once DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php'; - - $response = new WorkboardResponse(); - $response->warning_delay=$conf->bank->rappro->warning_delay/60/60/24; - $response->label=$langs->trans("TransactionsToConciliate"); - $response->url=DOL_URL_ROOT.'/compta/bank/list.php?leftmenu=bank&mainmenu=bank'; - $response->img=img_object('',"payment"); - - while ($obj=$this->db->fetch_object($resql)) - { - $response->nbtodo++; - if ($this->db->jdate($obj->datefin) < ($now - $conf->bank->rappro->warning_delay)) { - $response->nbtodolate++; - } - } - - return $response; - } - else - { - dol_print_error($this->db); - $this->error=$this->db->error(); - return -1; - } - } - - /** - * Charge indicateurs this->nb de tableau de bord - * @param int $filteraccountid To get info for a particular account id - * @return int <0 if ko, >0 if ok - */ - function load_state_board($filteraccountid = 0) - { - global $user; - - if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe - - $sql = "SELECT count(b.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; - $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable - $sql.= " AND clos = 0"; - if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid; - - $resql=$this->db->query($sql); - if ($resql) - { - while ($obj=$this->db->fetch_object($resql)) - { - $this->nb["banklines"]=$obj->nb; - } - $this->db->free($resql); - return 1; - } - else - { - dol_print_error($this->db); - $this->error=$this->db->error(); - return -1; - } - } - - - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @return int Nb of account we can reconciliate - */ - public static function countAccountToReconcile() - { - global $db, $conf, $user; - - //Protection against external users - if ($user->societe_id) { - return 0; - } + $resql = $this->db->query($sql); + if ($resql) { + $obj=$this->db->fetch_object($resql); + if ($obj->nb <= 1) $can_be_deleted=true; // Juste le solde + } + else { + dol_print_error($this->db); + } + return $can_be_deleted; + } - $nb=0; - $sql = "SELECT COUNT(ba.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE ba.rappro > 0 and ba.clos = 0"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql.= " AND ba.courant != 2"; - $resql=$db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $nb = $obj->nb; - } - else dol_print_error($db); - - return $nb; - } - - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto Include picto into link - * @param string $mode ''=Link to card, 'transactions'=Link to transactions card - * @param string $option ''=Show ref, 'reflabel'=Show ref+label - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string Chaine avec URL - */ - function getNomUrl($withpicto=0, $mode='', $option='', $save_lastsearch_value=-1) - { - global $conf, $langs; - - $result=''; - $label = '<u>' . $langs->trans("ShowAccount") . '</u>'; - $label .= '<br><b>' . $langs->trans('BankAccount') . ':</b> ' . $this->label; - $label .= '<br><b>' . $langs->trans('AccountNumber') . ':</b> ' . $this->number; - $label .= '<br><b>' . $langs->trans("AccountCurrency") . ':</b> ' . $this->currency_code; - if (! empty($conf->accounting->enabled)) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; - $langs->load("accountancy"); - $label .= '<br><b>' . $langs->trans('AccountAccounting') . ':</b> ' . length_accountg($this->account_number); - $label .= '<br><b>' . $langs->trans('AccountancyJournal') . ':</b> ' . $this->accountancy_journal; - } - $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; + /** + * Return error + * + * @return string Error string + */ + function error() + { + return $this->error; + } - $url = DOL_URL_ROOT.'/compta/bank/card.php?id='.$this->id; - if ($mode == 'transactions') - { - $url = DOL_URL_ROOT.'/compta/bank/bankentries_list.php?id='.$this->id; - } - else if ($mode == 'receipts') - { - $url = DOL_URL_ROOT.'/compta/bank/releve.php?account='.$this->id; - } + /** + * Return current sold + * + * @param int $option 1=Exclude future operation date (this is to exclude input made in advance and have real account sold) + * @return int Current sold (value date <= today) + */ + function solde($option=0) + { + $sql = "SELECT sum(amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank"; + $sql.= " WHERE fk_account = ".$this->id; + if ($option == 1) $sql.= " AND dateo <= '".$this->db->idate(dol_now())."'"; - if ($option != 'nolink') - { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; - if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; - } + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj=$this->db->fetch_object($resql); + $solde = $obj->amount; + } + $this->db->free($resql); + return $solde; + } + } - $link = '<a href="'.$url.$linkclose; - $linkend='</a>'; + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Objet user + * @param int $filteraccountid To get info for a particular account id + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + function load_board(User $user, $filteraccountid = 0) + { + global $conf, $langs; + + if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe + + $sql = "SELECT b.rowid, b.datev as datefin"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; + $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.rappro=0"; + $sql.= " AND b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable + $sql.= " AND clos = 0"; + if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid; + + $resql=$this->db->query($sql); + if ($resql) + { + $langs->load("banks"); + $now=dol_now(); - if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' '); - $result.=$link.$this->ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : '').$linkend; - return $result; - } + require_once DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php'; + $response = new WorkboardResponse(); + $response->warning_delay=$conf->bank->rappro->warning_delay/60/60/24; + $response->label=$langs->trans("TransactionsToConciliate"); + $response->url=DOL_URL_ROOT.'/compta/bank/list.php?leftmenu=bank&mainmenu=bank'; + $response->img=img_object('',"payment"); + + while ($obj=$this->db->fetch_object($resql)) + { + $response->nbtodo++; + if ($this->db->jdate($obj->datefin) < ($now - $conf->bank->rappro->warning_delay)) { + $response->nbtodolate++; + } + } + + return $response; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } - // Method after here are common to Account and CompanyBankAccount + /** + * Charge indicateurs this->nb de tableau de bord + * @param int $filteraccountid To get info for a particular account id + * @return int <0 if ko, >0 if ok + */ + function load_state_board($filteraccountid = 0) + { + global $user; + if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe - /** - * Return if an account has valid information for Direct debit payment - * - * @return int 1 if correct, <=0 if wrong - */ - function verif() - { - require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php'; + $sql = "SELECT count(b.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; + $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable + $sql.= " AND clos = 0"; + if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid; - $this->error_number = 0; + $resql=$this->db->query($sql); + if ($resql) + { + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["banklines"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } - // Call function to check BAN - if (! checkIbanForAccount($this) || ! checkSwiftForAccount($this)) - { - $this->error_number = 12; - $this->error_message = 'IBANSWIFTControlError'; - } - /*if (! checkBanForAccount($this)) + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @return int Nb of account we can reconciliate + */ + public static function countAccountToReconcile() + { + global $db, $conf, $user; + + //Protection against external users + if ($user->societe_id) { + return 0; + } + + $nb=0; + + $sql = "SELECT COUNT(ba.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE ba.rappro > 0 and ba.clos = 0"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql.= " AND ba.courant != 2"; + $resql=$db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $nb = $obj->nb; + } + else dol_print_error($db); + + return $nb; + } + + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto Include picto into link + * @param string $mode ''=Link to card, 'transactions'=Link to transactions card + * @param string $option ''=Show ref, 'reflabel'=Show ref+label + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine avec URL + */ + function getNomUrl($withpicto=0, $mode='', $option='', $save_lastsearch_value=-1) + { + global $conf, $langs; + + $result=''; + $label = '<u>' . $langs->trans("ShowAccount") . '</u>'; + $label .= '<br><b>' . $langs->trans('BankAccount') . ':</b> ' . $this->label; + $label .= '<br><b>' . $langs->trans('AccountNumber') . ':</b> ' . $this->number; + $label .= '<br><b>' . $langs->trans("AccountCurrency") . ':</b> ' . $this->currency_code; + if (! empty($conf->accounting->enabled)) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; + $langs->load("accountancy"); + $label .= '<br><b>' . $langs->trans('AccountAccounting') . ':</b> ' . length_accountg($this->account_number); + $label .= '<br><b>' . $langs->trans('AccountancyJournal') . ':</b> ' . $this->accountancy_journal; + } + $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; + + $url = DOL_URL_ROOT.'/compta/bank/card.php?id='.$this->id; + if ($mode == 'transactions') + { + $url = DOL_URL_ROOT.'/compta/bank/bankentries_list.php?id='.$this->id; + } + else if ($mode == 'receipts') + { + $url = DOL_URL_ROOT.'/compta/bank/releve.php?account='.$this->id; + } + + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + + $link = '<a href="'.$url.$linkclose; + $linkend='</a>'; + + if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' '); + $result.=$link.$this->ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : '').$linkend; + return $result; + } + + + // Method after here are common to Account and CompanyBankAccount + + + /** + * Return if an account has valid information for Direct debit payment + * + * @return int 1 if correct, <=0 if wrong + */ + function verif() + { + require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php'; + + $this->error_number = 0; + + // Call function to check BAN + + if (! checkIbanForAccount($this) || ! checkSwiftForAccount($this)) + { + $this->error_number = 12; + $this->error_message = 'IBANSWIFTControlError'; + } + /*if (! checkBanForAccount($this)) { $this->error_number = 12; $this->error_message = 'BANControlError'; }*/ - if ($this->error_number == 0) - { - return 1; - } - else - { - return 0; - } - } - - /** - * Return account country code - * - * @return string country code - */ - function getCountryCode() - { - global $mysoc; - - // We return country code of bank account - if (! empty($this->country_code)) return $this->country_code; - - // For backward compatibility, we try to guess country from other information - if (! empty($this->iban)) - { - // If IBAN defined, we can know country of account from it - if (preg_match("/^([a-zA-Z][a-zA-Z])/i",$this->iban,$reg)) return $reg[1]; - } + if ($this->error_number == 0) + { + return 1; + } + else + { + return 0; + } + } - // If this class is linked to a third party - if (! empty($this->socid)) - { - require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; - $company=new Societe($this->db); - $result=$company->fetch($this->socid); - if (! empty($company->country_code)) return $company->country_code; - } + /** + * Return account country code + * + * @return string country code + */ + function getCountryCode() + { + global $mysoc; + + // We return country code of bank account + if (! empty($this->country_code)) return $this->country_code; + + // For backward compatibility, we try to guess country from other information + if (! empty($this->iban)) + { + // If IBAN defined, we can know country of account from it + if (preg_match("/^([a-zA-Z][a-zA-Z])/i",$this->iban,$reg)) return $reg[1]; + } + + // If this class is linked to a third party + if (! empty($this->socid)) + { + require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; + $company=new Societe($this->db); + $result=$company->fetch($this->socid); + if (! empty($company->country_code)) return $company->country_code; + } + + // We return country code of managed company + if (! empty($mysoc->country_code)) return $mysoc->country_code; + + return ''; + } + + /** + * Return if a bank account is defined with detailed information (bank code, desk code, number and key). + * More information on codes used by countries on page http://en.wikipedia.org/wiki/Bank_code + * + * @return int 0=No bank code need + Account number is enough + * 1=Need 2 fields for bank code: Bank, Desk (France, Spain, ...) + Account number and key + * 2=Need 1 field for bank code: Bank only (Sort code for Great Britain, BSB for Australia) + Account number + */ + function useDetailedBBAN() + { + $country_code=$this->getCountryCode(); + + if (in_array($country_code,array('CH','FR','ES','GA','IT','NC'))) return 1; // France, Spain, Gabon, ... + if (in_array($country_code,array('AU','BE','CA','DE','DK','GR','GB','ID','IE','IR','KR','NL','NZ','UK','US'))) return 2; // Australia, England... + return 0; + } + + /** + * Return 1 if IBAN / BIC is mandatory (otherwise option) + * + * @return int 1 = mandatory / 0 = Not mandatory + */ + function needIBAN() + { + $country_code=$this->getCountryCode(); + + $country_code_in_EEC=array( + 'AT', // Austria + 'BE', // Belgium + 'BG', // Bulgaria + 'CY', // Cyprus + 'CZ', // Czech republic + 'DE', // Germany + 'DK', // Danemark + 'EE', // Estonia + 'ES', // Spain + 'FI', // Finland + 'FR', // France + 'GB', // United Kingdom + 'GR', // Greece + 'HR', // Croatia + 'NL', // Holland + 'HU', // Hungary + 'IE', // Ireland + 'IM', // Isle of Man - Included in UK + 'IT', // Italy + 'LT', // Lithuania + 'LU', // Luxembourg + 'LV', // Latvia + 'MC', // Monaco - Included in France + 'MT', // Malta + //'NO', // Norway + 'PL', // Poland + 'PT', // Portugal + 'RO', // Romania + 'SE', // Sweden + 'SK', // Slovakia + 'SI', // Slovenia + 'UK', // United Kingdom + //'CH', // Switzerland - No. Swizerland in not in EEC + ); - // We return country code of managed company - if (! empty($mysoc->country_code)) return $mysoc->country_code; - - return ''; - } - - /** - * Return if a bank account is defined with detailed information (bank code, desk code, number and key). - * More information on codes used by countries on page http://en.wikipedia.org/wiki/Bank_code - * - * @return int 0=No bank code need + Account number is enough - * 1=Need 2 fields for bank code: Bank, Desk (France, Spain, ...) + Account number and key - * 2=Need 1 field for bank code: Bank only (Sort code for Great Britain, BSB for Australia) + Account number - */ - function useDetailedBBAN() - { - $country_code=$this->getCountryCode(); - - if (in_array($country_code,array('CH','FR','ES','GA','IT','NC'))) return 1; // France, Spain, Gabon, ... - if (in_array($country_code,array('AU','BE','CA','DE','DK','GR','GB','ID','IE','IR','KR','NL','NZ','UK','US'))) return 2; // Australia, England... - return 0; - } - - /** - * Return 1 if IBAN / BIC is mandatory (otherwise option) - * - * @return int 1 = mandatory / 0 = Not mandatory - */ - function needIBAN() - { - $country_code=$this->getCountryCode(); - - $country_code_in_EEC=array( - 'AT', // Austria - 'BE', // Belgium - 'BG', // Bulgaria - 'CY', // Cyprus - 'CZ', // Czech republic - 'DE', // Germany - 'DK', // Danemark - 'EE', // Estonia - 'ES', // Spain - 'FI', // Finland - 'FR', // France - 'GB', // United Kingdom - 'GR', // Greece - 'HR', // Croatia - 'NL', // Holland - 'HU', // Hungary - 'IE', // Ireland - 'IM', // Isle of Man - Included in UK - 'IT', // Italy - 'LT', // Lithuania - 'LU', // Luxembourg - 'LV', // Latvia - 'MC', // Monaco - Included in France - 'MT', // Malta - //'NO', // Norway - 'PL', // Poland - 'PT', // Portugal - 'RO', // Romania - 'SE', // Sweden - 'SK', // Slovakia - 'SI', // Slovenia - 'UK', // United Kingdom - //'CH', // Switzerland - No. Swizerland in not in EEC - ); - - if (in_array($country_code,$country_code_in_EEC)) return 1; // France, Spain, ... - return 0; - } - - /** - * Load miscellaneous information for tab "Info" - * - * @param int $id Id of object to load - * @return void - */ - function info($id) - { - - } + if (in_array($country_code,$country_code_in_EEC)) return 1; // France, Spain, ... + return 0; + } + + /** + * Load miscellaneous information for tab "Info" + * + * @param int $id Id of object to load + * @return void + */ + function info($id) + { + + } /** * Returns the fields in order that this bank account should show to the user @@ -1571,157 +1571,157 @@ class Account extends CommonObject } - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - function initAsSpecimen() - { - $this->specimen = 1; - $this->ref = 'MBA'; - $this->label = 'My Big Company Bank account'; - $this->bank = 'MyBank'; - $this->courant = Account::TYPE_CURRENT; - $this->clos = Account::STATUS_OPEN; - $this->code_banque = '123'; - $this->code_guichet = '456'; - $this->number = 'ABC12345'; - $this->cle_rib = 50; - $this->bic = 'AA12'; - $this->iban = 'FR999999999'; - $this->domiciliation = 'My bank address'; - $this->proprio = 'Owner'; - $this->owner_address = 'Owner address'; - $this->country_id = 1; - } + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + $this->specimen = 1; + $this->ref = 'MBA'; + $this->label = 'My Big Company Bank account'; + $this->bank = 'MyBank'; + $this->courant = Account::TYPE_CURRENT; + $this->clos = Account::STATUS_OPEN; + $this->code_banque = '123'; + $this->code_guichet = '456'; + $this->number = 'ABC12345'; + $this->cle_rib = 50; + $this->bic = 'AA12'; + $this->iban = 'FR999999999'; + $this->domiciliation = 'My bank address'; + $this->proprio = 'Owner'; + $this->owner_address = 'Owner address'; + $this->country_id = 1; + } + +} + + +/** + * Class to manage bank transaction lines + */ +class AccountLine extends CommonObject +{ + var $error; + var $db; + var $element='bank'; + var $table_element='bank'; + var $picto = 'generic'; + + var $id; + var $ref; + var $datec; + var $dateo; + + /** + * Value date + */ + var $datev; + var $amount; + var $label; + var $note; + var $fk_user_author; + var $fk_user_rappro; + var $fk_type; + var $rappro; // Is it conciliated + var $num_releve; // If conciliated, what is bank statement + var $num_chq; // Num of cheque + var $bank_chq; // Bank of cheque + var $fk_bordereau; // Id of cheque receipt + + var $fk_account; // Id of bank account + var $bank_account_label; // Label of bank account + + public $emetteur; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct(DoliDB $db) + { + $this->db = $db; + } + + /** + * Load into memory content of a bank transaction line + * + * @param int $rowid Id of bank transaction to load + * @param string $ref Ref of bank transaction to load + * @param string $num External num to load (ex: num of transaction for paypal fee) + * @return int <0 if KO, 0 if OK but not found, >0 if OK and found + */ + function fetch($rowid,$ref='',$num='') + { + global $conf; + + // Check parameters + if (empty($rowid) && empty($ref) && empty($num)) return -1; + + $sql = "SELECT b.rowid, b.datec, b.datev, b.dateo, b.amount, b.label as label, b.fk_account,"; + $sql.= " b.fk_user_author, b.fk_user_rappro,"; + $sql.= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,"; + $sql.= " b.fk_bordereau, b.banque, b.emetteur,"; + //$sql.= " b.author"; // Is this used ? + $sql.= " ba.ref as bank_account_ref, ba.label as bank_account_label"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; + $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + if ($num) $sql.= " AND b.num_chq='".$this->db->escape($num)."'"; + else if ($ref) $sql.= " AND b.rowid='".$this->db->escape($ref)."'"; + else $sql.= " AND b.rowid=".$rowid; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $ret=0; -} + $obj = $this->db->fetch_object($result); + if ($obj) + { + $this->id = $obj->rowid; + $this->rowid = $obj->rowid; + $this->ref = $obj->rowid; + $this->datec = $obj->datec; + $this->datev = $obj->datev; + $this->dateo = $obj->dateo; + $this->amount = $obj->amount; + $this->label = $obj->label; + $this->note = $obj->note; -/** - * Class to manage bank transaction lines - */ -class AccountLine extends CommonObject -{ - var $error; - var $db; - var $element='bank'; - var $table_element='bank'; - var $picto = 'generic'; - - var $id; - var $ref; - var $datec; - var $dateo; - - /** - * Value date - */ - var $datev; - var $amount; - var $label; - var $note; - var $fk_user_author; - var $fk_user_rappro; - var $fk_type; - var $rappro; // Is it conciliated - var $num_releve; // If conciliated, what is bank statement - var $num_chq; // Num of cheque - var $bank_chq; // Bank of cheque - var $fk_bordereau; // Id of cheque receipt - - var $fk_account; // Id of bank account - var $bank_account_label; // Label of bank account - - public $emetteur; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct(DoliDB $db) - { - $this->db = $db; - } - - /** - * Load into memory content of a bank transaction line - * - * @param int $rowid Id of bank transaction to load - * @param string $ref Ref of bank transaction to load - * @param string $num External num to load (ex: num of transaction for paypal fee) - * @return int <0 if KO, 0 if OK but not found, >0 if OK and found - */ - function fetch($rowid,$ref='',$num='') - { - global $conf; - - // Check parameters - if (empty($rowid) && empty($ref) && empty($num)) return -1; - - $sql = "SELECT b.rowid, b.datec, b.datev, b.dateo, b.amount, b.label as label, b.fk_account,"; - $sql.= " b.fk_user_author, b.fk_user_rappro,"; - $sql.= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,"; - $sql.= " b.fk_bordereau, b.banque, b.emetteur,"; - //$sql.= " b.author"; // Is this used ? - $sql.= " ba.ref as bank_account_ref, ba.label as bank_account_label"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; - $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - if ($num) $sql.= " AND b.num_chq='".$this->db->escape($num)."'"; - else if ($ref) $sql.= " AND b.rowid='".$this->db->escape($ref)."'"; - else $sql.= " AND b.rowid=".$rowid; - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $ret=0; - - $obj = $this->db->fetch_object($result); - if ($obj) - { - $this->id = $obj->rowid; - $this->rowid = $obj->rowid; - $this->ref = $obj->rowid; - - $this->datec = $obj->datec; - $this->datev = $obj->datev; - $this->dateo = $obj->dateo; - $this->amount = $obj->amount; - $this->label = $obj->label; - $this->note = $obj->note; - - $this->fk_user_author = $obj->fk_user_author; - $this->fk_user_rappro = $obj->fk_user_rappro; - - $this->fk_type = $obj->fk_type; // Type of transaction - $this->rappro = $obj->rappro; - $this->num_releve = $obj->num_releve; - - $this->num_chq = $obj->num_chq; - $this->bank_chq = $obj->banque; - $this->fk_bordereau = $obj->fk_bordereau; - - $this->fk_account = $obj->fk_account; - $this->bank_account_ref = $obj->bank_account_ref; - $this->bank_account_label = $obj->bank_account_label; - - $ret=1; - } - $this->db->free($result); - return $ret; - } - else - { - return -1; - } - } + $this->fk_user_author = $obj->fk_user_author; + $this->fk_user_rappro = $obj->fk_user_rappro; + + $this->fk_type = $obj->fk_type; // Type of transaction + $this->rappro = $obj->rappro; + $this->num_releve = $obj->num_releve; + + $this->num_chq = $obj->num_chq; + $this->bank_chq = $obj->banque; + $this->fk_bordereau = $obj->fk_bordereau; + + $this->fk_account = $obj->fk_account; + $this->bank_account_ref = $obj->bank_account_ref; + $this->bank_account_label = $obj->bank_account_label; + + $ret=1; + } + $this->db->free($result); + return $ret; + } + else + { + return -1; + } + } /** * Inserts a transaction to a bank account @@ -1772,420 +1772,420 @@ class AccountLine extends CommonObject return $this->id; } - /** - * Delete transaction bank line record - * - * @param User $user User object that delete - * @return int <0 if KO, >0 if OK - */ - function delete(User $user = null) - { - $nbko=0; - - if ($this->rappro) - { - // Protection to avoid any delete of consolidated lines - $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; - return -1; - } + /** + * Delete transaction bank line record + * + * @param User $user User object that delete + * @return int <0 if KO, >0 if OK + */ + function delete(User $user = null) + { + $nbko=0; - $this->db->begin(); + if ($this->rappro) + { + // Protection to avoid any delete of consolidated lines + $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; + return -1; + } - // Delete urls - $result=$this->delete_urls($user); - if ($result < 0) - { - $nbko++; - } + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid=".(int) $this->rowid; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $result = $this->db->query($sql); - if (! $result) $nbko++; + // Delete urls + $result=$this->delete_urls($user); + if ($result < 0) + { + $nbko++; + } - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE rowid=".(int) $this->rowid; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $result = $this->db->query($sql); - if (! $result) $nbko++; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid=".(int) $this->rowid; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) $nbko++; - if (! $nbko) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -$nbko; - } - } + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE rowid=".(int) $this->rowid; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) $nbko++; + + if (! $nbko) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -$nbko; + } + } - /** - * Delete bank line records - * - * @param User $user User object that delete - * @return int <0 if KO, >0 if OK - */ - function delete_urls(User $user = null) - { - $nbko=0; + /** + * Delete bank line records + * + * @param User $user User object that delete + * @return int <0 if KO, >0 if OK + */ + function delete_urls(User $user = null) + { + $nbko=0; - if ($this->rappro) - { - // Protection to avoid any delete of consolidated lines - $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; - return -1; - } + if ($this->rappro) + { + // Protection to avoid any delete of consolidated lines + $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; + return -1; + } - $this->db->begin(); + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank=".(int) $this->rowid; - dol_syslog(get_class($this)."::delete_urls", LOG_DEBUG); - $result = $this->db->query($sql); - if (! $result) $nbko++; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank=".(int) $this->rowid; + dol_syslog(get_class($this)."::delete_urls", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) $nbko++; - if (! $nbko) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -$nbko; - } - } - - - /** - * Update bank account record in database - * - * @param User $user Object user making update - * @param int $notrigger 0=Disable all triggers - * @return int <0 if KO, >0 if OK - */ - function update(User $user, $notrigger = 0) - { - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " amount = ".price2num($this->amount).","; - $sql.= " datev='".$this->db->idate($this->datev)."',"; - $sql.= " dateo='".$this->db->idate($this->dateo)."'"; - $sql.= " WHERE rowid = ".$this->rowid; - - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - $this->error=$this->db->error(); - return -1; - } - } + if (! $nbko) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -$nbko; + } + } - /** - * Update conciliation field - * - * @param User $user Objet user making update - * @param int $cat Category id - * @return int <0 if KO, >0 if OK - */ - function update_conciliation(User $user, $cat) - { - global $conf; + /** + * Update bank account record in database + * + * @param User $user Object user making update + * @param int $notrigger 0=Disable all triggers + * @return int <0 if KO, >0 if OK + */ + function update(User $user, $notrigger = 0) + { + $this->db->begin(); - $this->db->begin(); + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " amount = ".price2num($this->amount).","; + $sql.= " datev='".$this->db->idate($this->datev)."',"; + $sql.= " dateo='".$this->db->idate($this->dateo)."'"; + $sql.= " WHERE rowid = ".$this->rowid; - // Check statement field - if (! empty($conf->global->BANK_STATEMENT_REGEX_RULE)) - { - if (! preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve)) - { - $this->errors[]=$langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE); - return -1; - } - } + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + $this->error=$this->db->error(); + return -1; + } + } - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " rappro = 1"; - $sql.= ", num_releve = '".$this->db->escape($this->num_releve)."'"; - $sql.= ", fk_user_rappro = ".$user->id; - $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (! empty($cat)) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class ("; - $sql.= "lineid"; - $sql.= ", fk_categ"; - $sql.= ") VALUES ("; - $sql.= $this->id; - $sql.= ", ".$cat; - $sql.= ")"; - - dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); - $this->db->query($sql); - - // No error check. Can fail if category already affected - } - - $this->rappro=1; - - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } - - - /** - * Increase/decrease value date of a rowid - * - * @param int $rowid Id of line - * @param int $sign 1 or -1 - * @return int >0 if OK, 0 if KO - */ - function datev_change($rowid,$sign=1) - { - $sql = "SELECT datev FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; - $resql = $this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - $newdate=$this->db->jdate($obj->datev)+(3600*24*$sign); - - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " datev = '".$this->db->idate($newdate)."'"; - $sql.= " WHERE rowid = ".$rowid; - - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->affected_rows($result)) - { - return 1; - } - } - else - { - dol_print_error($this->db); - return 0; - } - } - else dol_print_error($this->db); - return 0; - } - - /** - * Increase value date of a rowid - * - * @param int $id Id of line to change - * @return int >0 if OK, 0 if KO - */ - function datev_next($id) - { - return $this->datev_change($id,1); - } - - /** - * Decrease value date of a rowid - * - * @param int $id Id of line to change - * @return int >0 if OK, 0 if KO - */ - function datev_previous($id) - { - return $this->datev_change($id,-1); - } - - - /** - * Increase/decrease operation date of a rowid - * - * @param int $rowid Id of line - * @param int $sign 1 or -1 - * @return int >0 if OK, 0 if KO - */ - function dateo_change($rowid,$sign=1) - { - $sql = "SELECT dateo FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; - $resql = $this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - $newdate=$this->db->jdate($obj->dateo)+(3600*24*$sign); - - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " dateo = '".$this->db->idate($newdate)."'"; - $sql.= " WHERE rowid = ".$rowid; - - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->affected_rows($result)) - { - return 1; - } - } - else - { - dol_print_error($this->db); - return 0; - } - } - else dol_print_error($this->db); - return 0; - } - - /** - * Increase operation date of a rowid - * - * @param int $id Id of line to change - * @return int >0 if OK, 0 if KO - */ - function dateo_next($id) - { - return $this->dateo_change($id,1); - } - - /** - * Decrease operation date of a rowid - * - * @param int $id Id of line to change - * @return int >0 if OK, 0 if KO - */ - function dateo_previous($id) - { - return $this->dateo_change($id,-1); - } - - - /** - * Load miscellaneous information for tab "Info" - * - * @param int $id Id of object to load - * @return void - */ - function info($id) - { - $sql = 'SELECT b.rowid, b.datec, b.tms as datem,'; - $sql.= ' b.fk_user_author, b.fk_user_rappro'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'bank as b'; - $sql.= ' WHERE b.rowid = '.$id; - - $result=$this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; - - if ($obj->fk_user_author) - { - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; - } - if ($obj->fk_user_rappro) - { - $ruser = new User($this->db); - $ruser->fetch($obj->fk_user_rappro); - $this->user_rappro = $ruser; - } - - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_modification = $this->db->jdate($obj->datem); - //$this->date_rappro = $obj->daterappro; // Not yet managed - } - $this->db->free($result); - } - else - { - dol_print_error($this->db); - } - } - - - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $maxlen Longueur max libelle - * @param string $option Option ('showall') - * @return string Chaine avec URL - */ - function getNomUrl($withpicto=0,$maxlen=0,$option='') - { - global $langs; - - $result=''; - $label=$langs->trans("ShowTransaction").': '.$this->rowid; - $link = '<a href="'.DOL_URL_ROOT.'/compta/bank/ligne.php?rowid='.$this->rowid.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; - $linkend='</a>'; - - if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' '); - $result.=$link.$this->rowid.$linkend; - - if ($option == 'showall' || $option == 'showconciliated') $result.=' ('; - if ($option == 'showall') - { - $result.=$langs->trans("BankAccount").': '; - $accountstatic=new Account($this->db); - $accountstatic->id=$this->fk_account; - $accountstatic->ref=$this->bank_account_ref; - $accountstatic->label=$this->bank_account_label; - $result.=$accountstatic->getNomUrl(0).', '; - } - if ($option == 'showall' || $option == 'showconciliated') - { - $result.=$langs->trans("BankLineConciliated").': '; - $result.=yn($this->rappro); - } - if ($option == 'showall' || $option == 'showconciliated') $result.=')'; - - return $result; - } - - - /** - * Return label of status (activity, closed) - * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long - * @return string Libelle - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->status,$mode); - } - - /** - * Renvoi le libelle d'un statut donne - * - * @param int $statut Id statut - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle du statut - */ - function LibStatut($statut,$mode=0) - { - global $langs; - //$langs->load('companies'); - /* + /** + * Update conciliation field + * + * @param User $user Objet user making update + * @param int $cat Category id + * @return int <0 if KO, >0 if OK + */ + function update_conciliation(User $user, $cat) + { + global $conf; + + $this->db->begin(); + + // Check statement field + if (! empty($conf->global->BANK_STATEMENT_REGEX_RULE)) + { + if (! preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve)) + { + $this->errors[]=$langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE); + return -1; + } + } + + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " rappro = 1"; + $sql.= ", num_releve = '".$this->db->escape($this->num_releve)."'"; + $sql.= ", fk_user_rappro = ".$user->id; + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (! empty($cat)) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class ("; + $sql.= "lineid"; + $sql.= ", fk_categ"; + $sql.= ") VALUES ("; + $sql.= $this->id; + $sql.= ", ".$cat; + $sql.= ")"; + + dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); + $this->db->query($sql); + + // No error check. Can fail if category already affected + } + + $this->rappro=1; + + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } + + + /** + * Increase/decrease value date of a rowid + * + * @param int $rowid Id of line + * @param int $sign 1 or -1 + * @return int >0 if OK, 0 if KO + */ + function datev_change($rowid,$sign=1) + { + $sql = "SELECT datev FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; + $resql = $this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + $newdate=$this->db->jdate($obj->datev)+(3600*24*$sign); + + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " datev = '".$this->db->idate($newdate)."'"; + $sql.= " WHERE rowid = ".$rowid; + + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->affected_rows($result)) + { + return 1; + } + } + else + { + dol_print_error($this->db); + return 0; + } + } + else dol_print_error($this->db); + return 0; + } + + /** + * Increase value date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function datev_next($id) + { + return $this->datev_change($id,1); + } + + /** + * Decrease value date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function datev_previous($id) + { + return $this->datev_change($id,-1); + } + + + /** + * Increase/decrease operation date of a rowid + * + * @param int $rowid Id of line + * @param int $sign 1 or -1 + * @return int >0 if OK, 0 if KO + */ + function dateo_change($rowid,$sign=1) + { + $sql = "SELECT dateo FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; + $resql = $this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + $newdate=$this->db->jdate($obj->dateo)+(3600*24*$sign); + + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " dateo = '".$this->db->idate($newdate)."'"; + $sql.= " WHERE rowid = ".$rowid; + + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->affected_rows($result)) + { + return 1; + } + } + else + { + dol_print_error($this->db); + return 0; + } + } + else dol_print_error($this->db); + return 0; + } + + /** + * Increase operation date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function dateo_next($id) + { + return $this->dateo_change($id,1); + } + + /** + * Decrease operation date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function dateo_previous($id) + { + return $this->dateo_change($id,-1); + } + + + /** + * Load miscellaneous information for tab "Info" + * + * @param int $id Id of object to load + * @return void + */ + function info($id) + { + $sql = 'SELECT b.rowid, b.datec, b.tms as datem,'; + $sql.= ' b.fk_user_author, b.fk_user_rappro'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'bank as b'; + $sql.= ' WHERE b.rowid = '.$id; + + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + if ($obj->fk_user_rappro) + { + $ruser = new User($this->db); + $ruser->fetch($obj->fk_user_rappro); + $this->user_rappro = $ruser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + //$this->date_rappro = $obj->daterappro; // Not yet managed + } + $this->db->free($result); + } + else + { + dol_print_error($this->db); + } + } + + + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $maxlen Longueur max libelle + * @param string $option Option ('showall') + * @return string Chaine avec URL + */ + function getNomUrl($withpicto=0,$maxlen=0,$option='') + { + global $langs; + + $result=''; + $label=$langs->trans("ShowTransaction").': '.$this->rowid; + $link = '<a href="'.DOL_URL_ROOT.'/compta/bank/ligne.php?rowid='.$this->rowid.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; + $linkend='</a>'; + + if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' '); + $result.=$link.$this->rowid.$linkend; + + if ($option == 'showall' || $option == 'showconciliated') $result.=' ('; + if ($option == 'showall') + { + $result.=$langs->trans("BankAccount").': '; + $accountstatic=new Account($this->db); + $accountstatic->id=$this->fk_account; + $accountstatic->ref=$this->bank_account_ref; + $accountstatic->label=$this->bank_account_label; + $result.=$accountstatic->getNomUrl(0).', '; + } + if ($option == 'showall' || $option == 'showconciliated') + { + $result.=$langs->trans("BankLineConciliated").': '; + $result.=yn($this->rappro); + } + if ($option == 'showall' || $option == 'showconciliated') $result.=')'; + + return $result; + } + + + /** + * Return label of status (activity, closed) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long + * @return string Libelle + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->status,$mode); + } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $statut Id statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle du statut + */ + function LibStatut($statut,$mode=0) + { + global $langs; + //$langs->load('companies'); + /* if ($mode == 0) { if ($statut==0) return $langs->trans("ActivityCeased"); @@ -2216,7 +2216,7 @@ class AccountLine extends CommonObject if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"'); if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"'); }*/ - } + } } diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php index 9c1e6519db93bd69fce4b5d1de72c769d121459f..c7c13b1628a142843480f0d5e87d4d3e12ba1cbc 100644 --- a/htdocs/compta/facture/invoicetemplate_list.php +++ b/htdocs/compta/facture/invoicetemplate_list.php @@ -34,8 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; - //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; + require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; } require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; @@ -116,30 +116,30 @@ $permissiondellink=$user->rights->facture->creer; // Used by the include of acti $permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php $arrayfields=array( - 'f.titre'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 'f.total'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'f.tva'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>1), - 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>1), - 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>0), - 'f.fk_cond_reglement'=>array('label'=>$langs->trans("PaymentTerm"), 'checked'=>0), + 'f.titre'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 'f.total'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'f.tva'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>1), + 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>1), + 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>0), + 'f.fk_cond_reglement'=>array('label'=>$langs->trans("PaymentTerm"), 'checked'=>0), 'recurring'=>array('label'=>$langs->trans("RecurringInvoiceTemplate"), 'checked'=>1), - 'f.frequency'=>array('label'=>$langs->trans("Frequency"), 'checked'=>1), + 'f.frequency'=>array('label'=>$langs->trans("Frequency"), 'checked'=>1), 'f.unit_frequency'=>array('label'=>$langs->trans("FrequencyUnit"), 'checked'=>1), 'f.nb_gen_done'=>array('label'=>$langs->trans("NbOfGenerationDoneShort"), 'checked'=>1), - 'f.date_last_gen'=>array('label'=>$langs->trans("DateLastGeneration"), 'checked'=>1), - 'f.date_when'=>array('label'=>$langs->trans("NextDateToExecution"), 'checked'=>1), - 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>100), + 'f.date_last_gen'=>array('label'=>$langs->trans("DateLastGeneration"), 'checked'=>1), + 'f.date_when'=>array('label'=>$langs->trans("NextDateToExecution"), 'checked'=>1), + 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>100), 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } @@ -156,35 +156,35 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if (GETPOST('cancel','alpha')) $action=''; - - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - - // Do we click on purge search criteria ? - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers - { - $search_ref=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_payment_mode=''; - $search_payment_term=''; - $day=''; - $year=''; - $month=''; - $day_date_when=''; - $year_date_when=''; - $month_date_when=''; - $search_recurring=''; - $search_frequency=''; - $search_unit_frequency=''; - $search_array_options=array(); - } - - // Mass actions - /*$objectclass='MyObject'; + if (GETPOST('cancel','alpha')) $action=''; + + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Do we click on purge search criteria ? + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers + { + $search_ref=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $search_payment_mode=''; + $search_payment_term=''; + $day=''; + $year=''; + $month=''; + $day_date_when=''; + $year_date_when=''; + $month_date_when=''; + $search_recurring=''; + $search_frequency=''; + $search_unit_frequency=''; + $search_array_options=array(); + } + + // Mass actions + /*$objectclass='MyObject'; $objectlabel='MyObject'; $permtoread = $user->rights->mymodule->read; $permtodelete = $user->rights->mymodule->delete; @@ -241,29 +241,29 @@ if ($search_unit_frequency != '') $sql .= natural_search('f.unit_frequency', $se if ($month > 0) { - if ($year > 0 && empty($day)) - $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(f.date_last_gen, '%m') = '".$month."'"; + if ($year > 0 && empty($day)) + $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(f.date_last_gen, '%m') = '".$month."'"; } else if ($year > 0) { - $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; + $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($month_date_when > 0) { - if ($year_date_when > 0 && empty($day_date_when)) - $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,$month_date_when,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,$month_date_when,false))."'"; - else if ($year_date_when > 0 && ! empty($day_date_when)) - $sql.= " AND f.date_date_when_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date_when, $day_date_when, $year_date_when))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date_when, $day_date_when, $year_date_when))."'"; + if ($year_date_when > 0 && empty($day_date_when)) + $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,$month_date_when,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,$month_date_when,false))."'"; + else if ($year_date_when > 0 && ! empty($day_date_when)) + $sql.= " AND f.date_date_when_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date_when, $day_date_when, $year_date_when))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date_when, $day_date_when, $year_date_when))."'"; else $sql.= " AND date_format(f.date_when, '%m') = '".$month_date_when."'"; } else if ($year_date_when > 0) { - $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,1,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,12,false))."'"; + $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,1,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,12,false))."'"; } $nbtotalofrecords = ''; @@ -282,7 +282,7 @@ if ($resql) $num = $db->num_rows($resql); $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); if ($socid) $param.='&socid='.urlencode($socid); if ($day) $param.='&day='.urlencode($day); @@ -306,9 +306,9 @@ if ($resql) // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } $massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); @@ -342,117 +342,117 @@ if ($resql) // Ref if (! empty($arrayfields['f.titre']['checked'])) { - print '<td class="liste_titre" align="left">'; - print '<input class="flat" size="6" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; - print '</td>'; + print '<td class="liste_titre" align="left">'; + print '<input class="flat" size="6" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; + print '</td>'; } // Thirpdarty if (! empty($arrayfields['s.nom']['checked'])) { - print '<td class="liste_titre" align="left"><input class="flat" type="text" size="8" name="search_societe" value="'.dol_escape_htmltag($search_societe).'"></td>'; + print '<td class="liste_titre" align="left"><input class="flat" type="text" size="8" name="search_societe" value="'.dol_escape_htmltag($search_societe).'"></td>'; } if (! empty($arrayfields['f.total']['checked'])) { - // Amount net - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">'; - print '</td>'; + // Amount net + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">'; + print '</td>'; } if (! empty($arrayfields['f.tva']['checked'])) { - // Amount Vat - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">'; - print '</td>'; + // Amount Vat + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">'; + print '</td>'; } if (! empty($arrayfields['f.total_ttc']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">'; + print '</td>'; } if (! empty($arrayfields['f.fk_cond_reglement']['checked'])) { - // Payment term - print '<td class="liste_titre" align="right">'; - print $form->select_conditions_paiements($search_payment_term, 'search_payment_term', -1, 1, 1, 'maxwidth100'); - print "</td>"; + // Payment term + print '<td class="liste_titre" align="right">'; + print $form->select_conditions_paiements($search_payment_term, 'search_payment_term', -1, 1, 1, 'maxwidth100'); + print "</td>"; } if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) { - // Payment mode - print '<td class="liste_titre" align="right">'; - print $form->select_types_paiements($search_payment_mode, 'search_payment_mode', '', 0, 1, 1, 0, 1, 'maxwidth100'); - print '</td>'; + // Payment mode + print '<td class="liste_titre" align="right">'; + print $form->select_types_paiements($search_payment_mode, 'search_payment_mode', '', 0, 1, 1, 0, 1, 'maxwidth100'); + print '</td>'; } if (! empty($arrayfields['recurring']['checked'])) { - // Recurring or not - print '<td class="liste_titre" align="center">'; - print $form->selectyesno('search_recurring', $search_recurring, 1, false, 1); - print '</td>'; + // Recurring or not + print '<td class="liste_titre" align="center">'; + print $form->selectyesno('search_recurring', $search_recurring, 1, false, 1); + print '</td>'; } if (! empty($arrayfields['f.frequency']['checked'])) { - // Recurring or not - print '<td class="liste_titre" align="center">'; - print '<input class="flat" type="text" size="1" name="search_frequency" value="'.dol_escape_htmltag($search_frequency).'">'; - print '</td>'; + // Recurring or not + print '<td class="liste_titre" align="center">'; + print '<input class="flat" type="text" size="1" name="search_frequency" value="'.dol_escape_htmltag($search_frequency).'">'; + print '</td>'; } if (! empty($arrayfields['f.unit_frequency']['checked'])) { - // Frequency unit - print '<td class="liste_titre" align="center">'; - print '<input class="flat" type="text" size="1" name="search_unit_frequency" value="'.dol_escape_htmltag($search_unit_frequency).'">'; - print '</td>'; + // Frequency unit + print '<td class="liste_titre" align="center">'; + print '<input class="flat" type="text" size="1" name="search_unit_frequency" value="'.dol_escape_htmltag($search_unit_frequency).'">'; + print '</td>'; } if (! empty($arrayfields['f.nb_gen_done']['checked'])) { - // Nb generation - print '<td class="liste_titre" align="center">'; - print '</td>'; + // Nb generation + print '<td class="liste_titre" align="center">'; + print '</td>'; } // Date invoice if (! empty($arrayfields['f.date_last_gen']['checked'])) { - print '<td class="liste_titre" align="center">'; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.$day.'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">'; - $formother->select_year($year?$year:-1,'year',1, 20, 5); - print '</td>'; + print '<td class="liste_titre" align="center">'; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.$day.'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">'; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print '</td>'; } // Date due if (! empty($arrayfields['f.date_when']['checked'])) { - print '<td class="liste_titre" align="center">'; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day_date_when" value="'.$day_date_when.'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="month_date_when" value="'.$month_date_when.'">'; - $formother->select_year($year_date_when?$year_date_when:-1,'year_date_when',1, 20, 5); - print '</td>'; + print '<td class="liste_titre" align="center">'; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day_date_when" value="'.$day_date_when.'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="month_date_when" value="'.$month_date_when.'">'; + $formother->select_year($year_date_when?$year_date_when:-1,'year_date_when',1, 20, 5); + print '</td>'; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } - print '</td>'; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -461,20 +461,20 @@ if ($resql) // Date creation if (! empty($arrayfields['f.datec']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Date modification if (! empty($arrayfields['f.tms']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Status if (! empty($arrayfields['status']['checked'])) { - print '<td class="liste_titre" align="center">'; - print '</td>'; + print '<td class="liste_titre" align="center">'; + print '</td>'; } // Action column print '<td class="liste_titre" align="middle">'; @@ -590,10 +590,10 @@ if ($resql) } if (! empty($arrayfields['f.nb_gen_done']['checked'])) { - print '<td align="center">'; - print ($objp->frequency ? $objp->nb_gen_done.($objp->nb_gen_max>0?' / '. $objp->nb_gen_max:'') : '<span class="opacitymedium">'.$langs->trans('NA').'</span>'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + print ($objp->frequency ? $objp->nb_gen_done.($objp->nb_gen_max>0?' / '. $objp->nb_gen_max:'') : '<span class="opacitymedium">'.$langs->trans('NA').'</span>'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['f.date_last_gen']['checked'])) { @@ -634,19 +634,19 @@ if ($resql) print '<td align="center">'; if ($user->rights->facture->creer) { - if (empty($objp->frequency) || $db->jdate($objp->date_when) <= $today) - { + if (empty($objp->frequency) || $db->jdate($objp->date_when) <= $today) + { print '<a href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&socid='.$objp->socid.'&fac_rec='.$objp->facid.'">'; print $langs->trans("CreateBill").'</a>'; - } - else - { - print $langs->trans("DateIsNotEnough"); - } + } + else + { + print $langs->trans("DateIsNotEnough"); + } } else { - print " "; + print " "; } if (! $i) $totalarray['nbfield']++; print "</td>"; @@ -658,9 +658,9 @@ if ($resql) } else { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } - print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } //var_dump($totalarray); diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index a7cc2f9e7192d8aaed1c98f4b338c5cf7f908d98..9241726aaecc72c3aaf5311eb2bf301a5fa99374 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -136,46 +136,46 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'f.facnumber'=>'Ref', - 'f.ref_client'=>'RefCustomer', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'f.note_public'=>'NotePublic', + 'f.facnumber'=>'Ref', + 'f.ref_client'=>'RefCustomer', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'f.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["f.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'f.facnumber'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'f.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 'f.type'=>array('label'=>$langs->trans("Type"), 'checked'=>0), - 'f.date'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), - 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), - 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), - 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), - 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'dynamount_payed'=>array('label'=>$langs->trans("Received"), 'checked'=>0), - 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), - 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'f.facnumber'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'f.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 'f.type'=>array('label'=>$langs->trans("Type"), 'checked'=>0), + 'f.date'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), + 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), + 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), + 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), + 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'dynamount_payed'=>array('label'=>$langs->trans("Received"), 'checked'=>0), + 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), + 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! 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'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } @@ -195,144 +195,144 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','alpha') || GETPOST('button_removefilter.x','alpha')) // All tests are required to be compatible with all browsers { - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=''; - $search_refcustomer=''; - $search_type=''; - $search_project=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_localtax1=''; - $search_montant_localtax2=''; - $search_montant_ttc=''; - $search_status=''; - $search_paymentmode=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $day=''; - $year=''; - $month=''; - $option=''; - $filter=''; - $day_lim=''; - $year_lim=''; - $month_lim=''; - $toselect=''; - $search_array_options=array(); + $search_user=''; + $search_sale=''; + $search_product_category=''; + $search_ref=''; + $search_refcustomer=''; + $search_type=''; + $search_project=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_localtax1=''; + $search_montant_localtax2=''; + $search_montant_ttc=''; + $search_status=''; + $search_paymentmode=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $day=''; + $year=''; + $month=''; + $option=''; + $filter=''; + $day_lim=''; + $year_lim=''; + $month_lim=''; + $toselect=''; + $search_array_options=array(); } if (empty($reshook)) { $objectclass='Facture'; $objectlabel='Invoices'; - $permtoread = $user->rights->facture->lire; - $permtocreate = $user->rights->facture->creer; - $permtodelete = $user->rights->facture->supprimer; + $permtoread = $user->rights->facture->lire; + $permtocreate = $user->rights->facture->creer; + $permtodelete = $user->rights->facture->supprimer; $uploaddir = $conf->facture->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } if ($massaction == 'withdrawrequest') { - $langs->load("withdrawals"); - - if (!$user->rights->prelevement->bons->creer) - { - $error++; - setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); - } - else - { - //Checking error - $error = 0; - - $arrayofselected=is_array($toselect)?$toselect:array(); - $listofbills=array(); - foreach($arrayofselected as $toselectid) - { - $objecttmp=new Facture($db); - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $totalpaye = $objecttmp->getSommePaiement(); - $totalcreditnotes = $objecttmp->getSumCreditNotesUsed(); - $totaldeposits = $objecttmp->getSumDepositsUsed(); - $objecttmp->resteapayer = price2num($objecttmp->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT'); - $listofbills[] = $objecttmp; - if($objecttmp->paye || $objecttmp->resteapayer==0){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("AlreadyPaid"), $objecttmp->errors, 'errors'); - } else if($objecttmp->resteapayer<0){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors'); - } - if(!($objecttmp->statut > Facture::STATUS_DRAFT)){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors'); - } - - $rsql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande"; - $rsql .= " , pfd.date_traite as date_traite"; - $rsql .= " , pfd.amount"; - $rsql .= " , u.rowid as user_id, u.lastname, u.firstname, u.login"; - $rsql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - $rsql .= " , ".MAIN_DB_PREFIX."user as u"; - $rsql .= " WHERE fk_facture = ".$objecttmp->id; - $rsql .= " AND pfd.fk_user_demande = u.rowid"; - $rsql .= " AND pfd.traite = 0"; - $rsql .= " ORDER BY pfd.date_demande DESC"; - - $result_sql = $db->query($rsql); - if ($result_sql) - { - $numprlv = $db->num_rows($result_sql); - } - - if($numprlv>0){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'errors'); - } - if(!empty($objecttmp->mode_reglement_id ) && $objecttmp->mode_reglement_id != 3){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); - } - - } - } - - //Massive withdraw request - if(!empty($listofbills) && empty($error)) - { - $nbwithdrawrequestok=0; - foreach($listofbills as $aBill) - { - $db->begin(); - $result = $aBill->demande_prelevement($user, $aBill->resteapayer); - if ($result > 0) - { - $db->commit(); - $nbwithdrawrequestok++; - } - else - { - - $db->rollback(); - setEventMessages($aBill->error, $aBill->errors, 'errors'); - } - } - if ($nbwithdrawrequestok > 0) - { - setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs'); - } - } - } + $langs->load("withdrawals"); + + if (!$user->rights->prelevement->bons->creer) + { + $error++; + setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); + } + else + { + //Checking error + $error = 0; + + $arrayofselected=is_array($toselect)?$toselect:array(); + $listofbills=array(); + foreach($arrayofselected as $toselectid) + { + $objecttmp=new Facture($db); + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + $totalpaye = $objecttmp->getSommePaiement(); + $totalcreditnotes = $objecttmp->getSumCreditNotesUsed(); + $totaldeposits = $objecttmp->getSumDepositsUsed(); + $objecttmp->resteapayer = price2num($objecttmp->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT'); + $listofbills[] = $objecttmp; + if($objecttmp->paye || $objecttmp->resteapayer==0){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("AlreadyPaid"), $objecttmp->errors, 'errors'); + } else if($objecttmp->resteapayer<0){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors'); + } + if(!($objecttmp->statut > Facture::STATUS_DRAFT)){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors'); + } + + $rsql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande"; + $rsql .= " , pfd.date_traite as date_traite"; + $rsql .= " , pfd.amount"; + $rsql .= " , u.rowid as user_id, u.lastname, u.firstname, u.login"; + $rsql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + $rsql .= " , ".MAIN_DB_PREFIX."user as u"; + $rsql .= " WHERE fk_facture = ".$objecttmp->id; + $rsql .= " AND pfd.fk_user_demande = u.rowid"; + $rsql .= " AND pfd.traite = 0"; + $rsql .= " ORDER BY pfd.date_demande DESC"; + + $result_sql = $db->query($rsql); + if ($result_sql) + { + $numprlv = $db->num_rows($result_sql); + } + + if($numprlv>0){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'errors'); + } + if(!empty($objecttmp->mode_reglement_id ) && $objecttmp->mode_reglement_id != 3){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); + } + + } + } + + //Massive withdraw request + if(!empty($listofbills) && empty($error)) + { + $nbwithdrawrequestok=0; + foreach($listofbills as $aBill) + { + $db->begin(); + $result = $aBill->demande_prelevement($user, $aBill->resteapayer); + if ($result > 0) + { + $db->commit(); + $nbwithdrawrequestok++; + } + else + { + + $db->rollback(); + setEventMessages($aBill->error, $aBill->errors, 'errors'); + } + } + if ($nbwithdrawrequestok > 0) + { + setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs'); + } + } + } } @@ -384,8 +384,8 @@ if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE f.fk_soc = s.rowid'; $sql.= ' AND f.entity IN ('.getEntity('facture').')'; @@ -394,28 +394,28 @@ if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$db->escape($s if ($socid > 0) $sql.= ' AND s.rowid = '.$socid; if ($userid) { - if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL'; - else $sql.=' AND f.fk_user_author = '.$userid; + if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL'; + else $sql.=' AND f.fk_user_author = '.$userid; } if ($filtre) { - $aFilter = explode(',', $filtre); - foreach ($aFilter as $filter) - { - $filt = explode(':', $filter); - $sql .= ' AND ' . $db->escape(trim($filt[0])) . ' = ' . $db->escape(trim($filt[1])); - } + $aFilter = explode(',', $filtre); + foreach ($aFilter as $filter) + { + $filt = explode(':', $filter); + $sql .= ' AND ' . $db->escape(trim($filt[0])) . ' = ' . $db->escape(trim($filt[1])); + } } if ($search_ref) $sql .= natural_search('f.facnumber', $search_ref); if ($search_refcustomer) $sql .= natural_search('f.ref_client', $search_refcustomer); if ($search_type != '' && $search_type >= 0) { - if ($search_type == '0') $sql.=" AND f.type = 0"; // standard - if ($search_type == '1') $sql.=" AND f.type = 1"; // replacement - if ($search_type == '2') $sql.=" AND f.type = 2"; // credit note - if ($search_type == '3') $sql.=" AND f.type = 3"; // deposit - if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma - if ($search_type == '5') $sql.=" AND f.type = 5"; // situation + if ($search_type == '0') $sql.=" AND f.type = 0"; // standard + if ($search_type == '1') $sql.=" AND f.type = 1"; // replacement + if ($search_type == '2') $sql.=" AND f.type = 2"; // credit note + if ($search_type == '3') $sql.=" AND f.type = 3"; // deposit + if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma + if ($search_type == '5') $sql.=" AND f.type = 5"; // situation } if ($search_project) $sql .= natural_search('p.ref', $search_project); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); @@ -432,24 +432,24 @@ if ($search_montant_localtax2 != '') $sql.= natural_search('f.localtax2', $searc if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1); if ($search_status != '' && $search_status >= 0) { - if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft - if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed - if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) - if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned + if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft + if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed + if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) + if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned } if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$db->escape($search_paymentmode); if ($month > 0) { - if ($year > 0 && empty($day)) - $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(f.datef, '%m') = '".$month."'"; + if ($year > 0 && empty($day)) + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(f.datef, '%m') = '".$month."'"; } else if ($year > 0) { - $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($month_lim > 0) { @@ -468,21 +468,21 @@ if ($option == 'late') $sql.=" AND f.date_lim_reglement < '".$db->idate(dol_now( if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; if ($search_user > 0) { - $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; + $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -491,22 +491,22 @@ $sql.=$hookmanager->resPrint; if (! $sall) { - $sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.total, f.tva, f.total_ttc,'; - $sql.= ' f.localtax1, f.localtax2,'; - $sql.= ' f.datef, f.date_lim_reglement,'; - $sql.= ' f.paye, f.fk_statut,'; - $sql.= ' f.datec, f.tms,'; - $sql.= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.code_client, s.client, typent.code,'; - $sql.= ' state.code_departement, state.nom'; - - foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by - { - $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); - } + $sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.total, f.tva, f.total_ttc,'; + $sql.= ' f.localtax1, f.localtax2,'; + $sql.= ' f.datef, f.date_lim_reglement,'; + $sql.= ' f.paye, f.fk_statut,'; + $sql.= ' f.datec, f.tms,'; + $sql.= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.code_client, s.client, typent.code,'; + $sql.= ' state.code_departement, state.nom'; + + foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by + { + $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); + } } else { - $sql .= natural_search(array_keys($fieldstosearchall), $sall); + $sql .= natural_search(array_keys($fieldstosearchall), $sall); } $sql.= ' ORDER BY '; @@ -527,56 +527,56 @@ $sql.= $db->plimit($limit+1,$offset); $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($resql); + $num = $db->num_rows($resql); $arrayofselected=is_array($toselect)?$toselect:array(); - if ($socid) - { - $soc = new Societe($db); - $soc->fetch($socid); + if ($socid) + { + $soc = new Societe($db); + $soc->fetch($socid); if (empty($search_societe)) $search_societe = $soc->name; - } + } - $param='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + $param='&socid='.$socid; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($sall) $param.='&sall='.urlencode($sall); - if ($day) $param.='&day='.urlencode($day); - if ($month) $param.='&month='.urlencode($month); - if ($year) $param.='&year=' .urlencode($year); - if ($day_lim) $param.='&day_lim='.urlencode($day_lim); - if ($month_lim) $param.='&month_lim='.urlencode($month_lim); - if ($year_lim) $param.='&year_lim=' .urlencode($year_lim); - if ($search_ref) $param.='&search_ref=' .urlencode($search_ref); - if ($search_refcustomer) $param.='&search_refcustomer=' .urlencode($search_refcustomer); - if ($search_type != '') $param.='&search_type='.urlencode($search_type); - if ($search_societe) $param.='&search_societe=' .urlencode($search_societe); - if ($search_sale > 0) $param.='&search_sale=' .urlencode($search_sale); - if ($search_user > 0) $param.='&search_user=' .urlencode($search_user); - if ($search_product_category > 0) $param.='$search_product_category=' .urlencode($search_product_category); - if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); - if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); - if ($search_montant_localtax1 != '') $param.='&search_montant_localtax1='.urlencode($search_montant_localtax1); - if ($search_montant_localtax2 != '') $param.='&search_montant_localtax2='.urlencode($search_montant_localtax2); - if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); + if ($day) $param.='&day='.urlencode($day); + if ($month) $param.='&month='.urlencode($month); + if ($year) $param.='&year=' .urlencode($year); + if ($day_lim) $param.='&day_lim='.urlencode($day_lim); + if ($month_lim) $param.='&month_lim='.urlencode($month_lim); + if ($year_lim) $param.='&year_lim=' .urlencode($year_lim); + if ($search_ref) $param.='&search_ref=' .urlencode($search_ref); + if ($search_refcustomer) $param.='&search_refcustomer=' .urlencode($search_refcustomer); + if ($search_type != '') $param.='&search_type='.urlencode($search_type); + if ($search_societe) $param.='&search_societe=' .urlencode($search_societe); + if ($search_sale > 0) $param.='&search_sale=' .urlencode($search_sale); + if ($search_user > 0) $param.='&search_user=' .urlencode($search_user); + if ($search_product_category > 0) $param.='$search_product_category=' .urlencode($search_product_category); + if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); + if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); + if ($search_montant_localtax1 != '') $param.='&search_montant_localtax1='.urlencode($search_montant_localtax1); + if ($search_montant_localtax2 != '') $param.='&search_montant_localtax2='.urlencode($search_montant_localtax2); + if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); if ($search_status != '') $param.='&search_status='.urlencode($search_status); if ($search_paymentmode > 0) $param.='search_paymentmode='.urlencode($search_paymentmode); - if ($show_files) $param.='&show_files=' .$show_files; + if ($show_files) $param.='&show_files=' .$show_files; if ($option) $param.="&option=".$option; if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } $arrayofmassactions=array( - 'validate'=>$langs->trans("Validate"), + 'validate'=>$langs->trans("Validate"), 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if ($conf->prelevement->enabled) { @@ -585,31 +585,31 @@ if ($resql) } if ($user->rights->facture->supprimer) { - //if (! empty($conf->global->STOCK_CALCULATE_ON_BILL) || empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) - if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) - { - // mass deletion never possible on invoices on such situation - } - else - { - $arrayofmassactions['delete']=$langs->trans("Delete"); - } + //if (! empty($conf->global->STOCK_CALCULATE_ON_BILL) || empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) + if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) + { + // mass deletion never possible on invoices on such situation + } + else + { + $arrayofmassactions['delete']=$langs->trans("Delete"); + } } if ($massaction == 'presend') $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - $i = 0; - print '<form method="POST" name="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; + $i = 0; + print '<form method="POST" name="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; - print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; + if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; - print '<input type="hidden" name="action" value="list">'; - print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; - print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; - print '<input type="hidden" name="page" value="'.$page.'">'; - print '<input type="hidden" name="viewstatut" value="'.$viewstatut.'">'; - print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; + print '<input type="hidden" name="action" value="list">'; + print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; + print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; + print '<input type="hidden" name="page" value="'.$page.'">'; + print '<input type="hidden" name="viewstatut" value="'.$viewstatut.'">'; + print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_accountancy.png', 0, '', '', $limit); @@ -623,14 +623,14 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; } - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + if ($sall) + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } // If the user can view prospects other than his' - $moreforfilter=''; + $moreforfilter=''; if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); @@ -639,14 +639,14 @@ if ($resql) $moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); $moreforfilter.='</div>'; } - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) + { $moreforfilter.='<div class="divsearchfield">'; - $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='</div>'; - } + } // If the user can view prospects other than his' if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { @@ -657,51 +657,51 @@ if ($resql) $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter.='</div>'; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + $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; - if ($moreforfilter) - { + if ($moreforfilter) + { print '<div class="liste_titre liste_titre_bydiv centpercent">'; - print $moreforfilter; - print '</div>'; - } + print $moreforfilter; + print '</div>'; + } - $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); + $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); - print '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; + print '<div class="div-table-responsive">'; + print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; - // Filters lines - print '<tr class="liste_titre_filter">'; + // Filters lines + print '<tr class="liste_titre_filter">'; // Ref if (! empty($arrayfields['f.facnumber']['checked'])) { - print '<td class="liste_titre" align="left">'; - print '<input class="flat" size="6" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; - print '</td>'; + print '<td class="liste_titre" align="left">'; + print '<input class="flat" size="6" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; + print '</td>'; } // Ref customer if (! empty($arrayfields['f.ref_client']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" size="6" type="text" name="search_refcustomer" value="'.dol_escape_htmltag($search_refcustomer).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" size="6" type="text" name="search_refcustomer" value="'.dol_escape_htmltag($search_refcustomer).'">'; + print '</td>'; } // Type if (! empty($arrayfields['f.type']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone">'; $listtype=array( - Facture::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), - Facture::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), - Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), - Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), - ); + Facture::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), + Facture::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), + Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), + Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), + ); //$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma"); // A proformat invoice is not an invoice but must be an order. print $form->selectarray('search_type', $listtype, $search_type, 1, 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth100'); print '</td>'; @@ -709,26 +709,26 @@ if ($resql) // Date invoice if (! empty($arrayfields['f.date']['checked'])) { - print '<td class="liste_titre" align="center">'; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.dol_escape_htmltag($day).'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.dol_escape_htmltag($month).'">'; - $formother->select_year($year?$year:-1,'year',1, 20, 5); - print '</td>'; + print '<td class="liste_titre" align="center">'; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.dol_escape_htmltag($day).'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.dol_escape_htmltag($month).'">'; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print '</td>'; } // Date due if (! empty($arrayfields['f.date_lim_reglement']['checked'])) { - print '<td class="liste_titre" align="center">'; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day_lim" value="'.dol_escape_htmltag($day_lim).'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="month_lim" value="'.dol_escape_htmltag($month_lim).'">'; - $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); - print '<br><input type="checkbox" name="option" value="late"'.($option == 'late'?' checked':'').'> '.$langs->trans("Late"); - print '</td>'; + print '<td class="liste_titre" align="center">'; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day_lim" value="'.dol_escape_htmltag($day_lim).'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="month_lim" value="'.dol_escape_htmltag($month_lim).'">'; + $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); + print '<br><input type="checkbox" name="option" value="late"'.($option == 'late'?' checked':'').'> '.$langs->trans("Late"); + print '</td>'; } // Project if (! empty($arrayfields['p.ref']['checked'])) { - print '<td class="liste_titre" align="left"><input class="flat" type="text" size="6" name="search_project" value="'.$search_project.'"></td>'; + print '<td class="liste_titre" align="left"><input class="flat" type="text" size="6" name="search_project" value="'.$search_project.'"></td>'; } // Thirpdarty if (! empty($arrayfields['s.nom']['checked'])) @@ -742,98 +742,98 @@ if ($resql) // State if (! empty($arrayfields['state.nom']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; + print '</td>'; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print '<td class="liste_titre" align="center">'; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print '</td>'; + print '<td class="liste_titre" align="center">'; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print '</td>'; } // Company type if (! empty($arrayfields['typent.code']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="center">'; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT), 'maxwidth100'); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="center">'; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT), 'maxwidth100'); + print '</td>'; } // Payment mode if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) { - print '<td class="liste_titre" align="left">'; - $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); - print '</td>'; + print '<td class="liste_titre" align="left">'; + $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); + print '</td>'; } if (! empty($arrayfields['f.total_ht']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">'; + print '</td>'; } if (! empty($arrayfields['f.total_vat']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">'; + print '</td>'; } if (! empty($arrayfields['f.total_localtax1']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_localtax1" value="'.$search_montant_localtax1.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_localtax1" value="'.$search_montant_localtax1.'">'; + print '</td>'; } if (! empty($arrayfields['f.total_localtax2']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_localtax2" value="'.$search_montant_localtax2.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_localtax2" value="'.$search_montant_localtax2.'">'; + print '</td>'; } if (! empty($arrayfields['f.total_ttc']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">'; + print '</td>'; + } + if (! empty($arrayfields['dynamount_payed']['checked'])) + { + print '<td class="liste_titre" align="right">'; + print '</td>'; + } + if (! empty($arrayfields['rtp']['checked'])) + { + print '<td class="liste_titre" align="right">'; + print '</td>'; } - if (! empty($arrayfields['dynamount_payed']['checked'])) - { - print '<td class="liste_titre" align="right">'; - print '</td>'; - } - if (! empty($arrayfields['rtp']['checked'])) - { - print '<td class="liste_titre" align="right">'; - print '</td>'; - } - // Extra fields + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } - print '</td>'; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -842,360 +842,360 @@ if ($resql) // Date creation if (! empty($arrayfields['f.datec']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Date modification if (! empty($arrayfields['f.tms']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Status if (! empty($arrayfields['f.fk_statut']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="right">'; - $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled")); - print $form->selectarray('search_status', $liststatus, $search_status, 1); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="right">'; + $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled")); + print $form->selectarray('search_status', $liststatus, $search_status, 1); + print '</td>'; } // Action column print '<td class="liste_titre" align="middle">'; $searchpicto=$form->showFilterButtons(); print $searchpicto; - print '</td>'; - print "</tr>\n"; - - print '<tr class="liste_titre">'; - if (! empty($arrayfields['f.facnumber']['checked'])) print_liste_field_titre($arrayfields['f.facnumber']['label'],$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.ref_client']['checked'])) print_liste_field_titre($arrayfields['f.ref_client']['label'],$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'],$_SERVER["PHP_SELF"],'f.type','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.date']['checked'])) print_liste_field_titre($arrayfields['f.date']['label'],$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'],$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'],$_SERVER["PHP_SELF"],"f.fk_mode_reglement","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'],$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'],$_SERVER['PHP_SELF'],'f.tva','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'],$_SERVER['PHP_SELF'],'f.localtax1','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'],$_SERVER['PHP_SELF'],'f.localtax2','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'],$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye,type,dynamount_payed","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "</tr>\n"; - - if ($num > 0) - { - $i=0; - $totalarray=array(); - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); - - $datelimit=$db->jdate($obj->datelimite); - $facturestatic->id=$obj->id; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - $facturestatic->statut=$obj->fk_statut; - $facturestatic->date_lim_reglement=$db->jdate($obj->datelimite); - $facturestatic->note_public=$obj->note_public; - $facturestatic->note_private=$obj->note_private; - - $paiement = $facturestatic->getSommePaiement(); - $totalcreditnotes = $facturestatic->getSumCreditNotesUsed(); - $totaldeposits = $facturestatic->getSumDepositsUsed(); - $totalpay = $paiement + $totalcreditnotes + $totaldeposits; - $remaintopay = $obj->total_ttc - $totalpay; - - print '<tr class="oddeven">'; - if (! empty($arrayfields['f.facnumber']['checked'])) - { - print '<td class="nowrap">'; - - print '<table class="nobordernopadding"><tr class="nocellnopadd">'; - - print '<td class="nobordernopadding nowrap">'; - print $facturestatic->getNomUrl(1,'',200,0,'',0,1); - print empty($obj->increment)?'':' ('.$obj->increment.')'; - print '</td>'; - - print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->id; - print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir); - print '</td>'; - print '</tr>'; - print '</table>'; - - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; - } + print '</td>'; + print "</tr>\n"; + + print '<tr class="liste_titre">'; + if (! empty($arrayfields['f.facnumber']['checked'])) print_liste_field_titre($arrayfields['f.facnumber']['label'],$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.ref_client']['checked'])) print_liste_field_titre($arrayfields['f.ref_client']['label'],$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'],$_SERVER["PHP_SELF"],'f.type','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.date']['checked'])) print_liste_field_titre($arrayfields['f.date']['label'],$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'],$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'],$_SERVER["PHP_SELF"],"f.fk_mode_reglement","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'],$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'],$_SERVER['PHP_SELF'],'f.tva','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'],$_SERVER['PHP_SELF'],'f.localtax1','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'],$_SERVER['PHP_SELF'],'f.localtax2','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'],$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } + } + // Hook fields + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye,type,dynamount_payed","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); + print "</tr>\n"; + + if ($num > 0) + { + $i=0; + $totalarray=array(); + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); + + $datelimit=$db->jdate($obj->datelimite); + $facturestatic->id=$obj->id; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + $facturestatic->statut=$obj->fk_statut; + $facturestatic->date_lim_reglement=$db->jdate($obj->datelimite); + $facturestatic->note_public=$obj->note_public; + $facturestatic->note_private=$obj->note_private; + + $paiement = $facturestatic->getSommePaiement(); + $totalcreditnotes = $facturestatic->getSumCreditNotesUsed(); + $totaldeposits = $facturestatic->getSumDepositsUsed(); + $totalpay = $paiement + $totalcreditnotes + $totaldeposits; + $remaintopay = $obj->total_ttc - $totalpay; + + print '<tr class="oddeven">'; + if (! empty($arrayfields['f.facnumber']['checked'])) + { + print '<td class="nowrap">'; + + print '<table class="nobordernopadding"><tr class="nocellnopadd">'; + + print '<td class="nobordernopadding nowrap">'; + print $facturestatic->getNomUrl(1,'',200,0,'',0,1); + print empty($obj->increment)?'':' ('.$obj->increment.')'; + print '</td>'; + + print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->id; + print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir); + print '</td>'; + print '</tr>'; + print '</table>'; + + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; + } // Customer ref - if (! empty($arrayfields['f.ref_client']['checked'])) - { - print '<td class="nowrap">'; - print $obj->ref_client; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Type - if (! empty($arrayfields['f.type']['checked'])) - { - print '<td class="nowrap">'; - print $facturestatic->getLibType(); - print "</td>"; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['f.ref_client']['checked'])) + { + print '<td class="nowrap">'; + print $obj->ref_client; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Type + if (! empty($arrayfields['f.type']['checked'])) + { + print '<td class="nowrap">'; + print $facturestatic->getLibType(); + print "</td>"; + if (! $i) $totalarray['nbfield']++; + } // Date - if (! empty($arrayfields['f.date']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->df),'day'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Date limit - if (! empty($arrayfields['f.date_lim_reglement']['checked'])) - { - print '<td align="center" class="nowrap">'.dol_print_date($datelimit,'day'); - if ($facturestatic->hasDelay()) - { - print img_warning($langs->trans('Late')); - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Project - if (! empty($arrayfields['p.ref']['checked'])) - { - print '<td class="nowrap">'; - if ($obj->project_id > 0) - { - $projectstatic->id=$obj->project_id; - $projectstatic->ref=$obj->project_ref; - print $projectstatic->getNomUrl(1); - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Third party - if (! empty($arrayfields['s.nom']['checked'])) - { - print '<td class="tdoverflowmax200">'; - $thirdpartystatic->id=$obj->socid; - $thirdpartystatic->name=$obj->name; - $thirdpartystatic->client=$obj->client; - $thirdpartystatic->code_client=$obj->code_client; - $thirdpartystatic->email=$obj->email; - print $thirdpartystatic->getNomUrl(1,'customer'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->town; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->zip; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "<td>".$obj->state_name."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print '<td align="center">'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print '<td align="center">'; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Payment mode - if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) - { - print '<td>'; - $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Amount HT - if (! empty($arrayfields['f.total_ht']['checked'])) - { - print '<td align="right">'.price($obj->total_ht)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['f.total_vat']['checked'])) - { - print '<td align="right">'.price($obj->total_vat)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_vat; - } - // Amount LocalTax1 - if (! empty($arrayfields['f.total_localtax1']['checked'])) - { - print '<td align="right">'.price($obj->total_localtax1)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totallocaltax1field']=$totalarray['nbfield']; - $totalarray['totallocaltax1'] += $obj->total_localtax1; - } - // Amount LocalTax2 - if (! empty($arrayfields['f.total_localtax2']['checked'])) - { - print '<td align="right">'.price($obj->total_localtax2)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totallocaltax2field']=$totalarray['nbfield']; - $totalarray['totallocaltax2'] += $obj->total_localtax2; - } - // Amount TTC - if (! empty($arrayfields['f.total_ttc']['checked'])) - { - print '<td align="right">'.price($obj->total_ttc)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } - - if (! empty($arrayfields['dynamount_payed']['checked'])) - { - print '<td align="right">'.(! empty($totalpay)?price($totalpay,0,$langs):' ').'</td>'; // TODO Use a denormalized field - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalamfield']=$totalarray['nbfield']; - $totalarray['totalam'] += $totalpay; - } - - if (! empty($arrayfields['rtp']['checked'])) - { - print '<td align="right">'.(! empty($remaintopay)?price($remaintopay,0,$langs):' ').'</td>'; // TODO Use a denormalized field - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; - $totalarray['totalrtp'] += $remaintopay; - } - - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } - } - // 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['f.datec']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['f.tms']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['f.fk_statut']['checked'])) - { - print '<td align="right" class="nowrap">'; - print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5,$paiement,$obj->type); - print "</td>"; - if (! $i) $totalarray['nbfield']++; - } - - // Action column - print '<td class="nowrap" align="center">'; - 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->id, $arrayofselected)) $selected=1; - print '<input id="cb'.$obj->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->id.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>' ; - if (! $i) $totalarray['nbfield']++; - - print "</tr>\n"; - - $i++; - } - - // Show total line - if (isset($totalarray['totalhtfield']) + if (! empty($arrayfields['f.date']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->df),'day'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Date limit + if (! empty($arrayfields['f.date_lim_reglement']['checked'])) + { + print '<td align="center" class="nowrap">'.dol_print_date($datelimit,'day'); + if ($facturestatic->hasDelay()) + { + print img_warning($langs->trans('Late')); + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Project + if (! empty($arrayfields['p.ref']['checked'])) + { + print '<td class="nowrap">'; + if ($obj->project_id > 0) + { + $projectstatic->id=$obj->project_id; + $projectstatic->ref=$obj->project_ref; + print $projectstatic->getNomUrl(1); + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Third party + if (! empty($arrayfields['s.nom']['checked'])) + { + print '<td class="tdoverflowmax200">'; + $thirdpartystatic->id=$obj->socid; + $thirdpartystatic->name=$obj->name; + $thirdpartystatic->client=$obj->client; + $thirdpartystatic->code_client=$obj->code_client; + $thirdpartystatic->email=$obj->email; + print $thirdpartystatic->getNomUrl(1,'customer'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) + { + print '<td class="nocellnopadd">'; + print $obj->town; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print '<td class="nocellnopadd">'; + print $obj->zip; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "<td>".$obj->state_name."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print '<td align="center">'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print '<td align="center">'; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Payment mode + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) + { + print '<td>'; + $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Amount HT + if (! empty($arrayfields['f.total_ht']['checked'])) + { + print '<td align="right">'.price($obj->total_ht)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['f.total_vat']['checked'])) + { + print '<td align="right">'.price($obj->total_vat)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_vat; + } + // Amount LocalTax1 + if (! empty($arrayfields['f.total_localtax1']['checked'])) + { + print '<td align="right">'.price($obj->total_localtax1)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totallocaltax1field']=$totalarray['nbfield']; + $totalarray['totallocaltax1'] += $obj->total_localtax1; + } + // Amount LocalTax2 + if (! empty($arrayfields['f.total_localtax2']['checked'])) + { + print '<td align="right">'.price($obj->total_localtax2)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totallocaltax2field']=$totalarray['nbfield']; + $totalarray['totallocaltax2'] += $obj->total_localtax2; + } + // Amount TTC + if (! empty($arrayfields['f.total_ttc']['checked'])) + { + print '<td align="right">'.price($obj->total_ttc)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } + + if (! empty($arrayfields['dynamount_payed']['checked'])) + { + print '<td align="right">'.(! empty($totalpay)?price($totalpay,0,$langs):' ').'</td>'; // TODO Use a denormalized field + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalamfield']=$totalarray['nbfield']; + $totalarray['totalam'] += $totalpay; + } + + if (! empty($arrayfields['rtp']['checked'])) + { + print '<td align="right">'.(! empty($remaintopay)?price($remaintopay,0,$langs):' ').'</td>'; // TODO Use a denormalized field + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; + $totalarray['totalrtp'] += $remaintopay; + } + + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } + } + // 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['f.datec']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['f.tms']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['f.fk_statut']['checked'])) + { + print '<td align="right" class="nowrap">'; + print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5,$paiement,$obj->type); + print "</td>"; + if (! $i) $totalarray['nbfield']++; + } + + // Action column + print '<td class="nowrap" align="center">'; + 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->id, $arrayofselected)) $selected=1; + print '<input id="cb'.$obj->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->id.'"'.($selected?' checked="checked"':'').'>'; + } + print '</td>' ; + if (! $i) $totalarray['nbfield']++; + + print "</tr>\n"; + + $i++; + } + + // Show total line + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totallocaltax1field']) || isset($totalarray['totallocaltax2field']) @@ -1203,62 +1203,62 @@ if ($resql) || isset($totalarray['totalamfield']) || isset($totalarray['totalrtpfield']) ) - { - print '<tr class="liste_total">'; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; - else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; - } - elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; - elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; - elseif ($totalarray['totallocaltax1field'] == $i) print '<td align="right">'.price($totalarray['totallocaltax1']).'</td>'; - elseif ($totalarray['totallocaltax2field'] == $i) print '<td align="right">'.price($totalarray['totallocaltax2']).'</td>'; - elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; - elseif ($totalarray['totalamfield'] == $i) print '<td align="right">'.price($totalarray['totalam']).'</td>'; - elseif ($totalarray['totalrtpfield'] == $i) print '<td align="right">'.price($totalarray['totalrtp']).'</td>'; - else print '<td></td>'; - } - print '</tr>'; - - } - } - - $db->free($resql); + { + print '<tr class="liste_total">'; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; + else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; + } + elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; + elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; + elseif ($totalarray['totallocaltax1field'] == $i) print '<td align="right">'.price($totalarray['totallocaltax1']).'</td>'; + elseif ($totalarray['totallocaltax2field'] == $i) print '<td align="right">'.price($totalarray['totallocaltax2']).'</td>'; + elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; + elseif ($totalarray['totalamfield'] == $i) print '<td align="right">'.price($totalarray['totalam']).'</td>'; + elseif ($totalarray['totalrtpfield'] == $i) print '<td align="right">'.price($totalarray['totalrtp']).'</td>'; + else print '<td></td>'; + } + print '</tr>'; + + } + } + + $db->free($resql); $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); $reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print "</table>\n"; - print '</div>'; - - print "</form>\n"; - - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) - { - // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); - - $filedir=$diroutputmassaction; - $genallowed=$user->rights->facture->lire; - $delallowed=$user->rights->facture->lire; - - print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; - } + print '</div>'; + + print "</form>\n"; + + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); + + $filedir=$diroutputmassaction; + $genallowed=$user->rights->facture->lire; + $delallowed=$user->rights->facture->lire; + + print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; + } } else { - dol_print_error($db); + dol_print_error($db); } llxFooter(); diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index 4ba38dd17f623be8a1734397f3c00ccdab5e91ef..188b0236e5f575a11dbe3f0ca47d583481e580cf 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -42,418 +42,418 @@ class BonPrelevement extends CommonObject public $table_element='prelevement_bons'; public $picto = 'payment'; - var $date_echeance; - var $raison_sociale; - var $reference_remise; - var $emetteur_code_guichet; - var $emetteur_numero_compte; - var $emetteur_code_banque; - var $emetteur_number_key; - - var $emetteur_iban; - var $emetteur_bic; - var $emetteur_ics; - - var $total; - var $_fetched; - var $statut; // 0-Wait, 1-Trans, 2-Done - var $labelstatut=array(); - - var $invoice_in_error=array(); + var $date_echeance; + var $raison_sociale; + var $reference_remise; + var $emetteur_code_guichet; + var $emetteur_numero_compte; + var $emetteur_code_banque; + var $emetteur_number_key; + + var $emetteur_iban; + var $emetteur_bic; + var $emetteur_ics; + + var $total; + var $_fetched; + var $statut; // 0-Wait, 1-Trans, 2-Done + var $labelstatut=array(); + + var $invoice_in_error=array(); var $thirdparty_in_error=array(); - /** - * Constructor - * - * @param DoliDB $db Database handler - * @param string $filename Filename of withdraw receipt - */ - function __construct($db, $filename='') - { - global $conf,$langs; + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $filename Filename of withdraw receipt + */ + function __construct($db, $filename='') + { + global $conf,$langs; - $error = 0; - $this->db = $db; + $error = 0; + $this->db = $db; - $this->filename=$filename; + $this->filename=$filename; - $this->date_echeance = time(); - $this->raison_sociale = ""; - $this->reference_remise = ""; + $this->date_echeance = time(); + $this->raison_sociale = ""; + $this->reference_remise = ""; - $this->emetteur_code_guichet = ""; - $this->emetteur_numero_compte = ""; - $this->emetteur_code_banque = ""; - $this->emetteur_number_key = ""; + $this->emetteur_code_guichet = ""; + $this->emetteur_numero_compte = ""; + $this->emetteur_code_banque = ""; + $this->emetteur_number_key = ""; - $this->emetteur_iban = ""; - $this->emetteur_bic = ""; - $this->emetteur_ics = ""; + $this->emetteur_iban = ""; + $this->emetteur_bic = ""; + $this->emetteur_ics = ""; - $this->factures = array(); + $this->factures = array(); - $this->methodes_trans = array(); + $this->methodes_trans = array(); - $this->methodes_trans[0] = "Internet"; + $this->methodes_trans[0] = "Internet"; - $this->_fetched = 0; + $this->_fetched = 0; - $langs->load("withdrawals"); - $this->labelstatut[0]=$langs->trans("StatusWaiting"); - $this->labelstatut[1]=$langs->trans("StatusTrans"); - $this->labelstatut[2]=$langs->trans("StatusCredited"); + $langs->load("withdrawals"); + $this->labelstatut[0]=$langs->trans("StatusWaiting"); + $this->labelstatut[1]=$langs->trans("StatusTrans"); + $this->labelstatut[2]=$langs->trans("StatusCredited"); - return 1; - } + return 1; + } - /** - * Add invoice to withdrawal - * - * @param int $facture_id id invoice to add - * @param int $client_id id invoice customer - * @param string $client_nom customer name - * @param int $amount amount of invoice - * @param string $code_banque code of bank withdrawal - * @param string $code_guichet code of bank's office - * @param string $number bank account number - * @param string $number_key number key of account number - * @return int >0 if OK, <0 if KO - */ - function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) - { - $result = 0; - $line_id = 0; + /** + * Add invoice to withdrawal + * + * @param int $facture_id id invoice to add + * @param int $client_id id invoice customer + * @param string $client_nom customer name + * @param int $amount amount of invoice + * @param string $code_banque code of bank withdrawal + * @param string $code_guichet code of bank's office + * @param string $number bank account number + * @param string $number_key number key of account number + * @return int >0 if OK, <0 if KO + */ + function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) + { + $result = 0; + $line_id = 0; + + $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key); + + if ($result == 0) + { + if ($line_id > 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture ("; + $sql.= "fk_facture"; + $sql.= ",fk_prelevement_lignes"; + $sql.= ") VALUES ("; + $sql.= $facture_id; + $sql.= ", ".$line_id; + $sql.= ")"; + + if ($this->db->query($sql)) + { + $result = 0; + } + else + { + $result = -1; + dol_syslog(get_class($this)."::AddFacture Erreur $result"); + } + } + else + { + $result = -2; + dol_syslog(get_class($this)."::AddFacture Erreur $result"); + } + } + else + { + $result = -3; + dol_syslog(get_class($this)."::AddFacture Erreur $result"); + } - $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key); + return $result; - if ($result == 0) - { - if ($line_id > 0) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture ("; - $sql.= "fk_facture"; - $sql.= ",fk_prelevement_lignes"; - $sql.= ") VALUES ("; - $sql.= $facture_id; - $sql.= ", ".$line_id; - $sql.= ")"; - - if ($this->db->query($sql)) - { - $result = 0; - } - else - { - $result = -1; - dol_syslog(get_class($this)."::AddFacture Erreur $result"); - } - } - else - { - $result = -2; - dol_syslog(get_class($this)."::AddFacture Erreur $result"); - } - } - else - { - $result = -3; - dol_syslog(get_class($this)."::AddFacture Erreur $result"); - } - - return $result; - - } - - /** - * Add line to withdrawal - * - * @param int $line_id id line to add - * @param int $client_id id invoice customer - * @param string $client_nom customer name - * @param int $amount amount of invoice - * @param string $code_banque code of bank withdrawal - * @param string $code_guichet code of bank's office - * @param string $number bank account number - * @param string $number_key number key of account number - * @return int >0 if OK, <0 if KO - */ - function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) - { - $result = -1; - $concat = 0; - - if ($concat == 1) - { - /* + } + + /** + * Add line to withdrawal + * + * @param int $line_id id line to add + * @param int $client_id id invoice customer + * @param string $client_nom customer name + * @param int $amount amount of invoice + * @param string $code_banque code of bank withdrawal + * @param string $code_guichet code of bank's office + * @param string $number bank account number + * @param string $number_key number key of account number + * @return int >0 if OK, <0 if KO + */ + function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) + { + $result = -1; + $concat = 0; + + if ($concat == 1) + { + /* * We aggregate the lines */ - $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_lignes"; - $sql.= " WHERE fk_prelevement_bons = ".$this->id; - $sql.= " AND fk_soc =".$client_id; - $sql.= " AND code_banque ='".$code_banque."'"; - $sql.= " AND code_guichet ='".$code_guichet."'"; - $sql.= " AND number ='".$number."'"; - - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - } - else - { - $result = -1; - } - } - else - { - /* + $sql = "SELECT rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_lignes"; + $sql.= " WHERE fk_prelevement_bons = ".$this->id; + $sql.= " AND fk_soc =".$client_id; + $sql.= " AND code_banque ='".$code_banque."'"; + $sql.= " AND code_guichet ='".$code_guichet."'"; + $sql.= " AND number ='".$number."'"; + + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + } + else + { + $result = -1; + } + } + else + { + /* * No aggregate */ - $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes ("; - $sql.= "fk_prelevement_bons"; - $sql.= ", fk_soc"; - $sql.= ", client_nom"; - $sql.= ", amount"; - $sql.= ", code_banque"; - $sql.= ", code_guichet"; - $sql.= ", number"; - $sql.= ", cle_rib"; - $sql.= ") VALUES ("; - $sql.= $this->id; - $sql.= ", ".$client_id; - $sql.= ", '".$this->db->escape($client_nom)."'"; - $sql.= ", '".price2num($amount)."'"; - $sql.= ", '".$code_banque."'"; - $sql.= ", '".$code_guichet."'"; - $sql.= ", '".$number."'"; - $sql.= ", '".$number_key."'"; - $sql.= ")"; - - if ($this->db->query($sql)) - { - $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes"); - $result = 0; - } - else - { - dol_syslog(get_class($this)."::addline Error -2"); - $result = -2; - } - - } - - return $result; - } - - /** - * Return error string - * - * @param int $error Id of error - * @return string Error string - */ - function getErrorString($error) - { - global $langs; - - $errors = array(); - - $errors[1027] = $langs->trans("DateInvalid"); - - return $errors[abs($error)]; - } - - /** - * Get object and lines from database - * - * @param int $rowid Id of object to load - * @param string $ref Ref of direct debit - * @return int >0 if OK, <0 if KO - */ - function fetch($rowid, $ref='') - { - global $conf; - - $sql = "SELECT p.rowid, p.ref, p.amount, p.note"; - $sql.= ", p.datec as dc"; - $sql.= ", p.date_trans as date_trans"; - $sql.= ", p.method_trans, p.fk_user_trans"; - $sql.= ", p.date_credit as date_credit"; - $sql.= ", p.fk_user_credit"; - $sql.= ", p.statut"; - $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; - $sql.= " WHERE p.entity = ".$conf->entity; - if ($rowid > 0) $sql.= " AND p.rowid = ".$rowid; - else $sql.= " AND p.ref = '".$this->db->escape($ref)."'"; - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - - $this->id = $obj->rowid; - $this->ref = $obj->ref; - $this->amount = $obj->amount; - $this->note = $obj->note; - $this->datec = $this->db->jdate($obj->dc); - - $this->date_trans = $this->db->jdate($obj->date_trans); - $this->method_trans = $obj->method_trans; - $this->user_trans = $obj->fk_user_trans; - - $this->date_credit = $this->db->jdate($obj->date_credit); - $this->user_credit = $obj->fk_user_credit; - - $this->statut = $obj->statut; - - $this->_fetched = 1; - - return 0; - } - else - { - dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee"); - return -1; - } - } - else - { - return -2; - } - } - - /** - * Set credite and set status of linked invoices. Still used ?? - * - * @return int <0 if KO, >=0 if OK - */ - function set_credite() - { - global $user,$conf; - - $error = 0; - - if ($this->db->begin()) - { - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; - $sql.= " SET statut = 1"; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; - - $result=$this->db->query($sql); - if (! $result) - { - dol_syslog(get_class($this)."::set_credite Erreur 1"); - $error++; - } - - if (! $error) - { - $facs = array(); - $facs = $this->getListInvoices(); - - $num=count($facs); - for ($i = 0; $i < $num; $i++) - { - /* Tag invoice as payed */ - dol_syslog(get_class($this)."::set_credite set_paid fac ".$facs[$i]); - $fac = new Facture($this->db); - $fac->fetch($facs[$i]); - $result = $fac->set_paid($user); - } - } - - if (! $error) - { - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; - $sql.= " SET statut = 2"; - $sql.= " WHERE fk_prelevement_bons = ".$this->id; - - if (! $this->db->query($sql)) - { - dol_syslog(get_class($this)."::set_credite Erreur 1"); - $error++; - } - } - - /* + $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes ("; + $sql.= "fk_prelevement_bons"; + $sql.= ", fk_soc"; + $sql.= ", client_nom"; + $sql.= ", amount"; + $sql.= ", code_banque"; + $sql.= ", code_guichet"; + $sql.= ", number"; + $sql.= ", cle_rib"; + $sql.= ") VALUES ("; + $sql.= $this->id; + $sql.= ", ".$client_id; + $sql.= ", '".$this->db->escape($client_nom)."'"; + $sql.= ", '".price2num($amount)."'"; + $sql.= ", '".$code_banque."'"; + $sql.= ", '".$code_guichet."'"; + $sql.= ", '".$number."'"; + $sql.= ", '".$number_key."'"; + $sql.= ")"; + + if ($this->db->query($sql)) + { + $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes"); + $result = 0; + } + else + { + dol_syslog(get_class($this)."::addline Error -2"); + $result = -2; + } + + } + + return $result; + } + + /** + * Return error string + * + * @param int $error Id of error + * @return string Error string + */ + function getErrorString($error) + { + global $langs; + + $errors = array(); + + $errors[1027] = $langs->trans("DateInvalid"); + + return $errors[abs($error)]; + } + + /** + * Get object and lines from database + * + * @param int $rowid Id of object to load + * @param string $ref Ref of direct debit + * @return int >0 if OK, <0 if KO + */ + function fetch($rowid, $ref='') + { + global $conf; + + $sql = "SELECT p.rowid, p.ref, p.amount, p.note"; + $sql.= ", p.datec as dc"; + $sql.= ", p.date_trans as date_trans"; + $sql.= ", p.method_trans, p.fk_user_trans"; + $sql.= ", p.date_credit as date_credit"; + $sql.= ", p.fk_user_credit"; + $sql.= ", p.statut"; + $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; + $sql.= " WHERE p.entity = ".$conf->entity; + if ($rowid > 0) $sql.= " AND p.rowid = ".$rowid; + else $sql.= " AND p.ref = '".$this->db->escape($ref)."'"; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + + $this->id = $obj->rowid; + $this->ref = $obj->ref; + $this->amount = $obj->amount; + $this->note = $obj->note; + $this->datec = $this->db->jdate($obj->dc); + + $this->date_trans = $this->db->jdate($obj->date_trans); + $this->method_trans = $obj->method_trans; + $this->user_trans = $obj->fk_user_trans; + + $this->date_credit = $this->db->jdate($obj->date_credit); + $this->user_credit = $obj->fk_user_credit; + + $this->statut = $obj->statut; + + $this->_fetched = 1; + + return 0; + } + else + { + dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee"); + return -1; + } + } + else + { + return -2; + } + } + + /** + * Set credite and set status of linked invoices. Still used ?? + * + * @return int <0 if KO, >=0 if OK + */ + function set_credite() + { + global $user,$conf; + + $error = 0; + + if ($this->db->begin()) + { + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; + $sql.= " SET statut = 1"; + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; + + $result=$this->db->query($sql); + if (! $result) + { + dol_syslog(get_class($this)."::set_credite Erreur 1"); + $error++; + } + + if (! $error) + { + $facs = array(); + $facs = $this->getListInvoices(); + + $num=count($facs); + for ($i = 0; $i < $num; $i++) + { + /* Tag invoice as payed */ + dol_syslog(get_class($this)."::set_credite set_paid fac ".$facs[$i]); + $fac = new Facture($this->db); + $fac->fetch($facs[$i]); + $result = $fac->set_paid($user); + } + } + + if (! $error) + { + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; + $sql.= " SET statut = 2"; + $sql.= " WHERE fk_prelevement_bons = ".$this->id; + + if (! $this->db->query($sql)) + { + dol_syslog(get_class($this)."::set_credite Erreur 1"); + $error++; + } + } + + /* * End of procedure */ - if (! $error) - { - $this->db->commit(); - return 0; - } - else - { - $this->db->rollback(); - dol_syslog(get_class($this)."::set_credite ROLLBACK "); - - return -1; - } - } - else - { - dol_syslog(get_class($this)."::set_credite Ouverture transaction SQL impossible "); - return -2; - } - } - - /** - * Set direct debit order to "credited" status. - * - * @param User $user Id of user - * @param int $date date of action - * @return int >0 if OK, <0 if KO - */ - function set_infocredit($user, $date) - { - global $conf,$langs; - - $error = 0; - - if ($this->_fetched == 1) - { - if ($date >= $this->date_trans) - { - if ($this->db->begin()) - { - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; - $sql.= " SET fk_user_credit = ".$user->id; - $sql.= ", statut = 2"; - $sql.= ", date_credit = '".$this->db->idate($date)."'"; - $sql.= " WHERE rowid=".$this->id; - $sql.= " AND entity = ".$conf->entity; - $sql.= " AND statut = 1"; - - if ($this->db->query($sql)) - { - - $langs->load('withdrawals'); - $subject = $langs->trans("InfoCreditSubject", $this->ref); - $message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date,'dayhour')); - - //Add payment of withdrawal into bank - $bankaccount = $conf->global->PRELEVEMENT_ID_BANKACCOUNT; - $facs = array(); - $amounts = array(); - $amountsperthirdparty = array(); - - $facs = $this->getListInvoices(1); - - // Loop on each invoice. $facs=array(0=>id, 1=>amount requested) - $num=count($facs); - for ($i = 0; $i < $num; $i++) - { - $fac = new Facture($this->db); - $fac->fetch($facs[$i][0]); - $amounts[$fac->id] = $facs[$i][1]; - $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1]; + if (! $error) + { + $this->db->commit(); + return 0; + } + else + { + $this->db->rollback(); + dol_syslog(get_class($this)."::set_credite ROLLBACK "); + + return -1; + } + } + else + { + dol_syslog(get_class($this)."::set_credite Ouverture transaction SQL impossible "); + return -2; + } + } + + /** + * Set direct debit order to "credited" status. + * + * @param User $user Id of user + * @param int $date date of action + * @return int >0 if OK, <0 if KO + */ + function set_infocredit($user, $date) + { + global $conf,$langs; + + $error = 0; + + if ($this->_fetched == 1) + { + if ($date >= $this->date_trans) + { + if ($this->db->begin()) + { + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; + $sql.= " SET fk_user_credit = ".$user->id; + $sql.= ", statut = 2"; + $sql.= ", date_credit = '".$this->db->idate($date)."'"; + $sql.= " WHERE rowid=".$this->id; + $sql.= " AND entity = ".$conf->entity; + $sql.= " AND statut = 1"; + + if ($this->db->query($sql)) + { + + $langs->load('withdrawals'); + $subject = $langs->trans("InfoCreditSubject", $this->ref); + $message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date,'dayhour')); + + //Add payment of withdrawal into bank + $bankaccount = $conf->global->PRELEVEMENT_ID_BANKACCOUNT; + $facs = array(); + $amounts = array(); + $amountsperthirdparty = array(); + + $facs = $this->getListInvoices(1); + + // Loop on each invoice. $facs=array(0=>id, 1=>amount requested) + $num=count($facs); + for ($i = 0; $i < $num; $i++) + { + $fac = new Facture($this->db); + $fac->fetch($facs[$i][0]); + $amounts[$fac->id] = $facs[$i][1]; + $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1]; $totalpaye = $fac->getSommePaiement(); $totalcreditnotes = $fac->getSumCreditNotesUsed(); @@ -463,442 +463,442 @@ class BonPrelevement extends CommonObject if (price2num($alreadypayed + $facs[$i][1], 'MT') == $fac->total_ttc) { $result = $fac->set_paid($user); } - } - - // Make one payment per customer - foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts) - { - $paiement = new Paiement($this->db); - $paiement->datepaye = $date; - $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice - $paiement->paiementid = 3; // - $paiement->num_paiement = $this->ref; // Set ref of direct debit note + } + + // Make one payment per customer + foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts) + { + $paiement = new Paiement($this->db); + $paiement->datepaye = $date; + $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice + $paiement->paiementid = 3; // + $paiement->num_paiement = $this->ref; // Set ref of direct debit note $paiement->id_prelevement = $this->id; - $paiement_id = $paiement->create($user); - if ($paiement_id < 0) - { - dol_syslog(get_class($this)."::set_infocredit AddPayment Error"); - $error++; - } - else - { - $result=$paiement->addPaymentToBank($user,'payment','(WithdrawalPayment)',$bankaccount,'',''); - if ($result < 0) - { - dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error"); - $error++; - } - } - //var_dump($paiement->amounts); - //var_dump($thirdpartyid); - //var_dump($cursoramounts); - } + $paiement_id = $paiement->create($user); + if ($paiement_id < 0) + { + dol_syslog(get_class($this)."::set_infocredit AddPayment Error"); + $error++; + } + else + { + $result=$paiement->addPaymentToBank($user,'payment','(WithdrawalPayment)',$bankaccount,'',''); + if ($result < 0) + { + dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error"); + $error++; + } + } + //var_dump($paiement->amounts); + //var_dump($thirdpartyid); + //var_dump($cursoramounts); + } // Update withdrawal line - // TODO: Translate to ligneprelevement.class.php - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; - $sql.= " SET statut = 2"; - $sql.= " WHERE fk_prelevement_bons = ".$this->id; - - if (! $this->db->query($sql)) - { - dol_syslog(get_class($this)."::set_infocredit Update lines Error"); - $error++; - } - - } - else - { - dol_syslog(get_class($this)."::set_infocredit Update Bons Error"); - $error++; - } - - /* + // TODO: Translate to ligneprelevement.class.php + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; + $sql.= " SET statut = 2"; + $sql.= " WHERE fk_prelevement_bons = ".$this->id; + + if (! $this->db->query($sql)) + { + dol_syslog(get_class($this)."::set_infocredit Update lines Error"); + $error++; + } + + } + else + { + dol_syslog(get_class($this)."::set_infocredit Update Bons Error"); + $error++; + } + + /* * End of procedure */ - if ($error == 0) - { - $this->db->commit(); - return 0; - } - else - { - $this->db->rollback(); - dol_syslog("bon-prelevment::set_infocredit ROLLBACK "); - return -1; - } - } - else - { - dol_syslog(get_class($this)."::set_infocredit 1025 Open SQL transaction impossible "); - return -1025; - } - } - else - { - dol_syslog("bon-prelevment::set_infocredit 1027 Date de credit < Date de trans "); - return -1027; - } - } - else - { - return -1026; - } - } - - /** - * Set withdrawal to transmited status - * - * @param User $user id of user - * @param int $date date of action - * @param string $method method of transmision to bank - * @return int >0 if OK, <0 if KO - */ - function set_infotrans($user, $date, $method) - { - global $conf,$langs; - - $error = 0; - - dol_syslog(get_class($this)."::set_infotrans Start",LOG_INFO); - if ($this->db->begin()) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; - $sql.= " SET fk_user_trans = ".$user->id; - $sql.= " , date_trans = '".$this->db->idate($date)."'"; - $sql.= " , method_trans = ".$method; - $sql.= " , statut = 1"; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; - $sql.= " AND statut = 0"; - - if ($this->db->query($sql)) - { - $this->method_trans = $method; - $langs->load('withdrawals'); - $subject = $langs->trans("InfoTransSubject", $this->ref); - $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname)); - $message .=$langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date,'day')); - - // TODO Call trigger to create a notification using notification module - } - else - { - $error++; - } - - if ($error == 0) - { - $this->db->commit(); - return 0; - } - else - { - $this->db->rollback(); - dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR); - - return -1; - } - } - else - { + if ($error == 0) + { + $this->db->commit(); + return 0; + } + else + { + $this->db->rollback(); + dol_syslog("bon-prelevment::set_infocredit ROLLBACK "); + return -1; + } + } + else + { + dol_syslog(get_class($this)."::set_infocredit 1025 Open SQL transaction impossible "); + return -1025; + } + } + else + { + dol_syslog("bon-prelevment::set_infocredit 1027 Date de credit < Date de trans "); + return -1027; + } + } + else + { + return -1026; + } + } + + /** + * Set withdrawal to transmited status + * + * @param User $user id of user + * @param int $date date of action + * @param string $method method of transmision to bank + * @return int >0 if OK, <0 if KO + */ + function set_infotrans($user, $date, $method) + { + global $conf,$langs; + + $error = 0; + + dol_syslog(get_class($this)."::set_infotrans Start",LOG_INFO); + if ($this->db->begin()) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; + $sql.= " SET fk_user_trans = ".$user->id; + $sql.= " , date_trans = '".$this->db->idate($date)."'"; + $sql.= " , method_trans = ".$method; + $sql.= " , statut = 1"; + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; + $sql.= " AND statut = 0"; + + if ($this->db->query($sql)) + { + $this->method_trans = $method; + $langs->load('withdrawals'); + $subject = $langs->trans("InfoTransSubject", $this->ref); + $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname)); + $message .=$langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date,'day')); + + // TODO Call trigger to create a notification using notification module + } + else + { + $error++; + } - dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT); - return -2; - } - } + if ($error == 0) + { + $this->db->commit(); + return 0; + } + else + { + $this->db->rollback(); + dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR); + + return -1; + } + } + else + { - /** - * Get invoice list - * - * @param int $amounts If you want to get the amount of the order for each invoice - * @return array Id of invoices - */ - private function getListInvoices($amounts=0) - { - global $conf; + dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT); + return -2; + } + } - $arr = array(); + /** + * Get invoice list + * + * @param int $amounts If you want to get the amount of the order for each invoice + * @return array Id of invoices + */ + private function getListInvoices($amounts=0) + { + global $conf; + + $arr = array(); - /* + /* * Returns all invoices presented * within a withdrawal receipt */ - $sql = "SELECT fk_facture"; - if ($amounts) $sql .= ", SUM(pl.amount)"; - $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; - $sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; - $sql.= " , ".MAIN_DB_PREFIX."prelevement_facture as pf"; - $sql.= " WHERE pf.fk_prelevement_lignes = pl.rowid"; - $sql.= " AND pl.fk_prelevement_bons = p.rowid"; - $sql.= " AND p.rowid = ".$this->id; - $sql.= " AND p.entity = ".$conf->entity; - if ($amounts) $sql.= " GROUP BY fk_facture"; - - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - - if ($num) - { - $i = 0; - while ($i < $num) - { - $row = $this->db->fetch_row($resql); - if (!$amounts) $arr[$i] = $row[0]; - else - { - $arr[$i] = array( - $row[0], - $row[1] - ); - } - $i++; - } - } - $this->db->free($resql); - } - else - { - dol_syslog(get_class($this)."::getListInvoices Erreur"); - } - - return $arr; - } - - /** - * Returns amount of withdrawal - * - * @return double Total amount - */ - function SommeAPrelever() - { - global $conf; - - $sql = "SELECT sum(pfd.amount) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //$sql.= " ,".MAIN_DB_PREFIX."c_paiement as cp"; - $sql.= " WHERE f.fk_statut = 1"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND f.rowid = pfd.fk_facture"; - $sql.= " AND f.paye = 0"; - $sql.= " AND pfd.traite = 0"; - $sql.= " AND f.total_ttc > 0"; - - $resql = $this->db->query($sql); - if ( $resql ) - { - $obj = $this->db->fetch_object($resql); + $sql = "SELECT fk_facture"; + if ($amounts) $sql .= ", SUM(pl.amount)"; + $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; + $sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; + $sql.= " , ".MAIN_DB_PREFIX."prelevement_facture as pf"; + $sql.= " WHERE pf.fk_prelevement_lignes = pl.rowid"; + $sql.= " AND pl.fk_prelevement_bons = p.rowid"; + $sql.= " AND p.rowid = ".$this->id; + $sql.= " AND p.entity = ".$conf->entity; + if ($amounts) $sql.= " GROUP BY fk_facture"; - $this->db->free($resql); + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); - return $obj->nb; - } - else - { - $error = 1; - dol_syslog(get_class($this)."::SommeAPrelever Erreur -1"); - dol_syslog($this->db->error()); - } - } - - /** - * Get number of invoices to withdrawal - * TODO delete params banque and agence when not necesary - * - * @param int $banque dolibarr mysoc bank - * @param int $agence dolibarr mysoc agence - * @return int <O if KO, number of invoices if OK - */ - function NbFactureAPrelever($banque=0,$agence=0) - { - global $conf; - - $sql = "SELECT count(f.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //if ($banque || $agence) $sql.=", ".MAIN_DB_PREFIX."societe_rib as sr"; - $sql.= " WHERE f.fk_statut = 1"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND f.rowid = pfd.fk_facture"; - $sql.= " AND f.paye = 0"; - $sql.= " AND pfd.traite = 0"; - $sql.= " AND f.total_ttc > 0"; - //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid"; - //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; - //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; - - dol_syslog(get_class($this)."::SommeAPrelever"); - $resql = $this->db->query($sql); - - if ( $resql ) - { - $obj = $this->db->fetch_object($resql); + if ($num) + { + $i = 0; + while ($i < $num) + { + $row = $this->db->fetch_row($resql); + if (!$amounts) $arr[$i] = $row[0]; + else + { + $arr[$i] = array( + $row[0], + $row[1] + ); + } + $i++; + } + } + $this->db->free($resql); + } + else + { + dol_syslog(get_class($this)."::getListInvoices Erreur"); + } - $this->db->free($resql); + return $arr; + } - return $obj->nb; - } - else - { - $this->error=get_class($this)."::SommeAPrelever Erreur -1 sql=".$this->db->error(); - return -1; - } - } + /** + * Returns amount of withdrawal + * + * @return double Total amount + */ + function SommeAPrelever() + { + global $conf; + $sql = "SELECT sum(pfd.amount) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,"; + $sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + //$sql.= " ,".MAIN_DB_PREFIX."c_paiement as cp"; + $sql.= " WHERE f.fk_statut = 1"; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND f.rowid = pfd.fk_facture"; + $sql.= " AND f.paye = 0"; + $sql.= " AND pfd.traite = 0"; + $sql.= " AND f.total_ttc > 0"; + + $resql = $this->db->query($sql); + if ( $resql ) + { + $obj = $this->db->fetch_object($resql); - /** - * Create a withdraw - * TODO delete params banque and agence when not necesary - * - * @param int $banque dolibarr mysoc bank - * @param int $agence dolibarr mysoc bank office (guichet) - * @param string $mode real=do action, simu=test only - * @param string $format FRST, RCUR or ALL - * @return int <0 if KO, nbre of invoice withdrawed if OK - */ - function Create($banque=0, $agence=0, $mode='real', $format='ALL') - { - global $conf,$langs; + $this->db->free($resql); - dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence." mode=".$mode." format=".$format, LOG_DEBUG); + return $obj->nb; + } + else + { + $error = 1; + dol_syslog(get_class($this)."::SommeAPrelever Erreur -1"); + dol_syslog($this->db->error()); + } + } - require_once (DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"); - require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); + /** + * Get number of invoices to withdrawal + * TODO delete params banque and agence when not necesary + * + * @param int $banque dolibarr mysoc bank + * @param int $agence dolibarr mysoc agence + * @return int <O if KO, number of invoices if OK + */ + function NbFactureAPrelever($banque=0,$agence=0) + { + global $conf; - if (empty($format)) return 'ErrorBadParametersForDirectDebitFileCreate'; + $sql = "SELECT count(f.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + //if ($banque || $agence) $sql.=", ".MAIN_DB_PREFIX."societe_rib as sr"; + $sql.= " WHERE f.fk_statut = 1"; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND f.rowid = pfd.fk_facture"; + $sql.= " AND f.paye = 0"; + $sql.= " AND pfd.traite = 0"; + $sql.= " AND f.total_ttc > 0"; + //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid"; + //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; + //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; + + dol_syslog(get_class($this)."::SommeAPrelever"); + $resql = $this->db->query($sql); + + if ( $resql ) + { + $obj = $this->db->fetch_object($resql); - $error = 0; + $this->db->free($resql); - $datetimeprev = time(); + return $obj->nb; + } + else + { + $this->error=get_class($this)."::SommeAPrelever Erreur -1 sql=".$this->db->error(); + return -1; + } + } - $month = strftime("%m", $datetimeprev); - $year = strftime("%Y", $datetimeprev); - $puser = new User($this->db, $conf->global->PRELEVEMENT_USER); + /** + * Create a withdraw + * TODO delete params banque and agence when not necesary + * + * @param int $banque dolibarr mysoc bank + * @param int $agence dolibarr mysoc bank office (guichet) + * @param string $mode real=do action, simu=test only + * @param string $format FRST, RCUR or ALL + * @return int <0 if KO, nbre of invoice withdrawed if OK + */ + function Create($banque=0, $agence=0, $mode='real', $format='ALL') + { + global $conf,$langs; - $this->invoice_in_error = array(); - $this->thirdparty_in_error = array(); + dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence." mode=".$mode." format=".$format, LOG_DEBUG); - // Read invoices - $factures = array(); - $factures_prev = array(); - $factures_result = array(); - $factures_prev_id=array(); - $factures_errors=array(); + require_once (DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"); + require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); - if (! $error) - { - $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc"; - $sql.= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib"; - $sql.= ", pfd.amount"; - $sql.= ", s.nom as name"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr"; - $sql.= " WHERE f.rowid = pfd.fk_facture"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND s.rowid = f.fk_soc"; - //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc"; - $sql.= " AND f.fk_statut = 1"; - $sql.= " AND f.paye = 0"; - $sql.= " AND pfd.traite = 0"; - $sql.= " AND f.total_ttc > 0"; - //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; - //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; - - dol_syslog(__METHOD__."::Read invoices, sql=".$sql, LOG_DEBUG); - - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - - while ($i < $num) - { - $row = $this->db->fetch_row($resql); - $factures[$i] = $row; // All fields - $i++; - } - $this->db->free($resql); - dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG); - } - else - { - $error++; - dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR); - } - } - - if (! $error) - { - require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; - $soc = new Societe($this->db); - - // Check RIB - $i = 0; - dol_syslog(__METHOD__."::Check RIB", LOG_DEBUG); - - if (count($factures) > 0) - { - foreach ($factures as $key => $fac) - { - $fact = new Facture($this->db); - if ($fact->fetch($fac[0]) >= 0) // Field 0 of $fac is rowid of invoice - { - if ($soc->fetch($fact->socid) >= 0) - { - $bac = new CompanyBankAccount($this->db); - $bac->fetch(0, $soc->id); - - if ($format == 'FRST' && $bac->frstrecur != 'FRST') continue; - if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR')) continue; - - if ($bac->verif() >= 1) - { - $factures_prev[$i] = $fac; - /* second tableau necessaire pour BonPrelevement */ - $factures_prev_id[$i] = $fac[0]; - $i++; - } - else + if (empty($format)) return 'ErrorBadParametersForDirectDebitFileCreate'; + + $error = 0; + + $datetimeprev = time(); + + $month = strftime("%m", $datetimeprev); + $year = strftime("%Y", $datetimeprev); + + $puser = new User($this->db, $conf->global->PRELEVEMENT_USER); + + $this->invoice_in_error = array(); + $this->thirdparty_in_error = array(); + + // Read invoices + $factures = array(); + $factures_prev = array(); + $factures_result = array(); + $factures_prev_id=array(); + $factures_errors=array(); + + if (! $error) + { + $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc"; + $sql.= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib"; + $sql.= ", pfd.amount"; + $sql.= ", s.nom as name"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql.= ", ".MAIN_DB_PREFIX."societe as s"; + $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr"; + $sql.= " WHERE f.rowid = pfd.fk_facture"; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND s.rowid = f.fk_soc"; + //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc"; + $sql.= " AND f.fk_statut = 1"; + $sql.= " AND f.paye = 0"; + $sql.= " AND pfd.traite = 0"; + $sql.= " AND f.total_ttc > 0"; + //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; + //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; + + dol_syslog(__METHOD__."::Read invoices, sql=".$sql, LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + + while ($i < $num) + { + $row = $this->db->fetch_row($resql); + $factures[$i] = $row; // All fields + $i++; + } + $this->db->free($resql); + dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG); + } + else + { + $error++; + dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR); + } + } + + if (! $error) + { + require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + $soc = new Societe($this->db); + + // Check RIB + $i = 0; + dol_syslog(__METHOD__."::Check RIB", LOG_DEBUG); + + if (count($factures) > 0) + { + foreach ($factures as $key => $fac) + { + $fact = new Facture($this->db); + if ($fact->fetch($fac[0]) >= 0) // Field 0 of $fac is rowid of invoice + { + if ($soc->fetch($fact->socid) >= 0) + { + $bac = new CompanyBankAccount($this->db); + $bac->fetch(0, $soc->id); + + if ($format == 'FRST' && $bac->frstrecur != 'FRST') continue; + if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR')) continue; + + if ($bac->verif() >= 1) + { + $factures_prev[$i] = $fac; + /* second tableau necessaire pour BonPrelevement */ + $factures_prev_id[$i] = $fac[0]; + $i++; + } + else { dol_syslog(__METHOD__."::Check RIB Error on default bank number IBAN/BIC for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_ERR); $this->invoice_in_error[$fac[0]]="Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0); $this->thirdparty_in_error[$soc->id]="Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0); - } - } - else + } + } + else { - dol_syslog(__METHOD__."::Check RIB Failed to read company", LOG_ERR); - } - } - else + dol_syslog(__METHOD__."::Check RIB Failed to read company", LOG_ERR); + } + } + else { - dol_syslog(__METHOD__."::Check RIB Failed to read invoice", LOG_ERR); - } - } - } - else + dol_syslog(__METHOD__."::Check RIB Failed to read invoice", LOG_ERR); + } + } + } + else { - dol_syslog(__METHOD__."::Check RIB No invoice to process", LOG_ERR); - } - } + dol_syslog(__METHOD__."::Check RIB No invoice to process", LOG_ERR); + } + } - $ok=0; + $ok=0; - // Withdraw invoices in factures_prev array - $out=count($factures_prev)." invoices will be withdrawn."; - //print $out."\n"; - dol_syslog($out); + // Withdraw invoices in factures_prev array + $out=count($factures_prev)." invoices will be withdrawn."; + //print $out."\n"; + dol_syslog($out); - // Return warning - /*$i=0; + // Return warning + /*$i=0; foreach ($this->thirdparty_in_error as $key => $val) { if ($i < 10) setEventMessages($val, null, 'warnings'); @@ -906,34 +906,34 @@ class BonPrelevement extends CommonObject $i++; }*/ - if (count($factures_prev) > 0) - { - if ($mode=='real') - { - $ok=1; - } - else - { - print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n"; - } - } - - - if ($ok) - { - /* + if (count($factures_prev) > 0) + { + if ($mode=='real') + { + $ok=1; + } + else + { + print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n"; + } + } + + + if ($ok) + { + /* * We are in real mode. * We create withdraw receipt and build withdraw into disk */ - $this->db->begin(); + $this->db->begin(); - $now=dol_now(); + $now=dol_now(); - /* + /* * Traitements */ - if (!$error) - { + if (!$error) + { $ref = substr($year,-2).$month; $sql = "SELECT substring(ref from char_length(ref) - 1)"; @@ -955,48 +955,48 @@ class BonPrelevement extends CommonObject $this->filename = $dir.'/'.$ref.'.xml'; - // Create withdraw receipt in database - $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons ("; - $sql.= " ref, entity, datec"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->escape($ref)."'"; - $sql.= ", ".$conf->entity; - $sql.= ", '".$this->db->idate($now)."'"; - $sql.= ")"; - - $resql = $this->db->query($sql); - if ($resql) - { - $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons"); + // Create withdraw receipt in database + $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons ("; + $sql.= " ref, entity, datec"; + $sql.= ") VALUES ("; + $sql.= "'".$this->db->escape($ref)."'"; + $sql.= ", ".$conf->entity; + $sql.= ", '".$this->db->idate($now)."'"; + $sql.= ")"; + + $resql = $this->db->query($sql); + if ($resql) + { + $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons"); $this->id = $prev_id; $this->ref = $ref; - } - else + } + else { - $error++; - dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR); - } + $error++; + dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR); + } } else { $error++; dol_syslog(__METHOD__."::Get last withdraw receipt ".$this->db->lasterror(), LOG_ERR); } - } + } - if (!$error) - { - /* + if (!$error) + { + /* * Create withdrawal receipt in database */ - if (count($factures_prev) > 0) - { - foreach ($factures_prev as $fac) // Add a link in database for each invoice - { - // Fetch invoice - $fact = new Facture($this->db); - $fact->fetch($fac[0]); - /* + if (count($factures_prev) > 0) + { + foreach ($factures_prev as $fac) // Add a link in database for each invoice + { + // Fetch invoice + $fact = new Facture($this->db); + $fact->fetch($fac[0]); + /* * Add standing order * * @@ -1008,128 +1008,128 @@ class BonPrelevement extends CommonObject * $fac[8] : client nom * $fac[2] : client id */ - $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]); - if ($ri <> 0) - { - $error++; - } - - // Update invoice requests as done - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande"; - $sql.= " SET traite = 1"; - $sql.= ", date_traite = '".$this->db->idate($now)."'"; - $sql.= ", fk_prelevement_bons = ".$this->id; - $sql.= " WHERE rowid = ".$fac[1]; - - dol_syslog(__METHOD__."::Update Orders::Sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - - if (! $resql) - { - $error++; - dol_syslog(__METHOD__."::Update Orders::Error=".$this->db->error(), LOG_ERR); - } - - } - } - - } - - if (!$error) - { - /* + $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]); + if ($ri <> 0) + { + $error++; + } + + // Update invoice requests as done + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande"; + $sql.= " SET traite = 1"; + $sql.= ", date_traite = '".$this->db->idate($now)."'"; + $sql.= ", fk_prelevement_bons = ".$this->id; + $sql.= " WHERE rowid = ".$fac[1]; + + dol_syslog(__METHOD__."::Update Orders::Sql=".$sql, LOG_DEBUG); + $resql=$this->db->query($sql); + + if (! $resql) + { + $error++; + dol_syslog(__METHOD__."::Update Orders::Error=".$this->db->error(), LOG_ERR); + } + + } + } + + } + + if (!$error) + { + /* * Create direct debit order in a XML file */ - dol_syslog(__METHOD__."::Init withdraw receipt for ".count($factures_prev)." invoices", LOG_DEBUG); + dol_syslog(__METHOD__."::Init withdraw receipt for ".count($factures_prev)." invoices", LOG_DEBUG); - if (count($factures_prev) > 0) - { - $this->date_echeance = $datetimeprev; - $this->reference_remise = $ref; + if (count($factures_prev) > 0) + { + $this->date_echeance = $datetimeprev; + $this->reference_remise = $ref; - $id=$conf->global->PRELEVEMENT_ID_BANKACCOUNT; - $account = new Account($this->db); - if ($account->fetch($id)>0) - { - $this->emetteur_code_banque = $account->code_banque; - $this->emetteur_code_guichet = $account->code_guichet; - $this->emetteur_numero_compte = $account->number; - $this->emetteur_number_key = $account->cle_rib; - $this->emetteur_iban = $account->iban; - $this->emetteur_bic = $account->bic; + $id=$conf->global->PRELEVEMENT_ID_BANKACCOUNT; + $account = new Account($this->db); + if ($account->fetch($id)>0) + { + $this->emetteur_code_banque = $account->code_banque; + $this->emetteur_code_guichet = $account->code_guichet; + $this->emetteur_numero_compte = $account->number; + $this->emetteur_number_key = $account->cle_rib; + $this->emetteur_iban = $account->iban; + $this->emetteur_bic = $account->bic; - $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; + $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; - $this->raison_sociale = $account->proprio; - } + $this->raison_sociale = $account->proprio; + } - $this->factures = $factures_prev_id; + $this->factures = $factures_prev_id; - // Generation of SEPA file $this->filename - $this->generate($format); - } - dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG); - } + // Generation of SEPA file $this->filename + $this->generate($format); + } + dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG); + } //var_dump($factures_prev);exit; - /* + /* * Update total */ - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; - $sql.= " SET amount = ".price2num($this->total); - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; - - $resql=$this->db->query($sql); - if (! $resql) - { - $error++; - dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR); - } - - if (!$error) - { - $this->db->commit(); - } - else - { - $this->db->rollback(); - } - - return count($factures_prev); - } - else - { - return 0; - } - } - - - /** - * Get object and lines from database - * - * @return int >0 if OK, <0 if KO - */ - function delete() - { - $this->db->begin(); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_facture WHERE fk_prelevement_lignes IN (SELECT rowid FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id.")"; - $resql1=$this->db->query($sql); - if (! $resql1) dol_print_error($this->db); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id; - $resql2=$this->db->query($sql); - if (! $resql2) dol_print_error($this->db); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".$this->id; - $resql3=$this->db->query($sql); + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; + $sql.= " SET amount = ".price2num($this->total); + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; + + $resql=$this->db->query($sql); + if (! $resql) + { + $error++; + dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR); + } + + if (!$error) + { + $this->db->commit(); + } + else + { + $this->db->rollback(); + } + + return count($factures_prev); + } + else + { + return 0; + } + } + + + /** + * Get object and lines from database + * + * @return int >0 if OK, <0 if KO + */ + function delete() + { + $this->db->begin(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_facture WHERE fk_prelevement_lignes IN (SELECT rowid FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id.")"; + $resql1=$this->db->query($sql); + if (! $resql1) dol_print_error($this->db); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id; + $resql2=$this->db->query($sql); + if (! $resql2) dol_print_error($this->db); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".$this->id; + $resql3=$this->db->query($sql); if (! $resql3) dol_print_error($this->db); - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".$this->id; - $resql4=$this->db->query($sql); + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".$this->id; + $resql4=$this->db->query($sql); if (! $resql4) dol_print_error($this->db); if ($resql1 && $resql2 && $resql3) @@ -1142,153 +1142,153 @@ class BonPrelevement extends CommonObject $this->db->rollback(); return -1; } - } + } - /** - * Returns clickable name (with picto) - * - * @param int $withpicto link with picto - * @param string $option link target - * @return string URL of target - */ - function getNomUrl($withpicto=0,$option='') - { - global $langs; + /** + * Returns clickable name (with picto) + * + * @param int $withpicto link with picto + * @param string $option link target + * @return string URL of target + */ + function getNomUrl($withpicto=0,$option='') + { + global $langs; - $result=''; - $label = $langs->trans("ShowWithdraw").': '.$this->ref; + $result=''; + $label = $langs->trans("ShowWithdraw").': '.$this->ref; - $link = '<a href="'.DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; - $linkend='</a>'; + $link = '<a href="'.DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; + $linkend='</a>'; - if ($option == 'xxx') - { - $link = '<a href="'.DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; - $linkend='</a>'; - } - - if ($withpicto) $result.=($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); - $result.=$link.$this->ref.$linkend; - return $result; - } - - - /** - * Delete a notification def by id - * - * @param int $rowid id of notification - * @return int 0 if OK, <0 if KO - */ - function DeleteNotificationById($rowid) - { - $result = 0; - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; - $sql.= " WHERE rowid = '".$rowid."'"; - - if ($this->db->query($sql)) - { - return 0; - } - else - { - return -1; - } - } - - /** - * Delete a notification - * - * @param int $user notification user - * @param string $action notification action - * @return int >0 if OK, <0 if KO - */ - function DeleteNotification($user, $action) - { - $result = 0; - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; - $sql .= " WHERE fk_user=".$user." AND fk_action='".$action."'"; - - if ($this->db->query($sql)) - { - return 0; - } - else - { - return -1; - } - } - - /** - * Add a notification - * - * @param DoliDB $db database handler - * @param int $user notification user - * @param string $action notification action - * @return int 0 if OK, <0 if KO - */ - function AddNotification($db, $user, $action) - { - $result = 0; - - if ($this->DeleteNotification($user, $action) == 0) - { - $now=dol_now(); - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)"; - $sql .= " VALUES (".$db->idate($now).",".$user.", 'NULL', 'NULL', '".$action."')"; - - dol_syslog("adnotiff: ".$sql); - if ($this->db->query($sql)) - { - $result = 0; - } - else - { - $result = -1; - dol_syslog(get_class($this)."::AddNotification Error $result"); - } - } - - return $result; - } - - - /** - * Generate a withdrawal file. - * Generation Formats: - * - Europe: SEPA (France: CFONB no more supported, Spain: AEB19 if external module EsAEB is enabled) - * - Others countries: Warning message - * File is generated with name this->filename - * - * @param string $format FRST, RCUR or ALL - * @return int 0 if OK, <0 if KO - */ - function generate($format='ALL') - { - global $conf,$langs,$mysoc; - - //TODO: Optimize code to read lines in a single function - - $result = 0; - - dol_syslog(get_class($this)."::generate build file ".$this->filename); - - $this->file = fopen($this->filename,"w"); + if ($option == 'xxx') + { + $link = '<a href="'.DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; + $linkend='</a>'; + } + + if ($withpicto) $result.=($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + $result.=$link.$this->ref.$linkend; + return $result; + } + + + /** + * Delete a notification def by id + * + * @param int $rowid id of notification + * @return int 0 if OK, <0 if KO + */ + function DeleteNotificationById($rowid) + { + $result = 0; + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; + $sql.= " WHERE rowid = '".$rowid."'"; + + if ($this->db->query($sql)) + { + return 0; + } + else + { + return -1; + } + } + + /** + * Delete a notification + * + * @param int $user notification user + * @param string $action notification action + * @return int >0 if OK, <0 if KO + */ + function DeleteNotification($user, $action) + { + $result = 0; + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; + $sql .= " WHERE fk_user=".$user." AND fk_action='".$action."'"; + + if ($this->db->query($sql)) + { + return 0; + } + else + { + return -1; + } + } + + /** + * Add a notification + * + * @param DoliDB $db database handler + * @param int $user notification user + * @param string $action notification action + * @return int 0 if OK, <0 if KO + */ + function AddNotification($db, $user, $action) + { + $result = 0; + + if ($this->DeleteNotification($user, $action) == 0) + { + $now=dol_now(); + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)"; + $sql .= " VALUES (".$db->idate($now).",".$user.", 'NULL', 'NULL', '".$action."')"; + + dol_syslog("adnotiff: ".$sql); + if ($this->db->query($sql)) + { + $result = 0; + } + else + { + $result = -1; + dol_syslog(get_class($this)."::AddNotification Error $result"); + } + } + + return $result; + } + + + /** + * Generate a withdrawal file. + * Generation Formats: + * - Europe: SEPA (France: CFONB no more supported, Spain: AEB19 if external module EsAEB is enabled) + * - Others countries: Warning message + * File is generated with name this->filename + * + * @param string $format FRST, RCUR or ALL + * @return int 0 if OK, <0 if KO + */ + function generate($format='ALL') + { + global $conf,$langs,$mysoc; + + //TODO: Optimize code to read lines in a single function + + $result = 0; + + dol_syslog(get_class($this)."::generate build file ".$this->filename); + + $this->file = fopen($this->filename,"w"); if (empty($this->file)) { $this->error=$langs->trans('ErrorFailedToOpenFile', $this->filename); return -1; } - $found=0; + $found=0; - // Build file for European countries - if ($mysoc->isInEEC()) - { - $found++; + // Build file for European countries + if ($mysoc->isInEEC()) + { + $found++; /** * SECTION CREATION FICHIER SEPA @@ -1391,163 +1391,163 @@ class BonPrelevement extends CommonObject fputs($this->file, ' </PmtInf>'.$CrLf); fputs($this->file, ' </CstmrDrctDbtInitn>'.$CrLf); fputs($this->file, '</Document>'.$CrLf); - } + } - // Build file for Other Countries with unknow format - if (! $found) + // Build file for Other Countries with unknow format + if (! $found) { - $this->total = 0; - $sql = "SELECT pl.amount"; - $sql.= " FROM"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; - $sql.= " ".MAIN_DB_PREFIX."facture as f,"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf"; - $sql.= " WHERE pl.fk_prelevement_bons = ".$this->id; - $sql.= " AND pl.rowid = pf.fk_prelevement_lignes"; - $sql.= " AND pf.fk_facture = f.rowid"; - - //Lines - $i = 0; - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $this->total = $this->total + $obj->amount; - $i++; - } - } - else + $this->total = 0; + $sql = "SELECT pl.amount"; + $sql.= " FROM"; + $sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; + $sql.= " ".MAIN_DB_PREFIX."facture as f,"; + $sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf"; + $sql.= " WHERE pl.fk_prelevement_bons = ".$this->id; + $sql.= " AND pl.rowid = pf.fk_prelevement_lignes"; + $sql.= " AND pf.fk_facture = f.rowid"; + + //Lines + $i = 0; + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $this->total = $this->total + $obj->amount; + $i++; + } + } + else { - $result = -2; - } - - $langs->load('withdrawals'); - - // TODO Add here code to generate a generic file - fputs($this->file, $langs->trans('WithdrawalFileNotCapable', $mysoc->country_code)); - } - - fclose($this->file); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($this->file, octdec($conf->global->MAIN_UMASK)); - return $result; - - } - - - /** - * Write recipient of request (customer) - * - * @param int $rowid id of line - * @param string $client_nom name of customer - * @param string $rib_banque code of bank - * @param string $rib_guichet code of bank office - * @param string $rib_number bank account - * @param float $amount amount - * @param string $facnumber ref of invoice - * @param int $facid id of invoice + $result = -2; + } + + $langs->load('withdrawals'); + + // TODO Add here code to generate a generic file + fputs($this->file, $langs->trans('WithdrawalFileNotCapable', $mysoc->country_code)); + } + + fclose($this->file); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($this->file, octdec($conf->global->MAIN_UMASK)); + return $result; + + } + + + /** + * Write recipient of request (customer) + * + * @param int $rowid id of line + * @param string $client_nom name of customer + * @param string $rib_banque code of bank + * @param string $rib_guichet code of bank office + * @param string $rib_number bank account + * @param float $amount amount + * @param string $facnumber ref of invoice + * @param int $facid id of invoice * @param string $rib_dom rib domiciliation - * @return void - */ - function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $facnumber, $facid, $rib_dom='') - { - fputs($this->file, "06"); - fputs($this->file, "08"); // Prelevement ordinaire + * @return void + */ + function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $facnumber, $facid, $rib_dom='') + { + fputs($this->file, "06"); + fputs($this->file, "08"); // Prelevement ordinaire - fputs($this->file, " "); // Zone Reservee B2 + fputs($this->file, " "); // Zone Reservee B2 - fputs($this->file, $this->emetteur_ics); // ICS + fputs($this->file, $this->emetteur_ics); // ICS - // Date d'echeance C1 + // Date d'echeance C1 - fputs($this->file, " "); - fputs($this->file, strftime("%d%m", $this->date_echeance)); - fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); + fputs($this->file, " "); + fputs($this->file, strftime("%d%m", $this->date_echeance)); + fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); - // Raison Sociale Destinataire C2 + // Raison Sociale Destinataire C2 - fputs($this->file, substr(strtoupper($client_nom)." ",0,24)); + fputs($this->file, substr(strtoupper($client_nom)." ",0,24)); - // Domiciliation facultative D1 - $domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => "")); - fputs($this->file, substr($domiciliation." ",0,24)); + // Domiciliation facultative D1 + $domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => "")); + fputs($this->file, substr($domiciliation." ",0,24)); - // Zone Reservee D2 + // Zone Reservee D2 - fputs($this->file, substr(" ",0,8)); + fputs($this->file, substr(" ",0,8)); - // Code Guichet D3 + // Code Guichet D3 - fputs($this->file, $rib_guichet); + fputs($this->file, $rib_guichet); - // Numero de compte D4 + // Numero de compte D4 - fputs($this->file, substr("000000000000000".$rib_number, -11)); + fputs($this->file, substr("000000000000000".$rib_number, -11)); - // Zone E Montant + // Zone E Montant - $montant = (round($amount,2) * 100); + $montant = (round($amount,2) * 100); - fputs($this->file, substr("000000000000000".$montant, -16)); + fputs($this->file, substr("000000000000000".$montant, -16)); - // Libelle F + // Libelle F - fputs($this->file, substr("*_".$facnumber."_RDVnet".$rowid." ", 0, 31)); + fputs($this->file, substr("*_".$facnumber."_RDVnet".$rowid." ", 0, 31)); - // Code etablissement G1 + // Code etablissement G1 - fputs($this->file, $rib_banque); + fputs($this->file, $rib_banque); - // Zone Reservee G2 + // Zone Reservee G2 - fputs($this->file, substr(" ", 0, 5)); + fputs($this->file, substr(" ", 0, 5)); - fputs($this->file, "\n"); - } + fputs($this->file, "\n"); + } - /** - * Build RUM number for a customer bank account - * - * @param string $row_code_client Customer code (soc.code_client) - * @param int $row_datec Creation date of bank account (rib.datec) - * @param string $row_drum Id of customer bank account (rib.rowid) - * @return string RUM number - */ - static function buildRumNumber($row_code_client, $row_datec, $row_drum) - { - global $langs; + /** + * Build RUM number for a customer bank account + * + * @param string $row_code_client Customer code (soc.code_client) + * @param int $row_datec Creation date of bank account (rib.datec) + * @param string $row_drum Id of customer bank account (rib.rowid) + * @return string RUM number + */ + static function buildRumNumber($row_code_client, $row_datec, $row_drum) + { + global $langs; $pre = $langs->trans('RUM').'-'; return $pre.$row_code_client.'-'.$row_drum.'-'.date('U', $row_datec); - } - - /** - * Write recipient of request (customer) - * - * @param string $row_code_client soc.code_client as code, - * @param string $row_nom pl.client_nom AS name, - * @param string $row_address soc.address AS adr, - * @param string $row_zip soc.zip - * @param string $row_town soc.town - * @param string $row_country_code c.code AS country, - * @param string $row_cb pl.code_banque AS cb, Not used for SEPA - * @param string $row_cg pl.code_guichet AS cg, Not used for SEPA - * @param string $row_cc pl.number AS cc, Not used for SEPA - * @param string $row_somme pl.amount AS somme, - * @param string $row_facnumber f.facnumber - * @param string $row_idfac pf.fk_facture AS idfac, - * @param string $row_iban rib.iban_prefix AS iban, - * @param string $row_bic rib.bic AS bic, - * @param string $row_datec rib.datec, - * @param string $row_drum rib.rowid used to generate rum - * @return string Return string with SEPA part DrctDbtTxInf - */ - function EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_facnumber, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum) - { + } + + /** + * Write recipient of request (customer) + * + * @param string $row_code_client soc.code_client as code, + * @param string $row_nom pl.client_nom AS name, + * @param string $row_address soc.address AS adr, + * @param string $row_zip soc.zip + * @param string $row_town soc.town + * @param string $row_country_code c.code AS country, + * @param string $row_cb pl.code_banque AS cb, Not used for SEPA + * @param string $row_cg pl.code_guichet AS cg, Not used for SEPA + * @param string $row_cc pl.number AS cc, Not used for SEPA + * @param string $row_somme pl.amount AS somme, + * @param string $row_facnumber f.facnumber + * @param string $row_idfac pf.fk_facture AS idfac, + * @param string $row_iban rib.iban_prefix AS iban, + * @param string $row_bic rib.bic AS bic, + * @param string $row_datec rib.datec, + * @param string $row_drum rib.rowid used to generate rum + * @return string Return string with SEPA part DrctDbtTxInf + */ + function EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_facnumber, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum) + { $CrLf = "\n"; $Rowing = sprintf("%06d", $row_idfac); @@ -1597,90 +1597,90 @@ class BonPrelevement extends CommonObject $XML_DEBITOR .=' </RmtInf>'.$CrLf; $XML_DEBITOR .=' </DrctDbtTxInf>'.$CrLf; return $XML_DEBITOR; - } + } - /** - * Write sender of request (me) - * - * @return void - */ - function EnregEmetteur() - { - fputs($this->file, "03"); - fputs($this->file, "08"); // Prelevement ordinaire + /** + * Write sender of request (me) + * + * @return void + */ + function EnregEmetteur() + { + fputs($this->file, "03"); + fputs($this->file, "08"); // Prelevement ordinaire - fputs($this->file, " "); // Zone Reservee B2 + fputs($this->file, " "); // Zone Reservee B2 - fputs($this->file, $this->emetteur_ics); // ICS + fputs($this->file, $this->emetteur_ics); // ICS - // Date d'echeance C1 + // Date d'echeance C1 - fputs($this->file, " "); - fputs($this->file, strftime("%d%m", $this->date_echeance)); - fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); + fputs($this->file, " "); + fputs($this->file, strftime("%d%m", $this->date_echeance)); + fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); - // Raison Sociale C2 + // Raison Sociale C2 - fputs($this->file, substr($this->raison_sociale. " ",0,24)); + fputs($this->file, substr($this->raison_sociale. " ",0,24)); - // Reference de la remise creancier D1 sur 7 caracteres + // Reference de la remise creancier D1 sur 7 caracteres - fputs($this->file, substr($this->reference_remise. " ",0,7)); + fputs($this->file, substr($this->reference_remise. " ",0,7)); - // Zone Reservee D1-2 + // Zone Reservee D1-2 - fputs($this->file, substr(" ",0,17)); + fputs($this->file, substr(" ",0,17)); - // Zone Reservee D2 + // Zone Reservee D2 - fputs($this->file, substr(" ",0,2)); - fputs($this->file, "E"); - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,2)); + fputs($this->file, "E"); + fputs($this->file, substr(" ",0,5)); - // Code Guichet D3 + // Code Guichet D3 - fputs($this->file, $this->emetteur_code_guichet); + fputs($this->file, $this->emetteur_code_guichet); - // Numero de compte D4 + // Numero de compte D4 - fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11)); + fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11)); - // Zone Reservee E + // Zone Reservee E - fputs($this->file, substr(" ",0,16)); + fputs($this->file, substr(" ",0,16)); - // Zone Reservee F + // Zone Reservee F - fputs($this->file, substr(" ",0,31)); + fputs($this->file, substr(" ",0,31)); - // Code etablissement + // Code etablissement - fputs($this->file, $this->emetteur_code_banque); + fputs($this->file, $this->emetteur_code_banque); - // Zone Reservee G + // Zone Reservee G - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - fputs($this->file, "\n"); + fputs($this->file, "\n"); - } + } - /** - * Write sender of request (me). - * Note: The tag PmtInf is opened here but closed into caller - * - * @param string $configuration conf - * @param int $ladate Date - * @param int $nombre 0 or 1 - * @param float $total Total - * @param string $CrLf End of line character - * @param string $format FRST or RCUR or ALL - * @return string String with SEPA Sender - */ - function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n', $format='FRST') - { - // SEPA INITIALISATION + /** + * Write sender of request (me). + * Note: The tag PmtInf is opened here but closed into caller + * + * @param string $configuration conf + * @param int $ladate Date + * @param int $nombre 0 or 1 + * @param float $total Total + * @param string $CrLf End of line character + * @param string $format FRST or RCUR or ALL + * @return string String with SEPA Sender + */ + function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n', $format='FRST') + { + // SEPA INITIALISATION global $conf; $dateTime_YMD = dol_print_date($ladate, '%Y%m%d'); @@ -1692,16 +1692,16 @@ class BonPrelevement extends CommonObject $account = new Account($this->db); if ($account->fetch($id)>0) { - $this->emetteur_code_banque = $account->code_banque; - $this->emetteur_code_guichet = $account->code_guichet; - $this->emetteur_numero_compte = $account->number; - $this->emetteur_number_key = $account->cle_rib; - $this->emetteur_iban = $account->iban; - $this->emetteur_bic = $account->bic; + $this->emetteur_code_banque = $account->code_banque; + $this->emetteur_code_guichet = $account->code_guichet; + $this->emetteur_numero_compte = $account->number; + $this->emetteur_number_key = $account->cle_rib; + $this->emetteur_iban = $account->iban; + $this->emetteur_bic = $account->bic; - $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; + $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; - $this->raison_sociale = $account->proprio; + $this->raison_sociale = $account->proprio; } // Récupération info demandeur @@ -1787,131 +1787,131 @@ class BonPrelevement extends CommonObject return $XML_SEPA_INFO; } - /** - * Write end - * - * @param int $total total amount - * @return void - */ - function EnregTotal($total) - { - fputs($this->file, "08"); - fputs($this->file, "08"); // Prelevement ordinaire + /** + * Write end + * + * @param int $total total amount + * @return void + */ + function EnregTotal($total) + { + fputs($this->file, "08"); + fputs($this->file, "08"); // Prelevement ordinaire - fputs($this->file, " "); // Zone Reservee B2 + fputs($this->file, " "); // Zone Reservee B2 - fputs($this->file, $this->emetteur_ics); // ICS + fputs($this->file, $this->emetteur_ics); // ICS - // Reserve C1 + // Reserve C1 - fputs($this->file, substr(" ",0,12)); + fputs($this->file, substr(" ",0,12)); - // Raison Sociale C2 + // Raison Sociale C2 - fputs($this->file, substr(" ",0,24)); + fputs($this->file, substr(" ",0,24)); - // D1 + // D1 - fputs($this->file, substr(" ",0,24)); + fputs($this->file, substr(" ",0,24)); - // Zone Reservee D2 + // Zone Reservee D2 - fputs($this->file, substr(" ",0,8)); + fputs($this->file, substr(" ",0,8)); - // Code Guichet D3 + // Code Guichet D3 - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - // Numero de compte D4 + // Numero de compte D4 - fputs($this->file, substr(" ",0,11)); + fputs($this->file, substr(" ",0,11)); - // Zone E Montant + // Zone E Montant - $montant = ($total * 100); + $montant = ($total * 100); - fputs($this->file, substr("000000000000000".$montant, -16)); + fputs($this->file, substr("000000000000000".$montant, -16)); - // Zone Reservee F + // Zone Reservee F - fputs($this->file, substr(" ",0,31)); + fputs($this->file, substr(" ",0,31)); - // Code etablissement + // Code etablissement - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - // Zone Reservee F + // Zone Reservee F - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - fputs($this->file, "\n"); - } + fputs($this->file, "\n"); + } - /** - * Return status label of object - * - * @param int $mode 0=Label, 1=Picto + label, 2=Picto, 3=Label + Picto - * @return string Label - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->statut,$mode); - } + /** + * Return status label of object + * + * @param int $mode 0=Label, 1=Picto + label, 2=Picto, 3=Label + Picto + * @return string Label + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut,$mode); + } - /** - * Return status label for a status - * - * @param int $statut id statut + /** + * Return status label for a status + * + * @param int $statut id statut * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto - * @return string Label - */ - function LibStatut($statut,$mode=0) - { - global $langs; + * @return string Label + */ + function LibStatut($statut,$mode=0) + { + global $langs; - if ($mode == 0) - { - return $langs->trans($this->labelstatut[$statut]); - } + if ($mode == 0) + { + return $langs->trans($this->labelstatut[$statut]); + } - if ($mode == 1) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); - } - if ($mode == 2) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - if ($mode == 3) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - if ($mode == 4) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); - } - if ($mode == 5) - { - if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - if ($mode == 6) - { - if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - } + if ($mode == 1) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); + } + if ($mode == 2) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + if ($mode == 3) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + if ($mode == 4) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); + } + if ($mode == 5) + { + if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + if ($mode == 6) + { + if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + } } diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index 380132058fdaaad2293a81f0c6ef810083829f38..d9775250853e256e74a254669c46dc3a00fd2ff4 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -56,35 +56,35 @@ $format = GETPOST('format','aZ09'); // Change customer bank information to withdraw if ($action == 'modify') { - for ($i = 1 ; $i < 9 ; $i++) - { - dolibarr_set_const($db, GETPOST("nom$i"), GETPOST("value$i"),'chaine',0,'',$conf->entity); - } + for ($i = 1 ; $i < 9 ; $i++) + { + dolibarr_set_const($db, GETPOST("nom$i"), GETPOST("value$i"),'chaine',0,'',$conf->entity); + } } if ($action == 'create') { // $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty - $bprev = new BonPrelevement($db); - $result=$bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format); - if ($result < 0) - { - setEventMessages($bprev->error, $bprev->errors, 'errors'); - } - elseif ($result == 0) - { - $mesg=''; - $mesg=$langs->trans("NoInvoiceCouldBeWithdrawed"); - setEventMessages($mesg, null, 'errors'); - $mesg.='<br>'."\n"; - foreach($bprev->invoice_in_error as $key => $val) - { - $mesg.='<span class="warning">'.$val."</span><br>\n"; - } - } - else - { - setEventMessages($langs->trans("DirectDebitOrderCreated", $bprev->getNomUrl(1)), null); - } + $bprev = new BonPrelevement($db); + $result=$bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format); + if ($result < 0) + { + setEventMessages($bprev->error, $bprev->errors, 'errors'); + } + elseif ($result == 0) + { + $mesg=''; + $mesg=$langs->trans("NoInvoiceCouldBeWithdrawed"); + setEventMessages($mesg, null, 'errors'); + $mesg.='<br>'."\n"; + foreach($bprev->invoice_in_error as $key => $val) + { + $mesg.='<span class="warning">'.$val."</span><br>\n"; + } + } + else + { + setEventMessages($langs->trans("DirectDebitOrderCreated", $bprev->getNomUrl(1)), null); + } } @@ -124,7 +124,7 @@ $nb11=$bprev->NbFactureAPrelever(1,1); $pricetowithdraw=$bprev->SommeAPrelever(); if ($nb < 0 || $nb1 < 0 || $nb11 < 0) { - dol_print_error($bprev->error); + dol_print_error($bprev->error); } print '<table class="border" width="100%">'; @@ -148,34 +148,34 @@ print "<div class=\"tabsAction\">\n"; if ($nb) { - if ($pricetowithdraw) - { - if ($mysoc->isInEEC()) - { - print '<a class="butAction" href="create.php?action=create&format=FRST">'.$langs->trans("CreateForSepaFRST")."</a>\n"; - print '<a class="butAction" href="create.php?action=create&format=RCUR">'.$langs->trans("CreateForSepaRCUR")."</a>\n"; - } - else - { - print '<a class="butAction" href="create.php?action=create&format=ALL">'.$langs->trans("CreateAll")."</a>\n"; - } - } - else - { - if ($mysoc->isInEEC()) - { - print '<a class="butActionRefused" href="#">'.$langs->trans("CreateForSepaFRST")."</a>\n"; - print '<a class="butActionRefused" href="#">'.$langs->trans("CreateForSepaRCUR")."</a>\n"; - } - else - { - print '<a class="butActionRefused" href="#">'.$langs->trans("CreateAll")."</a>\n"; - } - } + if ($pricetowithdraw) + { + if ($mysoc->isInEEC()) + { + print '<a class="butAction" href="create.php?action=create&format=FRST">'.$langs->trans("CreateForSepaFRST")."</a>\n"; + print '<a class="butAction" href="create.php?action=create&format=RCUR">'.$langs->trans("CreateForSepaRCUR")."</a>\n"; + } + else + { + print '<a class="butAction" href="create.php?action=create&format=ALL">'.$langs->trans("CreateAll")."</a>\n"; + } + } + else + { + if ($mysoc->isInEEC()) + { + print '<a class="butActionRefused" href="#">'.$langs->trans("CreateForSepaFRST")."</a>\n"; + print '<a class="butActionRefused" href="#">'.$langs->trans("CreateForSepaRCUR")."</a>\n"; + } + else + { + print '<a class="butActionRefused" href="#">'.$langs->trans("CreateAll")."</a>\n"; + } + } } else { - print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NoInvoiceToWithdraw", $langs->transnoentitiesnoconv("StandingOrders"))).'">'.$langs->trans("CreateAll")."</a>\n"; + print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NoInvoiceToWithdraw", $langs->transnoentitiesnoconv("StandingOrders"))).'">'.$langs->trans("CreateAll")."</a>\n"; } print "</div>\n"; @@ -200,72 +200,72 @@ if ($socid) $sql.= " AND f.fk_soc = ".$socid; $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - - print load_fiche_titre($langs->trans("InvoiceWaitingWithdraw").($num > 0?' ('.$num.')':''),'',''); - - print '<table class="noborder" width="100%">'; - print '<tr class="liste_titre">'; - print '<td>'.$langs->trans("Invoice").'</td>'; - print '<td>'.$langs->trans("ThirdParty").'</td>'; - print '<td>'.$langs->trans("RIB").'</td>'; - print '<td>'.$langs->trans("RUM").'</td>'; - print '<td align="right">'.$langs->trans("AmountTTC").'</td>'; - print '<td align="right">'.$langs->trans("DateRequest").'</td>'; - print '</tr>'; - - if ($num) - { - require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; - $bac = new CompanyBankAccount($db); - - while ($i < $num && $i < 20) - { - $obj = $db->fetch_object($resql); - - print '<tr class="oddeven">'; - print '<td>'; - $invoicestatic->id=$obj->rowid; - $invoicestatic->ref=$obj->facnumber; - print $invoicestatic->getNomUrl(1,'withdraw'); - print '</td>'; - // Thirdparty - print '<td>'; - $thirdpartystatic->fetch($obj->socid); - print $thirdpartystatic->getNomUrl(1,'ban'); - print '</td>'; - // RIB - print '<td>'; - print $thirdpartystatic->display_rib(); - $bac->fetch(0, $obj->socid); - if ($bac->verif() <= 0) print img_warning('Error on default bank number for IBAN : '.$bac->error_message); - print '</td>'; - // RUM - print '<td>'; - print $thirdpartystatic->display_rib('rum'); - $format = $thirdpartystatic->display_rib('format'); - if ($format) print ' ('.$format.')'; - print '</td>'; - // Amount - print '<td align="right">'; - print price($obj->amount,0,$langs,0,0,-1,$conf->currency); - print '</td>'; - // Date - print '<td align="right">'; - print dol_print_date($db->jdate($obj->date_demande),'day'); - print '</td>'; - print '</tr>'; - $i++; - } - } - else print '<tr '.$bc[0].'><td colspan="5" class="opacitymedium">'.$langs->trans("None").'</td></tr>'; - print "</table>"; - print "<br>\n"; + $num = $db->num_rows($resql); + $i = 0; + + print load_fiche_titre($langs->trans("InvoiceWaitingWithdraw").($num > 0?' ('.$num.')':''),'',''); + + print '<table class="noborder" width="100%">'; + print '<tr class="liste_titre">'; + print '<td>'.$langs->trans("Invoice").'</td>'; + print '<td>'.$langs->trans("ThirdParty").'</td>'; + print '<td>'.$langs->trans("RIB").'</td>'; + print '<td>'.$langs->trans("RUM").'</td>'; + print '<td align="right">'.$langs->trans("AmountTTC").'</td>'; + print '<td align="right">'.$langs->trans("DateRequest").'</td>'; + print '</tr>'; + + if ($num) + { + require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + $bac = new CompanyBankAccount($db); + + while ($i < $num && $i < 20) + { + $obj = $db->fetch_object($resql); + + print '<tr class="oddeven">'; + print '<td>'; + $invoicestatic->id=$obj->rowid; + $invoicestatic->ref=$obj->facnumber; + print $invoicestatic->getNomUrl(1,'withdraw'); + print '</td>'; + // Thirdparty + print '<td>'; + $thirdpartystatic->fetch($obj->socid); + print $thirdpartystatic->getNomUrl(1,'ban'); + print '</td>'; + // RIB + print '<td>'; + print $thirdpartystatic->display_rib(); + $bac->fetch(0, $obj->socid); + if ($bac->verif() <= 0) print img_warning('Error on default bank number for IBAN : '.$bac->error_message); + print '</td>'; + // RUM + print '<td>'; + print $thirdpartystatic->display_rib('rum'); + $format = $thirdpartystatic->display_rib('format'); + if ($format) print ' ('.$format.')'; + print '</td>'; + // Amount + print '<td align="right">'; + print price($obj->amount,0,$langs,0,0,-1,$conf->currency); + print '</td>'; + // Date + print '<td align="right">'; + print dol_print_date($db->jdate($obj->date_demande),'day'); + print '</td>'; + print '</tr>'; + $i++; + } + } + else print '<tr '.$bc[0].'><td colspan="5" class="opacitymedium">'.$langs->trans("None").'</td></tr>'; + print "</table>"; + print "<br>\n"; } else { - dol_print_error($db); + dol_print_error($db); } diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index ac953d802dea96b2b9eabb172dd4b76ad3d5f7f4..4b0356c8e520b14299a0652e82b9dcfd2b81335a 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -95,25 +95,25 @@ $contextpage='contactlist'; $titre = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); if ($type == "p") { - $contextpage='contactprospectlist'; + $contextpage='contactprospectlist'; $titre.=' ('.$langs->trans("ThirdPartyProspects").')'; $urlfiche="card.php"; } if ($type == "c") { - $contextpage='contactcustomerlist'; + $contextpage='contactcustomerlist'; $titre.=' ('.$langs->trans("ThirdPartyCustomers").')'; $urlfiche="card.php"; } else if ($type == "f") { - $contextpage='contactsupplierlist'; + $contextpage='contactsupplierlist'; $titre.=' ('.$langs->trans("ThirdPartySuppliers").')'; $urlfiche="card.php"; } else if ($type == "o") { - $contextpage='contactotherlist'; + $contextpage='contactotherlist'; $titre.=' ('.$langs->trans("OthersNotLinkedToThirdParty").')'; $urlfiche=""; } @@ -128,31 +128,31 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'p.lastname'=>'Lastname', - 'p.firstname'=>'Firstname', - 'p.email'=>'EMail', - 's.nom'=>"ThirdParty", + 'p.lastname'=>'Lastname', + 'p.firstname'=>'Firstname', + 'p.email'=>'EMail', + 's.nom'=>"ThirdParty", ); // Definition of fields for list $arrayfields=array( 'p.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0)), 'p.lastname'=>array('label'=>"Lastname", 'checked'=>1), - 'p.firstname'=>array('label'=>"Firstname", 'checked'=>1), - 'p.poste'=>array('label'=>"PostOrFunction", 'checked'=>1), - 'p.town'=>array('label'=>"Town", 'checked'=>0), - 'p.zip'=>array('label'=>"Zip", 'checked'=>0), - 'p.phone'=>array('label'=>"Phone", 'checked'=>1), - 'p.phone_perso'=>array('label'=>"PhonePerso", 'checked'=>0), - 'p.phone_mobile'=>array('label'=>"PhoneMobile", 'checked'=>1), - 'p.fax'=>array('label'=>"Fax", 'checked'=>1), - 'p.email'=>array('label'=>"EMail", 'checked'=>1), - 'p.skype'=>array('label'=>"Skype", 'checked'=>1, 'enabled'=>(! empty($conf->skype->enabled))), - 'p.thirdparty'=>array('label'=>"ThirdParty", 'checked'=>1, 'enabled'=>empty($conf->global->SOCIETE_DISABLE_CONTACTS)), - 'p.priv'=>array('label'=>"ContactVisibility", 'checked'=>1, 'position'=>200), - 'p.datec'=>array('label'=>"DateCreationShort", 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), - 'p.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), + 'p.firstname'=>array('label'=>"Firstname", 'checked'=>1), + 'p.poste'=>array('label'=>"PostOrFunction", 'checked'=>1), + 'p.town'=>array('label'=>"Town", 'checked'=>0), + 'p.zip'=>array('label'=>"Zip", 'checked'=>0), + 'p.phone'=>array('label'=>"Phone", 'checked'=>1), + 'p.phone_perso'=>array('label'=>"PhonePerso", 'checked'=>0), + 'p.phone_mobile'=>array('label'=>"PhoneMobile", 'checked'=>1), + 'p.fax'=>array('label'=>"Fax", 'checked'=>1), + 'p.email'=>array('label'=>"EMail", 'checked'=>1), + 'p.skype'=>array('label'=>"Skype", 'checked'=>1, 'enabled'=>(! empty($conf->skype->enabled))), + 'p.thirdparty'=>array('label'=>"ThirdParty", 'checked'=>1, 'enabled'=>empty($conf->global->SOCIETE_DISABLE_CONTACTS)), + 'p.priv'=>array('label'=>"ContactVisibility", 'checked'=>1, 'position'=>200), + 'p.datec'=>array('label'=>"DateCreationShort", 'checked'=>0, 'position'=>500), + 'p.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), + 'p.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), 'p.import_key'=>array('label'=>"ImportId", 'checked'=>0, 'position'=>1100), ); // Extra fields @@ -160,15 +160,15 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { 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'=>$extrafields->attribute_perms[$key]); + 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'=>$extrafields->attribute_perms[$key]); } } $object=new Contact($db); if (($id > 0 || ! empty($ref)) && $action != 'add') { - $result=$object->fetch($id,$ref); - if ($result < 0) dol_print_error($db); + $result=$object->fetch($id,$ref); + if ($result < 0) dol_print_error($db); } @@ -185,43 +185,43 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - - // Did we click on purge search criteria ? - if (GETPOST('button_removefilter_x') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter')) // All tests are required to be compatible with all browsers - { - $sall=""; - $search_id=''; - $search_firstlast_only=""; - $search_lastname=""; - $search_firstname=""; - $search_societe=""; - $search_poste=""; - $search_phone=""; - $search_phone_perso=""; - $search_phone_pro=""; - $search_phone_mobile=""; - $search_fax=""; - $search_email=""; - $search_skype=""; - $search_priv=""; - $search_status=-1; - $search_categ=''; - $search_categ_thirdparty=''; - $search_categ_supplier=''; - $search_import_key=''; - $toselect=''; - $search_array_options=array(); - } - - // Mass actions - $objectclass='Contact'; - $objectlabel='Contact'; - $permtoread = $user->rights->societe->lire; - $permtodelete = $user->rights->societe->supprimer; - $uploaddir = $conf->societe->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Did we click on purge search criteria ? + if (GETPOST('button_removefilter_x') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter')) // All tests are required to be compatible with all browsers + { + $sall=""; + $search_id=''; + $search_firstlast_only=""; + $search_lastname=""; + $search_firstname=""; + $search_societe=""; + $search_poste=""; + $search_phone=""; + $search_phone_perso=""; + $search_phone_pro=""; + $search_phone_mobile=""; + $search_fax=""; + $search_email=""; + $search_skype=""; + $search_priv=""; + $search_status=-1; + $search_categ=''; + $search_categ_thirdparty=''; + $search_categ_supplier=''; + $search_import_key=''; + $toselect=''; + $search_array_options=array(); + } + + // Mass actions + $objectclass='Contact'; + $objectlabel='Contact'; + $permtoread = $user->rights->societe->lire; + $permtodelete = $user->rights->societe->supprimer; + $uploaddir = $conf->societe->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } if ($search_priv < 0) $search_priv=''; @@ -262,7 +262,7 @@ if (!$user->rights->societe->client->voir && !$socid) //restriction } if (! empty($userid)) // propre au commercial { - $sql .= " AND p.fk_user_creat=".$db->escape($userid); + $sql .= " AND p.fk_user_creat=".$db->escape($userid); } // Filter to exclude not owned private contacts @@ -303,37 +303,37 @@ if ($search_status != '' && $search_status >= 0) $sql.= " AND p.statut = ".$db-> if ($search_import_key) $sql.= natural_search("p.import_key",$search_import_key); if ($type == "o") // filtre sur type { - $sql .= " AND p.fk_soc IS NULL"; + $sql .= " AND p.fk_soc IS NULL"; } else if ($type == "f") // filtre sur type { - $sql .= " AND s.fournisseur = 1"; + $sql .= " AND s.fournisseur = 1"; } else if ($type == "c") // filtre sur type { - $sql .= " AND s.client IN (1, 3)"; + $sql .= " AND s.client IN (1, 3)"; } else if ($type == "p") // filtre sur type { - $sql .= " AND s.client IN (2, 3)"; + $sql .= " AND s.client IN (2, 3)"; } if (! empty($socid)) { - $sql .= " AND s.rowid = ".$socid; + $sql .= " AND s.rowid = ".$socid; } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -342,19 +342,19 @@ $sql.=$hookmanager->resPrint; // Add order if ($view == "recent") { - $sql.= $db->order("p.datec","DESC"); + $sql.= $db->order("p.datec","DESC"); } else { - $sql.= $db->order($sortfield,$sortorder); + $sql.= $db->order($sortfield,$sortorder); } // Count total nb of records $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1, $offset); @@ -362,8 +362,8 @@ $sql.= $db->plimit($limit+1, $offset); $result = $db->query($sql); if (! $result) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($result); @@ -372,10 +372,10 @@ $arrayofselected=is_array($toselect)?$toselect:array(); if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && ($sall != '' || $seearch_cti != '')) { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/contact/card.php?id='.$id); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/contact/card.php?id='.$id); + exit; } $help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'; @@ -409,9 +409,9 @@ if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available @@ -437,37 +437,37 @@ print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } if ($search_firstlast_only) { - print $langs->trans("FilterOnInto", $search_firstlast_only) . $langs->trans("Lastname").", ".$langs->trans("Firstname"); + print $langs->trans("FilterOnInto", $search_firstlast_only) . $langs->trans("Lastname").", ".$langs->trans("Firstname"); } $moreforfilter=''; if (! empty($conf->categorie->enabled)) { require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='<div class="divsearchfield">'; + $moreforfilter.='<div class="divsearchfield">'; $moreforfilter.=$langs->trans('Categories'). ': '; $moreforfilter.=$formother->select_categories(Categorie::TYPE_CONTACT,$search_categ,'search_categ',1); $moreforfilter.='</div>'; if (empty($type) || $type == 'c' || $type == 'p') { - $moreforfilter.='<div class="divsearchfield">'; - if ($type == 'c') $moreforfilter.=$langs->trans('CustomersCategoriesShort'). ': '; - else if ($type == 'p') $moreforfilter.=$langs->trans('ProspectsCategoriesShort'). ': '; - else $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort'). ': '; - $moreforfilter.=$formother->select_categories(Categorie::TYPE_CUSTOMER,$search_categ_thirdparty,'search_categ_thirdparty',1); - $moreforfilter.='</div>'; + $moreforfilter.='<div class="divsearchfield">'; + if ($type == 'c') $moreforfilter.=$langs->trans('CustomersCategoriesShort'). ': '; + else if ($type == 'p') $moreforfilter.=$langs->trans('ProspectsCategoriesShort'). ': '; + else $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort'). ': '; + $moreforfilter.=$formother->select_categories(Categorie::TYPE_CUSTOMER,$search_categ_thirdparty,'search_categ_thirdparty',1); + $moreforfilter.='</div>'; } if (empty($type) || $type == 'f') { - $moreforfilter.='<div class="divsearchfield">'; + $moreforfilter.='<div class="divsearchfield">'; $moreforfilter.=$langs->trans('SuppliersCategoriesShort'). ': '; - $moreforfilter.=$formother->select_categories(Categorie::TYPE_SUPPLIER,$search_categ_supplier,'search_categ_supplier',1); - $moreforfilter.='</div>'; + $moreforfilter.=$formother->select_categories(Categorie::TYPE_SUPPLIER,$search_categ_supplier,'search_categ_supplier',1); + $moreforfilter.='</div>'; } } if ($moreforfilter) @@ -476,7 +476,7 @@ if ($moreforfilter) print $moreforfilter; $parameters=array('type'=>$type); $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; print '</div>'; } @@ -497,79 +497,79 @@ if (! empty($arrayfields['p.rowid']['checked'])) } if (! empty($arrayfields['p.lastname']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_lastname" size="6" value="'.dol_escape_htmltag($search_lastname).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_lastname" size="6" value="'.dol_escape_htmltag($search_lastname).'">'; + print '</td>'; } if (! empty($arrayfields['p.firstname']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_firstname" size="6" value="'.dol_escape_htmltag($search_firstname).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_firstname" size="6" value="'.dol_escape_htmltag($search_firstname).'">'; + print '</td>'; } if (! empty($arrayfields['p.poste']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_poste" size="5" value="'.dol_escape_htmltag($search_poste).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_poste" size="5" value="'.dol_escape_htmltag($search_poste).'">'; + print '</td>'; } if (! empty($arrayfields['p.zip']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_zip" size="3" value="'.dol_escape_htmltag($search_zip).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_zip" size="3" value="'.dol_escape_htmltag($search_zip).'">'; + print '</td>'; } if (! empty($arrayfields['p.town']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_town" size="5" value="'.dol_escape_htmltag($search_town).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_town" size="5" value="'.dol_escape_htmltag($search_town).'">'; + print '</td>'; } if (! empty($arrayfields['p.phone']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_phone_pro" size="6" value="'.dol_escape_htmltag($search_phone_pro).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_phone_pro" size="6" value="'.dol_escape_htmltag($search_phone_pro).'">'; + print '</td>'; } if (! empty($arrayfields['p.phone_perso']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_phone_perso" size="6" value="'.dol_escape_htmltag($search_phone_perso).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_phone_perso" size="6" value="'.dol_escape_htmltag($search_phone_perso).'">'; + print '</td>'; } if (! empty($arrayfields['p.phone_mobile']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_phone_mobile" size="6" value="'.dol_escape_htmltag($search_phone_mobile).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_phone_mobile" size="6" value="'.dol_escape_htmltag($search_phone_mobile).'">'; + print '</td>'; } if (! empty($arrayfields['p.fax']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_fax" size="6" value="'.dol_escape_htmltag($search_fax).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_fax" size="6" value="'.dol_escape_htmltag($search_fax).'">'; + print '</td>'; } if (! empty($arrayfields['p.email']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_email" size="6" value="'.dol_escape_htmltag($search_email).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_email" size="6" value="'.dol_escape_htmltag($search_email).'">'; + print '</td>'; } if (! empty($arrayfields['p.skype']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_skype" size="6" value="'.dol_escape_htmltag($search_skype).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_skype" size="6" value="'.dol_escape_htmltag($search_skype).'">'; + print '</td>'; } if (! empty($arrayfields['p.thirdparty']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_societe" size="8" value="'.dol_escape_htmltag($search_societe).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_societe" size="8" value="'.dol_escape_htmltag($search_societe).'">'; + print '</td>'; } if (! empty($arrayfields['p.priv']['checked'])) { - print '<td class="liste_titre" align="center">'; + print '<td class="liste_titre" align="center">'; $selectarray=array('0'=>$langs->trans("ContactPublic"),'1'=>$langs->trans("ContactPrivate")); print $form->selectarray('search_priv',$selectarray,$search_priv,1); print '</td>'; @@ -581,12 +581,12 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { if (! empty($arrayfields["ef.".$key]['checked'])) { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { - $crit=$val; + $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); $searchclass=''; if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; @@ -604,21 +604,21 @@ print $hookmanager->resPrint; // Date creation if (! empty($arrayfields['p.datec']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Date modification if (! empty($arrayfields['p.tms']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Status if (! empty($arrayfields['p.statut']['checked'])) { - print '<td class="liste_titre center">'; - print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')),$search_status); - print '</td>'; + print '<td class="liste_titre center">'; + print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')),$search_status); + print '</td>'; } if (! empty($arrayfields['p.import_key']['checked'])) { @@ -655,13 +655,13 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); $sortonfield = "ef.".$key; if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + } } } // Hook fields @@ -680,9 +680,9 @@ $i = 0; $totalarray=array(); while ($i < min($num,$limit)) { - $obj = $db->fetch_object($result); + $obj = $db->fetch_object($result); - print '<tr class="oddeven">'; + print '<tr class="oddeven">'; $contactstatic->lastname=$obj->lastname; $contactstatic->firstname=''; @@ -702,98 +702,98 @@ while ($i < min($num,$limit)) print '<td class="tdoverflowmax50">'; print $obj->rowid; print "</td>\n"; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } // Name - if (! empty($arrayfields['p.lastname']['checked'])) - { - print '<td valign="middle">'; - print $contactstatic->getNomUrl(1,'',0); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.lastname']['checked'])) + { + print '<td valign="middle">'; + print $contactstatic->getNomUrl(1,'',0); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } // Firstname - if (! empty($arrayfields['p.firstname']['checked'])) - { - print '<td>'.$obj->firstname.'</td>'; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.firstname']['checked'])) + { + print '<td>'.$obj->firstname.'</td>'; + if (! $i) $totalarray['nbfield']++; + } // Zip - if (! empty($arrayfields['p.zip']['checked'])) - { - print '<td>'.$obj->zip.'</td>'; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.zip']['checked'])) + { + print '<td>'.$obj->zip.'</td>'; + if (! $i) $totalarray['nbfield']++; + } // Town - if (! empty($arrayfields['p.town']['checked'])) - { - print '<td>'.$obj->town.'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Function - if (! empty($arrayfields['p.poste']['checked'])) - { - print '<td>'.dol_trunc($obj->poste,20).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Phone - if (! empty($arrayfields['p.phone']['checked'])) - { - print '<td>'.dol_print_phone($obj->phone_pro,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Phone perso - if (! empty($arrayfields['p.phone_perso']['checked'])) - { - print '<td>'.dol_print_phone($obj->phone_perso,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Phone mobile - if (! empty($arrayfields['p.phone_mobile']['checked'])) - { - print '<td>'.dol_print_phone($obj->phone_mobile,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Fax - if (! empty($arrayfields['p.fax']['checked'])) - { - print '<td>'.dol_print_phone($obj->fax,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // EMail - if (! empty($arrayfields['p.email']['checked'])) - { - print '<td>'.dol_print_email($obj->email,$obj->rowid,$obj->socid,'AC_EMAIL',18).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Skype - if (! empty($arrayfields['p.skype']['checked'])) - { - if (! empty($conf->skype->enabled)) { print '<td>'.dol_print_skype($obj->skype,$obj->rowid,$obj->socid,'AC_SKYPE',18).'</td>'; } - if (! $i) $totalarray['nbfield']++; - } - // Company - if (! empty($arrayfields['p.thirdparty']['checked'])) - { + if (! empty($arrayfields['p.town']['checked'])) + { + print '<td>'.$obj->town.'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Function + if (! empty($arrayfields['p.poste']['checked'])) + { + print '<td>'.dol_trunc($obj->poste,20).'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Phone + if (! empty($arrayfields['p.phone']['checked'])) + { + print '<td>'.dol_print_phone($obj->phone_pro,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Phone perso + if (! empty($arrayfields['p.phone_perso']['checked'])) + { + print '<td>'.dol_print_phone($obj->phone_perso,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Phone mobile + if (! empty($arrayfields['p.phone_mobile']['checked'])) + { + print '<td>'.dol_print_phone($obj->phone_mobile,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Fax + if (! empty($arrayfields['p.fax']['checked'])) + { + print '<td>'.dol_print_phone($obj->fax,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // EMail + if (! empty($arrayfields['p.email']['checked'])) + { + print '<td>'.dol_print_email($obj->email,$obj->rowid,$obj->socid,'AC_EMAIL',18).'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Skype + if (! empty($arrayfields['p.skype']['checked'])) + { + if (! empty($conf->skype->enabled)) { print '<td>'.dol_print_skype($obj->skype,$obj->rowid,$obj->socid,'AC_SKYPE',18).'</td>'; } + if (! $i) $totalarray['nbfield']++; + } + // Company + if (! empty($arrayfields['p.thirdparty']['checked'])) + { print '<td>'; - if ($obj->socid) - { + if ($obj->socid) + { $objsoc = new Societe($db); $objsoc->fetch($obj->socid); print $objsoc->getNomUrl(1); - } - else - print ' '; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Private/Public - if (! empty($arrayfields['p.priv']['checked'])) - { - print '<td align="center">'.$contactstatic->LibPubPriv($obj->priv).'</td>'; - if (! $i) $totalarray['nbfield']++; - } + } + else + print ' '; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Private/Public + if (! empty($arrayfields['p.priv']['checked'])) + { + print '<td align="center">'.$contactstatic->LibPubPriv($obj->priv).'</td>'; + if (! $i) $totalarray['nbfield']++; + } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) @@ -809,57 +809,57 @@ while ($i < min($num,$limit)) $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } } } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + // 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['p.datec']['checked'])) - { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['p.statut']['checked'])) - { - print '<td align="center">'.$contactstatic->getLibStatut(3).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['p.import_key']['checked'])) - { - print '<td class="tdoverflowmax100">'; - print $obj->import_key; - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - - // Action column - print '<td class="nowrap" align="center">'; - 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; + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['p.datec']['checked'])) + { + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['p.statut']['checked'])) + { + print '<td align="center">'.$contactstatic->getLibStatut(3).'</td>'; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['p.import_key']['checked'])) + { + print '<td class="tdoverflowmax100">'; + print $obj->import_key; + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + + // Action column + print '<td class="nowrap" align="center">'; + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; - print "</tr>\n"; - $i++; + print "</tr>\n"; + $i++; } $db->free($result); diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index d32986cbeeb8e3f891032729d2ee910e60d8bdf1..611eae49e4cef0a629a6b2e399f66922d7639ee7 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -106,39 +106,39 @@ $extralabels = $extrafields->fetch_name_optionals_label('contrat'); $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'c.ref'=>'Ref', - 'c.ref_customer'=>'RefCustomer', - 'c.ref_supplier'=>'RefSupplier', - 's.nom'=>"ThirdParty", - 'cd.description'=>'Description', - 'c.note_public'=>'NotePublic', + 'c.ref'=>'Ref', + 'c.ref_customer'=>'RefCustomer', + 'c.ref_supplier'=>'RefSupplier', + 's.nom'=>"ThirdParty", + 'cd.description'=>'Description', + 'c.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["c.note_private"]="NotePrivate"; $arrayfields=array( - 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'c.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 'c.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.email'=>array('label'=>$langs->trans("ThirdPartyEmail"), 'checked'=>0), + 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'c.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 'c.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.email'=>array('label'=>$langs->trans("ThirdPartyEmail"), 'checked'=>0), 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>0), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'sale_representative'=>array('label'=>$langs->trans("SalesRepresentative"), 'checked'=>1), - 'c.date_contrat'=>array('label'=>$langs->trans("DateContract"), 'checked'=>1), - 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'lower_planned_end_date'=>array('label'=>$langs->trans("LowerDateEndPlannedShort"), 'checked'=>1, 'position'=>900), - 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'sale_representative'=>array('label'=>$langs->trans("SalesRepresentative"), 'checked'=>1), + 'c.date_contrat'=>array('label'=>$langs->trans("DateContract"), 'checked'=>1), + 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'lower_planned_end_date'=>array('label'=>$langs->trans("LowerDateEndPlannedShort"), 'checked'=>1, 'position'=>900), + 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! 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'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } @@ -163,10 +163,10 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $year=''; $search_dfmonth=''; $search_dfyear=''; - $search_op2df=''; - $search_name=""; - $search_email=""; - $search_town=''; + $search_op2df=''; + $search_name=""; + $search_email=""; + $search_town=''; $search_zip=""; $search_state=""; $search_type=''; @@ -174,9 +174,9 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_contract=""; $search_ref_customer=""; $search_ref_supplier=""; - $search_user=''; - $search_sale=''; - $search_product_category=''; + $search_user=''; + $search_sale=''; + $search_product_category=''; $sall=""; $search_status=""; $toselect=''; @@ -185,12 +185,12 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', if (empty($reshook)) { - $objectclass='Contrat'; - $objectlabel='Contracts'; - $permtoread = $user->rights->contrat->lire; - $permtodelete = $user->rights->contrat->supprimer; - $uploaddir = $conf->contrat->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + $objectclass='Contrat'; + $objectlabel='Contracts'; + $permtoread = $user->rights->contrat->lire; + $permtodelete = $user->rights->contrat->supprimer; + $uploaddir = $conf->contrat->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -235,8 +235,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= " WHERE c.fk_soc = s.rowid "; $sql.= ' AND c.entity IN ('.getEntity('contract').')'; @@ -245,12 +245,12 @@ if ($socid) $sql.= " AND s.rowid = ".$db->escape($socid); if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($month > 0) { - if ($year > 0 && empty($day)) - $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(c.date_contrat, '%m') = '".$month."'"; + if ($year > 0 && empty($day)) + $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(c.date_contrat, '%m') = '".$month."'"; } else if ($year > 0) { @@ -270,16 +270,16 @@ if ($search_user > 0) $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.elemen // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -305,7 +305,7 @@ $sql.=$hookmanager->resPrint; if ($search_dfyear > 0) { - $sql.= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") ".$search_op2df."= '".$db->idate(($search_op2df == "<" ? dol_get_last_day($search_dfyear,$search_dfmonth,false) : dol_get_first_day($search_dfyear,$search_dfmonth,false)))."'"; + $sql.= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") ".$search_op2df."= '".$db->idate(($search_op2df == "<" ? dol_get_last_day($search_dfyear,$search_dfmonth,false) : dol_get_first_day($search_dfyear,$search_dfmonth,false)))."'"; } $sql.= $db->order($sortfield,$sortorder); @@ -314,14 +314,14 @@ $totalnboflines=0; $result=$db->query($sql); if ($result) { - $totalnboflines = $db->num_rows($result); + $totalnboflines = $db->num_rows($result); } $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit + 1, $offset); @@ -329,10 +329,10 @@ $sql.= $db->plimit($limit + 1, $offset); $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; + $num = $db->num_rows($resql); + $i = 0; - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected=is_array($toselect)?$toselect:array(); if ($socid > 0) { @@ -341,42 +341,42 @@ if ($resql) if (empty($search_name)) $search_name = $soc->name; } - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($sall != '') $param.='&sall='.urlencode($sall); - if ($search_contract != '') $param.='&search_contract='.urlencode($search_contract); - if ($search_name != '') $param.='&search_name='.urlencode($search_name); - if ($search_email != '') $param.='&search_email='.urlencode($search_email); - if ($search_ref_customer != '') $param.='&search_ref_customer='.urlencode($search_ref_customer); - if ($search_ref_supplier != '') $param.='&search_ref_supplier='.urlencode($search_ref_supplier); - if ($search_op2df != '') $param.='&search_op2df='.urlencode($search_op2df); - if ($search_dfyear != '') $param.='&search_dfyear='.urlencode($search_dfyear); - if ($search_dfmonth != '') $param.='&search_dfmonth='.urlencode($search_dfmonth); - if ($search_sale != '') $param.='&search_sale=' .urlencode($search_sale); - if ($search_user != '') $param.='&search_user=' .urlencode($search_user); - if ($search_product_category != '') $param.='&search_product_category=' .urlencode($search_product_category); - if ($show_files) $param.='&show_files=' .urlencode($show_files); - if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - // List of mass actions available - $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), - ); - if ($user->rights->contrat->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - if ($massaction == 'presend') $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - - print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($sall != '') $param.='&sall='.urlencode($sall); + if ($search_contract != '') $param.='&search_contract='.urlencode($search_contract); + if ($search_name != '') $param.='&search_name='.urlencode($search_name); + if ($search_email != '') $param.='&search_email='.urlencode($search_email); + if ($search_ref_customer != '') $param.='&search_ref_customer='.urlencode($search_ref_customer); + if ($search_ref_supplier != '') $param.='&search_ref_supplier='.urlencode($search_ref_supplier); + if ($search_op2df != '') $param.='&search_op2df='.urlencode($search_op2df); + if ($search_dfyear != '') $param.='&search_dfyear='.urlencode($search_dfyear); + if ($search_dfmonth != '') $param.='&search_dfmonth='.urlencode($search_dfmonth); + if ($search_sale != '') $param.='&search_sale=' .urlencode($search_sale); + if ($search_user != '') $param.='&search_user=' .urlencode($search_user); + if ($search_product_category != '') $param.='&search_product_category=' .urlencode($search_product_category); + if ($show_files) $param.='&show_files=' .urlencode($show_files); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + // Add $param from extra fields + foreach ($search_array_options as $key => $val) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } + + // List of mass actions available + $arrayofmassactions = array( + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), + ); + if ($user->rights->contrat->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + if ($massaction == 'presend') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + + print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">'; + if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -384,41 +384,41 @@ if ($resql) print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="page" value="'.$page.'">'; - print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'title_commercial.png', 0, '', '', $limit); + print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'title_commercial.png', 0, '', '', $limit); - if ($massaction == 'presend') - { - $topicmail="SendContractRef"; - $modelmail="contract"; - $objecttmp=new Contrat($db); - $trackid='con'.$object->id; + if ($massaction == 'presend') + { + $topicmail="SendContractRef"; + $modelmail="contract"; + $objecttmp=new Contrat($db); + $trackid='con'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; - } + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; + } if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } - - $moreforfilter=''; - - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter.='<div class="divsearchfield">'; - $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; - $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user,0,1,'maxwidth200'); - $moreforfilter.='</div>'; - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } + + $moreforfilter=''; + + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) + { + $langs->load("commercial"); + $moreforfilter.='<div class="divsearchfield">'; + $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; + $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user,0,1,'maxwidth200'); + $moreforfilter.='</div>'; + } // If the user can view other users if ($user->rights->user->user->lire) { $moreforfilter.='<div class="divsearchfield">'; $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='</div>'; } // If the user can view categories of products @@ -432,440 +432,440 @@ if ($resql) $moreforfilter.='</div>'; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + $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; - if (! empty($moreforfilter)) - { - print '<div class="liste_titre liste_titre_bydiv centpercent">'; - print $moreforfilter; - print '</div>'; - } + if (! empty($moreforfilter)) + { + print '<div class="liste_titre liste_titre_bydiv centpercent">'; + print $moreforfilter; + print '</div>'; + } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $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); - print '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; - - print '<tr class="liste_titre_filter">'; - if (! empty($arrayfields['c.ref']['checked'])) - { - print '<td class="liste_titre">'; - print '<input type="text" class="flat" size="3" name="search_contract" value="'.dol_escape_htmltag($search_contract).'">'; - print '</td>'; - } - if (! empty($arrayfields['c.ref_customer']['checked'])) - { - print '<td class="liste_titre">'; - print '<input type="text" class="flat" size="6" name="search_ref_customer" value="'.dol_escape_htmltag($search_ref_customer).'">'; - print '</td>'; - } - if (! empty($arrayfields['c.ref_supplier']['checked'])) - { - print '<td class="liste_titre">'; - print '<input type="text" class="flat" size="6" name="search_ref_supplier" value="'.dol_escape_htmltag($search_ref_supplier).'">'; - print '</td>'; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print '<td class="liste_titre">'; - print '<input type="text" class="flat" size="8" name="search_name" value="'.dol_escape_htmltag($search_name).'">'; - print '</td>'; - } - if (! empty($arrayfields['s.email']['checked'])) - { - print '<td class="liste_titre">'; - print '<input type="text" class="flat" size="6" name="search_email" value="'.dol_escape_htmltag($search_email).'">'; - print '</td>'; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; - // Zip - if (! empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_zip" value="'.$search_zip.'"></td>'; - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print '<td class="liste_titre">'; - print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; - print '</td>'; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print '<td class="liste_titre" align="center">'; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print '</td>'; - } - // Company type - if (! empty($arrayfields['typent.code']['checked'])) - { - print '<td class="liste_titre maxwidthonsmartphone" align="center">'; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print '</td>'; - } - if (! empty($arrayfields['sale_representative']['checked'])) - { - print '<td class="liste_titre"></td>'; - } - if (! empty($arrayfields['c.date_contrat']['checked'])) - { - // Date contract - print '<td class="liste_titre center">'; - //print $langs->trans('Month').': '; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.$day.'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">'; - //print ' '.$langs->trans('Year').': '; - $syear = $year; - $formother->select_year($syear,'year',1, 20, 5); - print '</td>'; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } - print '</td>'; - } - } - } - // 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; - // Date creation - if (! empty($arrayfields['c.datec']['checked'])) - { - print '<td class="liste_titre">'; - print '</td>'; - } - // Date modification - if (! empty($arrayfields['c.tms']['checked'])) - { - print '<td class="liste_titre">'; - print '</td>'; - } - // First end date - if (! empty($arrayfields['lower_planned_end_date']['checked'])) - { - print '<td class="liste_titre" align="center">'; - $arrayofoperators=array('<'=>'<','>'=>'>'); - print $form->selectarray('search_op2df',$arrayofoperators,$search_op2df,0); - print '</br>'; - print $formother->select_month($search_dfmonth, 'search_dfmonth', 1); - print ' '; - $formother->select_year($search_dfyear, 'search_dfyear', 1, 20, 5); - print '</td>'; - } - // Status - if (! empty($arrayfields['status']['checked'])) - { - print '<td class="liste_titre" colspan="4" align="right"></td>'; - } - print '<td class="liste_titre" align="middle">'; - $searchpicto=$form->showFilterButtons(); - print $searchpicto; - print '</td>'; - print "</tr>\n"; - - print '<tr class="liste_titre">'; - if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); + print '<div class="div-table-responsive">'; + print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; + + print '<tr class="liste_titre_filter">'; + if (! empty($arrayfields['c.ref']['checked'])) + { + print '<td class="liste_titre">'; + print '<input type="text" class="flat" size="3" name="search_contract" value="'.dol_escape_htmltag($search_contract).'">'; + print '</td>'; + } + if (! empty($arrayfields['c.ref_customer']['checked'])) + { + print '<td class="liste_titre">'; + print '<input type="text" class="flat" size="6" name="search_ref_customer" value="'.dol_escape_htmltag($search_ref_customer).'">'; + print '</td>'; + } + if (! empty($arrayfields['c.ref_supplier']['checked'])) + { + print '<td class="liste_titre">'; + print '<input type="text" class="flat" size="6" name="search_ref_supplier" value="'.dol_escape_htmltag($search_ref_supplier).'">'; + print '</td>'; + } + if (! empty($arrayfields['s.nom']['checked'])) + { + print '<td class="liste_titre">'; + print '<input type="text" class="flat" size="8" name="search_name" value="'.dol_escape_htmltag($search_name).'">'; + print '</td>'; + } + if (! empty($arrayfields['s.email']['checked'])) + { + print '<td class="liste_titre">'; + print '<input type="text" class="flat" size="6" name="search_email" value="'.dol_escape_htmltag($search_email).'">'; + print '</td>'; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; + // Zip + if (! empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_zip" value="'.$search_zip.'"></td>'; + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print '<td class="liste_titre">'; + print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; + print '</td>'; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print '<td class="liste_titre" align="center">'; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print '</td>'; + } + // Company type + if (! empty($arrayfields['typent.code']['checked'])) + { + print '<td class="liste_titre maxwidthonsmartphone" align="center">'; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print '</td>'; + } + if (! empty($arrayfields['sale_representative']['checked'])) + { + print '<td class="liste_titre"></td>'; + } + if (! empty($arrayfields['c.date_contrat']['checked'])) + { + // Date contract + print '<td class="liste_titre center">'; + //print $langs->trans('Month').': '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.$day.'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">'; + //print ' '.$langs->trans('Year').': '; + $syear = $year; + $formother->select_year($syear,'year',1, 20, 5); + print '</td>'; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } + print '</td>'; + } + } + } + // 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; + // Date creation + if (! empty($arrayfields['c.datec']['checked'])) + { + print '<td class="liste_titre">'; + print '</td>'; + } + // Date modification + if (! empty($arrayfields['c.tms']['checked'])) + { + print '<td class="liste_titre">'; + print '</td>'; + } + // First end date + if (! empty($arrayfields['lower_planned_end_date']['checked'])) + { + print '<td class="liste_titre" align="center">'; + $arrayofoperators=array('<'=>'<','>'=>'>'); + print $form->selectarray('search_op2df',$arrayofoperators,$search_op2df,0); + print '</br>'; + print $formother->select_month($search_dfmonth, 'search_dfmonth', 1); + print ' '; + $formother->select_year($search_dfyear, 'search_dfyear', 1, 20, 5); + print '</td>'; + } + // Status + if (! empty($arrayfields['status']['checked'])) + { + print '<td class="liste_titre" colspan="4" align="right"></td>'; + } + print '<td class="liste_titre" align="middle">'; + $searchpicto=$form->showFilterButtons(); + print $searchpicto; + print '</td>'; + print "</tr>\n"; + + print '<tr class="liste_titre">'; + if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat","","$param",'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat","","$param",'align="center"',$sortfield,$sortorder); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'],$_SERVER["PHP_SELF"],"c.date_creation","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'],$_SERVER["PHP_SELF"],"c.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['lower_planned_end_date']['checked'])) print_liste_field_titre($arrayfields['lower_planned_end_date']['label'],$_SERVER["PHP_SELF"],"lower_planned_end_date","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['status']['checked'])) - { - print_liste_field_titre($staticcontratligne->LibStatut(0,3), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(4,3,0), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(4,3,1), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(5,3), '', '', '', '', 'width="16"'); - } + if (! empty($arrayfields['lower_planned_end_date']['checked'])) print_liste_field_titre($arrayfields['lower_planned_end_date']['label'],$_SERVER["PHP_SELF"],"lower_planned_end_date","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['status']['checked'])) + { + print_liste_field_titre($staticcontratligne->LibStatut(0,3), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(4,3,0), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(4,3,1), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(5,3), '', '', '', '', 'width="16"'); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "</tr>\n"; - - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); - - $contracttmp->ref=$obj->ref; - $contracttmp->id=$obj->rowid; - $contracttmp->ref_customer=$obj->ref_customer; - $contracttmp->ref_supplier=$obj->ref_supplier; - - if ($obj->socid > 0) - { - $result=$socstatic->fetch($obj->socid); - } - - print '<tr class="oddeven">'; - if (! empty($arrayfields['c.ref']['checked'])) - { - print '<td class="nowrap">'; - print $contracttmp->getNomUrl(1); - if ($obj->nb_late) print img_warning($langs->trans("Late")); - if (!empty($obj->note_private) || !empty($obj->note_public)) - { - print ' <span class="note">'; - print '<a href="'.DOL_URL_ROOT.'/contrat/note.php?id='.$obj->rowid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>'; - print '</span>'; - } - - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->contrat->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($contracttmp->element, $filename, $filedir); - print '</td>'; - - print '</td>'; - } - if (! empty($arrayfields['c.ref_customer']['checked'])) - { - print '<td>'.$obj->ref_customer.'</td>'; - } - if (! empty($arrayfields['c.ref_supplier']['checked'])) - { - print '<td>'.$obj->ref_supplier.'</td>'; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print '<td>'; - //print '<a href="../comm/card.php?socid='.$obj->socid.'">'.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.'</a>'; - if ($obj->socid > 0) - { - print $socstatic->getNomUrl(1, ''); - } - print '</td>'; - } - if (! empty($arrayfields['s.email']['checked'])) - { - print '<td>'.$obj->email.'</td>'; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->town; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->zip; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "<td>".$obj->state_name."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print '<td align="center">'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print '<td align="center">'; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['sale_representative']['checked'])) - { - // Sales representatives - print '<td>'; - if ($obj->socid > 0) - { - $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); - if ($listsalesrepresentatives < 0) dol_print_error($db); - $nbofsalesrepresentative=count($listsalesrepresentatives); - if ($nbofsalesrepresentative > 3) // We print only number - { - print '<a href="'.DOL_URL_ROOT.'/societe/commerciaux.php?socid='.$socstatic->id.'">'; - print $nbofsalesrepresentative; - print '</a>'; - } - else if ($nbofsalesrepresentative > 0) - { - $userstatic=new User($db); - $j=0; - foreach($listsalesrepresentatives as $val) - { - $userstatic->id=$val['id']; - $userstatic->lastname=$val['lastname']; - $userstatic->firstname=$val['firstname']; - print '<div class="float">'.$userstatic->getNomUrl(1); - $j++; - if ($j < $nbofsalesrepresentative) print ', '; - print '</div>'; - } - } - //else print $langs->trans("NoSalesRepresentativeAffected"); - } - else - { - print ' '; - } - print '</td>'; - } - // Date - if (! empty($arrayfields['c.date_contrat']['checked'])) - { - print '<td align="center">'.dol_print_date($db->jdate($obj->date_contrat), 'day').'</td>'; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } - } - // 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['c.datec']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['c.tms']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date lower end date - if (! empty($arrayfields['lower_planned_end_date']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['status']['checked'])) - { - print '<td align="center">'.($obj->nb_initial>0?$obj->nb_initial:'').'</td>'; - print '<td align="center">'.($obj->nb_running>0?$obj->nb_running:'').'</td>'; - print '<td align="center">'.($obj->nb_expired>0?$obj->nb_expired:'').'</td>'; - print '<td align="center">'.($obj->nb_closed>0 ?$obj->nb_closed:'').'</td>'; - } - // Action column - print '<td class="nowrap" align="center">'; - 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - - print "</tr>\n"; - $i++; - } - $db->free($resql); - - print '</table>'; - print '</div>'; - - print '</form>'; - - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) - { - /* + print "</tr>\n"; + + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); + + $contracttmp->ref=$obj->ref; + $contracttmp->id=$obj->rowid; + $contracttmp->ref_customer=$obj->ref_customer; + $contracttmp->ref_supplier=$obj->ref_supplier; + + if ($obj->socid > 0) + { + $result=$socstatic->fetch($obj->socid); + } + + print '<tr class="oddeven">'; + if (! empty($arrayfields['c.ref']['checked'])) + { + print '<td class="nowrap">'; + print $contracttmp->getNomUrl(1); + if ($obj->nb_late) print img_warning($langs->trans("Late")); + if (!empty($obj->note_private) || !empty($obj->note_public)) + { + print ' <span class="note">'; + print '<a href="'.DOL_URL_ROOT.'/contrat/note.php?id='.$obj->rowid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>'; + print '</span>'; + } + + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->contrat->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($contracttmp->element, $filename, $filedir); + print '</td>'; + + print '</td>'; + } + if (! empty($arrayfields['c.ref_customer']['checked'])) + { + print '<td>'.$obj->ref_customer.'</td>'; + } + if (! empty($arrayfields['c.ref_supplier']['checked'])) + { + print '<td>'.$obj->ref_supplier.'</td>'; + } + if (! empty($arrayfields['s.nom']['checked'])) + { + print '<td>'; + //print '<a href="../comm/card.php?socid='.$obj->socid.'">'.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.'</a>'; + if ($obj->socid > 0) + { + print $socstatic->getNomUrl(1, ''); + } + print '</td>'; + } + if (! empty($arrayfields['s.email']['checked'])) + { + print '<td>'.$obj->email.'</td>'; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) + { + print '<td class="nocellnopadd">'; + print $obj->town; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print '<td class="nocellnopadd">'; + print $obj->zip; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "<td>".$obj->state_name."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print '<td align="center">'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print '<td align="center">'; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['sale_representative']['checked'])) + { + // Sales representatives + print '<td>'; + if ($obj->socid > 0) + { + $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); + if ($listsalesrepresentatives < 0) dol_print_error($db); + $nbofsalesrepresentative=count($listsalesrepresentatives); + if ($nbofsalesrepresentative > 3) // We print only number + { + print '<a href="'.DOL_URL_ROOT.'/societe/commerciaux.php?socid='.$socstatic->id.'">'; + print $nbofsalesrepresentative; + print '</a>'; + } + else if ($nbofsalesrepresentative > 0) + { + $userstatic=new User($db); + $j=0; + foreach($listsalesrepresentatives as $val) + { + $userstatic->id=$val['id']; + $userstatic->lastname=$val['lastname']; + $userstatic->firstname=$val['firstname']; + print '<div class="float">'.$userstatic->getNomUrl(1); + $j++; + if ($j < $nbofsalesrepresentative) print ', '; + print '</div>'; + } + } + //else print $langs->trans("NoSalesRepresentativeAffected"); + } + else + { + print ' '; + } + print '</td>'; + } + // Date + if (! empty($arrayfields['c.date_contrat']['checked'])) + { + print '<td align="center">'.dol_print_date($db->jdate($obj->date_contrat), 'day').'</td>'; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } + } + // 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['c.datec']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['c.tms']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date lower end date + if (! empty($arrayfields['lower_planned_end_date']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['status']['checked'])) + { + print '<td align="center">'.($obj->nb_initial>0?$obj->nb_initial:'').'</td>'; + print '<td align="center">'.($obj->nb_running>0?$obj->nb_running:'').'</td>'; + print '<td align="center">'.($obj->nb_expired>0?$obj->nb_expired:'').'</td>'; + print '<td align="center">'.($obj->nb_closed>0 ?$obj->nb_closed:'').'</td>'; + } + // Action column + print '<td class="nowrap" align="center">'; + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + + print "</tr>\n"; + $i++; + } + $db->free($resql); + + print '</table>'; + print '</div>'; + + print '</form>'; + + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); - - $filedir=$diroutputmassaction; - $genallowed=$user->rights->contrat->lire; - $delallowed=$user->rights->contrat->lire; - - print $formfile->showdocuments('massfilesarea_contract','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; - } + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); + + $filedir=$diroutputmassaction; + $genallowed=$user->rights->contrat->lire; + $delallowed=$user->rights->contrat->lire; + + print $formfile->showdocuments('massfilesarea_contract','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; + } } else { - dol_print_error($db); + dol_print_error($db); } diff --git a/htdocs/contrat/services.php b/htdocs/contrat/services.php index d39c61e397c184ff55e4b29140bc0304a3ea1dee..84a7fd17cc28f9f6d489427a57d3a1aa42d4c260 100644 --- a/htdocs/contrat/services.php +++ b/htdocs/contrat/services.php @@ -92,20 +92,20 @@ $result = restrictedArea($user, 'contrat',$contratid); if ($search_status != '') { - $tmp=explode('&', $search_status); - $mode=$tmp[0]; - if (empty($tmp[1])) $filter=''; - else - { - if ($tmp[1] == 'filter=notexpired') $filter='notexpired'; - if ($tmp[1] == 'filter=expired') $filter='expired'; - } + $tmp=explode('&', $search_status); + $mode=$tmp[0]; + if (empty($tmp[1])) $filter=''; + else + { + if ($tmp[1] == 'filter=notexpired') $filter='notexpired'; + if ($tmp[1] == 'filter=expired') $filter='expired'; + } } else { - $search_status = $mode; - if ($filter == 'expired') $search_status.='&filter=expired'; - if ($filter == 'notexpired') $search_status.='&filter=notexpired'; + $search_status = $mode; + if ($filter == 'expired') $search_status.='&filter=expired'; + if ($filter == 'notexpired') $search_status.='&filter=notexpired'; } $staticcontrat=new Contrat($db); @@ -113,29 +113,29 @@ $staticcontratligne=new ContratLigne($db); $companystatic=new Societe($db); $arrayfields=array( - 'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80), - 'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80), + 'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80), + 'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80), 'cd.qty'=>array('label'=>$langs->trans("Qty"), 'checked'=>0, 'position'=>100), 'cd.total_ht'=>array('label'=>$langs->trans("TotalHT"), 'checked'=>0, 'position'=>100), 'cd.total_tva'=>array('label'=>$langs->trans("TotalVAT"), 'checked'=>0, 'position'=>100), 'cd.tva_tx'=>array('label'=>$langs->trans("VAT"), 'checked'=>0, 'position'=>100), 'cd.subprice'=>array('label'=>$langs->trans("PriceUHT"), 'checked'=>0, 'position'=>100), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>100), - 'cd.date_ouverture_prevue'=>array('label'=>$langs->trans("DateStartPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode == "0")), - 'cd.date_ouverture'=>array('label'=>$langs->trans("DateStartRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode > 0)), - 'cd.date_fin_validite'=>array('label'=>$langs->trans("DateEndPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode < 5)), - 'cd.date_cloture'=>array('label'=>$langs->trans("DateEndRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode >= 5)), - 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1), - //'cd.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>100), + 'cd.date_ouverture_prevue'=>array('label'=>$langs->trans("DateStartPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode == "0")), + 'cd.date_ouverture'=>array('label'=>$langs->trans("DateStartRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode > 0)), + 'cd.date_fin_validite'=>array('label'=>$langs->trans("DateEndPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode < 5)), + 'cd.date_cloture'=>array('label'=>$langs->trans("DateEndRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode >= 5)), + 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1), + //'cd.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } @@ -154,37 +154,37 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers + { $search_product_category=0; - $search_name=""; - $search_contract=""; - $search_service=""; - $search_status=-1; - $opouvertureprevuemonth=""; - $opouvertureprevueday=""; - $opouvertureprevueyear=""; - $filter_opouvertureprevue=""; - $op1month=""; - $op1day=""; - $op1year=""; - $filter_op1=""; - $op2month=""; - $op2day=""; - $op2year=""; - $filter_op2=""; - $opcloturemonth=""; - $opclotureday=""; - $opclotureyear=""; - $filter_opcloture=""; - $mode=''; - $filter=''; - $toselect=''; - $search_array_options=array(); - } + $search_name=""; + $search_contract=""; + $search_service=""; + $search_status=-1; + $opouvertureprevuemonth=""; + $opouvertureprevueday=""; + $opouvertureprevueyear=""; + $filter_opouvertureprevue=""; + $op1month=""; + $op1day=""; + $op1year=""; + $filter_op1=""; + $op2month=""; + $op2day=""; + $op2year=""; + $filter_op2=""; + $opcloturemonth=""; + $opclotureday=""; + $opclotureyear=""; + $filter_opcloture=""; + $mode=''; + $filter=''; + $toselect=''; + $search_array_options=array(); + } } @@ -249,24 +249,24 @@ if (! empty($filter_opcloture) && $filter_opcloture != -1 && $filter_datecloture // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode_search=0; - if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode_search); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode_search=0; + if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode_search); + } } $sql .= $db->order($sortfield,$sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql .= $db->plimit($limit + 1, $offset); @@ -276,8 +276,8 @@ dol_syslog("contrat/services.php", LOG_DEBUG); $resql=$db->query($sql); if (! $resql) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($resql); @@ -313,15 +313,15 @@ if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->contrat->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); //if ($massaction == 'presend') $arrayofmassactions=array(); @@ -346,8 +346,8 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } $morefilter = ''; @@ -355,12 +355,12 @@ $morefilter = ''; // If the user can view categories of products if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { - include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $moreforfilter.='<div class="divsearchfield">'; - $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter.='</div>'; + include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter.='<div class="divsearchfield">'; + $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); + $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); + $moreforfilter.='</div>'; } $parameters=array(); @@ -371,9 +371,9 @@ else $moreforfilter = $hookmanager->resPrint; if (! empty($moreforfilter)) { - print '<div class="liste_titre liste_titre_bydiv centpercent">'; - print $moreforfilter; - print '</div>'; + print '<div class="liste_titre liste_titre_bydiv centpercent">'; + print $moreforfilter; + print '</div>'; } $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; @@ -399,16 +399,16 @@ if (! empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); $sortonfield = "ef.".$key; if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -432,7 +432,7 @@ if (! empty($arrayfields['c.ref']['checked'])) // Service label if (! empty($arrayfields['p.description']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input type="text" class="flat maxwidth100" name="search_service" value="'.dol_escape_htmltag($search_service).'">'; print '</td>'; } @@ -465,7 +465,7 @@ if (! empty($arrayfields['cd.subprice']['checked'])) // Third party if (! empty($arrayfields['s.nom']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input type="text" class="flat maxwidth100" name="search_name" value="'.dol_escape_htmltag($search_name).'">'; print '</td>'; } @@ -474,7 +474,7 @@ if (! empty($arrayfields['s.nom']['checked'])) if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) { print '<td class="liste_titre" align="center">'; - $arrayofoperators=array('<'=>'<','>'=>'>'); + $arrayofoperators=array('<'=>'<','>'=>'>'); print $form->selectarray('filter_opouvertureprevue',$arrayofoperators,$filter_opouvertureprevue,1); print ' '; $filter_dateouvertureprevue=dol_mktime(0,0,0,$opouvertureprevuemonth,$opouvertureprevueday,$opouvertureprevueyear); @@ -484,7 +484,7 @@ if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) if (! empty($arrayfields['cd.date_ouverture']['checked'])) { print '<td class="liste_titre" align="center">'; - $arrayofoperators=array('<'=>'<','>'=>'>'); + $arrayofoperators=array('<'=>'<','>'=>'>'); print $form->selectarray('filter_op1',$arrayofoperators,$filter_op1,1); print ' '; $filter_date1=dol_mktime(0,0,0,$op1month,$op1day,$op1year); @@ -503,41 +503,41 @@ if (! empty($arrayfields['cd.date_fin_validite']['checked'])) } if (! empty($arrayfields['cd.date_cloture']['checked'])) { - print '<td class="liste_titre" align="center">'; - $arrayofoperators=array('<'=>'<','>'=>'>'); - print $form->selectarray('filter_opcloture',$arrayofoperators,$filter_opcloture,1); - print ' '; - $filter_date_cloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear); - print $form->select_date($filter_date_cloture,'opcloture',0,0,1,'',1,0,1); - print '</td>'; + print '<td class="liste_titre" align="center">'; + $arrayofoperators=array('<'=>'<','>'=>'>'); + print $form->selectarray('filter_opcloture',$arrayofoperators,$filter_opcloture,1); + print ' '; + $filter_date_cloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear); + print $form->select_date($filter_date_cloture,'opcloture',0,0,1,'',1,0,1); + print '</td>'; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } 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') echo $extrafields->showInputField($key, $search_array_options['search_options_'.$key], '', '', 'search_'); } - print '</td>'; - } - } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -545,26 +545,26 @@ $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // N print $hookmanager->resPrint; if (! empty($arrayfields['cd.datec']['checked'])) { - // Date creation - print '<td class="liste_titre">'; - print '</td>'; + // Date creation + print '<td class="liste_titre">'; + print '</td>'; } if (! empty($arrayfields['cd.tms']['checked'])) { - // Date modification - print '<td class="liste_titre">'; - print '</td>'; + // Date modification + print '<td class="liste_titre">'; + print '</td>'; } if (! empty($arrayfields['status']['checked'])) { - // Status - print '<td class="liste_titre" align="right">'; + // Status + print '<td class="liste_titre" align="right">'; $arrayofstatus=array( - '0'=>$langs->trans("ServiceStatusInitial"), - '4'=>$langs->trans("ServiceStatusRunning"), - '4&filter=notexpired'=>$langs->trans("ServiceStatusNotLate"), - '4&filter=expired'=>$langs->trans("ServiceStatusLate"), - '5'=>$langs->trans("ServiceStatusClosed") + '0'=>$langs->trans("ServiceStatusInitial"), + '4'=>$langs->trans("ServiceStatusRunning"), + '4&filter=notexpired'=>$langs->trans("ServiceStatusNotLate"), + '4&filter=expired'=>$langs->trans("ServiceStatusLate"), + '5'=>$langs->trans("ServiceStatusClosed") ); print $form->selectarray('search_status', $arrayofstatus, (strstr($search_status, ',')?-1:$search_status), 1, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone'); print '</td>'; @@ -591,16 +591,16 @@ while ($i < min($num,$limit)) print '<tr class="oddeven">'; // Ref - if (! empty($arrayfields['c.ref']['checked'])) - { - print '<td>'; + if (! empty($arrayfields['c.ref']['checked'])) + { + print '<td>'; print $contractstatic->getNomUrl(1,16); print '</td>'; - } + } // Service - if (! empty($arrayfields['p.description']['checked'])) - { - print '<td>'; + if (! empty($arrayfields['p.description']['checked'])) + { + print '<td>'; if ($obj->pid) { $productstatic->id=$obj->pid; @@ -608,8 +608,8 @@ while ($i < min($num,$limit)) $productstatic->ref=$obj->pref; $productstatic->entity=$obj->pentity; print $productstatic->getNomUrl(1,'',24); - print $obj->label?' - '.dol_trunc($obj->label,16):''; - if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '<br>'.dol_nl2br($obj->description); + print $obj->label?' - '.dol_trunc($obj->label,16):''; + if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '<br>'.dol_nl2br($obj->description); } else { @@ -617,54 +617,54 @@ while ($i < min($num,$limit)) if ($obj->type == 1) print img_object($obj->description,'service').' '.dol_trunc($obj->description,24); } print '</td>'; - } - - if (! empty($arrayfields['cd.qty']['checked'])) - { - print '<td>'; - print $obj->qty; - print '</td>'; - } - if (! empty($arrayfields['cd.total_ht']['checked'])) - { - print '<td>'; - print price($obj->total_ht); - print '</td>'; - } - if (! empty($arrayfields['cd.total_tva']['checked'])) - { - print '<td>'; - print price($obj->total_tva); - print '</td>'; - } - if (! empty($arrayfields['cd.tva_tx']['checked'])) - { - print '<td>'; - print price2num($obj->tva_tx).'%'; - print '</td>'; - } - if (! empty($arrayfields['cd.subprice']['checked'])) - { - print '<td>'; - print price($obj->subprice); - print '</td>'; - } + } + + if (! empty($arrayfields['cd.qty']['checked'])) + { + print '<td>'; + print $obj->qty; + print '</td>'; + } + if (! empty($arrayfields['cd.total_ht']['checked'])) + { + print '<td>'; + print price($obj->total_ht); + print '</td>'; + } + if (! empty($arrayfields['cd.total_tva']['checked'])) + { + print '<td>'; + print price($obj->total_tva); + print '</td>'; + } + if (! empty($arrayfields['cd.tva_tx']['checked'])) + { + print '<td>'; + print price2num($obj->tva_tx).'%'; + print '</td>'; + } + if (! empty($arrayfields['cd.subprice']['checked'])) + { + print '<td>'; + print price($obj->subprice); + print '</td>'; + } // Third party - if (! empty($arrayfields['s.nom']['checked'])) - { - print '<td>'; + if (! empty($arrayfields['s.nom']['checked'])) + { + print '<td>'; $companystatic->id=$obj->socid; $companystatic->name=$obj->name; $companystatic->client=1; print $companystatic->getNomUrl(1,'customer',28); print '</td>'; - } + } // Start date - if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) - { + if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) + { print '<td align="center">'; print ($obj->date_ouverture_prevue?dol_print_date($db->jdate($obj->date_ouverture_prevue)):' '); if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) @@ -672,45 +672,45 @@ while ($i < min($num,$limit)) else print ' '; print '</td>'; } - if (! empty($arrayfields['cd.date_ouverture']['checked'])) - { - print '<td align="center">'.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture)):' ').'</td>'; + if (! empty($arrayfields['cd.date_ouverture']['checked'])) + { + print '<td align="center">'.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture)):' ').'</td>'; } // End date - if (! empty($arrayfields['cd.date_fin_validite']['checked'])) - { - print '<td align="center">'.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite)):' '); + if (! empty($arrayfields['cd.date_fin_validite']['checked'])) + { + print '<td align="center">'.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite)):' '); if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) { - $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; - $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); - print img_warning($textlate); + $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; + $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); + print img_warning($textlate); } else print ' '; - print '</td>'; - } - if (! empty($arrayfields['cd.date_cloture']['checked'])) - { - print '<td align="center">'.dol_print_date($db->jdate($obj->date_cloture)).'</td>'; - } + print '</td>'; + } + if (! empty($arrayfields['cd.date_cloture']['checked'])) + { + print '<td align="center">'.dol_print_date($db->jdate($obj->date_cloture)).'</td>'; + } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); @@ -719,18 +719,18 @@ while ($i < min($num,$limit)) // Date creation if (! empty($arrayfields['cd.datec']['checked'])) { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['cd.tms']['checked'])) { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Status if (! empty($arrayfields['status']['checked'])) @@ -738,11 +738,11 @@ while ($i < min($num,$limit)) print '<td align="right">'; if ($obj->cstatut == 0) // If contract is draft, we say line is also draft { - print $contractstatic->LibStatut(0,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)); + print $contractstatic->LibStatut(0,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)); } else { - print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0); + print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0); } print '</td>'; } @@ -750,9 +750,9 @@ while ($i < min($num,$limit)) print '<td class="nowrap" align="center">'; 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; } print '</td>'; if (! $i) $totalarray['nbfield']++; diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 0b196699dc06d792c6629ab42abbb2b8b57f8fef..4aec6179365f8953f7f42bcc69bbfd9162400e35 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -34,8 +34,8 @@ // Protection if (empty($objectclass) || empty($uploaddir)) { - dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined'); - exit; + dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined'); + exit; } @@ -43,442 +43,442 @@ if (empty($objectclass) || empty($uploaddir)) $maxformassaction=(empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS)?1000:$conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS); if (! empty($massaction) && count($toselect) < 1) { - $error++; - setEventMessages($langs->trans("NoRecordSelected"), null, "warnings"); + $error++; + setEventMessages($langs->trans("NoRecordSelected"), null, "warnings"); } if (! $error && count($toselect) > $maxformassaction) { - setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors'); - $error++; + setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors'); + $error++; } if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail')) // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form { - $massaction='presend'; + $massaction='presend'; } if (! $error && $massaction == 'confirm_presend') { - $resaction = ''; - $nbsent = 0; - $nbignored = 0; - $langs->load("mails"); - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - $listofobjectid=array(); - $listofobjectthirdparties=array(); - $listofobjectref=array(); - - if (! $error) - { - $thirdparty=new Societe($db); - if ($objecttmp->element == 'expensereport') $thirdparty=new User($db); - - $objecttmp=new $objectclass($db); - foreach($toselect as $toselectid) - { - $objecttmp=new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $listofobjectid[$toselectid]=$toselectid; - $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; - if ($objecttmp->element == 'societe') $thirdpartyid=$objecttmp->id; - if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author; - $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; - $listofobjectref[$thirdpartyid][$toselectid]=$objecttmp; - } - } - } - - // Check mandatory parameters - if (empty($user->email)) - { - $error++; - setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings'); - $massaction='presend'; - } - - $receiver=$_POST['receiver']; - if (! is_array($receiver)) - { - if (empty($receiver) || $receiver == '-1') $receiver=array(); - else $receiver=array($receiver); - } - if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) // if only one recipient, receiver is mandatory - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings'); - $massaction='presend'; - } - - if (! GETPOST('subject','none')) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings'); - $massaction='presend'; - } - - // Loop on each recipient/thirdparty - if (! $error) - { - foreach ($listofobjectthirdparties as $thirdpartyid) - { - $result = $thirdparty->fetch($thirdpartyid); - if ($result < 0) - { - dol_print_error($db); - exit; - } - - $sendto=''; - $sendtocc=''; - $sendtobcc=''; - $sendtoid = array(); - - // Define $sendto - $tmparray=array(); - if (trim($_POST['sendto'])) - { - // Recipients are provided into free text - $tmparray[] = trim($_POST['sendto']); - } - if (count($receiver)>0) - { - foreach($receiver as $key=>$val) - { - // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party or user - { - $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; - } - elseif ($val && method_exists($thirdparty, 'contact_get_property')) // Id of contact - { - $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); - $sendtoid[] = $val; - } - } - } - $sendto=implode(',',$tmparray); - - // Define $sendtocc - $receivercc=$_POST['receivercc']; - if (! is_array($receivercc)) - { - if ($receivercc == '-1') $receivercc=array(); - else $receivercc=array($receivercc); - } - $tmparray=array(); - if (trim($_POST['sendtocc'])) - { - $tmparray[] = trim($_POST['sendtocc']); - } - if (count($receivercc) > 0) - { - foreach($receivercc as $key=>$val) - { - // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party - { - $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; - } - elseif ($val) // Id du contact - { - $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); - //$sendtoid[] = $val; TODO Add also id of contact in CC ? - } - } - } - $sendtocc=implode(',',$tmparray); - - //var_dump($listofobjectref);exit; - $attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array()); - $listofqualifiedid=array(); - $listofqualifiedref=array(); - $thirdpartywithoutemail=array(); - - foreach($listofobjectref[$thirdpartyid] as $objectid => $object) - { - //var_dump($thirdpartyid.' - '.$objectid.' - '.$object->statut); - if ($objectclass == 'Propal' && $object->statut == Propal::STATUS_DRAFT) - { - $langs->load("errors"); - $nbignored++; - $resaction.='<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$object->ref).'</div><br>'; - continue; // Payment done or started or canceled - } - if ($objectclass == 'Commande' && $object->statut == Commande::STATUS_DRAFT) - { - $langs->load("errors"); - $nbignored++; - $resaction.='<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$object->ref).'</div><br>'; - continue; - } - if ($objectclass == 'Facture' && $object->statut != Facture::STATUS_VALIDATED) - { - $langs->load("errors"); - $nbignored++; - $resaction.='<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$object->ref).'</div><br>'; - continue; // Payment done or started or canceled - } - - // Test recipient - if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send) - { - if ($object->element == 'expensereport') - { + $resaction = ''; + $nbsent = 0; + $nbignored = 0; + $langs->load("mails"); + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + $listofobjectid=array(); + $listofobjectthirdparties=array(); + $listofobjectref=array(); + + if (! $error) + { + $thirdparty=new Societe($db); + if ($objecttmp->element == 'expensereport') $thirdparty=new User($db); + + $objecttmp=new $objectclass($db); + foreach($toselect as $toselectid) + { + $objecttmp=new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + $listofobjectid[$toselectid]=$toselectid; + $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; + if ($objecttmp->element == 'societe') $thirdpartyid=$objecttmp->id; + if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author; + $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; + $listofobjectref[$thirdpartyid][$toselectid]=$objecttmp; + } + } + } + + // Check mandatory parameters + if (empty($user->email)) + { + $error++; + setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings'); + $massaction='presend'; + } + + $receiver=$_POST['receiver']; + if (! is_array($receiver)) + { + if (empty($receiver) || $receiver == '-1') $receiver=array(); + else $receiver=array($receiver); + } + if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) // if only one recipient, receiver is mandatory + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings'); + $massaction='presend'; + } + + if (! GETPOST('subject','none')) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings'); + $massaction='presend'; + } + + // Loop on each recipient/thirdparty + if (! $error) + { + foreach ($listofobjectthirdparties as $thirdpartyid) + { + $result = $thirdparty->fetch($thirdpartyid); + if ($result < 0) + { + dol_print_error($db); + exit; + } + + $sendto=''; + $sendtocc=''; + $sendtobcc=''; + $sendtoid = array(); + + // Define $sendto + $tmparray=array(); + if (trim($_POST['sendto'])) + { + // Recipients are provided into free text + $tmparray[] = trim($_POST['sendto']); + } + if (count($receiver)>0) + { + foreach($receiver as $key=>$val) + { + // Recipient was provided from combo list + if ($val == 'thirdparty') // Id of third party or user + { + $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; + } + elseif ($val && method_exists($thirdparty, 'contact_get_property')) // Id of contact + { + $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); + $sendtoid[] = $val; + } + } + } + $sendto=implode(',',$tmparray); + + // Define $sendtocc + $receivercc=$_POST['receivercc']; + if (! is_array($receivercc)) + { + if ($receivercc == '-1') $receivercc=array(); + else $receivercc=array($receivercc); + } + $tmparray=array(); + if (trim($_POST['sendtocc'])) + { + $tmparray[] = trim($_POST['sendtocc']); + } + if (count($receivercc) > 0) + { + foreach($receivercc as $key=>$val) + { + // Recipient was provided from combo list + if ($val == 'thirdparty') // Id of third party + { + $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; + } + elseif ($val) // Id du contact + { + $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); + //$sendtoid[] = $val; TODO Add also id of contact in CC ? + } + } + } + $sendtocc=implode(',',$tmparray); + + //var_dump($listofobjectref);exit; + $attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array()); + $listofqualifiedid=array(); + $listofqualifiedref=array(); + $thirdpartywithoutemail=array(); + + foreach($listofobjectref[$thirdpartyid] as $objectid => $object) + { + //var_dump($thirdpartyid.' - '.$objectid.' - '.$object->statut); + if ($objectclass == 'Propal' && $object->statut == Propal::STATUS_DRAFT) + { + $langs->load("errors"); + $nbignored++; + $resaction.='<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$object->ref).'</div><br>'; + continue; // Payment done or started or canceled + } + if ($objectclass == 'Commande' && $object->statut == Commande::STATUS_DRAFT) + { + $langs->load("errors"); + $nbignored++; + $resaction.='<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$object->ref).'</div><br>'; + continue; + } + if ($objectclass == 'Facture' && $object->statut != Facture::STATUS_VALIDATED) + { + $langs->load("errors"); + $nbignored++; + $resaction.='<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$object->ref).'</div><br>'; + continue; // Payment done or started or canceled + } + + // Test recipient + if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send) + { + if ($object->element == 'expensereport') + { $fuser = new User($db); $fuser->fetch($object->fk_user_author); $sendto = $fuser->email; - } - else - { - $object->fetch_thirdparty(); - $sendto = $object->thirdparty->email; - } - } - - if (empty($sendto)) - { - //print "No recipient for thirdparty ".$object->thirdparty->name; - $nbignored++; - if (empty($thirdpartywithoutemail[$object->thirdparty->id])) - { - $resaction.='<div class="error">'.$langs->trans('NoRecipientEmail',$object->thirdparty->name).'</div><br>'; - } - dol_syslog('No recipient for thirdparty: '.$object->thirdparty->name, LOG_WARNING); - $thirdpartywithoutemail[$object->thirdparty->id]=1; - continue; - } - - if ($_POST['addmaindocfile']) - { - // TODO Use future field $object->fullpathdoc to know where is stored default file - // TODO If not defined, use $object->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc. - $filename=dol_sanitizeFileName($object->ref).'.pdf'; - $filedir=$uploaddir . '/' . dol_sanitizeFileName($object->ref); - $file = $filedir . '/' . $filename; - $mime = dol_mimetype($file); - - if (dol_is_file($file)) - { - // Create form object - $attachedfiles=array( - 'paths'=>array_merge($attachedfiles['paths'],array($file)), - 'names'=>array_merge($attachedfiles['names'],array($filename)), - 'mimes'=>array_merge($attachedfiles['mimes'],array($mime)) - ); - } - else - { - $nbignored++; - $langs->load("errors"); - $resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div><br>'; - dol_syslog('Failed to read file: '.$file, LOG_WARNING); - continue; - } - } - - // Object of thirdparty qualified - $listofqualifiedid[$objectid]=$object; - $listofqualifiedref[$objectid]=$object->ref; - - - //var_dump($listofqualifiedref); - } - - // Send email if there is at least one qualified record - if (count($listofqualifiedid) > 0) - { - $langs->load("commercial"); - - $fromtype = GETPOST('fromtype'); - if ($fromtype === 'user') { - $from = $user->getFullName($langs) .' <'.$user->email.'>'; - } - elseif ($fromtype === 'company') { - $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; - } - elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) { - $tmp=explode(',', $user->email_aliases); - $from = trim($tmp[($reg[1] - 1)]); - } - elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) { - $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); - $from = trim($tmp[($reg[1] - 1)]); - } - elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) { - $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1]; - $resql = $db->query($sql); - $obj = $db->fetch_object($resql); - if ($obj) - { - $from = $obj->label.' <'.$obj->email.'>'; - } - } - else { - $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; - } - - $replyto = $from; - $subject = GETPOST('subject','none'); - $message = GETPOST('message','none'); - $sendtocc = GETPOST('sentocc'); - $sendtobcc = ''; - if ($objectclass == 'Propale') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO); - if ($objectclass == 'Commande') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO); - if ($objectclass == 'Facture') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO); - if ($objectclass == 'Supplier_Proposal') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO); - if ($objectclass == 'CommandeFournisseur') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO); - if ($objectclass == 'FactureFournisseur') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO); - - // $listofqualifiedid is array with key = object id of qualified objects for the current thirdparty - $oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0); - $looparray=array(); - if (! $oneemailperrecipient) - { - $looparray = $listofqualifiedid; - } - else - { - $objectforloop=new $objectclass($db); - $objectforloop->thirdparty = $thirdparty; - $looparray[0]=$objectforloop; - } - //var_dump($looparray);exit; + } + else + { + $object->fetch_thirdparty(); + $sendto = $object->thirdparty->email; + } + } + + if (empty($sendto)) + { + //print "No recipient for thirdparty ".$object->thirdparty->name; + $nbignored++; + if (empty($thirdpartywithoutemail[$object->thirdparty->id])) + { + $resaction.='<div class="error">'.$langs->trans('NoRecipientEmail',$object->thirdparty->name).'</div><br>'; + } + dol_syslog('No recipient for thirdparty: '.$object->thirdparty->name, LOG_WARNING); + $thirdpartywithoutemail[$object->thirdparty->id]=1; + continue; + } + + if ($_POST['addmaindocfile']) + { + // TODO Use future field $object->fullpathdoc to know where is stored default file + // TODO If not defined, use $object->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc. + $filename=dol_sanitizeFileName($object->ref).'.pdf'; + $filedir=$uploaddir . '/' . dol_sanitizeFileName($object->ref); + $file = $filedir . '/' . $filename; + $mime = dol_mimetype($file); + + if (dol_is_file($file)) + { + // Create form object + $attachedfiles=array( + 'paths'=>array_merge($attachedfiles['paths'],array($file)), + 'names'=>array_merge($attachedfiles['names'],array($filename)), + 'mimes'=>array_merge($attachedfiles['mimes'],array($mime)) + ); + } + else + { + $nbignored++; + $langs->load("errors"); + $resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div><br>'; + dol_syslog('Failed to read file: '.$file, LOG_WARNING); + continue; + } + } + + // Object of thirdparty qualified + $listofqualifiedid[$objectid]=$object; + $listofqualifiedref[$objectid]=$object->ref; + + + //var_dump($listofqualifiedref); + } + + // Send email if there is at least one qualified record + if (count($listofqualifiedid) > 0) + { + $langs->load("commercial"); + + $fromtype = GETPOST('fromtype'); + if ($fromtype === 'user') { + $from = $user->getFullName($langs) .' <'.$user->email.'>'; + } + elseif ($fromtype === 'company') { + $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; + } + elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) { + $tmp=explode(',', $user->email_aliases); + $from = trim($tmp[($reg[1] - 1)]); + } + elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) { + $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); + $from = trim($tmp[($reg[1] - 1)]); + } + elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) { + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1]; + $resql = $db->query($sql); + $obj = $db->fetch_object($resql); + if ($obj) + { + $from = $obj->label.' <'.$obj->email.'>'; + } + } + else { + $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; + } + + $replyto = $from; + $subject = GETPOST('subject','none'); + $message = GETPOST('message','none'); + $sendtocc = GETPOST('sentocc'); + $sendtobcc = ''; + if ($objectclass == 'Propale') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO); + if ($objectclass == 'Commande') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO); + if ($objectclass == 'Facture') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO); + if ($objectclass == 'Supplier_Proposal') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO); + if ($objectclass == 'CommandeFournisseur') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO); + if ($objectclass == 'FactureFournisseur') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO); + + // $listofqualifiedid is array with key = object id of qualified objects for the current thirdparty + $oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0); + $looparray=array(); + if (! $oneemailperrecipient) + { + $looparray = $listofqualifiedid; + } + else + { + $objectforloop=new $objectclass($db); + $objectforloop->thirdparty = $thirdparty; + $looparray[0]=$objectforloop; + } + //var_dump($looparray);exit; foreach ($looparray as $objecttmp) // $objecttmp is a real object or an empty if we choose to send one email per thirdparty instead of per record { - // Make substitution in email content - $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp); - $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedid)) : $objecttmp->id); - $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref); - $substitutionarray['__EMAIL__'] = $thirdparty->email; - $substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>'; - - $parameters=array('mode'=>'formemail'); - complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters); - - $subject=make_substitutions($subject, $substitutionarray); - $message=make_substitutions($message, $substitutionarray); - - $filepath = $attachedfiles['paths']; - $filename = $attachedfiles['names']; - $mimetype = $attachedfiles['mimes']; - - //var_dump($filepath); - - // Send mail (substitutionarray must be done just before this) - require_once(DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'); - $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1); - if ($mailfile->error) - { - $resaction.='<div class="error">'.$mailfile->error.'</div>'; - } - else - { - $result=$mailfile->sendfile(); - if ($result) - { - $resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>'; // Must not contain " - - $error=0; - - // Insert logs into agenda - foreach($listofqualifiedid as $objid => $object) - { - /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP'; + // Make substitution in email content + $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp); + $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedid)) : $objecttmp->id); + $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref); + $substitutionarray['__EMAIL__'] = $thirdparty->email; + $substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>'; + + $parameters=array('mode'=>'formemail'); + complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters); + + $subject=make_substitutions($subject, $substitutionarray); + $message=make_substitutions($message, $substitutionarray); + + $filepath = $attachedfiles['paths']; + $filename = $attachedfiles['names']; + $mimetype = $attachedfiles['mimes']; + + //var_dump($filepath); + + // Send mail (substitutionarray must be done just before this) + require_once(DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'); + $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1); + if ($mailfile->error) + { + $resaction.='<div class="error">'.$mailfile->error.'</div>'; + } + else + { + $result=$mailfile->sendfile(); + if ($result) + { + $resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>'; // Must not contain " + + $error=0; + + // Insert logs into agenda + foreach($listofqualifiedid as $objid => $object) + { + /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP'; if ($objectclass == 'Commande') $actiontypecode='AC_COM'; if ($objectclass == 'Facture') $actiontypecode='AC_FAC'; if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO'; if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD'; if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/ - $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; - if ($message) - { - if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); - $actionmsg = dol_concatdesc($actionmsg, $message); - } - $actionmsg2=''; - - // Initialisation donnees - $object->sendtoid = 0; - $object->actionmsg = $actionmsg; // Long text - $object->actionmsg2 = $actionmsg2; // Short text - $object->fk_element = $objid; - $object->elementtype = $object->element; - - $triggername = strtoupper(get_class($object)) .'_SENTBYMAIL'; - if ($triggername == 'SOCIETE_SENTBYMAIL') $triggername = 'COMPANY_SENTBYEMAIL'; - if ($triggername == 'CONTRAT_SENTBYMAIL') $triggername = 'CONTRACT_SENTBYEMAIL'; - if ($triggername == 'COMMANDE_SENTBYMAIL') $triggername = 'ORDER_SENTBYEMAIL'; - if ($triggername == 'FACTURE_SENTBYMAIL') $triggername = 'BILL_SENTBYEMAIL'; - if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL'; - if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL'; - if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL'; - if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL'; - - if (! empty($trigger_name)) - { - // Appel des triggers - include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); - $interface=new Interfaces($db); - $result=$interface->run_triggers($trigger_name, $object, $user, $langs, $conf); - if ($result < 0) { $error++; $errors=$interface->errors; } - // Fin appel triggers - - if ($error) - { - setEventMessages($db->lasterror(), $errors, 'errors'); - dol_syslog("Error in trigger ".$trigger_name.' '.$db->lasterror(), LOG_ERR); - } - } - - $nbsent++; - } - } - else - { - $langs->load("other"); - if ($mailfile->error) - { - $resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); - $resaction.='<br><div class="error">'.$mailfile->error.'</div>'; - } - else - { - $resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>'; - } - } - } + $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; + if ($message) + { + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); + } + $actionmsg2=''; + + // Initialisation donnees + $object->sendtoid = 0; + $object->actionmsg = $actionmsg; // Long text + $object->actionmsg2 = $actionmsg2; // Short text + $object->fk_element = $objid; + $object->elementtype = $object->element; + + $triggername = strtoupper(get_class($object)) .'_SENTBYMAIL'; + if ($triggername == 'SOCIETE_SENTBYMAIL') $triggername = 'COMPANY_SENTBYEMAIL'; + if ($triggername == 'CONTRAT_SENTBYMAIL') $triggername = 'CONTRACT_SENTBYEMAIL'; + if ($triggername == 'COMMANDE_SENTBYMAIL') $triggername = 'ORDER_SENTBYEMAIL'; + if ($triggername == 'FACTURE_SENTBYMAIL') $triggername = 'BILL_SENTBYEMAIL'; + if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL'; + if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL'; + if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL'; + if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL'; + + if (! empty($trigger_name)) + { + // Appel des triggers + include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); + $interface=new Interfaces($db); + $result=$interface->run_triggers($trigger_name, $object, $user, $langs, $conf); + if ($result < 0) { $error++; $errors=$interface->errors; } + // Fin appel triggers + + if ($error) + { + setEventMessages($db->lasterror(), $errors, 'errors'); + dol_syslog("Error in trigger ".$trigger_name.' '.$db->lasterror(), LOG_ERR); + } + } + + $nbsent++; + } + } + else + { + $langs->load("other"); + if ($mailfile->error) + { + $resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); + $resaction.='<br><div class="error">'.$mailfile->error.'</div>'; + } + else + { + $resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>'; + } + } + } } - } - } - - $resaction.=($resaction?'<br>':$resaction); - $resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n"; - $resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>"; - $resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>"; - $resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>"; - - if ($nbsent) - { - $action=''; // Do not show form post if there was at least one successfull sent - //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs'); - setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs'); - setEventMessages($resaction, null, 'mesgs'); - } - else - { - //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file - setEventMessages($resaction, null, 'warnings'); - } - - $action='list'; - $massaction=''; - } + } + } + + $resaction.=($resaction?'<br>':$resaction); + $resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n"; + $resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>"; + $resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>"; + $resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>"; + + if ($nbsent) + { + $action=''; // Do not show form post if there was at least one successfull sent + //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs'); + setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs'); + setEventMessages($resaction, null, 'mesgs'); + } + else + { + //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file + setEventMessages($resaction, null, 'warnings'); + } + + $action='list'; + $massaction=''; + } } if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_search')) @@ -489,59 +489,59 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se exit; } - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - - $objecttmp=new $objectclass($db); - $listofobjectid=array(); - $listofobjectthirdparties=array(); - $listofobjectref=array(); - foreach($toselect as $toselectid) - { - $objecttmp=new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $listofobjectid[$toselectid]=$toselectid; - $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; - $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; - $listofobjectref[$toselectid]=$objecttmp->ref; - } - } - - $arrayofinclusion=array(); - foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote($tmppdf.'.pdf','/').'$'; - $listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true); - - // build list of files with full path - $files = array(); - foreach($listofobjectref as $basename) - { - foreach($listoffiles as $filefound) - { - if (strstr($filefound["name"],$basename)) - { - $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"]; - break; - } - } - } - - // Define output language (Here it is not used because we do only merging existing PDF) - $outputlangs = $langs; - $newlang=''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->thirdparty->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); - } - - if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) - { - // Create output dir if not exists + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + + $objecttmp=new $objectclass($db); + $listofobjectid=array(); + $listofobjectthirdparties=array(); + $listofobjectref=array(); + foreach($toselect as $toselectid) + { + $objecttmp=new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + $listofobjectid[$toselectid]=$toselectid; + $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; + $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; + $listofobjectref[$toselectid]=$objecttmp->ref; + } + } + + $arrayofinclusion=array(); + foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote($tmppdf.'.pdf','/').'$'; + $listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true); + + // build list of files with full path + $files = array(); + foreach($listofobjectref as $basename) + { + foreach($listoffiles as $filefound) + { + if (strstr($filefound["name"],$basename)) + { + $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"]; + break; + } + } + } + + // Define output language (Here it is not used because we do only merging existing PDF) + $outputlangs = $langs; + $newlang=''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->thirdparty->default_lang; + if (! empty($newlang)) + { + $outputlangs = new Translate("",$conf); + $outputlangs->setDefaultLang($newlang); + } + + if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) + { + // Create output dir if not exists dol_mkdir($diroutputmassaction); // Defined name of merged file @@ -549,7 +549,7 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se $filename=preg_replace('/\s/','_',$filename); // Save merged file - if (in_array($object->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) + if (in_array($object->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) { if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); @@ -557,107 +557,107 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se if ($year) $filename.='_'.$year; if ($month) $filename.='_'.$month; - if (count($files)>0) - { - $now=dol_now(); - $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf'; - - $input_files = ''; - foreach($files as $f) { - $input_files.=' '.escapeshellarg($f); - } - - $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file); - exec($cmd); - - if (! empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); - - $langs->load("exports"); - setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); - } - else - { - setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors'); - } - } - else { - // Create empty PDF - $formatarray=pdf_getFormat(); - $page_largeur = $formatarray['width']; - $page_hauteur = $formatarray['height']; - $format = array($page_largeur,$page_hauteur); - - $pdf=pdf_getInstance($format); - - if (class_exists('TCPDF')) - { + if (count($files)>0) + { + $now=dol_now(); + $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf'; + + $input_files = ''; + foreach($files as $f) { + $input_files.=' '.escapeshellarg($f); + } + + $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file); + exec($cmd); + + if (! empty($conf->global->MAIN_UMASK)) + @chmod($file, octdec($conf->global->MAIN_UMASK)); + + $langs->load("exports"); + setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); + } + else + { + setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors'); + } + } + else { + // Create empty PDF + $formatarray=pdf_getFormat(); + $page_largeur = $formatarray['width']; + $page_hauteur = $formatarray['height']; + $format = array($page_largeur,$page_hauteur); + + $pdf=pdf_getInstance($format); + + if (class_exists('TCPDF')) + { $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); - } - $pdf->SetFont(pdf_getPDFFont($outputlangs)); + } + $pdf->SetFont(pdf_getPDFFont($outputlangs)); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - // Add all others - foreach($files as $file) - { + // Add all others + foreach($files as $file) + { // Charge un document PDF depuis un fichier. $pagecount = $pdf->setSourceFile($file); for ($i = 1; $i <= $pagecount; $i++) { - $tplidx = $pdf->importPage($i); - $s = $pdf->getTemplatesize($tplidx); - $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); - $pdf->useTemplate($tplidx); + $tplidx = $pdf->importPage($i); + $s = $pdf->getTemplatesize($tplidx); + $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); + $pdf->useTemplate($tplidx); } - } + } - // Create output dir if not exists - dol_mkdir($diroutputmassaction); + // Create output dir if not exists + dol_mkdir($diroutputmassaction); - // Defined name of merged file - $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel))); - $filename=preg_replace('/\s/','_',$filename); + // Defined name of merged file + $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel))); + $filename=preg_replace('/\s/','_',$filename); - // Save merged file - if (in_array($object->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) - { + // Save merged file + if (in_array($object->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) + { if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); - } - if ($year) $filename.='_'.$year; - if ($month) $filename.='_'.$month; - if ($pagecount) - { + } + if ($year) $filename.='_'.$year; + if ($month) $filename.='_'.$month; + if ($pagecount) + { $now=dol_now(); $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf'; $pdf->Output($file,'F'); if (! empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); + @chmod($file, octdec($conf->global->MAIN_UMASK)); - $langs->load("exports"); - setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); - } - else - { + $langs->load("exports"); + setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); + } + else + { setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors'); - } - } + } + } } // Remove a file from massaction area if ($action == 'remove_file') { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - $langs->load("other"); - $upload_dir = $diroutputmassaction; - $file = $upload_dir . '/' . GETPOST('file'); - $ret=dol_delete_file($file); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); - $action=''; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + $langs->load("other"); + $upload_dir = $diroutputmassaction; + $file = $upload_dir . '/' . GETPOST('file'); + $ret=dol_delete_file($file); + if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); + else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + $action=''; } // Validate records @@ -729,17 +729,17 @@ if (! $error && $massaction == 'validate' && $permtocreate) // Delete records if (! $error && $massaction == 'delete' && $permtodelete) { - $db->begin(); - - $objecttmp=new $objectclass($db); - $nbok = 0; - foreach($toselect as $toselectid) - { - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - // Refuse deletion for some status ? - /* + $db->begin(); + + $objecttmp=new $objectclass($db); + $nbok = 0; + foreach($toselect as $toselectid) + { + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + // Refuse deletion for some status ? + /* if ($objectclass == 'Facture' && $objecttmp->status == Facture::STATUS_DRAFT) { $langs->load("errors"); @@ -748,36 +748,36 @@ if (! $error && $massaction == 'delete' && $permtodelete) continue; }*/ - if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); - else $result = $objecttmp->delete($user); - - if ($result <= 0) - { - setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); - $error++; - break; - } - else $nbok++; - } - else - { - setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); - $error++; - break; - } - } - - if (! $error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); - $db->commit(); - } - else - { - $db->rollback(); - } - //var_dump($listofobjectthirdparties);exit; + if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); + else $result = $objecttmp->delete($user); + + if ($result <= 0) + { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + else $nbok++; + } + else + { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + } + + if (! $error) + { + if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); + else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + $db->commit(); + } + else + { + $db->rollback(); + } + //var_dump($listofobjectthirdparties);exit; } $parameters['toselect']=$toselect; diff --git a/htdocs/core/class/emailsenderprofile.class.php b/htdocs/core/class/emailsenderprofile.class.php index c93d6517a22eddf3eb00aaf62b96f26698bd49f8..66e37744cc71bbed7a157f4150d98c302c2ab666 100644 --- a/htdocs/core/class/emailsenderprofile.class.php +++ b/htdocs/core/class/emailsenderprofile.class.php @@ -167,43 +167,43 @@ class EmailSenderProfile extends CommonObject public function createFromClone(User $user, $fromid) { global $hookmanager, $langs; - $error = 0; + $error = 0; - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); - $object = new self($this->db); + $object = new self($this->db); - $this->db->begin(); + $this->db->begin(); - // Load source object - $object->fetchCommon($fromid); - // Reset some properties - unset($object->id); - unset($object->fk_user_creat); - unset($object->import_key); + // Load source object + $object->fetchCommon($fromid); + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); - // Clear fields - $object->ref = "copy_of_".$object->ref; - $object->title = $langs->trans("CopyOf")." ".$object->title; - // ... + // Clear fields + $object->ref = "copy_of_".$object->ref; + $object->title = $langs->trans("CopyOf")." ".$object->title; + // ... - // Create clone + // Create clone $object->context['createfromclone'] = 'createfromclone'; - $result = $object->createCommon($user); - if ($result < 0) { - $error++; - $this->error = $object->error; - $this->errors = $object->errors; - } - - // End - if (!$error) { - $this->db->commit(); - return $object; - } else { - $this->db->rollback(); - return -1; - } + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } } /** diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index fcec7cce16567067be0b03bae9ec7e6847a47a90..cc09b8bb521348d6bea0cbae83b37bc1efb72432 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -34,20 +34,20 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php'; */ class FormMail extends Form { - var $db; + var $db; - var $withform; // 1=Include HTML form tag and show submit button, 0=Do not include form tag and submit button, -1=Do not include form tag but include submit button + var $withform; // 1=Include HTML form tag and show submit button, 0=Do not include form tag and submit button, -1=Do not include form tag but include submit button - var $fromname; - var $frommail; - var $replytoname; - var $replytomail; - var $toname; - var $tomail; + var $fromname; + var $frommail; + var $replytoname; + var $replytomail; + var $toname; + var $tomail; var $trackid; - var $withsubstit; // Show substitution array - var $withfrom; + var $withsubstit; // Show substitution array + var $withfrom; /** * @var int * @deprecated Fill withto with array before calling method. @@ -57,221 +57,221 @@ class FormMail extends Form /** * @var int|int[] */ - public $withto; // Show recipient emails - var $withtofree; // Show free text for recipient emails - var $withtocc; - var $withtoccc; - var $withtopic; - var $withfile; // 0=No attaches files, 1=Show attached files, 2=Can add new attached files - var $withmaindocfile; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default) - var $withbody; - - var $withfromreadonly; - var $withreplytoreadonly; - var $withtoreadonly; - var $withtoccreadonly; + public $withto; // Show recipient emails + var $withtofree; // Show free text for recipient emails + var $withtocc; + var $withtoccc; + var $withtopic; + var $withfile; // 0=No attaches files, 1=Show attached files, 2=Can add new attached files + var $withmaindocfile; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default) + var $withbody; + + var $withfromreadonly; + var $withreplytoreadonly; + var $withtoreadonly; + var $withtoccreadonly; var $withtocccreadonly; var $withtopicreadonly; - var $withfilereadonly; - var $withdeliveryreceipt; - var $withcancel; - var $withfckeditor; - - var $substit=array(); - var $substit_lines=array(); - var $param=array(); - - var $error; - - public $lines_model; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - - $this->withform=1; - - $this->withfrom=1; - $this->withto=1; - $this->withtofree=1; - $this->withtocc=1; - $this->withtoccc=0; - $this->witherrorsto=0; - $this->withtopic=1; - $this->withfile=0; // 1=Add section "Attached files". 2=Can add files. - $this->withmaindocfile=0; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default) - $this->withbody=1; - - $this->withfromreadonly=1; - $this->withreplytoreadonly=1; - $this->withtoreadonly=0; - $this->withtoccreadonly=0; - $this->withtocccreadonly=0; - $this->witherrorstoreadonly=0; - $this->withtopicreadonly=0; - $this->withfilereadonly=0; - $this->withbodyreadonly=0; - $this->withdeliveryreceiptreadonly=0; - $this->withfckeditor=-1; // -1 = Auto - - return 1; - } - - /** - * Clear list of attached files in send mail form (also stored in session) - * - * @return void - */ - function clear_attached_files() - { - global $conf,$user; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - // Set tmp user directory - $vardir=$conf->user->dir_output."/".$user->id; - $upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path - if (is_dir($upload_dir)) dol_delete_dir_recursive($upload_dir); - - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined - unset($_SESSION["listofpaths".$keytoavoidconflict]); - unset($_SESSION["listofnames".$keytoavoidconflict]); - unset($_SESSION["listofmimes".$keytoavoidconflict]); - } - - /** - * Add a file into the list of attached files (stored in SECTION array) - * - * @param string $path Full absolute path on filesystem of file, including file name - * @param string $file Only filename - * @param string $type Mime type - * @return void - */ - function add_attached_files($path,$file,$type) - { - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); - - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined - if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); - if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); - if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]); - if (! in_array($file,$listofnames)) - { - $listofpaths[]=$path; - $listofnames[]=$file; - $listofmimes[]=$type; - $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths); - $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames); - $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes); - } - } - - /** - * Remove a file from the list of attached files (stored in SECTION array) - * - * @param string $keytodelete Key in file array (0, 1, 2, ...) - * @return void - */ - function remove_attached_files($keytodelete) - { - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); - - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined - if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); - if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); - if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]); - if ($keytodelete >= 0) - { - unset ($listofpaths[$keytodelete]); - unset ($listofnames[$keytodelete]); - unset ($listofmimes[$keytodelete]); - $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths); - $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames); - $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes); - //var_dump($_SESSION['listofpaths']); - } - } - - /** - * Return list of attached files (stored in SECTION array) - * - * @return array array('paths'=> ,'names'=>, 'mimes'=> ) - */ - function get_attached_files() - { - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); - - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined - if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); - if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); - if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]); - return array('paths'=>$listofpaths, 'names'=>$listofnames, 'mimes'=>$listofmimes); - } - - /** - * Show the form to input an email - * this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files - * this->withmaindocfile - * - * @param string $addfileaction Name of action when posting file attachments - * @param string $removefileaction Name of action when removing file attachments - * @return void - */ - function show_form($addfileaction='addfile',$removefileaction='removefile') - { - print $this->get_form($addfileaction,$removefileaction); - } - - /** - * Get the form to input an email - * this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files - * this->withfile - * this->param: Contains more parameteres like email templates info - * - * @param string $addfileaction Name of action when posting file attachments - * @param string $removefileaction Name of action when removing file attachments - * @return string Form to show - */ - function get_form($addfileaction='addfile',$removefileaction='removefile') - { - global $conf, $langs, $user, $hookmanager, $form; - - if (! is_object($form)) $form=new Form($this->db); - - $langs->load("other"); - $langs->load("mails"); - - $hookmanager->initHooks(array('formmail')); - - $parameters=array( - 'addfileaction' => $addfileaction, - 'removefileaction'=> $removefileaction, - 'trackid'=> $this->trackid - ); - $reshook=$hookmanager->executeHooks('getFormMail', $parameters, $this); - - if (!empty($reshook)) - { - return $hookmanager->resPrint; - } - else + var $withfilereadonly; + var $withdeliveryreceipt; + var $withcancel; + var $withfckeditor; + + var $substit=array(); + var $substit_lines=array(); + var $param=array(); + + var $error; + + public $lines_model; + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db = $db; + + $this->withform=1; + + $this->withfrom=1; + $this->withto=1; + $this->withtofree=1; + $this->withtocc=1; + $this->withtoccc=0; + $this->witherrorsto=0; + $this->withtopic=1; + $this->withfile=0; // 1=Add section "Attached files". 2=Can add files. + $this->withmaindocfile=0; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default) + $this->withbody=1; + + $this->withfromreadonly=1; + $this->withreplytoreadonly=1; + $this->withtoreadonly=0; + $this->withtoccreadonly=0; + $this->withtocccreadonly=0; + $this->witherrorstoreadonly=0; + $this->withtopicreadonly=0; + $this->withfilereadonly=0; + $this->withbodyreadonly=0; + $this->withdeliveryreceiptreadonly=0; + $this->withfckeditor=-1; // -1 = Auto + + return 1; + } + + /** + * Clear list of attached files in send mail form (also stored in session) + * + * @return void + */ + function clear_attached_files() + { + global $conf,$user; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + // Set tmp user directory + $vardir=$conf->user->dir_output."/".$user->id; + $upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path + if (is_dir($upload_dir)) dol_delete_dir_recursive($upload_dir); + + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + unset($_SESSION["listofpaths".$keytoavoidconflict]); + unset($_SESSION["listofnames".$keytoavoidconflict]); + unset($_SESSION["listofmimes".$keytoavoidconflict]); + } + + /** + * Add a file into the list of attached files (stored in SECTION array) + * + * @param string $path Full absolute path on filesystem of file, including file name + * @param string $file Only filename + * @param string $type Mime type + * @return void + */ + function add_attached_files($path,$file,$type) + { + $listofpaths=array(); + $listofnames=array(); + $listofmimes=array(); + + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); + if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); + if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]); + if (! in_array($file,$listofnames)) + { + $listofpaths[]=$path; + $listofnames[]=$file; + $listofmimes[]=$type; + $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths); + $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames); + $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes); + } + } + + /** + * Remove a file from the list of attached files (stored in SECTION array) + * + * @param string $keytodelete Key in file array (0, 1, 2, ...) + * @return void + */ + function remove_attached_files($keytodelete) + { + $listofpaths=array(); + $listofnames=array(); + $listofmimes=array(); + + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); + if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); + if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]); + if ($keytodelete >= 0) + { + unset ($listofpaths[$keytodelete]); + unset ($listofnames[$keytodelete]); + unset ($listofmimes[$keytodelete]); + $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths); + $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames); + $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes); + //var_dump($_SESSION['listofpaths']); + } + } + + /** + * Return list of attached files (stored in SECTION array) + * + * @return array array('paths'=> ,'names'=>, 'mimes'=> ) + */ + function get_attached_files() + { + $listofpaths=array(); + $listofnames=array(); + $listofmimes=array(); + + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); + if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); + if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]); + return array('paths'=>$listofpaths, 'names'=>$listofnames, 'mimes'=>$listofmimes); + } + + /** + * Show the form to input an email + * this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files + * this->withmaindocfile + * + * @param string $addfileaction Name of action when posting file attachments + * @param string $removefileaction Name of action when removing file attachments + * @return void + */ + function show_form($addfileaction='addfile',$removefileaction='removefile') + { + print $this->get_form($addfileaction,$removefileaction); + } + + /** + * Get the form to input an email + * this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files + * this->withfile + * this->param: Contains more parameteres like email templates info + * + * @param string $addfileaction Name of action when posting file attachments + * @param string $removefileaction Name of action when removing file attachments + * @return string Form to show + */ + function get_form($addfileaction='addfile',$removefileaction='removefile') + { + global $conf, $langs, $user, $hookmanager, $form; + + if (! is_object($form)) $form=new Form($this->db); + + $langs->load("other"); + $langs->load("mails"); + + $hookmanager->initHooks(array('formmail')); + + $parameters=array( + 'addfileaction' => $addfileaction, + 'removefileaction'=> $removefileaction, + 'trackid'=> $this->trackid + ); + $reshook=$hookmanager->executeHooks('getFormMail', $parameters, $this); + + if (!empty($reshook)) + { + return $hookmanager->resPrint; + } + else { - $out=''; + $out=''; - $disablebademails=1; + $disablebademails=1; - // Define output language + // Define output language $outputlangs = $langs; $newlang = ''; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $this->param['langsmodels']; @@ -865,7 +865,7 @@ class FormMail extends Form } - if (isset($_POST["message"]) && ! $_POST['modelselected']) $defaultmessage=$_POST["message"]; + if (isset($_POST["message"]) && ! $_POST['modelselected']) $defaultmessage=$_POST["message"]; else { $defaultmessage=make_substitutions($defaultmessage,$this->substit); @@ -874,59 +874,59 @@ class FormMail extends Form $defaultmessage=preg_replace("/^\n+/","",$defaultmessage); } - $out.= '<tr>'; - $out.= '<td valign="top">'.$langs->trans("MailText").'</td>'; - $out.= '<td>'; - if ($this->withbodyreadonly) - { - $out.= nl2br($defaultmessage); - $out.= '<input type="hidden" id="message" name="message" value="'.$defaultmessage.'" />'; - } - else - { - if (! isset($this->ckeditortoolbar)) $this->ckeditortoolbar = 'dolibarr_notes'; + $out.= '<tr>'; + $out.= '<td valign="top">'.$langs->trans("MailText").'</td>'; + $out.= '<td>'; + if ($this->withbodyreadonly) + { + $out.= nl2br($defaultmessage); + $out.= '<input type="hidden" id="message" name="message" value="'.$defaultmessage.'" />'; + } + else + { + if (! isset($this->ckeditortoolbar)) $this->ckeditortoolbar = 'dolibarr_notes'; - // Editor wysiwyg - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - if ($this->withfckeditor == -1) - { - if (! empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $this->withfckeditor=1; + // Editor wysiwyg + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + if ($this->withfckeditor == -1) + { + if (! empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $this->withfckeditor=1; else $this->withfckeditor=0; - } + } - $doleditor=new DolEditor('message',$defaultmessage,'',280,$this->ckeditortoolbar,'In',true,true,$this->withfckeditor,8,'95%'); - $out.= $doleditor->Create(1); - } - $out.= "</td></tr>\n"; - } + $doleditor=new DolEditor('message',$defaultmessage,'',280,$this->ckeditortoolbar,'In',true,true,$this->withfckeditor,8,'95%'); + $out.= $doleditor->Create(1); + } + $out.= "</td></tr>\n"; + } - $out.= '</table>'."\n"; + $out.= '</table>'."\n"; - if ($this->withform == 1 || $this->withform == -1) - { - $out.= '<br><div class="center">'; - $out.= '<input class="button" type="submit" id="sendmail" name="sendmail" value="'.$langs->trans("SendMail").'"'; - // Add a javascript test to avoid to forget to submit file before sending email - if ($this->withfile == 2 && $conf->use_javascript_ajax) - { - $out.= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"'; - } - $out.= ' />'; - if ($this->withcancel) - { - $out.= ' '; - $out.= '<input class="button" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'" />'; - } - $out.= '</div>'."\n"; - } + if ($this->withform == 1 || $this->withform == -1) + { + $out.= '<br><div class="center">'; + $out.= '<input class="button" type="submit" id="sendmail" name="sendmail" value="'.$langs->trans("SendMail").'"'; + // Add a javascript test to avoid to forget to submit file before sending email + if ($this->withfile == 2 && $conf->use_javascript_ajax) + { + $out.= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"'; + } + $out.= ' />'; + if ($this->withcancel) + { + $out.= ' '; + $out.= '<input class="button" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'" />'; + } + $out.= '</div>'."\n"; + } - if ($this->withform == 1) $out.= '</form>'."\n"; + if ($this->withform == 1) $out.= '</form>'."\n"; - // Disable enter key if option MAIN_MAILFORM_DISABLE_ENTERKEY is set - if (! empty($conf->global->MAIN_MAILFORM_DISABLE_ENTERKEY)) - { - $out.= '<script type="text/javascript" language="javascript">'; - $out.= 'jQuery(document).ready(function () {'; + // Disable enter key if option MAIN_MAILFORM_DISABLE_ENTERKEY is set + if (! empty($conf->global->MAIN_MAILFORM_DISABLE_ENTERKEY)) + { + $out.= '<script type="text/javascript" language="javascript">'; + $out.= 'jQuery(document).ready(function () {'; $out.= ' $(document).on("keypress", \'#mailform\', function (e) { /* Note this is called at every key pressed ! */ var code = e.keyCode || e.which; if (code == 13) { @@ -936,13 +936,13 @@ class FormMail extends Form });'; $out.=' })'; $out.= '</script>'; - } + } - $out.= "<!-- End form mail -->\n"; + $out.= "<!-- End form mail -->\n"; - return $out; - } - } + return $out; + } + } @@ -992,22 +992,22 @@ class FormMail extends Form { $defaultmessage=''; if ($type_template=='facture_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoice"); } - elseif ($type_template=='facture_relance') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder"); } - elseif ($type_template=='propal_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendProposal"); } - elseif ($type_template=='supplier_proposal_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal"); } - elseif ($type_template=='order_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendOrder"); } - elseif ($type_template=='order_supplier_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder"); } - elseif ($type_template=='invoice_supplier_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice"); } - elseif ($type_template=='shipping_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendShipping"); } - elseif ($type_template=='fichinter_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendFichInter"); } - elseif ($type_template=='thirdparty') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentThirdparty"); } - elseif ($type_template=='user') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentUser"); } - - $ret['label']='default'; - $ret['lang']=$outputlangs->defaultlang; - $ret['topic']=''; - $ret['joinfiles']=1; - $ret['content']=$defaultmessage; + elseif ($type_template=='facture_relance') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder"); } + elseif ($type_template=='propal_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendProposal"); } + elseif ($type_template=='supplier_proposal_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal"); } + elseif ($type_template=='order_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendOrder"); } + elseif ($type_template=='order_supplier_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder"); } + elseif ($type_template=='invoice_supplier_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice"); } + elseif ($type_template=='shipping_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendShipping"); } + elseif ($type_template=='fichinter_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendFichInter"); } + elseif ($type_template=='thirdparty') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentThirdparty"); } + elseif ($type_template=='user') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentUser"); } + + $ret['label']='default'; + $ret['lang']=$outputlangs->defaultlang; + $ret['topic']=''; + $ret['joinfiles']=1; + $ret['content']=$defaultmessage; $ret['content_lines']=''; } @@ -1130,41 +1130,41 @@ class FormMail extends Form $this->substit=$tmparray; - // Fill substit_lines with each object lines content - if (is_array($object->lines)) - { - foreach ($object->lines as $line) - { - $substit_line = array( - '__PRODUCT_REF__' => isset($line->product_ref) ? $line->product_ref : '', - '__PRODUCT_LABEL__' => isset($line->product_label) ? $line->product_label : '', - '__PRODUCT_DESCRIPTION__' => isset($line->product_desc) ? $line->product_desc : '', - '__LABEL__' => isset($line->label) ? $line->label : '', - '__DESCRIPTION__' => isset($line->desc) ? $line->desc : '', - '__DATE_START_YMD__' => dol_print_date($line->date_start, 'day', 0, $outputlangs), - '__DATE_END_YMD__' => dol_print_date($line->date_end, 'day', 0, $outputlangs), - '__QUANTITY__' => $line->qty, - '__SUBPRICE__' => price($line->subprice), - '__AMOUNT__' => price($line->total_ttc), - '__AMOUNT_EXCL_TAX__' => price($line->total_ht), - //'__PRODUCT_EXTRAFIELD_FIELD__' Done dinamically just after - ); - - // Create dynamic tags for __PRODUCT_EXTRAFIELD_FIELD__ - if (!empty($line->fk_product)) - { - $extrafields = new ExtraFields($this->db); - $extralabels = $extrafields->fetch_name_optionals_label('product', true); - $product = new Product($this->db); - $product->fetch($line->fk_product, '', '', 1); - $product->fetch_optionals($product->id, $extralabels); - foreach ($extrafields->attribute_label as $key => $label) { - $substit_line['__PRODUCT_EXTRAFIELD_' . strtoupper($key) . '__'] = $product->array_options['options_' . $key]; - } - } - $this->substit_lines[] = $substit_line; - } - } + // Fill substit_lines with each object lines content + if (is_array($object->lines)) + { + foreach ($object->lines as $line) + { + $substit_line = array( + '__PRODUCT_REF__' => isset($line->product_ref) ? $line->product_ref : '', + '__PRODUCT_LABEL__' => isset($line->product_label) ? $line->product_label : '', + '__PRODUCT_DESCRIPTION__' => isset($line->product_desc) ? $line->product_desc : '', + '__LABEL__' => isset($line->label) ? $line->label : '', + '__DESCRIPTION__' => isset($line->desc) ? $line->desc : '', + '__DATE_START_YMD__' => dol_print_date($line->date_start, 'day', 0, $outputlangs), + '__DATE_END_YMD__' => dol_print_date($line->date_end, 'day', 0, $outputlangs), + '__QUANTITY__' => $line->qty, + '__SUBPRICE__' => price($line->subprice), + '__AMOUNT__' => price($line->total_ttc), + '__AMOUNT_EXCL_TAX__' => price($line->total_ht), + //'__PRODUCT_EXTRAFIELD_FIELD__' Done dinamically just after + ); + + // Create dynamic tags for __PRODUCT_EXTRAFIELD_FIELD__ + if (!empty($line->fk_product)) + { + $extrafields = new ExtraFields($this->db); + $extralabels = $extrafields->fetch_name_optionals_label('product', true); + $product = new Product($this->db); + $product->fetch($line->fk_product, '', '', 1); + $product->fetch_optionals($product->id, $extralabels); + foreach ($extrafields->attribute_label as $key => $label) { + $substit_line['__PRODUCT_EXTRAFIELD_' . strtoupper($key) . '__'] = $product->array_options['options_' . $key]; + } + } + $this->substit_lines[] = $substit_line; + } + } } /** @@ -1188,11 +1188,11 @@ class FormMail extends Form if ($mode == 'formwithlines') { - $tmparray['__LINES__'] = '__LINES__'; // Will be set by the get_form function + $tmparray['__LINES__'] = '__LINES__'; // Will be set by the get_form function } if ($mode == 'formforlines') { - $tmparray['__QUANTITY__'] = '__QUANTITY__'; // Will be set by the get_form function + $tmparray['__QUANTITY__'] = '__QUANTITY__'; // Will be set by the get_form function } } diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 6aafc6c2bbde4b4ce5060cff84952874ad0d86d5..f56cd2f523d84b085caa90a98fc2c9ee47f7b115 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -275,17 +275,17 @@ function GETPOSTISSET($paramname) */ function GETPOST($paramname, $check='alpha', $method=0, $filter=NULL, $options=NULL) { - global $mysoc,$user,$conf; + global $mysoc,$user,$conf; - if (empty($paramname)) return 'BadFirstParameterForGETPOST'; - if (empty($check)) - { - dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING); - // Enable this line to know who call the GETPOST with '' $check parameter. - //var_dump(debug_backtrace()[0]); - } + if (empty($paramname)) return 'BadFirstParameterForGETPOST'; + if (empty($check)) + { + dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING); + // Enable this line to know who call the GETPOST with '' $check parameter. + //var_dump(debug_backtrace()[0]); + } - if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:''); + if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:''); elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:''; elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:''; elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:''); @@ -295,38 +295,38 @@ function GETPOST($paramname, $check='alpha', $method=0, $filter=NULL, $options=N if (empty($method) || $method == 3 || $method == 4) { - $relativepathstring = $_SERVER["PHP_SELF"]; - // Clean $relativepathstring - if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring); - $relativepathstring = preg_replace('/^\//', '', $relativepathstring); - $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring); + $relativepathstring = $_SERVER["PHP_SELF"]; + // Clean $relativepathstring + if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring); + $relativepathstring = preg_replace('/^\//', '', $relativepathstring); + $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring); //var_dump($relativepathstring); //var_dump($user->default_values); - // Code for search criteria persistence. - // Retrieve values if restore_lastsearch_values is set and there is saved values - if (! empty($_GET['restore_lastsearch_values']) && ! empty($_SESSION['lastsearch_values_'.$relativepathstring])) // Keep $_GET here - { - $tmp=json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true); - if (is_array($tmp)) - { - foreach($tmp as $key => $val) - { - if ($key == $paramname) - { - $out=$val; - break; - } - } - } - } - // Else, retreive default values if we are not doing a sort - elseif (! isset($_GET['sortfield']) && ! empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set - { - if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) - { - if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' - { + // Code for search criteria persistence. + // Retrieve values if restore_lastsearch_values is set and there is saved values + if (! empty($_GET['restore_lastsearch_values']) && ! empty($_SESSION['lastsearch_values_'.$relativepathstring])) // Keep $_GET here + { + $tmp=json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true); + if (is_array($tmp)) + { + foreach($tmp as $key => $val) + { + if ($key == $paramname) + { + $out=$val; + break; + } + } + } + } + // Else, retreive default values if we are not doing a sort + elseif (! isset($_GET['sortfield']) && ! empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set + { + if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) + { + if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' + { if (isset($user->default_values[$relativepathstring]['createform'])) { foreach($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) @@ -348,107 +348,107 @@ function GETPOST($paramname, $check='alpha', $method=0, $filter=NULL, $options=N if ($qualified) { - //var_dump($user->default_values[$relativepathstring][$defkey]['createform']); - if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) - { - $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname]; - break; - } + //var_dump($user->default_values[$relativepathstring][$defkey]['createform']); + if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) + { + $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname]; + break; + } } } } } - } - // Management of default search_filters and sort order - //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) - elseif (! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) - { - if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' - { - //var_dump($user->default_values[$relativepathstring]); - if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ? - { - if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...'] - { - foreach($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) - { - $qualified = 0; - if ($defkey != '_noquery_') - { - $tmpqueryarraytohave=explode('&', $defkey); - $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); - $foundintru=0; - foreach($tmpqueryarraytohave as $tmpquerytohave) - { - if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1; - } - if (! $foundintru) $qualified=1; - //var_dump($defkey.'-'.$qualified); - } - else $qualified = 1; - - if ($qualified) - { - $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , - foreach($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) - { - if ($out) $out.=', '; - if ($paramname == 'sortfield') - { - $out.=dol_string_nospecial($key, '', $forbidden_chars_to_replace); - } - if ($paramname == 'sortorder') - { - $out.=dol_string_nospecial($val, '', $forbidden_chars_to_replace); - } - } - //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?) - } - } + } + // Management of default search_filters and sort order + //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) + elseif (! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) + { + if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' + { + //var_dump($user->default_values[$relativepathstring]); + if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ? + { + if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...'] + { + foreach($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) + { + $qualified = 0; + if ($defkey != '_noquery_') + { + $tmpqueryarraytohave=explode('&', $defkey); + $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); + $foundintru=0; + foreach($tmpqueryarraytohave as $tmpquerytohave) + { + if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1; + } + if (! $foundintru) $qualified=1; + //var_dump($defkey.'-'.$qualified); + } + else $qualified = 1; + + if ($qualified) + { + $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , + foreach($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) + { + if ($out) $out.=', '; + if ($paramname == 'sortfield') + { + $out.=dol_string_nospecial($key, '', $forbidden_chars_to_replace); + } + if ($paramname == 'sortorder') + { + $out.=dol_string_nospecial($val, '', $forbidden_chars_to_replace); + } + } + //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?) + } + } } - } - elseif (isset($user->default_values[$relativepathstring]['filters'])) - { - foreach($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) - { - $qualified = 0; - if ($defkey != '_noquery_') - { - $tmpqueryarraytohave=explode('&', $defkey); - $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); - $foundintru=0; - foreach($tmpqueryarraytohave as $tmpquerytohave) - { - if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1; - } - if (! $foundintru) $qualified=1; - //var_dump($defkey.'-'.$qualified); - } - else $qualified = 1; + } + elseif (isset($user->default_values[$relativepathstring]['filters'])) + { + foreach($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) + { + $qualified = 0; + if ($defkey != '_noquery_') + { + $tmpqueryarraytohave=explode('&', $defkey); + $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); + $foundintru=0; + foreach($tmpqueryarraytohave as $tmpquerytohave) + { + if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1; + } + if (! $foundintru) $qualified=1; + //var_dump($defkey.'-'.$qualified); + } + else $qualified = 1; if ($qualified) { - if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) - { - // We made a search from quick search menu, do we still use default filter ? - if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) - { - $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , - $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace); - } - } - else - { - $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , - $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace); - } - break; + if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) + { + // We made a search from quick search menu, do we still use default filter ? + if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) + { + $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , + $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace); + } + } + else + { + $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , + $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace); + } + break; } - } - } - } - } - } + } + } + } + } + } } @@ -457,110 +457,110 @@ function GETPOST($paramname, $check='alpha', $method=0, $filter=NULL, $options=N // We do this only if var is a GET. If it is a POST, may be we want to post the text with vars as the setup text. if (! is_array($out) && empty($_POST[$paramname])) { - $maxloop=20; $loopnb=0; // Protection against infinite loop - while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side. - { - $loopnb++; $newout = ''; - - if ($reg[1] == 'DAY') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mday']; } - elseif ($reg[1] == 'MONTH') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mon']; } - elseif ($reg[1] == 'YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['year']; } - elseif ($reg[1] == 'PREVIOUS_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } - elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_month($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } - elseif ($reg[1] == 'PREVIOUS_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] - 1); } - elseif ($reg[1] == 'NEXT_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } - elseif ($reg[1] == 'NEXT_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_month($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } - elseif ($reg[1] == 'NEXT_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] + 1); } - elseif ($reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') - { - $newout = $mysoc->country_id; - } - elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') - { - $newout = $user->id; - } - elseif ($reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') - { - $newout = $user->fk_user; - } - elseif ($reg[1] == 'ENTITYID') - { - $newout = $conf->entity; - } - else $newout = ''; // Key not found, we replace with empty string - //var_dump('__'.$reg[1].'__ -> '.$newout); - $out = preg_replace('/__'.preg_quote($reg[1],'/').'__/', $newout, $out); - } - } - - // Check is done after replacement - switch ($check) - { - case 'none': - break; - case 'int': // Check param is a numeric value (integer but also float or hexadecimal) - if (! is_numeric($out)) { $out=''; } - break; - case 'intcomma': - if (preg_match('/[^0-9,]+/i',$out)) $out=''; - break; - case 'alpha': - $out=trim($out); - // '"' is dangerous because param in url can close the href= or src= and add javascript functions. - // '../' is dangerous because it allows dir transversals - if (preg_match('/"/',$out)) $out=''; - else if (preg_match('/\.\.\//',$out)) $out=''; - break; - case 'san_alpha': - $out=filter_var($out,FILTER_SANITIZE_STRING); - break; - case 'aZ': - $out=trim($out); - if (preg_match('/[^a-z]+/i',$out)) $out=''; - break; - case 'aZ09': - $out=trim($out); - if (preg_match('/[^a-z0-9_\-\.]+/i',$out)) $out=''; - break; - case 'array': - if (! is_array($out) || empty($out)) $out=array(); - break; + $maxloop=20; $loopnb=0; // Protection against infinite loop + while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side. + { + $loopnb++; $newout = ''; + + if ($reg[1] == 'DAY') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mday']; } + elseif ($reg[1] == 'MONTH') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mon']; } + elseif ($reg[1] == 'YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['year']; } + elseif ($reg[1] == 'PREVIOUS_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } + elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_month($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } + elseif ($reg[1] == 'PREVIOUS_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] - 1); } + elseif ($reg[1] == 'NEXT_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } + elseif ($reg[1] == 'NEXT_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_month($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } + elseif ($reg[1] == 'NEXT_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] + 1); } + elseif ($reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') + { + $newout = $mysoc->country_id; + } + elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') + { + $newout = $user->id; + } + elseif ($reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') + { + $newout = $user->fk_user; + } + elseif ($reg[1] == 'ENTITYID') + { + $newout = $conf->entity; + } + else $newout = ''; // Key not found, we replace with empty string + //var_dump('__'.$reg[1].'__ -> '.$newout); + $out = preg_replace('/__'.preg_quote($reg[1],'/').'__/', $newout, $out); + } + } + + // Check is done after replacement + switch ($check) + { + case 'none': + break; + case 'int': // Check param is a numeric value (integer but also float or hexadecimal) + if (! is_numeric($out)) { $out=''; } + break; + case 'intcomma': + if (preg_match('/[^0-9,]+/i',$out)) $out=''; + break; + case 'alpha': + $out=trim($out); + // '"' is dangerous because param in url can close the href= or src= and add javascript functions. + // '../' is dangerous because it allows dir transversals + if (preg_match('/"/',$out)) $out=''; + else if (preg_match('/\.\.\//',$out)) $out=''; + break; + case 'san_alpha': + $out=filter_var($out,FILTER_SANITIZE_STRING); + break; + case 'aZ': + $out=trim($out); + if (preg_match('/[^a-z]+/i',$out)) $out=''; + break; + case 'aZ09': + $out=trim($out); + if (preg_match('/[^a-z0-9_\-\.]+/i',$out)) $out=''; + break; + case 'array': + if (! is_array($out) || empty($out)) $out=array(); + break; case 'nohtml': - $out=dol_string_nohtmltag($out); + $out=dol_string_nohtmltag($out); break; case 'alphanohtml': // Recommended for search params - $out=trim($out); - // '"' is dangerous because param in url can close the href= or src= and add javascript functions. - // '../' is dangerous because it allows dir transversals - if (preg_match('/"/',$out)) $out=''; - else if (preg_match('/\.\.\//',$out)) $out=''; - $out=dol_string_nohtmltag($out); + $out=trim($out); + // '"' is dangerous because param in url can close the href= or src= and add javascript functions. + // '../' is dangerous because it allows dir transversals + if (preg_match('/"/',$out)) $out=''; + else if (preg_match('/\.\.\//',$out)) $out=''; + $out=dol_string_nohtmltag($out); break; case 'custom': - if (empty($filter)) return 'BadFourthParameterForGETPOST'; - $out=filter_var($out, $filter, $options); - break; - } + if (empty($filter)) return 'BadFourthParameterForGETPOST'; + $out=filter_var($out, $filter, $options); + break; + } - // Code for search criteria persistence. + // Code for search criteria persistence. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year' if (empty($method) || $method == 3 || $method == 4) { - //if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield", 'smonth', 'syear', 'month', 'year'))) - if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder','sortfield'))) - { - //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]); + //if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield", 'smonth', 'syear', 'month', 'year'))) + if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder','sortfield'))) + { + //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]); - // We save search key only if: - // - not empty, or - // - if value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not). + // We save search key only if: + // - not empty, or + // - if value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not). - //if (! empty($out) || ! empty($user->default_values[$relativepathstring]['filters'][$paramname])) - if (! empty($out)) - { - $user->lastsearch_values_tmp[$relativepathstring][$paramname]=$out; - } - } + //if (! empty($out) || ! empty($user->default_values[$relativepathstring]['filters'][$paramname])) + if (! empty($out)) + { + $user->lastsearch_values_tmp[$relativepathstring][$paramname]=$out; + } + } } return $out; @@ -577,14 +577,14 @@ function GETPOST($paramname, $check='alpha', $method=0, $filter=NULL, $options=N */ function dol_getprefix($mode='') { - global $conf; + global $conf; - // If MAIL_PREFIX_FOR_EMAIL_ID is set and prefix is for email - if ($mode == 'email' && ! empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) - { - if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID; - else if (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"]; - } + // If MAIL_PREFIX_FOR_EMAIL_ID is set and prefix is for email + if ($mode == 'email' && ! empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) + { + if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID; + else if (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"]; + } if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) { @@ -670,18 +670,18 @@ function dol_buildpath($path, $type=0, $returnemptyifnotfound=0) { if ($key == 'main') { - if ($type == 3) - { - global $dolibarr_main_url_root; - - // 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 - - $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).'/'.$path; // Test on start with http is for old conf syntax - } - continue; + if ($type == 3) + { + global $dolibarr_main_url_root; + + // 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 + + $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).'/'.$path; // Test on start with http is for old conf syntax + } + continue; } preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?' if (! empty($regs[1])) @@ -695,18 +695,18 @@ function dol_buildpath($path, $type=0, $returnemptyifnotfound=0) } if ($type == 2) { - $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path; + $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path; } if ($type == 3) { - global $dolibarr_main_url_root; + global $dolibarr_main_url_root; - // 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 $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 - $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax + $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax } break; } @@ -789,8 +789,8 @@ function dol_sanitizeFileName($str,$newstr='_',$unaccent=1) */ function dol_sanitizePathName($str,$newstr='_',$unaccent=1) { - $filesystem_forbidden_chars = array('<','>','?','*','|','"','°'); - return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars); + $filesystem_forbidden_chars = array('<','>','?','*','|','"','°'); + return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars); } /** @@ -974,54 +974,54 @@ function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename=' if (! empty($message)) { - // Test log level - $logLevels = array(LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG); - if (!in_array($level, $logLevels, true)) - { - throw new Exception('Incorrect log level'); - } - if ($level > $conf->global->SYSLOG_LEVEL) return; - - // If adding log inside HTML page is required - if (! empty($_REQUEST['logtohtml']) && (! empty($conf->global->MAIN_ENABLE_LOG_TO_HTML) || ! empty($conf->global->MAIN_LOGTOHTML))) // MAIN_LOGTOHTML kept for backward compatibility - { - $conf->logbuffer[] = dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message; - } - - //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output - // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments - if (! empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && ! empty($_GET["log"])) - { - print "\n\n<!-- Log start\n"; - print $message."\n"; - print "Log end -->\n"; - } - - $data = array( - 'message' => $message, - 'script' => (isset($_SERVER['PHP_SELF'])? basename($_SERVER['PHP_SELF'],'.php') : false), - 'level' => $level, - 'user' => ((is_object($user) && $user->id) ? $user->login : false), - 'ip' => false - ); - - // This is when server run behind a reverse proxy - if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].(empty($_SERVER["REMOTE_ADDR"])?'':'->'.$_SERVER['REMOTE_ADDR']); - // This is when server run normally on a server - else if (! empty($_SERVER["REMOTE_ADDR"])) $data['ip'] = $_SERVER['REMOTE_ADDR']; - // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache) - else if (! empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR']; - // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it). - else if (! empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']); - // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it). - else if (! empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME']; - // Loop on each log handler and send output - foreach ($conf->loghandlers as $loghandlerinstance) - { - if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue; - $loghandlerinstance->export($data,$suffixinfilename); - } - unset($data); + // Test log level + $logLevels = array(LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG); + if (!in_array($level, $logLevels, true)) + { + throw new Exception('Incorrect log level'); + } + if ($level > $conf->global->SYSLOG_LEVEL) return; + + // If adding log inside HTML page is required + if (! empty($_REQUEST['logtohtml']) && (! empty($conf->global->MAIN_ENABLE_LOG_TO_HTML) || ! empty($conf->global->MAIN_LOGTOHTML))) // MAIN_LOGTOHTML kept for backward compatibility + { + $conf->logbuffer[] = dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message; + } + + //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output + // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments + if (! empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && ! empty($_GET["log"])) + { + print "\n\n<!-- Log start\n"; + print $message."\n"; + print "Log end -->\n"; + } + + $data = array( + 'message' => $message, + 'script' => (isset($_SERVER['PHP_SELF'])? basename($_SERVER['PHP_SELF'],'.php') : false), + 'level' => $level, + 'user' => ((is_object($user) && $user->id) ? $user->login : false), + 'ip' => false + ); + + // This is when server run behind a reverse proxy + if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].(empty($_SERVER["REMOTE_ADDR"])?'':'->'.$_SERVER['REMOTE_ADDR']); + // This is when server run normally on a server + else if (! empty($_SERVER["REMOTE_ADDR"])) $data['ip'] = $_SERVER['REMOTE_ADDR']; + // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache) + else if (! empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR']; + // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it). + else if (! empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']); + // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it). + else if (! empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME']; + // Loop on each log handler and send output + foreach ($conf->loghandlers as $loghandlerinstance) + { + if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue; + $loghandlerinstance->export($data,$suffixinfilename); + } + unset($data); } if (! empty($ident)) @@ -1099,7 +1099,7 @@ function dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $pi $limittoshow=(empty($conf->global->MAIN_MAXTABS_IN_CARD)?99:$conf->global->MAIN_MAXTABS_IN_CARD); $displaytab=0; $nbintab=0; - $popuptab=0; $outmore=''; + $popuptab=0; $outmore=''; for ($i = 0 ; $i <= $maxkey ; $i++) { if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2])) @@ -1150,13 +1150,13 @@ function dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $pi } else { - // The popup with the other tabs + // The popup with the other tabs if (! $popuptab) { - $popuptab=1; - $outmore.='<div class="popuptabset">'; + $popuptab=1; + $outmore.='<div class="popuptabset">'; } - $outmore.='<div class="popuptab" style="display:inherit;">'; + $outmore.='<div class="popuptab" style="display:inherit;">'; if (isset($links[$i][2]) && $links[$i][2] == 'image') { if (!empty($links[$i][0])) @@ -1266,26 +1266,26 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r if (class_exists("Imagick")) { - if ($object->element == 'propal') $modulepart='propal'; + if ($object->element == 'propal') $modulepart='propal'; if ($object->element == 'commande') $modulepart='commande'; if ($object->element == 'facture') $modulepart='facture'; if ($object->element == 'fichinter') $modulepart='ficheinter'; if ($object->element == 'contrat') $modulepart='contract'; - if ($object->element == 'supplier_proposal') $modulepart='supplier_proposal'; + if ($object->element == 'supplier_proposal') $modulepart='supplier_proposal'; if ($object->element == 'order_supplier') $modulepart='supplier_order'; - if ($object->element == 'invoice_supplier') $modulepart='supplier_invoice'; + if ($object->element == 'invoice_supplier') $modulepart='supplier_invoice'; if ($object->element == 'expensereport') $modulepart='expensereport'; } if ($object->element == 'product') { - $width=80; $cssclass='photoref'; - $showimage=$object->is_photo_available($conf->product->multidir_output[$object->entity]); - $maxvisiblephotos=(isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO)?$conf->global->PRODUCT_MAX_VISIBLE_PHOTO:5); + $width=80; $cssclass='photoref'; + $showimage=$object->is_photo_available($conf->product->multidir_output[$object->entity]); + $maxvisiblephotos=(isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO)?$conf->global->PRODUCT_MAX_VISIBLE_PHOTO:5); if ($conf->browser->phone) $maxvisiblephotos=1; if ($showimage) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos($conf->product->multidir_output[$object->entity],'small',$maxvisiblephotos,0,0,0,$width,0).'</div>'; - else - { + else + { if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) { $nophoto=''; $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"></div>'; @@ -1294,153 +1294,153 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r $nophoto='/public/theme/common/nophoto.png'; $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'"></div>'; //} - } + } } else { if ($showimage) - { - if ($modulepart != 'unknown') - { - $phototoshow=''; - // Check if a preview file is available - if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) - { - $objectref = dol_sanitizeFileName($object->ref); - $dir_output = $conf->$modulepart->dir_output . "/"; - if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) - { - $subdir = get_exdir($object->id, 2, 0, 0, $object, $modulepart).$objectref; - } - else - { - $subdir = get_exdir($object->id, 0, 0, 0, $object, $modulepart).$objectref; - } - $filepath = $dir_output . $subdir . "/"; - $file = $filepath . $objectref . ".pdf"; - $relativepath = $subdir.'/'.$objectref.'.pdf'; - - // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png") - $fileimage = $file.'_preview.png'; // If PDF has 1 page - $fileimagebis = $file.'_preview-0.png'; // If PDF has more than one page - $relativepathimage = $relativepath.'_preview.png'; - - // Si fichier PDF existe - if (file_exists($file)) - { - $encfile = urlencode($file); - // Conversion du PDF en image png si fichier png non existant - if ( (! file_exists($fileimage) || (filemtime($fileimage) < filemtime($file))) - && (! file_exists($fileimagebis) || (filemtime($fileimagebis) < filemtime($file))) - ) - { - if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experienc trouble with pdf thumb generation and imagick, you can disable here. - { - $ret = dol_convert_file($file, 'png', $fileimage); - if ($ret < 0) $error++; - } - } - - $heightforphotref=70; - if (! empty($conf->dol_optimize_smallscreen)) $heightforphotref=60; - // Si fichier png PDF d'1 page trouve - if (file_exists($fileimage)) - { - $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">'; - $phototoshow.= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&file='.urlencode($relativepathimage).'">'; - $phototoshow.= '</div></div>'; - } - // Si fichier png PDF de plus d'1 page trouve - elseif (file_exists($fileimagebis)) - { - $preview = preg_replace('/\.png/','',$relativepathimage) . "-0.png"; - $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">'; - $phototoshow.= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&file='.urlencode($preview).'"><p>'; - $phototoshow.= '</div></div>'; - } - } - } - else if (! $phototoshow) - { - $phototoshow = $form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos); - } - - if ($phototoshow) - { - $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'; - $morehtmlleft.=$phototoshow; - $morehtmlleft.='</div>'; - } - } - - if (! $phototoshow) // Show No photo link (picto of pbject) - { - $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'; - if ($object->element == 'action') - { - $width=80; - $cssclass='photorefcenter'; - $nophoto=img_picto('', 'title_agenda', '', false, 1); - } - else - { - $width=14; $cssclass='photorefcenter'; - $picto = $object->picto; - if ($object->element == 'project' && ! $object->public) $picto = 'project'; // instead of projectpub - $nophoto=img_picto('', 'object_'.$picto, '', false, 1); - } - $morehtmlleft.='<!-- No photo to show -->'; - $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.$nophoto.'"></div></div>'; - - $morehtmlleft.='</div>'; - } - } + { + if ($modulepart != 'unknown') + { + $phototoshow=''; + // Check if a preview file is available + if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) + { + $objectref = dol_sanitizeFileName($object->ref); + $dir_output = $conf->$modulepart->dir_output . "/"; + if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) + { + $subdir = get_exdir($object->id, 2, 0, 0, $object, $modulepart).$objectref; + } + else + { + $subdir = get_exdir($object->id, 0, 0, 0, $object, $modulepart).$objectref; + } + $filepath = $dir_output . $subdir . "/"; + $file = $filepath . $objectref . ".pdf"; + $relativepath = $subdir.'/'.$objectref.'.pdf'; + + // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png") + $fileimage = $file.'_preview.png'; // If PDF has 1 page + $fileimagebis = $file.'_preview-0.png'; // If PDF has more than one page + $relativepathimage = $relativepath.'_preview.png'; + + // Si fichier PDF existe + if (file_exists($file)) + { + $encfile = urlencode($file); + // Conversion du PDF en image png si fichier png non existant + if ( (! file_exists($fileimage) || (filemtime($fileimage) < filemtime($file))) + && (! file_exists($fileimagebis) || (filemtime($fileimagebis) < filemtime($file))) + ) + { + if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experienc trouble with pdf thumb generation and imagick, you can disable here. + { + $ret = dol_convert_file($file, 'png', $fileimage); + if ($ret < 0) $error++; + } + } + + $heightforphotref=70; + if (! empty($conf->dol_optimize_smallscreen)) $heightforphotref=60; + // Si fichier png PDF d'1 page trouve + if (file_exists($fileimage)) + { + $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">'; + $phototoshow.= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&file='.urlencode($relativepathimage).'">'; + $phototoshow.= '</div></div>'; + } + // Si fichier png PDF de plus d'1 page trouve + elseif (file_exists($fileimagebis)) + { + $preview = preg_replace('/\.png/','',$relativepathimage) . "-0.png"; + $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">'; + $phototoshow.= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&file='.urlencode($preview).'"><p>'; + $phototoshow.= '</div></div>'; + } + } + } + else if (! $phototoshow) + { + $phototoshow = $form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos); + } + + if ($phototoshow) + { + $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'; + $morehtmlleft.=$phototoshow; + $morehtmlleft.='</div>'; + } + } + + if (! $phototoshow) // Show No photo link (picto of pbject) + { + $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'; + if ($object->element == 'action') + { + $width=80; + $cssclass='photorefcenter'; + $nophoto=img_picto('', 'title_agenda', '', false, 1); + } + else + { + $width=14; $cssclass='photorefcenter'; + $picto = $object->picto; + if ($object->element == 'project' && ! $object->public) $picto = 'project'; // instead of projectpub + $nophoto=img_picto('', 'object_'.$picto, '', false, 1); + } + $morehtmlleft.='<!-- No photo to show -->'; + $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.$nophoto.'"></div></div>'; + + $morehtmlleft.='</div>'; + } + } } if ($showbarcode) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>'; if ($object->element == 'societe') { - if (! empty($conf->use_javascript_ajax) && $user->rights->societe->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) - { - $morehtmlstatus.=ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased'); - } + if (! empty($conf->use_javascript_ajax) && $user->rights->societe->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) + { + $morehtmlstatus.=ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased'); + } } elseif ($object->element == 'product') { - //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') '; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - $morehtmlstatus.=ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); - } else { - $morehtmlstatus.='<span class="statusrefsell">'.$object->getLibStatut(5,0).'</span>'; - } - $morehtmlstatus.=' '; - //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') '; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - $morehtmlstatus.=ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); - } else { - $morehtmlstatus.='<span class="statusrefbuy">'.$object->getLibStatut(5,1).'</span>'; - } + //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') '; + if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + $morehtmlstatus.=ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); + } else { + $morehtmlstatus.='<span class="statusrefsell">'.$object->getLibStatut(5,0).'</span>'; + } + $morehtmlstatus.=' '; + //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') '; + if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + $morehtmlstatus.=ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); + } else { + $morehtmlstatus.='<span class="statusrefbuy">'.$object->getLibStatut(5,1).'</span>'; + } } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan'))) { - $tmptxt=$object->getLibStatut(6, $object->totalpaye); - if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5, $object->totalpaye); + $tmptxt=$object->getLibStatut(6, $object->totalpaye); + if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5, $object->totalpaye); $morehtmlstatus.=$tmptxt; } elseif ($object->element == 'contrat' || $object->element == 'contract') { - if ($object->statut==0) $morehtmlstatus.=$object->getLibStatut(2); - else $morehtmlstatus.=$object->getLibStatut(4); + if ($object->statut==0) $morehtmlstatus.=$object->getLibStatut(2); + else $morehtmlstatus.=$object->getLibStatut(4); } elseif ($object->element == 'facturerec') { - if ($object->frequency==0) $morehtmlstatus.=$object->getLibStatut(2); - else $morehtmlstatus.=$object->getLibStatut(4); + if ($object->frequency==0) $morehtmlstatus.=$object->getLibStatut(2); + else $morehtmlstatus.=$object->getLibStatut(4); } else { // Generic case - $tmptxt=$object->getLibStatut(6); - if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5); + $tmptxt=$object->getLibStatut(6); + if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5); $morehtmlstatus.=$tmptxt; } if (! empty($object->name_alias)) $morehtmlref.='<div class="refidno">'.$object->name_alias.'</div>'; // For thirdparty @@ -1453,9 +1453,9 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r if ($object->element != 'product' && $object->element != 'bookmark' && $object->element != 'ecm_directories') { - $morehtmlref.='<div class="refidno">'; - $morehtmlref.=$object->getBannerAddress('refaddress',$object); - $morehtmlref.='</div>'; + $morehtmlref.='<div class="refidno">'; + $morehtmlref.=$object->getBannerAddress('refaddress',$object); + $morehtmlref.='</div>'; } if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && in_array($object->element, array('societe', 'contact', 'member', 'product'))) { @@ -1714,7 +1714,7 @@ function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$e { // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs. $month=adodb_strftime('%m', $time+$offsettz+$offsetdst); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. - $month=sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'. + $month=sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'. if ($encodetooutput) { $monthtext=$outputlangs->transnoentities('Month'.$month); @@ -1898,7 +1898,7 @@ function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1) */ function dol_now($mode='gmt') { - $ret=''; + $ret=''; // Note that gmmktime and mktime return same value (GMT) when used without parameters //if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() function instead if ($mode == 'gmt') $ret=time(); // Time for now at greenwich. @@ -2141,9 +2141,9 @@ function dol_print_phone($phone,$countrycode='',$cid=0,$socid=0,$addlink='',$sep if (strtoupper($countrycode) == "CA") { - if (dol_strlen($phone) == 10) { - $newphone=($separ!=''?'(':'').substr($newphone,0,3).($separ!=''?')':'').$separ.substr($newphone,3,3).($separ!=''?'-':'').substr($newphone,6,4); - } + if (dol_strlen($phone) == 10) { + $newphone=($separ!=''?'(':'').substr($newphone,0,3).($separ!=''?')':'').$separ.substr($newphone,3,3).($separ!=''?'-':'').substr($newphone,6,4); + } } if (! empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set) @@ -2299,37 +2299,37 @@ function dol_print_address($address, $htmlid, $mode, $id, $noprint=0, $charfornl if ($address) { - if ($hookmanager) { - $parameters = array('element' => $mode, 'id' => $id); - $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address); - $out.=$hookmanager->resPrint; - } - if (empty($reshook)) - { - if (empty($charfornl)) $out.=nl2br($address); - else $out.=preg_replace('/[\r\n]+/', $charfornl, $address); - - $showgmap=$showomap=0; - - // TODO Add a hook here - if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1; - if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1; - if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1; - if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap=1; - if ($mode=='contact' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap=1; - if ($mode=='member' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap=1; - - if ($showgmap) - { - $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id,1); - $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>'; - } - if ($showomap) - { - $url=dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id,1); - $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>'; - } - } + if ($hookmanager) { + $parameters = array('element' => $mode, 'id' => $id); + $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address); + $out.=$hookmanager->resPrint; + } + if (empty($reshook)) + { + if (empty($charfornl)) $out.=nl2br($address); + else $out.=preg_replace('/[\r\n]+/', $charfornl, $address); + + $showgmap=$showomap=0; + + // TODO Add a hook here + if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1; + if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1; + if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1; + if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap=1; + if ($mode=='contact' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap=1; + if ($mode=='member' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap=1; + + if ($showgmap) + { + $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id,1); + $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>'; + } + if ($showomap) + { + $url=dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id,1); + $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>'; + } + } } if ($noprint) return $out; else print $out; @@ -2432,9 +2432,9 @@ function dol_print_graph($htmlid,$width,$height,$data,$showlegend=0,$type='pie', if ($shownographyet) { - print '<div class="nographyet" style="width:'.$width.'px;height:'.$height.'px;"></div>'; - print '<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>'; - return; + print '<div class="nographyet" style="width:'.$width.'px;height:'.$height.'px;"></div>'; + print '<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>'; + return; } if (empty($conf->use_javascript_ajax)) return; @@ -2928,9 +2928,9 @@ function img_delete($titlealt = 'default', $other = 'class="pictodelete"') */ function img_printer($titlealt = "default", $other='') { - global $conf,$langs; - if ($titlealt=="default") $titlealt=$langs->trans("Print"); - return img_picto($titlealt,'printer.png',$other); + global $conf,$langs; + if ($titlealt=="default") $titlealt=$langs->trans("Print"); + return img_picto($titlealt,'printer.png',$other); } /** @@ -3021,7 +3021,7 @@ function img_error($titlealt = 'default') * * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"') - * @return string Return img tag + * @return string Return img tag */ function img_next($titlealt = 'default', $moreatt='') { @@ -3320,8 +3320,8 @@ function dol_print_error($db='',$error='',$errors=null) } else // Mode CLI { - // No dol_escape_htmltag for output, we are in CLI mode - $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n"; + // No dol_escape_htmltag for output, we are in CLI mode + $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n"; $out.='> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->transnoentities("ErrorNoRequestInError"))."\n"; $out.='> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno()?$db->lasterrno():$langs->transnoentities("ErrorNoRequestInError"))."\n"; $out.='> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror()?$db->lasterror():$langs->transnoentities("ErrorNoRequestInError"))."\n"; @@ -3439,7 +3439,7 @@ function getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $m $sortorder=strtoupper($sortorder); $out=''; - $sortimg=''; + $sortimg=''; $tag='th'; if ($thead==2) $tag='div'; @@ -3464,13 +3464,13 @@ function getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $m if ($field1 != $sortfield1) // We are on another field { - if (preg_match('/^DESC/', $sortorder)) $out.= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'; - else $out.= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'; + if (preg_match('/^DESC/', $sortorder)) $out.= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'; + else $out.= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'; } else // We are of first sorting criteria { - if (preg_match('/^ASC/', $sortorder)) $out.= '<a class="reposition" href="'.$file.'?sortfield='.$sortfield.'&sortorder=desc&begin='.$begin.$options.'">'; - else $out.= '<a class="reposition" href="'.$file.'?sortfield='.$sortfield.'&sortorder=asc&begin='.$begin.$options.'">'; + if (preg_match('/^ASC/', $sortorder)) $out.= '<a class="reposition" href="'.$file.'?sortfield='.$sortfield.'&sortorder=desc&begin='.$begin.$options.'">'; + else $out.= '<a class="reposition" href="'.$file.'?sortfield='.$sortfield.'&sortorder=asc&begin='.$begin.$options.'">'; } } @@ -3620,8 +3620,8 @@ function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $so global $conf,$langs; $savlimit = $limit; - $savtotalnboflines = $totalnboflines; - $totalnboflines=abs($totalnboflines); + $savtotalnboflines = $totalnboflines; + $totalnboflines=abs($totalnboflines); if ($picto == 'setup') $picto='title_setup.png'; if (($conf->browser->name == 'ie') && $picto=='title_generic.png') $picto='title.gif'; @@ -3734,40 +3734,40 @@ function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betwee print '<div class="pagination"><ul>'; if ((int) $limit >= 0 && empty($hideselectlimit)) { - $pagesizechoices='10:10,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000'; - //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported - //$pagesizechoices.=',2:2'; - if (! empty($conf->global->MAIN_PAGESIZE_CHOICES)) $pagesizechoices=$conf->global->MAIN_PAGESIZE_CHOICES; - - print '<li class="pagination">'; - print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">'; - $tmpchoice=explode(',',$pagesizechoices); - $tmpkey=$limit.':'.$limit; - if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey; - $tmpkey=$conf->liste_limit.':'.$conf->liste_limit; - if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey; - asort($tmpchoice, SORT_NUMERIC); - $found=false; - foreach($tmpchoice as $val) - { - $selected=''; - $tmp=explode(':',$val); - $key=$tmp[0]; - $val=$tmp[1]; - if ($key != '' && $val != '') - { - if ((int) $key == (int) $limit) - { - $selected = ' selected="selected"'; - $found = true; - } - print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n"; - } - } - print '</select>'; - if ($conf->use_javascript_ajax) - { - print '<!-- JS CODE TO ENABLE select limit to launch submit of page --> + $pagesizechoices='10:10,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000'; + //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported + //$pagesizechoices.=',2:2'; + if (! empty($conf->global->MAIN_PAGESIZE_CHOICES)) $pagesizechoices=$conf->global->MAIN_PAGESIZE_CHOICES; + + print '<li class="pagination">'; + print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">'; + $tmpchoice=explode(',',$pagesizechoices); + $tmpkey=$limit.':'.$limit; + if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey; + $tmpkey=$conf->liste_limit.':'.$conf->liste_limit; + if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey; + asort($tmpchoice, SORT_NUMERIC); + $found=false; + foreach($tmpchoice as $val) + { + $selected=''; + $tmp=explode(':',$val); + $key=$tmp[0]; + $val=$tmp[1]; + if ($key != '' && $val != '') + { + if ((int) $key == (int) $limit) + { + $selected = ' selected="selected"'; + $found = true; + } + print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n"; + } + } + print '</select>'; + if ($conf->use_javascript_ajax) + { + print '<!-- JS CODE TO ENABLE select limit to launch submit of page --> <script type="text/javascript"> jQuery(document).ready(function () { jQuery(".selectlimit").change(function() { @@ -3777,8 +3777,8 @@ function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betwee }); </script> '; - } - print '</li>'; + } + print '</li>'; } if ($page > 0) { @@ -3814,17 +3814,17 @@ function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betwee */ function vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0) { - $morelabel=''; + $morelabel=''; - if (preg_match('/%/',$rate)) + if (preg_match('/%/',$rate)) { $rate=str_replace('%','',$rate); $addpercent=true; } if (preg_match('/\((.*)\)/',$rate,$reg)) { - $morelabel=' ('.$reg[1].')'; - $rate=preg_replace('/\s*'.preg_quote($morelabel,'/').'/','',$rate); + $morelabel=' ('.$reg[1].')'; + $rate=preg_replace('/\s*'.preg_quote($morelabel,'/').'/','',$rate); } if (preg_match('/\*/',$rate)) { @@ -4035,32 +4035,32 @@ function price2num($amount,$rounding='',$alreadysqlnb=0) */ function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no') { - require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; - if (($forceunitoutput == 'no' && $dimension < 1/10000) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) - { - $dimension = $dimension * 1000000; - $unit = $unit - 6; - } - elseif (($forceunitoutput == 'no' && $dimension < 1/10) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) - { - $dimension = $dimension * 1000; - $unit = $unit - 3; - } - elseif (($forceunitoutput == 'no' && $dimension > 100000000) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) - { - $dimension = $dimension / 1000000; - $unit = $unit + 6; - } - elseif (($forceunitoutput == 'no' && $dimension > 100000) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) - { - $dimension = $dimension / 1000; - $unit = $unit + 3; - } + if (($forceunitoutput == 'no' && $dimension < 1/10000) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) + { + $dimension = $dimension * 1000000; + $unit = $unit - 6; + } + elseif (($forceunitoutput == 'no' && $dimension < 1/10) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) + { + $dimension = $dimension * 1000; + $unit = $unit - 3; + } + elseif (($forceunitoutput == 'no' && $dimension > 100000000) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) + { + $dimension = $dimension / 1000000; + $unit = $unit + 6; + } + elseif (($forceunitoutput == 'no' && $dimension > 100000) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) + { + $dimension = $dimension / 1000; + $unit = $unit + 3; + } - $ret=price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuring_units_string($unit, $type); + $ret=price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuring_units_string($unit, $type); - return $ret; + return $ret; } @@ -4087,8 +4087,8 @@ function get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller $vatratecleaned = $vatrate; if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)" { - $vatratecleaned = trim($reg[1]); - $vatratecode = $reg[2]; + $vatratecleaned = trim($reg[1]); + $vatratecode = $reg[2]; } /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code) @@ -4134,47 +4134,47 @@ function get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on. if (in_array($mysoc->country_code, array('ES'))) { - $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1; + $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1; } // Search local taxes if (! empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) { - if ($local==1) - { - if ($thirdparty_seller != $mysoc) - { - if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate - { - return $thirdparty_seller->localtax1_value; - } - } - else // i am the seller - { - if (!isOnlyOneLocalTax($local)) // TODO If seller is me, why not always returning this, even if there is only one locatax vat. - { - return $conf->global->MAIN_INFO_VALUE_LOCALTAX1; - } - } - } - if ($local==2) - { - if ($thirdparty_seller != $mysoc) - { - if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate - // TODO We should also return value defined on thirdparty only if defined - { - return $thirdparty_seller->localtax2_value; - } - } - else // i am the seller - { - if (!isOnlyOneLocalTax($local)) // This is for spain only, we don't return value found into datbase even if there is only one locatax vat. - { - return $conf->global->MAIN_INFO_VALUE_LOCALTAX2; - } - } - } + if ($local==1) + { + if ($thirdparty_seller != $mysoc) + { + if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate + { + return $thirdparty_seller->localtax1_value; + } + } + else // i am the seller + { + if (!isOnlyOneLocalTax($local)) // TODO If seller is me, why not always returning this, even if there is only one locatax vat. + { + return $conf->global->MAIN_INFO_VALUE_LOCALTAX1; + } + } + } + if ($local==2) + { + if ($thirdparty_seller != $mysoc) + { + if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate + // TODO We should also return value defined on thirdparty only if defined + { + return $thirdparty_seller->localtax2_value; + } + } + else // i am the seller + { + if (!isOnlyOneLocalTax($local)) // This is for spain only, we don't return value found into datbase even if there is only one locatax vat. + { + return $conf->global->MAIN_INFO_VALUE_LOCALTAX2; + } + } + } } // By default, search value of local tax on line of common tax @@ -4264,41 +4264,41 @@ function get_localtax_by_third($local) */ function getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1) { - global $db, $mysoc; + global $db, $mysoc; - dol_syslog("getTaxesFromId vatrowid=".$vatrate); + dol_syslog("getTaxesFromId vatrowid=".$vatrate); - // Search local taxes - $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t"; - if ($firstparamisid) $sql.= " WHERE t.rowid = ".(int) $vatrate; - else - { - $vatratecleaned = $vatrate; - $vatratecode = ''; - if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)" - { - $vatratecleaned = $reg[1]; - $vatratecode = $reg[2]; - } + // Search local taxes + $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t"; + if ($firstparamisid) $sql.= " WHERE t.rowid = ".(int) $vatrate; + else + { + $vatratecleaned = $vatrate; + $vatratecode = ''; + if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)" + { + $vatratecleaned = $reg[1]; + $vatratecode = $reg[2]; + } - $sql.=", ".MAIN_DB_PREFIX."c_country as c"; - if ($mysoc->country_code == 'ES') $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'"; // local tax in spain use the buyer country ?? - else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'"; - $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1"; - if ($vatratecode) $sql.= " AND t.code = '".$vatratecode."'"; - } + $sql.=", ".MAIN_DB_PREFIX."c_country as c"; + if ($mysoc->country_code == 'ES') $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'"; // local tax in spain use the buyer country ?? + else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'"; + $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1"; + if ($vatratecode) $sql.= " AND t.code = '".$vatratecode."'"; + } - $resql=$db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - if ($obj) return array('rowid'=>$obj->rowid, 'code'=>$obj->code, 'rate'=>$obj->rate, 'npr'=>$obj->npr, 'accountancy_code_sell'=>$obj->accountancy_code_sell, 'accountancy_code_buy'=>$obj->accountancy_code_buy); - else return array(); - } - else dol_print_error($db); + $resql=$db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + if ($obj) return array('rowid'=>$obj->rowid, 'code'=>$obj->code, 'rate'=>$obj->rate, 'npr'=>$obj->npr, 'accountancy_code_sell'=>$obj->accountancy_code_sell, 'accountancy_code_buy'=>$obj->accountancy_code_buy); + else return array(); + } + else dol_print_error($db); - return array(); + return array(); } /** @@ -4328,19 +4328,19 @@ function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisi if ($firstparamisid) $sql.= " WHERE t.rowid = ".(int) $vatrate; else { - $vatratecleaned = $vatrate; - $vatratecode = ''; - if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)" - { - $vatratecleaned = $reg[1]; - $vatratecode = $reg[2]; - } + $vatratecleaned = $vatrate; + $vatratecode = ''; + if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)" + { + $vatratecleaned = $reg[1]; + $vatratecode = $reg[2]; + } - $sql.=", ".MAIN_DB_PREFIX."c_country as c"; - if ($mysoc->country_code == 'ES') $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'"; // local tax in spain use the buyer country ?? - else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'"; - $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1"; - if ($vatratecode) $sql.= " AND t.code = '".$vatratecode."'"; + $sql.=", ".MAIN_DB_PREFIX."c_country as c"; + if ($mysoc->country_code == 'ES') $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'"; // local tax in spain use the buyer country ?? + else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'"; + $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1"; + if ($vatratecode) $sql.= " AND t.code = '".$vatratecode."'"; } $resql=$db->query($sql); @@ -4784,10 +4784,10 @@ function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart) // TODO // We will enhance here a common way of forging path for document storage // Here, object->id, object->ref and object->modulepart are required. - if (in_array($modulepart, array('thirdparty','contact','member'))) - { - $path=$object->ref?$object->ref:$object->id; - } + if (in_array($modulepart, array('thirdparty','contact','member'))) + { + $path=$object->ref?$object->ref:$object->id; + } } if (empty($withoutslash) && ! empty($path)) $path.='/'; @@ -4899,11 +4899,11 @@ function dol_string_nohtmltag($stringtoclean,$removelinefeed=1,$pagecodeto='UTF- $stringtoclean = preg_replace('/<br[^>]*>/', "\n", $stringtoclean); $temp = dol_html_entity_decode($stringtoclean,ENT_COMPAT,$pagecodeto); - // Exemple of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a> - $temp = preg_replace($pattern,"",$temp); // pass 1 - // $temp after pass 1: <a href="/myurl" title="A title">0000-021 - $temp = preg_replace($pattern,"",$temp); // pass 2 - // $temp after pass 2: 0000-021 + // Exemple of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a> + $temp = preg_replace($pattern,"",$temp); // pass 1 + // $temp after pass 1: <a href="/myurl" title="A title">0000-021 + $temp = preg_replace($pattern,"",$temp); // pass 2 + // $temp after pass 2: 0000-021 // Supprime aussi les retours if ($removelinefeed) $temp=str_replace(array("\r\n","\r","\n")," ",$temp); @@ -4938,9 +4938,9 @@ function dolGetFirstLineOfText($text, $nboflines=1) } else { - $firstline=preg_replace('/[\n\r].*/','',$text); + $firstline=preg_replace('/[\n\r].*/','',$text); } - return $firstline.((strlen($firstline) != strlen($text))?'...':''); + return $firstline.((strlen($firstline) != strlen($text))?'...':''); } else { @@ -4971,7 +4971,7 @@ function dolGetFirstLineOfText($text, $nboflines=1) $i++; } unset($a); - return $firstline.(($i < $nba)?'...':''); + return $firstline.(($i < $nba)?'...':''); } } @@ -5257,222 +5257,222 @@ function dol_concatdesc($text1,$text2,$forxml=false) */ function getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null) { - global $db, $conf, $mysoc, $user; - - $substitutionarray=array(); - - if (empty($exclude) || ! in_array('system', $exclude)) - { - $substitutionarray['__(AnyTranslationKey)__']=$outputlangs->trans('TranslationKey'); - $substitutionarray['__DOL_MAIN_URL_ROOT__']=DOL_MAIN_URL_ROOT; - } - if (empty($exclude) || ! in_array('mycompany', $exclude)) - { - $substitutionarray=array_merge($substitutionarray, array( - '__MYCOMPANY_NAME__' => $mysoc->name, - '__MYCOMPANY_EMAIL__' => $mysoc->email, - '__MYCOMPANY_PROFID1__' => $mysoc->idprof1, - '__MYCOMPANY_PROFID2__' => $mysoc->idprof2, - '__MYCOMPANY_PROFID3__' => $mysoc->idprof3, - '__MYCOMPANY_PROFID4__' => $mysoc->idprof4, - '__MYCOMPANY_PROFID5__' => $mysoc->idprof5, - '__MYCOMPANY_PROFID6__' => $mysoc->idprof6, - '__MYCOMPANY_CAPITAL__' => $mysoc->capital, - '__MYCOMPANY_FULLADDRESS__' => $mysoc->getFullAddress(1, ', '), - '__MYCOMPANY_ADDRESS__' => $mysoc->address, - '__MYCOMPANY_ZIP__' => $mysoc->zip, - '__MYCOMPANY_TOWN__' => $mysoc->town, - '__MYCOMPANY_COUNTRY__' => $mysoc->country, - '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id - )); - } - if (($onlykey || is_object($object)) && (empty($exclude) || ! in_array('object', $exclude))) - { - if ($onlykey) - { - $substitutionarray['__ID__'] = '__ID__'; - $substitutionarray['__REF__'] = '__REF__'; - $substitutionarray['__REFCLIENT__'] = '__REFCLIENT__'; - $substitutionarray['__REFSUPPLIER__'] = '__REFSUPPLIER__'; - $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__'; - - $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__'; - $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__'; - - if (is_object($object) && $object->element == 'shipping') - { - $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__'; - $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__'; + global $db, $conf, $mysoc, $user; + + $substitutionarray=array(); + + if (empty($exclude) || ! in_array('system', $exclude)) + { + $substitutionarray['__(AnyTranslationKey)__']=$outputlangs->trans('TranslationKey'); + $substitutionarray['__DOL_MAIN_URL_ROOT__']=DOL_MAIN_URL_ROOT; + } + if (empty($exclude) || ! in_array('mycompany', $exclude)) + { + $substitutionarray=array_merge($substitutionarray, array( + '__MYCOMPANY_NAME__' => $mysoc->name, + '__MYCOMPANY_EMAIL__' => $mysoc->email, + '__MYCOMPANY_PROFID1__' => $mysoc->idprof1, + '__MYCOMPANY_PROFID2__' => $mysoc->idprof2, + '__MYCOMPANY_PROFID3__' => $mysoc->idprof3, + '__MYCOMPANY_PROFID4__' => $mysoc->idprof4, + '__MYCOMPANY_PROFID5__' => $mysoc->idprof5, + '__MYCOMPANY_PROFID6__' => $mysoc->idprof6, + '__MYCOMPANY_CAPITAL__' => $mysoc->capital, + '__MYCOMPANY_FULLADDRESS__' => $mysoc->getFullAddress(1, ', '), + '__MYCOMPANY_ADDRESS__' => $mysoc->address, + '__MYCOMPANY_ZIP__' => $mysoc->zip, + '__MYCOMPANY_TOWN__' => $mysoc->town, + '__MYCOMPANY_COUNTRY__' => $mysoc->country, + '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id + )); + } + if (($onlykey || is_object($object)) && (empty($exclude) || ! in_array('object', $exclude))) + { + if ($onlykey) + { + $substitutionarray['__ID__'] = '__ID__'; + $substitutionarray['__REF__'] = '__REF__'; + $substitutionarray['__REFCLIENT__'] = '__REFCLIENT__'; + $substitutionarray['__REFSUPPLIER__'] = '__REFSUPPLIER__'; + $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__'; + + $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__'; + $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__'; + + if (is_object($object) && $object->element == 'shipping') + { + $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__'; + $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'; - - $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'LinkToPayOnlineIfApplicable'; - $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)'; - $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)'; - $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order'; - $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice'; - $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service'; - - if (is_object($object) && $object->element == 'shipping') - { - $substitutionarray['__SHIPPINGTRACKNUM__']='Shipping tacking number'; - $substitutionarray['__SHIPPINGTRACKNUMURL__']='Shipping tracking url'; - } - } - else - { - $substitutionarray['__ID__'] = $object->id; - $substitutionarray['__REF__'] = $object->ref; - $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : '')); - $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : ''); - - // TODO USe this ? - $msgishtml = 0; - - $birthday = dol_print_date($object->birth,'day'); - - if (method_exists($object, 'getCivilityLabel')) $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel(); - $substitutionarray['__MEMBER_FIRSTNAME__']=$msgishtml?dol_htmlentitiesbr($object->firstname):$object->firstname; - $substitutionarray['__MEMBER_LASTNAME__']=$msgishtml?dol_htmlentitiesbr($object->lastname):$object->lastname; - if (method_exists($object, 'getFullName')) $substitutionarray['__MEMBER_FULLNAME__']=$msgishtml?dol_htmlentitiesbr($object->getFullName($outputlangs)):$object->getFullName($outputlangs); - $substitutionarray['__MEMBER_COMPANY__']=$msgishtml?dol_htmlentitiesbr($object->societe):$object->societe; - $substitutionarray['__MEMBER_ADDRESS__']=$msgishtml?dol_htmlentitiesbr($object->address):$object->address; - $substitutionarray['__MEMBER_ZIP__']=$msgishtml?dol_htmlentitiesbr($object->zip):$object->zip; - $substitutionarray['__MEMBER_TOWN__']=$msgishtml?dol_htmlentitiesbr($object->town):$object->town; - $substitutionarray['__MEMBER_COUNTRY__']=$msgishtml?dol_htmlentitiesbr($object->country):$object->country; - $substitutionarray['__MEMBER_EMAIL__']=$msgishtml?dol_htmlentitiesbr($object->email):$object->email; - $substitutionarray['__MEMBER_BIRTH__']=$msgishtml?dol_htmlentitiesbr($birthday):$birthday; - $substitutionarray['__MEMBER_PHOTO__']=$msgishtml?dol_htmlentitiesbr($object->photo):$object->photo; - $substitutionarray['__MEMBER_LOGIN__']=$msgishtml?dol_htmlentitiesbr($object->login):$object->login; - $substitutionarray['__MEMBER_PASSWORD__']=$msgishtml?dol_htmlentitiesbr($object->pass):$object->pass; - $substitutionarray['__MEMBER_PHONE__']=$msgishtml?dol_htmlentitiesbr($object->phone):$object->phone; - $substitutionarray['__MEMBER_PHONEPRO__']=$msgishtml?dol_htmlentitiesbr($object->phone_perso):$object->phone_perso; - $substitutionarray['__MEMBER_PHONEMOBILE__']=$msgishtml?dol_htmlentitiesbr($object->phone_mobile):$object->phone_mobile; - - if (is_object($object->thirdparty) && $object->thirdparty->id > 0) - { - $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty)?$object->thirdparty->id:''); - $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty)?$object->thirdparty->name:''); - } - - if (is_object($object->projet) && $object->projet->id > 0) - { - $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet)?$object->projet->id:''); - $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet)?$object->projet->ref:''); - $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet)?$object->projet->title:''); - } - - if (is_object($object) && $object->element == 'shipping') - { - $substitutionarray['__SHIPPINGTRACKNUM__']=$object->tracking_number; - $substitutionarray['__SHIPPINGTRACKNUMURL__']=$object->tracking_url; - } - - if (is_object($object) && $object->element == 'contrat' && is_array($object->lines)) - { - $dateplannedstart=''; - $datenextexpiration=''; - foreach($object->lines as $line) - { - if ($line->date_ouverture_prevue > $dateplannedstart) $dateplannedstart = $line->date_ouverture_prevue; - if ($line->statut == 4 && $line->date_fin_prevue && (! $datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) $datenextexpiration = $line->date_fin_prevue; - } - $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc'); - $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard'); - $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc'); - $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard'); - } - - // Create dynamic tags for __EXTRAFIELD_FIELD__ - if ($object->table_element && $object->id > 0) - { - $extrafieldstmp = new ExtraFields($db); - $extralabels = $extrafieldstmp->fetch_name_optionals_label($object->table_element, true); - $object->fetch_optionals($object->id, $extralabels); - foreach ($extrafieldstmp->attribute_label as $key => $label) { - $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = $object->array_options['options_' . $key]; - } - } - - $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'TODO'; - } - } - if (empty($exclude) || ! in_array('objectamount', $exclude)) - { + $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__'] = 'LinkToPayOnlineIfApplicable'; + $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)'; + $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)'; + $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order'; + $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice'; + $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service'; + + if (is_object($object) && $object->element == 'shipping') + { + $substitutionarray['__SHIPPINGTRACKNUM__']='Shipping tacking number'; + $substitutionarray['__SHIPPINGTRACKNUMURL__']='Shipping tracking url'; + } + } + else + { + $substitutionarray['__ID__'] = $object->id; + $substitutionarray['__REF__'] = $object->ref; + $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : '')); + $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : ''); + + // TODO USe this ? + $msgishtml = 0; + + $birthday = dol_print_date($object->birth,'day'); + + if (method_exists($object, 'getCivilityLabel')) $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel(); + $substitutionarray['__MEMBER_FIRSTNAME__']=$msgishtml?dol_htmlentitiesbr($object->firstname):$object->firstname; + $substitutionarray['__MEMBER_LASTNAME__']=$msgishtml?dol_htmlentitiesbr($object->lastname):$object->lastname; + if (method_exists($object, 'getFullName')) $substitutionarray['__MEMBER_FULLNAME__']=$msgishtml?dol_htmlentitiesbr($object->getFullName($outputlangs)):$object->getFullName($outputlangs); + $substitutionarray['__MEMBER_COMPANY__']=$msgishtml?dol_htmlentitiesbr($object->societe):$object->societe; + $substitutionarray['__MEMBER_ADDRESS__']=$msgishtml?dol_htmlentitiesbr($object->address):$object->address; + $substitutionarray['__MEMBER_ZIP__']=$msgishtml?dol_htmlentitiesbr($object->zip):$object->zip; + $substitutionarray['__MEMBER_TOWN__']=$msgishtml?dol_htmlentitiesbr($object->town):$object->town; + $substitutionarray['__MEMBER_COUNTRY__']=$msgishtml?dol_htmlentitiesbr($object->country):$object->country; + $substitutionarray['__MEMBER_EMAIL__']=$msgishtml?dol_htmlentitiesbr($object->email):$object->email; + $substitutionarray['__MEMBER_BIRTH__']=$msgishtml?dol_htmlentitiesbr($birthday):$birthday; + $substitutionarray['__MEMBER_PHOTO__']=$msgishtml?dol_htmlentitiesbr($object->photo):$object->photo; + $substitutionarray['__MEMBER_LOGIN__']=$msgishtml?dol_htmlentitiesbr($object->login):$object->login; + $substitutionarray['__MEMBER_PASSWORD__']=$msgishtml?dol_htmlentitiesbr($object->pass):$object->pass; + $substitutionarray['__MEMBER_PHONE__']=$msgishtml?dol_htmlentitiesbr($object->phone):$object->phone; + $substitutionarray['__MEMBER_PHONEPRO__']=$msgishtml?dol_htmlentitiesbr($object->phone_perso):$object->phone_perso; + $substitutionarray['__MEMBER_PHONEMOBILE__']=$msgishtml?dol_htmlentitiesbr($object->phone_mobile):$object->phone_mobile; + + if (is_object($object->thirdparty) && $object->thirdparty->id > 0) + { + $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty)?$object->thirdparty->id:''); + $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty)?$object->thirdparty->name:''); + } + + if (is_object($object->projet) && $object->projet->id > 0) + { + $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet)?$object->projet->id:''); + $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet)?$object->projet->ref:''); + $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet)?$object->projet->title:''); + } + + if (is_object($object) && $object->element == 'shipping') + { + $substitutionarray['__SHIPPINGTRACKNUM__']=$object->tracking_number; + $substitutionarray['__SHIPPINGTRACKNUMURL__']=$object->tracking_url; + } + + if (is_object($object) && $object->element == 'contrat' && is_array($object->lines)) + { + $dateplannedstart=''; + $datenextexpiration=''; + foreach($object->lines as $line) + { + if ($line->date_ouverture_prevue > $dateplannedstart) $dateplannedstart = $line->date_ouverture_prevue; + if ($line->statut == 4 && $line->date_fin_prevue && (! $datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) $datenextexpiration = $line->date_fin_prevue; + } + $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc'); + $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard'); + $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc'); + $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard'); + } + + // Create dynamic tags for __EXTRAFIELD_FIELD__ + if ($object->table_element && $object->id > 0) + { + $extrafieldstmp = new ExtraFields($db); + $extralabels = $extrafieldstmp->fetch_name_optionals_label($object->table_element, true); + $object->fetch_optionals($object->id, $extralabels); + foreach ($extrafieldstmp->attribute_label as $key => $label) { + $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = $object->array_options['options_' . $key]; + } + } + + $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'TODO'; + } + } + if (empty($exclude) || ! in_array('objectamount', $exclude)) + { $substitutionarray['__DATE_YMD__'] = is_object($object)?(isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : '') : ''; $substitutionarray['__DATE_DUE_YMD__'] = is_object($object)?(isset($object->date_lim_reglement)? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : '') : ''; - $substitutionarray['__AMOUNT__'] = is_object($object)?$object->total_ttc:''; + $substitutionarray['__AMOUNT__'] = is_object($object)?$object->total_ttc:''; $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object)?$object->total_ht:''; - $substitutionarray['__AMOUNT_VAT__'] = is_object($object)?($object->total_vat?$object->total_vat:$object->total_tva):''; + $substitutionarray['__AMOUNT_VAT__'] = is_object($object)?($object->total_vat?$object->total_vat:$object->total_tva):''; /* TODO Add key for multicurrency $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object)?price($object->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency_code):''; $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object)?price($object->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency_code):''; $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object)?($object->total_vat?price($object->total_vat, 0, $outputlangs, 0, 0, -1, $conf->currency_code):price($object->total_tva, 0, $outputlangs, 0, 0, -1, $conf->currency_code)):''; */ - // For backward compatibility - if ($onlykey != 2) - { - $substitutionarray['__TOTAL_TTC__'] = is_object($object)?$object->total_ttc:''; - $substitutionarray['__TOTAL_HT__'] = is_object($object)?$object->total_ht:''; - $substitutionarray['__TOTAL_VAT__'] = is_object($object)?($object->total_vat?$object->total_vat:$object->total_tva):''; - } - } - - if (empty($exclude) || ! in_array('date', $exclude)) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - - $tmp=dol_getdate(dol_now(), true); - $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); - $tmp3=dol_get_prev_month($tmp['mday'], $tmp['mon'], $tmp['year']); - $tmp4=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); - $tmp5=dol_get_next_month($tmp['mday'], $tmp['mon'], $tmp['year']); - - $substitutionarray=array_merge($substitutionarray, array( - '__DAY__' => (string) $tmp['mday'], - '__MONTH__' => (string) $tmp['mon'], - '__YEAR__' => (string) $tmp['year'], - '__PREVIOUS_DAY__' => (string) $tmp2['day'], - '__PREVIOUS_MONTH__' => (string) $tmp3['month'], - '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1), - '__NEXT_DAY__' => (string) $tmp4['day'], - '__NEXT_MONTH__' => (string) $tmp5['month'], - '__NEXT_YEAR__' => (string) ($tmp['year'] + 1), - )); - } - - if (empty($exclude) || ! in_array('user', $exclude)) - { - $substitutionarray=array_merge($substitutionarray, array( - '__USER_ID__' => (string) $user->id, - '__USER_LOGIN__' => (string) $user->login, - '__USER_LASTNAME__' => (string) $user->lastname, - '__USER_FIRSTNAME__' => (string) $user->firstname, - '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs), - '__USER_SUPERVISOR_ID__' => (string) $user->fk_user, - '__USER_SIGNATURE__' => (string) (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($user->signature), 30) : $user->signature) : '') - ) - ); - // For backward compatibility - if ($onlykey != 2) - { - $substitutionarray['__SIGNATURE__'] = (string) (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($user->signature), 30) : $user->signature) : ''); - } - } - if (! empty($conf->multicompany->enabled)) - { - $substitutionarray=array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity)); - } - - return $substitutionarray; + // For backward compatibility + if ($onlykey != 2) + { + $substitutionarray['__TOTAL_TTC__'] = is_object($object)?$object->total_ttc:''; + $substitutionarray['__TOTAL_HT__'] = is_object($object)?$object->total_ht:''; + $substitutionarray['__TOTAL_VAT__'] = is_object($object)?($object->total_vat?$object->total_vat:$object->total_tva):''; + } + } + + if (empty($exclude) || ! in_array('date', $exclude)) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + + $tmp=dol_getdate(dol_now(), true); + $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); + $tmp3=dol_get_prev_month($tmp['mday'], $tmp['mon'], $tmp['year']); + $tmp4=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); + $tmp5=dol_get_next_month($tmp['mday'], $tmp['mon'], $tmp['year']); + + $substitutionarray=array_merge($substitutionarray, array( + '__DAY__' => (string) $tmp['mday'], + '__MONTH__' => (string) $tmp['mon'], + '__YEAR__' => (string) $tmp['year'], + '__PREVIOUS_DAY__' => (string) $tmp2['day'], + '__PREVIOUS_MONTH__' => (string) $tmp3['month'], + '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1), + '__NEXT_DAY__' => (string) $tmp4['day'], + '__NEXT_MONTH__' => (string) $tmp5['month'], + '__NEXT_YEAR__' => (string) ($tmp['year'] + 1), + )); + } + + if (empty($exclude) || ! in_array('user', $exclude)) + { + $substitutionarray=array_merge($substitutionarray, array( + '__USER_ID__' => (string) $user->id, + '__USER_LOGIN__' => (string) $user->login, + '__USER_LASTNAME__' => (string) $user->lastname, + '__USER_FIRSTNAME__' => (string) $user->firstname, + '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs), + '__USER_SUPERVISOR_ID__' => (string) $user->fk_user, + '__USER_SIGNATURE__' => (string) (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($user->signature), 30) : $user->signature) : '') + ) + ); + // For backward compatibility + if ($onlykey != 2) + { + $substitutionarray['__SIGNATURE__'] = (string) (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($user->signature), 30) : $user->signature) : ''); + } + } + if (! empty($conf->multicompany->enabled)) + { + $substitutionarray=array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity)); + } + + return $substitutionarray; } /** @@ -5497,7 +5497,7 @@ function make_substitutions($text, $substitutionarray, $outputlangs=null) { while (preg_match('/__\(([^\)]*)\)__/', $text, $reg)) { - // If key is __(TranslationKey|langfile)__, then force load of langfile.lang + // If key is __(TranslationKey|langfile)__, then force load of langfile.lang $tmp=explode('|',$reg[1]); if (! empty($tmp[1])) $outputlangs->load($tmp[1]); @@ -5644,7 +5644,7 @@ function dolGetFirstLastname($firstname,$lastname,$nameorder=-1) if ($nameorder < 0) $nameorder=(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)); if ($nameorder && ((string) $nameorder != '2')) { - $ret.=$firstname; + $ret.=$firstname; if ($firstname && $lastname) $ret.=' '; $ret.=$lastname; } @@ -5926,8 +5926,8 @@ function dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensiti $sizearray=count($array); if (is_array($array) && $sizearray>0) { - $temp = array(); - foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index]; + $temp = array(); + foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index]; if (!$natsort) ($order=='asc') ? asort($temp) : arsort($temp); else @@ -6096,13 +6096,13 @@ function dol_eval($s, $returnvalue=0, $hideerrors=1) //print $s."<br>\n"; if ($returnvalue) { - if ($hideerrors) return @eval('return '.$s.';'); - else return eval('return '.$s.';'); + if ($hideerrors) return @eval('return '.$s.';'); + else return eval('return '.$s.';'); } else { - if ($hideerrors) @eval($s); - else eval($s); + if ($hideerrors) @eval($s); + else eval($s); } } @@ -6290,32 +6290,32 @@ function printCommonFooter($zone='private') if (! empty($conf->use_javascript_ajax)) { print '<!-- Reposition management (does not work if a redirect is done after action of submission) -->'."\n"; - print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() {'."\n"; + print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() {'."\n"; - print '<!-- If page_y set, we set scollbar with it -->'."\n"; - print "page_y=getParameterByName('page_y', 0);"; - print "if (page_y > 0) $('html, body').scrollTop(page_y);\n"; + print '<!-- If page_y set, we set scollbar with it -->'."\n"; + print "page_y=getParameterByName('page_y', 0);"; + print "if (page_y > 0) $('html, body').scrollTop(page_y);\n"; - print '<!-- Set handler to add page_y param on some a href links -->'."\n"; - print 'jQuery(".reposition").click(function() { + print '<!-- Set handler to add page_y param on some a href links -->'."\n"; + print 'jQuery(".reposition").click(function() { var page_y = $(document).scrollTop(); /*alert(page_y);*/ this.href=this.href+\'&page_y=\'+page_y; });'."\n"; - print '});'."\n"; + print '});'."\n"; - if (empty($conf->dol_use_jmobile)) - { - print '<!-- Set handler to switch left menu page (menuhider) -->'."\n"; - print 'jQuery(".menuhider").click(function() {'; - print ' console.log("We click on .menuhider");'."\n"; - //print " $('.side-nav').animate({width:'toggle'},200);\n"; // OK with eldy theme but not with md - print " $('.side-nav').toggle()\n"; - print " $('.login_block').toggle()\n"; - print '});'."\n"; - } + if (empty($conf->dol_use_jmobile)) + { + print '<!-- Set handler to switch left menu page (menuhider) -->'."\n"; + print 'jQuery(".menuhider").click(function() {'; + print ' console.log("We click on .menuhider");'."\n"; + //print " $('.side-nav').animate({width:'toggle'},200);\n"; // OK with eldy theme but not with md + print " $('.side-nav').toggle()\n"; + print " $('.login_block').toggle()\n"; + print '});'."\n"; + } - print '</script>'."\n"; + print '</script>'."\n"; } // Google Analytics (need Google module) @@ -6405,7 +6405,7 @@ function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=') { if ($a = explode($delimiter, $string)) { - $ka = array(); + $ka = array(); foreach ($a as $s) { // each part if ($s) { if ($pos = strpos($s, $kv)) { // key/value delimiter @@ -6443,11 +6443,11 @@ function dol_set_focus($selector) */ function dol_getmypid() { - if (! function_exists('getmypid')) { - return mt_rand(1,32768); - } else { - return getmypid(); - } + if (! function_exists('getmypid')) { + return mt_rand(1,32768); + } else { + return getmypid(); + } } @@ -6467,64 +6467,64 @@ function dol_getmypid() */ function natural_search($fields, $value, $mode=0, $nofirstand=0) { - global $db,$langs; - - $value=trim($value); - - if ($mode == 0) - { - $value=preg_replace('/\*/','%',$value); // Replace * with % - } - if ($mode == 1) - { - $value=preg_replace('/([<>=]+)\s+([0-9'.preg_quote($langs->trans("DecimalSeparator"),'/').'\-])/','\1\2',$value); // Clean string '< 10' into '<10' so we can the explode on space to get all tests to do - } - - $value = preg_replace('/\s*\|\s*/','|', $value); - - $crits = explode(' ', $value); - $res = ''; - if (! is_array($fields)) $fields = array($fields); - - $nboffields = count($fields); - $end2 = count($crits); - $j = 0; - foreach ($crits as $crit) - { - $i = 0; $i2 = 0; - $newres = ''; - foreach ($fields as $field) - { - if ($mode == 1) - { - $operator='='; - $newcrit = preg_replace('/([<>=]+)/','',trim($crit)); - - preg_match('/([<>=]+)/',trim($crit), $reg); - if ($reg[1]) - { - $operator = $reg[1]; - } - if ($newcrit != '') - { - $numnewcrit = price2num($newcrit); - if (is_numeric($numnewcrit)) - { - $newres .= ($i2 > 0 ? ' OR ' : '') . $field . ' '.$operator.' '.$numnewcrit; - } - else - { - $newres .= ($i2 > 0 ? ' OR ' : '') . '1 = 2'; // force false - } - $i2++; // a criteria was added to string - } - } - else if ($mode == 2) - { + global $db,$langs; + + $value=trim($value); + + if ($mode == 0) + { + $value=preg_replace('/\*/','%',$value); // Replace * with % + } + if ($mode == 1) + { + $value=preg_replace('/([<>=]+)\s+([0-9'.preg_quote($langs->trans("DecimalSeparator"),'/').'\-])/','\1\2',$value); // Clean string '< 10' into '<10' so we can the explode on space to get all tests to do + } + + $value = preg_replace('/\s*\|\s*/','|', $value); + + $crits = explode(' ', $value); + $res = ''; + if (! is_array($fields)) $fields = array($fields); + + $nboffields = count($fields); + $end2 = count($crits); + $j = 0; + foreach ($crits as $crit) + { + $i = 0; $i2 = 0; + $newres = ''; + foreach ($fields as $field) + { + if ($mode == 1) + { + $operator='='; + $newcrit = preg_replace('/([<>=]+)/','',trim($crit)); + + preg_match('/([<>=]+)/',trim($crit), $reg); + if ($reg[1]) + { + $operator = $reg[1]; + } + if ($newcrit != '') + { + $numnewcrit = price2num($newcrit); + if (is_numeric($numnewcrit)) + { + $newres .= ($i2 > 0 ? ' OR ' : '') . $field . ' '.$operator.' '.$numnewcrit; + } + else + { + $newres .= ($i2 > 0 ? ' OR ' : '') . '1 = 2'; // force false + } + $i2++; // a criteria was added to string + } + } + else if ($mode == 2) + { $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $db->escape(trim($crit)) . ")"; - $i2++; // a criteria was added to string - } - else // $mode=0 + $i2++; // a criteria was added to string + } + else // $mode=0 { $textcrit = ''; $tmpcrits = explode('|',$crit); @@ -6541,41 +6541,41 @@ function natural_search($fields, $value, $mode=0, $nofirstand=0) { $newres .= $field . " LIKE '"; - $tmpcrit=trim($tmpcrit); - $tmpcrit2=$tmpcrit; - $tmpbefore='%'; $tmpafter='%'; - if (preg_match('/^[\^\$]/', $tmpcrit)) - { - $tmpbefore=''; - $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2); - } + $tmpcrit=trim($tmpcrit); + $tmpcrit2=$tmpcrit; + $tmpbefore='%'; $tmpafter='%'; + if (preg_match('/^[\^\$]/', $tmpcrit)) + { + $tmpbefore=''; + $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2); + } if (preg_match('/[\^\$]$/', $tmpcrit)) - { - $tmpafter=''; - $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2); - } - $newres .= $tmpbefore; - $newres .= $db->escape($tmpcrit2); - $newres .= $tmpafter; - $newres .= "'"; - if ($tmpcrit2 == '') - { - $newres .= ' OR ' . $field . " IS NULL"; - } + { + $tmpafter=''; + $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2); + } + $newres .= $tmpbefore; + $newres .= $db->escape($tmpcrit2); + $newres .= $tmpafter; + $newres .= "'"; + if ($tmpcrit2 == '') + { + $newres .= ' OR ' . $field . " IS NULL"; + } } - $i3++; + $i3++; } $i2++; // a criteria was added to string - } - $i++; - } - if ($newres) $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') .$newres . ($i2 > 1 ? ')' : ''); - $j++; - } - $res = ($nofirstand?"":" AND ")."(" . $res . ")"; - //print 'xx'.$res.'yy'; - return $res; + } + $i++; + } + if ($newres) $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') .$newres . ($i2 > 1 ? ')' : ''); + $j++; + } + $res = ($nofirstand?"":" AND ")."(" . $res . ")"; + //print 'xx'.$res.'yy'; + return $res; } /** @@ -6591,21 +6591,21 @@ function getImageFileNameForSize($file, $extName, $extImgTarget='') $dirName = dirname($file); if ($dirName == '.') $dirName=''; - $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp)$/i','',$file); // We remove extension, whatever is its case + $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp)$/i','',$file); // We remove extension, whatever is its case $fileName = basename($fileName); if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpg$/i',$file)?'.jpg':''); - if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpeg$/i',$file)?'.jpeg':''); - if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.gif$/i',$file)?'.gif':''); - if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.png$/i',$file)?'.png':''); - if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.bmp$/i',$file)?'.bmp':''); + if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpeg$/i',$file)?'.jpeg':''); + if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.gif$/i',$file)?'.gif':''); + if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.png$/i',$file)?'.png':''); + if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.bmp$/i',$file)?'.bmp':''); - if (! $extImgTarget) return $file; + if (! $extImgTarget) return $file; - $subdir=''; - if ($extName) $subdir = 'thumbs/'; + $subdir=''; + if ($extName) $subdir = 'thumbs/'; - return ($dirName?$dirName.'/':'').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb + return ($dirName?$dirName.'/':'').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb } @@ -6620,24 +6620,24 @@ function getImageFileNameForSize($file, $extName, $extImgTarget='') */ function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='') { - global $conf, $langs; + global $conf, $langs; - if (empty($conf->use_javascript_ajax)) return ''; + if (empty($conf->use_javascript_ajax)) return ''; - $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css'); - //$mime_preview[]='vnd.oasis.opendocument.presentation'; - //$mime_preview[]='archive'; - $num_mime = array_search(dol_mimetype($relativepath, '', 1), $mime_preview); + $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css'); + //$mime_preview[]='vnd.oasis.opendocument.presentation'; + //$mime_preview[]='archive'; + $num_mime = array_search(dol_mimetype($relativepath, '', 1), $mime_preview); - if ($alldata == 1) - { - if ($num_mime !== false) return array('target'=>'_blank', 'css'=>'documentpreview', 'url'=>DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath), 'mime'=>dol_mimetype($relativepath), ); - else return array(); - } + if ($alldata == 1) + { + if ($num_mime !== false) return array('target'=>'_blank', 'css'=>'documentpreview', 'url'=>DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath), 'mime'=>dol_mimetype($relativepath), ); + else return array(); + } - // old behavior - if ($num_mime !== false) return 'javascript:document_preview(\''.dol_escape_js(DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath).($param?'&'.$param:'')).'\', \''.dol_mimetype($relativepath).'\', \''.dol_escape_js($langs->trans('Preview')).'\')'; - else return ''; + // old behavior + if ($num_mime !== false) return 'javascript:document_preview(\''.dol_escape_js(DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath).($param?'&'.$param:'')).'\', \''.dol_mimetype($relativepath).'\', \''.dol_escape_js($langs->trans('Preview')).'\')'; + else return ''; } @@ -6652,103 +6652,103 @@ function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='' */ function dol_mimetype($file,$default='application/octet-stream',$mode=0) { - $mime=$default; - $imgmime='other.png'; - $srclang=''; - - $tmpfile=preg_replace('/\.noexe$/','',$file); - - // Text files - if (preg_match('/\.txt$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; } - if (preg_match('/\.rtx$/i',$tmpfile)) { $mime='text/richtext'; $imgmime='text.png'; } - if (preg_match('/\.csv$/i',$tmpfile)) { $mime='text/csv'; $imgmime='text.png'; } - if (preg_match('/\.tsv$/i',$tmpfile)) { $mime='text/tab-separated-values'; $imgmime='text.png'; } - if (preg_match('/\.(cf|conf|log)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; } - if (preg_match('/\.ini$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='ini'; } - if (preg_match('/\.css$/i',$tmpfile)) { $mime='text/css'; $imgmime='css.png'; $srclang='css'; } - // Certificate files - if (preg_match('/\.(crt|cer|key|pub)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; } - // HTML/XML - if (preg_match('/\.(html|htm|shtml)$/i',$tmpfile)) { $mime='text/html'; $imgmime='html.png'; $srclang='html'; } - if (preg_match('/\.(xml|xhtml)$/i',$tmpfile)) { $mime='text/xml'; $imgmime='other.png'; $srclang='xml'; } - // Languages - if (preg_match('/\.bas$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='bas'; } - if (preg_match('/\.(c)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='c'; } - if (preg_match('/\.(cpp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='cpp'; } - if (preg_match('/\.(h)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='h'; } - if (preg_match('/\.(java|jsp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='java'; } - if (preg_match('/\.php([0-9]{1})?$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; } - if (preg_match('/\.phtml$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; } - if (preg_match('/\.(pl|pm)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='pl.png'; $srclang='perl'; } - if (preg_match('/\.sql$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='sql'; } - if (preg_match('/\.js$/i',$tmpfile)) { $mime='text/x-javascript'; $imgmime='jscript.png'; $srclang='js'; } - // Open office - if (preg_match('/\.odp$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.presentation'; $imgmime='ooffice.png'; } - if (preg_match('/\.ods$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.spreadsheet'; $imgmime='ooffice.png'; } - if (preg_match('/\.odt$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.text'; $imgmime='ooffice.png'; } - // MS Office - if (preg_match('/\.mdb$/i',$tmpfile)) { $mime='application/msaccess'; $imgmime='mdb.png'; } - if (preg_match('/\.doc(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; } - if (preg_match('/\.dot(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; } - if (preg_match('/\.xlt(x)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; } - if (preg_match('/\.xla(m)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; } - if (preg_match('/\.xls$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; } - if (preg_match('/\.xls(b|m|x)$/i',$tmpfile)) { $mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime='xls.png'; } - if (preg_match('/\.pps(m|x)?$/i',$tmpfile)) { $mime='application/vnd.ms-powerpoint'; $imgmime='ppt.png'; } - if (preg_match('/\.ppt(m|x)?$/i',$tmpfile)) { $mime='application/x-mspowerpoint'; $imgmime='ppt.png'; } - // Other - if (preg_match('/\.pdf$/i',$tmpfile)) { $mime='application/pdf'; $imgmime='pdf.png'; } - // Scripts - if (preg_match('/\.bat$/i',$tmpfile)) { $mime='text/x-bat'; $imgmime='script.png'; $srclang='dos'; } - if (preg_match('/\.sh$/i',$tmpfile)) { $mime='text/x-sh'; $imgmime='script.png'; $srclang='bash'; } - if (preg_match('/\.ksh$/i',$tmpfile)) { $mime='text/x-ksh'; $imgmime='script.png'; $srclang='bash'; } - if (preg_match('/\.bash$/i',$tmpfile)) { $mime='text/x-bash'; $imgmime='script.png'; $srclang='bash'; } - // Images - if (preg_match('/\.ico$/i',$tmpfile)) { $mime='image/x-icon'; $imgmime='image.png'; } - if (preg_match('/\.(jpg|jpeg)$/i',$tmpfile)) { $mime='image/jpeg'; $imgmime='image.png'; } - if (preg_match('/\.png$/i',$tmpfile)) { $mime='image/png'; $imgmime='image.png'; } - if (preg_match('/\.gif$/i',$tmpfile)) { $mime='image/gif'; $imgmime='image.png'; } - if (preg_match('/\.bmp$/i',$tmpfile)) { $mime='image/bmp'; $imgmime='image.png'; } - if (preg_match('/\.(tif|tiff)$/i',$tmpfile)) { $mime='image/tiff'; $imgmime='image.png'; } - // Calendar - if (preg_match('/\.vcs$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; } - if (preg_match('/\.ics$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; } - // Other - if (preg_match('/\.torrent$/i',$tmpfile)) { $mime='application/x-bittorrent'; $imgmime='other.png'; } - // Audio - if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i',$tmpfile)) { $mime='audio'; $imgmime='audio.png'; } - // Video - if (preg_match('/\.ogv$/i',$tmpfile)) { $mime='video/ogg'; $imgmime='video.png'; } - if (preg_match('/\.webm$/i',$tmpfile)) { $mime='video/webm'; $imgmime='video.png'; } - if (preg_match('/\.avi$/i',$tmpfile)) { $mime='video/x-msvideo'; $imgmime='video.png'; } - if (preg_match('/\.divx$/i',$tmpfile)) { $mime='video/divx'; $imgmime='video.png'; } - if (preg_match('/\.xvid$/i',$tmpfile)) { $mime='video/xvid'; $imgmime='video.png'; } - if (preg_match('/\.(wmv|mpg|mpeg)$/i',$tmpfile)) { $mime='video'; $imgmime='video.png'; } - // Archive - if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i',$tmpfile)) { $mime='archive'; $imgmime='archive.png'; } // application/xxx where zzz is zip, ... - // Exe - if (preg_match('/\.(exe|com)$/i',$tmpfile)) { $mime='application/octet-stream'; $imgmime='other.png'; } - // Lib - if (preg_match('/\.(dll|lib|o|so|a)$/i',$tmpfile)) { $mime='library'; $imgmime='library.png'; } - // Err - if (preg_match('/\.err$/i',$tmpfile)) { $mime='error'; $imgmime='error.png'; } - - // Return string - if ($mode == 1) - { - $tmp=explode('/',$mime); - return (! empty($tmp[1])?$tmp[1]:$tmp[0]); - } - if ($mode == 2) - { - return $imgmime; - } - if ($mode == 3) - { - return $srclang; - } - - return $mime; + $mime=$default; + $imgmime='other.png'; + $srclang=''; + + $tmpfile=preg_replace('/\.noexe$/','',$file); + + // Text files + if (preg_match('/\.txt$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; } + if (preg_match('/\.rtx$/i',$tmpfile)) { $mime='text/richtext'; $imgmime='text.png'; } + if (preg_match('/\.csv$/i',$tmpfile)) { $mime='text/csv'; $imgmime='text.png'; } + if (preg_match('/\.tsv$/i',$tmpfile)) { $mime='text/tab-separated-values'; $imgmime='text.png'; } + if (preg_match('/\.(cf|conf|log)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; } + if (preg_match('/\.ini$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='ini'; } + if (preg_match('/\.css$/i',$tmpfile)) { $mime='text/css'; $imgmime='css.png'; $srclang='css'; } + // Certificate files + if (preg_match('/\.(crt|cer|key|pub)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; } + // HTML/XML + if (preg_match('/\.(html|htm|shtml)$/i',$tmpfile)) { $mime='text/html'; $imgmime='html.png'; $srclang='html'; } + if (preg_match('/\.(xml|xhtml)$/i',$tmpfile)) { $mime='text/xml'; $imgmime='other.png'; $srclang='xml'; } + // Languages + if (preg_match('/\.bas$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='bas'; } + if (preg_match('/\.(c)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='c'; } + if (preg_match('/\.(cpp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='cpp'; } + if (preg_match('/\.(h)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='h'; } + if (preg_match('/\.(java|jsp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='java'; } + if (preg_match('/\.php([0-9]{1})?$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; } + if (preg_match('/\.phtml$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; } + if (preg_match('/\.(pl|pm)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='pl.png'; $srclang='perl'; } + if (preg_match('/\.sql$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='sql'; } + if (preg_match('/\.js$/i',$tmpfile)) { $mime='text/x-javascript'; $imgmime='jscript.png'; $srclang='js'; } + // Open office + if (preg_match('/\.odp$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.presentation'; $imgmime='ooffice.png'; } + if (preg_match('/\.ods$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.spreadsheet'; $imgmime='ooffice.png'; } + if (preg_match('/\.odt$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.text'; $imgmime='ooffice.png'; } + // MS Office + if (preg_match('/\.mdb$/i',$tmpfile)) { $mime='application/msaccess'; $imgmime='mdb.png'; } + if (preg_match('/\.doc(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; } + if (preg_match('/\.dot(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; } + if (preg_match('/\.xlt(x)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; } + if (preg_match('/\.xla(m)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; } + if (preg_match('/\.xls$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; } + if (preg_match('/\.xls(b|m|x)$/i',$tmpfile)) { $mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime='xls.png'; } + if (preg_match('/\.pps(m|x)?$/i',$tmpfile)) { $mime='application/vnd.ms-powerpoint'; $imgmime='ppt.png'; } + if (preg_match('/\.ppt(m|x)?$/i',$tmpfile)) { $mime='application/x-mspowerpoint'; $imgmime='ppt.png'; } + // Other + if (preg_match('/\.pdf$/i',$tmpfile)) { $mime='application/pdf'; $imgmime='pdf.png'; } + // Scripts + if (preg_match('/\.bat$/i',$tmpfile)) { $mime='text/x-bat'; $imgmime='script.png'; $srclang='dos'; } + if (preg_match('/\.sh$/i',$tmpfile)) { $mime='text/x-sh'; $imgmime='script.png'; $srclang='bash'; } + if (preg_match('/\.ksh$/i',$tmpfile)) { $mime='text/x-ksh'; $imgmime='script.png'; $srclang='bash'; } + if (preg_match('/\.bash$/i',$tmpfile)) { $mime='text/x-bash'; $imgmime='script.png'; $srclang='bash'; } + // Images + if (preg_match('/\.ico$/i',$tmpfile)) { $mime='image/x-icon'; $imgmime='image.png'; } + if (preg_match('/\.(jpg|jpeg)$/i',$tmpfile)) { $mime='image/jpeg'; $imgmime='image.png'; } + if (preg_match('/\.png$/i',$tmpfile)) { $mime='image/png'; $imgmime='image.png'; } + if (preg_match('/\.gif$/i',$tmpfile)) { $mime='image/gif'; $imgmime='image.png'; } + if (preg_match('/\.bmp$/i',$tmpfile)) { $mime='image/bmp'; $imgmime='image.png'; } + if (preg_match('/\.(tif|tiff)$/i',$tmpfile)) { $mime='image/tiff'; $imgmime='image.png'; } + // Calendar + if (preg_match('/\.vcs$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; } + if (preg_match('/\.ics$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; } + // Other + if (preg_match('/\.torrent$/i',$tmpfile)) { $mime='application/x-bittorrent'; $imgmime='other.png'; } + // Audio + if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i',$tmpfile)) { $mime='audio'; $imgmime='audio.png'; } + // Video + if (preg_match('/\.ogv$/i',$tmpfile)) { $mime='video/ogg'; $imgmime='video.png'; } + if (preg_match('/\.webm$/i',$tmpfile)) { $mime='video/webm'; $imgmime='video.png'; } + if (preg_match('/\.avi$/i',$tmpfile)) { $mime='video/x-msvideo'; $imgmime='video.png'; } + if (preg_match('/\.divx$/i',$tmpfile)) { $mime='video/divx'; $imgmime='video.png'; } + if (preg_match('/\.xvid$/i',$tmpfile)) { $mime='video/xvid'; $imgmime='video.png'; } + if (preg_match('/\.(wmv|mpg|mpeg)$/i',$tmpfile)) { $mime='video'; $imgmime='video.png'; } + // Archive + if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i',$tmpfile)) { $mime='archive'; $imgmime='archive.png'; } // application/xxx where zzz is zip, ... + // Exe + if (preg_match('/\.(exe|com)$/i',$tmpfile)) { $mime='application/octet-stream'; $imgmime='other.png'; } + // Lib + if (preg_match('/\.(dll|lib|o|so|a)$/i',$tmpfile)) { $mime='library'; $imgmime='library.png'; } + // Err + if (preg_match('/\.err$/i',$tmpfile)) { $mime='error'; $imgmime='error.png'; } + + // Return string + if ($mode == 1) + { + $tmp=explode('/',$mime); + return (! empty($tmp[1])?$tmp[1]:$tmp[0]); + } + if ($mode == 2) + { + return $imgmime; + } + if ($mode == 3) + { + return $srclang; + } + + return $mime; } /** diff --git a/htdocs/expedition/list.php b/htdocs/expedition/list.php index 2c1427c87f5ec74f88b851cc78ee954325f3ea29..009e163eeb0bf95d28b5e094193d8cffe2b6eb8e 100644 --- a/htdocs/expedition/list.php +++ b/htdocs/expedition/list.php @@ -81,38 +81,38 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'e.ref'=>"Ref", - 's.nom'=>"ThirdParty", - 'e.note_public'=>'NotePublic', + 'e.ref'=>"Ref", + 's.nom'=>"ThirdParty", + 'e.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["e.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'e.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'e.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'e.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1), - 'e.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'e.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'e.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), - 'l.ref'=>array('label'=>$langs->trans("DeliveryRef"), 'checked'=>1, 'enabled'=>$conf->livraison_bon->enabled), - 'l.date_delivery'=>array('label'=>$langs->trans("DateReceived"), 'checked'=>1, 'enabled'=>$conf->livraison_bon->enabled), - 'e.billed'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>(!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) + 'e.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'e.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'e.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1), + 'e.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'e.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'e.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'l.ref'=>array('label'=>$langs->trans("DeliveryRef"), 'checked'=>1, 'enabled'=>$conf->livraison_bon->enabled), + 'l.date_delivery'=>array('label'=>$langs->trans("DateReceived"), 'checked'=>1, 'enabled'=>$conf->livraison_bon->enabled), + 'e.billed'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>(!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } @@ -132,35 +132,35 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_ref_exp=''; - $search_ref_liv=''; - $search_ref_customer=''; - $search_company=''; - $search_town=''; + $search_ref_exp=''; + $search_ref_liv=''; + $search_ref_customer=''; + $search_company=''; + $search_town=''; $search_zip=""; - $search_state=""; + $search_state=""; $search_type=''; $search_country=''; $search_type_thirdparty=''; $search_billed=''; - $viewstatut=''; - $search_array_options=array(); + $viewstatut=''; + $search_array_options=array(); } if (empty($reshook)) { - // Mass actions. Controls on number of lines checked - $maxformassaction=1000; - if (! empty($massaction) && count($toselect) < 1) - { - $error++; - setEventMessages($langs->trans("NoLineChecked"), null, "warnings"); - } - if (! $error && count($toselect) > $maxformassaction) - { - setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors'); - $error++; - } + // Mass actions. Controls on number of lines checked + $maxformassaction=1000; + if (! empty($massaction) && count($toselect) < 1) + { + $error++; + setEventMessages($langs->trans("NoLineChecked"), null, "warnings"); + } + if (! $error && count($toselect) > $maxformassaction) + { + setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors'); + $error++; + } } @@ -230,16 +230,16 @@ if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -249,8 +249,8 @@ $sql.=$hookmanager->resPrint; $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->order($sortfield,$sortorder); @@ -265,7 +265,7 @@ if ($resql) $expedition = new Expedition($db); $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($sall) $param.= "&sall=".urlencode($sall); if ($search_ref_exp) $param.= "&search_ref_exp=".urlencode($search_ref_exp); @@ -276,135 +276,135 @@ if ($resql) // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } //$massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); $i = 0; - print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; - print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; - print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; - print '<input type="hidden" name="action" value="list">'; - print '<input type="hidden" name="page" value="'.$page.'">'; - print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; - print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; + print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'."\n"; + if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; + print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; + print '<input type="hidden" name="action" value="list">'; + print '<input type="hidden" name="page" value="'.$page.'">'; + print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; + print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print_barre_liste($langs->trans('ListOfSendings'), $page, $_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $nbtotalofrecords, '', 0, '', '', $limit); - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } - - $moreforfilter=''; - if (! empty($moreforfilter)) - { - print '<div class="liste_titre liste_titre_bydiv centpercent">'; - print $moreforfilter; - $parameters=array('type'=>$type); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - print '</div>'; - } - - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - - print '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; + if ($sall) + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } + + $moreforfilter=''; + if (! empty($moreforfilter)) + { + print '<div class="liste_titre liste_titre_bydiv centpercent">'; + print $moreforfilter; + $parameters=array('type'=>$type); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + print '</div>'; + } + + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + + print '<div class="div-table-responsive">'; + print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; // Lignes des champs de filtre print '<tr class="liste_titre_filter">'; // Ref if (! empty($arrayfields['e.ref']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" size="6" type="text" name="search_ref_exp" value="'.$search_ref_exp.'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" size="6" type="text" name="search_ref_exp" value="'.$search_ref_exp.'">'; + print '</td>'; } // Ref customer if (! empty($arrayfields['e.ref_customer']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" size="6" type="text" name="search_ref_customer" value="'.$search_ref_customer.'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" size="6" type="text" name="search_ref_customer" value="'.$search_ref_customer.'">'; + print '</td>'; } // Thirdparty if (! empty($arrayfields['s.nom']['checked'])) { - print '<td class="liste_titre" align="left">'; - print '<input class="flat" type="text" size="8" name="search_company" value="'.dol_escape_htmltag($search_company).'">'; - print '</td>'; + print '<td class="liste_titre" align="left">'; + print '<input class="flat" type="text" size="8" name="search_company" value="'.dol_escape_htmltag($search_company).'">'; + print '</td>'; } // Town if (! empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; // Zip if (! empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_zip" value="'.$search_zip.'"></td>'; // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print '<td class="liste_titre">'; - print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; - print '</td>'; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print '<td class="liste_titre" align="center">'; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print '</td>'; - } + if (! empty($arrayfields['state.nom']['checked'])) + { + print '<td class="liste_titre">'; + print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; + print '</td>'; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print '<td class="liste_titre" align="center">'; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print '</td>'; + } // Company type - if (! empty($arrayfields['typent.code']['checked'])) - { - print '<td class="liste_titre maxwidthonsmartphone" align="center">'; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print '</td>'; - } + if (! empty($arrayfields['typent.code']['checked'])) + { + print '<td class="liste_titre maxwidthonsmartphone" align="center">'; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print '</td>'; + } // Date delivery planned if (! empty($arrayfields['e.date_delivery']['checked'])) { - print '<td class="liste_titre"> </td>'; + print '<td class="liste_titre"> </td>'; } if (! empty($arrayfields['l.ref']['checked'])) { - // Delivery ref + // Delivery ref print '<td class="liste_titre">'; print '<input class="flat" size="10" type="text" name="search_ref_liv" value="'.$search_ref_liv.'"'; print '</td>'; } if (! empty($arrayfields['l.date_delivery']['checked'])) { - // Date received + // Date received print '<td class="liste_titre"> </td>'; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } - print '</td>'; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -413,34 +413,34 @@ if ($resql) // Date creation if (! empty($arrayfields['e.datec']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Date modification if (! empty($arrayfields['e.tms']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Status if (! empty($arrayfields['e.fk_statut']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="right">'; - print $form->selectarray('viewstatut', array('0'=>$langs->trans('StatusSendingDraftShort'),'1'=>$langs->trans('StatusSendingValidatedShort'),'2'=>$langs->trans('StatusSendingProcessedShort')),$viewstatut,1); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="right">'; + print $form->selectarray('viewstatut', array('0'=>$langs->trans('StatusSendingDraftShort'),'1'=>$langs->trans('StatusSendingValidatedShort'),'2'=>$langs->trans('StatusSendingProcessedShort')),$viewstatut,1); + print '</td>'; } // Status billed if (! empty($arrayfields['e.billed']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="center">'; - print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="center">'; + print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); + print '</td>'; } // Action column print '<td class="liste_titre" align="middle">'; $searchpicto=$form->showFilterAndCheckAddButtons(0); print $searchpicto; - print '</td>'; + print '</td>'; print "</tr>\n"; print '<tr class="liste_titre">'; @@ -458,16 +458,16 @@ if ($resql) // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -487,135 +487,135 @@ if ($resql) { $obj = $db->fetch_object($resql); - $shipment->id=$obj->rowid; - $shipment->ref=$obj->ref; + $shipment->id=$obj->rowid; + $shipment->ref=$obj->ref; - $companystatic->id=$obj->socid; - $companystatic->ref=$obj->name; - $companystatic->name=$obj->name; + $companystatic->id=$obj->socid; + $companystatic->ref=$obj->name; + $companystatic->name=$obj->name; - print '<tr class="oddeven">'; + print '<tr class="oddeven">'; // Ref if (! empty($arrayfields['e.ref']['checked'])) { - print "<td>"; - print $shipment->getNomUrl(1); - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; + print "<td>"; + print $shipment->getNomUrl(1); + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; } // Ref customer if (! empty($arrayfields['e.ref_customer']['checked'])) { - print "<td>"; - print $obj->ref_customer; - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; + print "<td>"; + print $obj->ref_customer; + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; } // Third party if (! empty($arrayfields['s.nom']['checked'])) { - print '<td>'; - print $companystatic->getNomUrl(1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td>'; + print $companystatic->getNomUrl(1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Town if (! empty($arrayfields['s.town']['checked'])) { - print '<td class="nocellnopadd">'; - print $obj->town; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="nocellnopadd">'; + print $obj->town; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Zip if (! empty($arrayfields['s.zip']['checked'])) { - print '<td class="nocellnopadd">'; - print $obj->zip; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="nocellnopadd">'; + print $obj->zip; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // State if (! empty($arrayfields['state.nom']['checked'])) { - print "<td>".$obj->state_name."</td>\n"; - if (! $i) $totalarray['nbfield']++; + print "<td>".$obj->state_name."</td>\n"; + if (! $i) $totalarray['nbfield']++; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print '<td align="center">'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Type ent if (! empty($arrayfields['typent.code']['checked'])) { - print '<td align="center">'; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Date delivery planed if (! empty($arrayfields['e.date_delivery']['checked'])) { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_livraison),"day"); - /*$now = time(); + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_livraison),"day"); + /*$now = time(); if ( ($now - $db->jdate($obj->date_expedition)) > $conf->warnings->lim && $obj->statutid == 1 ) { }*/ - print "</td>\n"; + print "</td>\n"; } if (! empty($arrayfields['l.ref']['checked']) || ! empty($arrayfields['l.date_delivery']['checked'])) - { - $shipment->fetchObjectLinked($shipment->id,$shipment->element); - $receiving=''; - if (count($shipment->linkedObjects['delivery']) > 0) $receiving=reset($shipment->linkedObjects['delivery']); - - if (! empty($arrayfields['l.ref']['checked'])) - { - // Ref - print '<td>'; - print !empty($receiving) ? $receiving->getNomUrl($db) : ''; - print '</td>'; - } - - if (! empty($arrayfields['l.date_delivery']['checked'])) - { - // Date received - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_reception),"day"); - print '</td>'."\n"; - } + { + $shipment->fetchObjectLinked($shipment->id,$shipment->element); + $receiving=''; + if (count($shipment->linkedObjects['delivery']) > 0) $receiving=reset($shipment->linkedObjects['delivery']); + + if (! empty($arrayfields['l.ref']['checked'])) + { + // Ref + print '<td>'; + print !empty($receiving) ? $receiving->getNomUrl($db) : ''; + print '</td>'; + } + + if (! empty($arrayfields['l.date_delivery']['checked'])) + { + // Date received + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_reception),"day"); + print '</td>'."\n"; + } } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td class="tdofextrafield"'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td class="tdofextrafield"'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); @@ -624,24 +624,24 @@ if ($resql) // Date creation if (! empty($arrayfields['e.datec']['checked'])) { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['e.tms']['checked'])) { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Status if (! empty($arrayfields['e.fk_statut']['checked'])) { - print '<td align="right" class="nowrap">'.$shipment->LibStatut($obj->fk_statut,5).'</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="right" class="nowrap">'.$shipment->LibStatut($obj->fk_statut,5).'</td>'; + if (! $i) $totalarray['nbfield']++; } // Billed if (! empty($arrayfields['e.billed']['checked'])) diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index ef97d487298b57afd34ea2bcefe69d9a69279758..d806923a241954f53a120069b9cf55e18648c2fa 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -92,34 +92,34 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'f.ref'=>'Ref', - 's.nom'=>"ThirdParty", - 'f.description'=>'Description', - 'f.note_public'=>'NotePublic', + 'f.ref'=>'Ref', + 's.nom'=>"ThirdParty", + 'f.description'=>'Description', + 'f.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["f.note_private"]="NotePrivate"; if (! empty($conf->global->FICHINTER_DISABLE_DETAILS)) unset($fieldstosearchall['f.description']); // Definition of fields for list $arrayfields=array( - 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), 'f.fk_project'=>array('label'=>$langs->trans("Project"), 'checked'=>1), - 'f.fk_contrat'=>array('label'=>$langs->trans("Contract"), 'checked'=>1), - 'f.description'=>array('label'=>$langs->trans("Description"), 'checked'=>1), - 'fd.description'=>array('label'=>"xx", 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), - 'fd.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), - 'fd.duree'=>array('label'=>$langs->trans("Duration"), 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), + 'f.fk_contrat'=>array('label'=>$langs->trans("Contract"), 'checked'=>1), + 'f.description'=>array('label'=>$langs->trans("Description"), 'checked'=>1), + 'fd.description'=>array('label'=>"xx", 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), + 'fd.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), + 'fd.duree'=>array('label'=>$langs->trans("Duration"), 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! 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'=>$extrafields->attribute_perms[$key]); + 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'=>$extrafields->attribute_perms[$key]); } } @@ -137,10 +137,10 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Purge search criteria + // Purge search criteria if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { $search_ref=""; @@ -149,7 +149,7 @@ if (empty($reshook)) $search_contract=""; $search_desc=""; $search_status=""; - $toselect=''; + $toselect=''; $search_array_options=array(); } @@ -197,17 +197,17 @@ $sql.= ", ".MAIN_DB_PREFIX."societe as s"; $sql.= " WHERE f.fk_soc = s.rowid "; $sql.= " AND f.entity = ".$conf->entity; if ($search_ref) { - $sql .= natural_search('f.ref', $search_ref); + $sql .= natural_search('f.ref', $search_ref); } if ($search_company) { - $sql .= natural_search('s.nom', $search_company); + $sql .= natural_search('s.nom', $search_company); } if ($search_desc) { - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) $sql .= natural_search(array('f.description', 'fd.description'), $search_desc); - else $sql .= natural_search(array('f.description'), $search_desc); + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) $sql .= natural_search(array('f.description', 'fd.description'), $search_desc); + else $sql .= natural_search(array('f.description'), $search_desc); } if ($search_status != '' && $search_status >= 0) { - $sql .= ' AND f.fk_statut = '.$search_status; + $sql .= ' AND f.fk_statut = '.$search_status; } if (! $user->rights->societe->client->voir && empty($socid)) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; @@ -219,16 +219,16 @@ if ($sall) { // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -262,7 +262,7 @@ if ($resql) } $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($sall) $urlparam.="&sall=".$sall; if ($socid) $param.="&socid=".$socid; @@ -270,97 +270,97 @@ if ($resql) if ($search_company) $param.="&search_company=".urlencode($search_company); if ($search_desc) $param.="&search_desc=".urlencode($search_desc); if ($search_status != '' && $search_status > -1) $param.="&search_status=".urlencode($search_status); - if ($show_files) $param.='&show_files=' .$show_files; + if ($show_files) $param.='&show_files=' .$show_files; if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - // List of mass actions available - $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), - ); - //if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); - if ($user->rights->ficheinter->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - //if ($massaction == 'presend' || $massaction == 'createbills') $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + // Add $param from extra fields + foreach ($search_array_options as $key => $val) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } + + // List of mass actions available + $arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), + ); + //if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); + if ($user->rights->ficheinter->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + //if ($massaction == 'presend' || $massaction == 'createbills') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); // Lines of title fields - print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; - print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; + print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; + if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; - print '<input type="hidden" name="action" value="list">'; - print '<input type="hidden" name="page" value="'.$page.'">'; - print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; - print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; - print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; + print '<input type="hidden" name="action" value="list">'; + print '<input type="hidden" name="page" value="'.$page.'">'; + print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; + print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; + print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print_barre_liste($title, $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, '', '', $limit); if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } - $moreforfilter=''; + $moreforfilter=''; - $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; + $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; - if (! empty($moreforfilter)) - { - print '<div class="liste_titre liste_titre_bydiv centpercent">'; - print $moreforfilter; - print '</div>'; - } + if (! empty($moreforfilter)) + { + print '<div class="liste_titre liste_titre_bydiv centpercent">'; + print $moreforfilter; + print '</div>'; + } $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); - print '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; + print '<div class="div-table-responsive">'; + print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; print '<tr class="liste_titre_filter">'; - if (! empty($arrayfields['f.ref']['checked'])) - { + if (! empty($arrayfields['f.ref']['checked'])) + { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_ref" value="'.$search_ref.'" size="8">'; print '</td>'; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print '<td class="liste_titre">'; + } + if (! empty($arrayfields['s.nom']['checked'])) + { + print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_company" value="'.$search_company.'" size="10">'; print '</td>'; - } - if (! empty($arrayfields['f.description']['checked'])) - { + } + if (! empty($arrayfields['f.description']['checked'])) + { print '<td class="liste_titre">'; - print '<input type="text" class="flat" name="search_desc" value="'.$search_desc.'" size="12">'; + print '<input type="text" class="flat" name="search_desc" value="'.$search_desc.'" size="12">'; print '</td>'; - } - if (! empty($arrayfields['fd.description']['checked'])) - { - // Desc of line + } + if (! empty($arrayfields['fd.description']['checked'])) + { + // Desc of line + print '<td class="liste_titre"> </td>'; + } + if (! empty($arrayfields['fd.date']['checked'])) + { + print '<td class="liste_titre"> </td>'; + } + if (! empty($arrayfields['fd.duree']['checked'])) + { print '<td class="liste_titre"> </td>'; - } - if (! empty($arrayfields['fd.date']['checked'])) - { - print '<td class="liste_titre"> </td>'; - } - if (! empty($arrayfields['fd.duree']['checked'])) - { - print '<td class="liste_titre"> </td>'; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) @@ -369,84 +369,84 @@ if ($resql) { if (! empty($arrayfields["ef.".$key]['checked'])) { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; } print '</td>'; } } } - // Fields from hook + // 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; - if (! empty($arrayfields['f.datec']['checked'])) - { - // Date creation - print '<td class="liste_titre">'; - print '</td>'; - } - if (! empty($arrayfields['f.tms']['checked'])) - { - // Date modification - print '<td class="liste_titre">'; - print '</td>'; - } - // Status + $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['f.datec']['checked'])) + { + // Date creation + print '<td class="liste_titre">'; + print '</td>'; + } + if (! empty($arrayfields['f.tms']['checked'])) + { + // Date modification + print '<td class="liste_titre">'; + print '</td>'; + } + // Status if (! empty($arrayfields['f.fk_statut']['checked'])) - { + { print '<td class="liste_titre" align="right">'; $liststatus=$objectstatic->statuts_short; if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 1); print '</td>'; - } + } print '<td class="liste_titre" align="right">'; $searchpicto=$form->showFilterButtons(); print $searchpicto; print '</td>'; - print "</tr>\n"; - - print '<tr class="liste_titre">'; - if (! empty($arrayfields['f.ref']['checked'])) print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"f.ref","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre("ThirdParty",$_SERVER["PHP_SELF"],"s.nom","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.description']['checked'])) print_liste_field_titre("Description",$_SERVER["PHP_SELF"],"f.description","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['fd.description']['checked'])) print_liste_field_titre('',$_SERVER["PHP_SELF"],''); - if (! empty($arrayfields['fd.date']['checked'])) print_liste_field_titre("Date",$_SERVER["PHP_SELF"],"fd.date","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['fd.duree']['checked'])) print_liste_field_titre("Duration",$_SERVER["PHP_SELF"],"fd.duree","",$param,'align="right"',$sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre("DateCreationShort",$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre("DateModificationShort",$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"f.fk_statut","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "</tr>\n"; + print "</tr>\n"; + + print '<tr class="liste_titre">'; + if (! empty($arrayfields['f.ref']['checked'])) print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"f.ref","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre("ThirdParty",$_SERVER["PHP_SELF"],"s.nom","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.description']['checked'])) print_liste_field_titre("Description",$_SERVER["PHP_SELF"],"f.description","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['fd.description']['checked'])) print_liste_field_titre('',$_SERVER["PHP_SELF"],''); + if (! empty($arrayfields['fd.date']['checked'])) print_liste_field_titre("Date",$_SERVER["PHP_SELF"],"fd.date","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['fd.duree']['checked'])) print_liste_field_titre("Duration",$_SERVER["PHP_SELF"],"fd.duree","",$param,'align="right"',$sortfield,$sortorder); + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } + } + // Hook fields + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre("DateCreationShort",$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre("DateModificationShort",$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"f.fk_statut","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); + print "</tr>\n"; $total = 0; $i = 0; @@ -461,44 +461,44 @@ if ($resql) print '<tr class="oddeven">'; - if (! empty($arrayfields['f.ref']['checked'])) + if (! empty($arrayfields['f.ref']['checked'])) { print "<td>"; print '<table class="nobordernopadding"><tr class="nocellnopadd">'; - // Picto + Ref - print '<td class="nobordernopadding nowrap">'; - print $objectstatic->getNomUrl(1); - print '</td>'; - // Warning - $warnornote=''; - //if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->fichinter->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); - if (! empty($obj->note_private)) - { - $warnornote.=($warnornote?' ':''); - $warnornote.= '<span class="note">'; - $warnornote.= '<a href="note.php?id='.$obj->rowid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>'; - $warnornote.= '</span>'; - } - if ($warnornote) - { - print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; - print $warnornote; - print '</td>'; - } - - // Other picto tool - print '<td width="16" align="right" class="nobordernopadding hideonsmartphone">'; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->ficheinter->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); - print '</td></tr></table>'; + // Picto + Ref + print '<td class="nobordernopadding nowrap">'; + print $objectstatic->getNomUrl(1); + print '</td>'; + // Warning + $warnornote=''; + //if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->fichinter->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); + if (! empty($obj->note_private)) + { + $warnornote.=($warnornote?' ':''); + $warnornote.= '<span class="note">'; + $warnornote.= '<a href="note.php?id='.$obj->rowid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>'; + $warnornote.= '</span>'; + } + if ($warnornote) + { + print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; + print $warnornote; + print '</td>'; + } + + // Other picto tool + print '<td width="16" align="right" class="nobordernopadding hideonsmartphone">'; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->ficheinter->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); + print '</td></tr></table>'; print "</td>\n"; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['s.nom']['checked'])) + if (! empty($arrayfields['s.nom']['checked'])) { print '<td>'; $companystatic->name=$obj->name; @@ -506,33 +506,33 @@ if ($resql) $companystatic->client=$obj->client; print $companystatic->getNomUrl(1,'',44); print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['f.description']['checked'])) + if (! empty($arrayfields['f.description']['checked'])) { print '<td>'.dol_trunc(dolGetFirstLineOfText($obj->description),48).'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['fd.description']['checked'])) + if (! empty($arrayfields['fd.description']['checked'])) { //print '<td>'.dol_trunc(dol_escape_htmltag(dolGetFirstLineOfText($obj->descriptiondetail)),48).'</td>'; print '<td>'.dolGetFirstLineOfText($obj->descriptiondetail).'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['fd.date']['checked'])) + if (! empty($arrayfields['fd.date']['checked'])) { print '<td align="center">'.dol_print_date($db->jdate($obj->dp),'dayhour')."</td>\n"; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['fd.duree']['checked'])) + if (! empty($arrayfields['fd.duree']['checked'])) { print '<td align="right">'.convertSecondToTime($obj->duree, 'allhourmin').'</td>'; if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totaldurationfield']=$totalarray['nbfield']; - $totalarray['totalduration']+=$obj->duree; + if (! $i) $totalarray['totaldurationfield']=$totalarray['nbfield']; + $totalarray['totalduration']+=$obj->duree; } - // Extra fields + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) @@ -546,46 +546,46 @@ if ($resql) $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } } } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + // 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['f.datec']['checked'])) - { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['f.tms']['checked'])) - { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['f.fk_statut']['checked'])) - { + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['f.datec']['checked'])) + { + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['f.tms']['checked'])) + { + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['f.fk_statut']['checked'])) + { print '<td align="right">'.$objectstatic->LibStatut($obj->fk_statut,5).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Action column - print '<td class="nowrap" align="center">'; - 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; + } + // Action column + print '<td class="nowrap" align="center">'; + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; print "</tr>\n"; @@ -596,20 +596,20 @@ if ($resql) // Show total line if (isset($totalarray['totalduration'])) { - print '<tr class="liste_total">'; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; - else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; - } - elseif ($totalarray['totaldurationfield'] == $i) print '<td align="right">'.convertSecondToTime($totalarray['totalduration'], 'allhourmin').'</td>'; - else print '<td></td>'; - } - print '</tr>'; + print '<tr class="liste_total">'; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; + else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; + } + elseif ($totalarray['totaldurationfield'] == $i) print '<td align="right">'.convertSecondToTime($totalarray['totalduration'], 'allhourmin').'</td>'; + else print '<td></td>'; + } + print '</tr>'; } $db->free($resql); @@ -625,21 +625,21 @@ if ($resql) if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->ficheinter->lire; - $delallowed=$user->rights->ficheinter->supprimer; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->ficheinter->lire; + $delallowed=$user->rights->ficheinter->supprimer; - print $formfile->showdocuments('massfilesarea_interventions','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + print $formfile->showdocuments('massfilesarea_interventions','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } else { - print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; + print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; } } diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index e74a3b4df8e73ec81e0d60cc68aaa56076408ac1..e6c8023496cf3c8c087bd4b67e62a654cb42a349 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -62,7 +62,7 @@ $socid = GETPOST('socid','int'); if ($user->societe_id > 0) { $action=''; - $_GET["action"] = ''; + $_GET["action"] = ''; $socid = $user->societe_id; } @@ -136,47 +136,47 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'f.ref'=>'Ref', - 'f.ref_supplier'=>'RefSupplier', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'f.note_public'=>'NotePublic', + 'f.ref'=>'Ref', + 'f.ref_supplier'=>'RefSupplier', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'f.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["f.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'f.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), - 'f.label'=>array('label'=>$langs->trans("Label"), 'checked'=>0), - 'f.datef'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), - 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), + 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'f.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), + 'f.label'=>array('label'=>$langs->trans("Label"), 'checked'=>0), + 'f.datef'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), + 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), 'p.ref'=>array('label'=>$langs->trans("Project"), 'checked'=>0), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), - 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), - 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), - 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'dynamount_payed'=>array('label'=>$langs->trans("Payed"), 'checked'=>0), - 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), - 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), + 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), + 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), + 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'dynamount_payed'=>array('label'=>$langs->trans("Payed"), 'checked'=>0), + 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), + 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! 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'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } @@ -193,55 +193,55 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','alpha') || GETPOST('button_removefilter.x','alpha')) // All tests must be present to be compatible with all browsers - { - $search_all=""; - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=""; - $search_refsupplier=""; - $search_label=""; - $search_project=''; - $search_societe=""; - $search_company=""; - $search_amount_no_tax=""; - $search_amount_all_tax=""; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_localtax1=''; - $search_montant_localtax2=''; - $search_montant_ttc=''; - $search_status=''; - $search_paymentmode=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $year=""; - $month=""; - $day=""; - $year_lim=""; - $month_lim=""; - $day_lim=""; - $toselect=''; - $search_array_options=array(); - $filter=''; - $option=''; - } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','alpha') || GETPOST('button_removefilter.x','alpha')) // All tests must be present to be compatible with all browsers + { + $search_all=""; + $search_user=''; + $search_sale=''; + $search_product_category=''; + $search_ref=""; + $search_refsupplier=""; + $search_label=""; + $search_project=''; + $search_societe=""; + $search_company=""; + $search_amount_no_tax=""; + $search_amount_all_tax=""; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_localtax1=''; + $search_montant_localtax2=''; + $search_montant_ttc=''; + $search_status=''; + $search_paymentmode=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $year=""; + $month=""; + $day=""; + $year_lim=""; + $month_lim=""; + $day_lim=""; + $toselect=''; + $search_array_options=array(); + $filter=''; + $option=''; + } - // Mass actions - $objectclass='FactureFournisseur'; - $objectlabel='SupplierInvoices'; - $permtoread = $user->rights->fournisseur->facture->lire; - $permtocreate = $user->rights->fournisseur->facture->creer; - $permtodelete = $user->rights->fournisseur->facture->supprimer; - $uploaddir = $conf->fournisseur->facture->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Mass actions + $objectclass='FactureFournisseur'; + $objectlabel='SupplierInvoices'; + $permtoread = $user->rights->fournisseur->facture->lire; + $permtocreate = $user->rights->fournisseur->facture->creer; + $permtodelete = $user->rights->fournisseur->facture->supprimer; + $uploaddir = $conf->fournisseur->facture->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -290,8 +290,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = f.fk_projet"; if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE f.fk_soc = s.rowid'; $sql.= ' AND f.entity IN ('.getEntity('facture_fourn').')'; @@ -364,21 +364,21 @@ if ($filter && $filter != -1) if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$db->escape($search_sale); if ($search_user > 0) { - $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='invoice_supplier' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; + $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='invoice_supplier' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -387,22 +387,22 @@ $sql.=$hookmanager->resPrint; if (! $search_all) { - $sql.= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.datef, f.date_lim_reglement, f.fk_mode_reglement,"; - $sql.= " f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut, f.libelle, f.datec, f.tms,"; - $sql.= " f.localtax1, f.localtax2,"; - $sql.= " s.rowid, s.nom, s.town, s.zip, s.fk_pays, s.client, s.code_client,"; - $sql.= " typent.code,"; - $sql.= " state.code_departement, state.nom,"; - $sql.= " p.rowid, p.ref"; - - foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by - { - $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); - } + $sql.= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.datef, f.date_lim_reglement, f.fk_mode_reglement,"; + $sql.= " f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut, f.libelle, f.datec, f.tms,"; + $sql.= " f.localtax1, f.localtax2,"; + $sql.= " s.rowid, s.nom, s.town, s.zip, s.fk_pays, s.client, s.code_client,"; + $sql.= " typent.code,"; + $sql.= " state.code_departement, state.nom,"; + $sql.= " p.rowid, p.ref"; + + foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by + { + $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); + } } else { - $sql.= natural_search(array_keys($fieldstosearchall), $search_all); + $sql.= natural_search(array_keys($fieldstosearchall), $search_all); } $sql.= $db->order($sortfield,$sortorder); @@ -432,10 +432,10 @@ if ($resql) } $param='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($search_all) $param.='&search_all='.urlencode($search_all); - if ($day) $param.='&day='.urlencode($day); + if ($day) $param.='&day='.urlencode($day); if ($month) $param.='&month='.urlencode($month); if ($year) $param.='&year=' .urlencode($year); if ($day_lim) $param.='&day_lim='.urlencode($day_lim); @@ -445,30 +445,30 @@ if ($resql) if ($search_refsupplier) $param.='&search_refsupplier='.urlencode($search_refsupplier); if ($search_label) $param.='&search_label='.urlencode($search_label); if ($search_company) $param.='&search_company='.urlencode($search_company); - if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); - if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); - if ($search_montant_localtax1 != '') $param.='&search_montant_localtax1='.urlencode($search_montant_localtax1); - if ($search_montant_localtax2 != '') $param.='&search_montant_localtax2='.urlencode($search_montant_localtax2); - if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); + if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); + if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); + if ($search_montant_localtax1 != '') $param.='&search_montant_localtax1='.urlencode($search_montant_localtax1); + if ($search_montant_localtax2 != '') $param.='&search_montant_localtax2='.urlencode($search_montant_localtax2); + if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); if ($search_amount_no_tax) $param.='&search_amount_no_tax='.urlencode($search_amount_no_tax); if ($search_amount_all_tax) $param.='&search_amount_all_tax='.urlencode($search_amount_all_tax); if ($search_status >= 0) $param.="&search_status=".urlencode($search_status); - if ($show_files) $param.='&show_files=' .$show_files; + if ($show_files) $param.='&show_files=' .$show_files; if ($option) $param.="&option=".$option; if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - 'validate'=>$langs->trans("Validate"), + 'validate'=>$langs->trans("Validate"), //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), + //'builddoc'=>$langs->trans("PDFMerge"), ); //if($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if ($user->rights->fournisseur->facture->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); @@ -477,13 +477,13 @@ if ($resql) $i = 0; print '<form method="POST" name="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; - print '<input type="hidden" name="page" value="'.$page.'">'; + print '<input type="hidden" name="page" value="'.$page.'">'; print '<input type="hidden" name="viewstatut" value="'.$viewstatut.'">'; print '<input type="hidden" name="socid" value="'.$socid.'">'; @@ -501,52 +501,52 @@ if ($resql) if ($massaction == 'createbills') { - //var_dump($_REQUEST); - print '<input type="hidden" name="massaction" value="confirm_createbills">'; - - print '<table class="border" width="100%" >'; - print '<tr>'; - print '<td class="titlefieldmiddle">'; - print $langs->trans('DateInvoice'); - print '</td>'; - print '<td>'; - print $form->select_date('', '', '', '', '', '', 1, 1); - print '</td>'; - print '</tr>'; - print '<tr>'; - print '<td>'; - print $langs->trans('CreateOneBillByThird'); - print '</td>'; - print '<td>'; - print $form->selectyesno('createbills_onebythird', '', 1); - print '</td>'; - print '</tr>'; - print '<tr>'; - print '<td>'; - print $langs->trans('ValidateInvoices'); - print '</td>'; - print '<td>'; - print $form->selectyesno('valdate_invoices', 1, 1); - print '</td>'; - print '</tr>'; - print '</table>'; - - print '<br>'; - print '<div class="center">'; - print '<input type="submit" class="button" id="createbills" name="createbills" value="'.$langs->trans('CreateInvoiceForThisCustomer').'"> '; - print '<input type="submit" class="button" id="cancel" name="cancel" value="'.$langs->trans('Cancel').'">'; - print '</div>'; - print '<br>'; + //var_dump($_REQUEST); + print '<input type="hidden" name="massaction" value="confirm_createbills">'; + + print '<table class="border" width="100%" >'; + print '<tr>'; + print '<td class="titlefieldmiddle">'; + print $langs->trans('DateInvoice'); + print '</td>'; + print '<td>'; + print $form->select_date('', '', '', '', '', '', 1, 1); + print '</td>'; + print '</tr>'; + print '<tr>'; + print '<td>'; + print $langs->trans('CreateOneBillByThird'); + print '</td>'; + print '<td>'; + print $form->selectyesno('createbills_onebythird', '', 1); + print '</td>'; + print '</tr>'; + print '<tr>'; + print '<td>'; + print $langs->trans('ValidateInvoices'); + print '</td>'; + print '<td>'; + print $form->selectyesno('valdate_invoices', 1, 1); + print '</td>'; + print '</tr>'; + print '</table>'; + + print '<br>'; + print '<div class="center">'; + print '<input type="submit" class="button" id="createbills" name="createbills" value="'.$langs->trans('CreateInvoiceForThisCustomer').'"> '; + print '<input type="submit" class="button" id="cancel" name="cancel" value="'.$langs->trans('Cancel').'">'; + print '</div>'; + print '<br>'; } if ($search_all) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); + } // If the user can view prospects other than his' - $moreforfilter=''; + $moreforfilter=''; if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); @@ -555,14 +555,14 @@ if ($resql) $moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); $moreforfilter.='</div>'; } - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) + { $moreforfilter.='<div class="divsearchfield">'; - $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='</div>'; - } + } // If the user can view prospects other than his' if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { @@ -573,76 +573,76 @@ if ($resql) $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter.='</div>'; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + $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; - if ($moreforfilter) - { + if ($moreforfilter) + { print '<div class="liste_titre liste_titre_bydiv centpercent">'; - print $moreforfilter; - print '</div>'; - } + print $moreforfilter; + print '</div>'; + } - $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); + $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); - print '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; + print '<div class="div-table-responsive">'; + print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; // Line for filters print '<tr class="liste_titre_filter">'; // Ref if (! empty($arrayfields['f.ref']['checked'])) { - print '<td class="liste_titre" align="left">'; - print '<input class="flat" size="6" type="text" name="search_ref" value="'.$search_ref.'">'; - print '</td>'; + print '<td class="liste_titre" align="left">'; + print '<input class="flat" size="6" type="text" name="search_ref" value="'.$search_ref.'">'; + print '</td>'; } // Ref supplier if (! empty($arrayfields['f.ref_supplier']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" size="6" type="text" name="search_refsupplier" value="'.$search_refsupplier.'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" size="6" type="text" name="search_refsupplier" value="'.$search_refsupplier.'">'; + print '</td>'; } // Label if (! empty($arrayfields['f.label']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" size="6" type="text" name="search_label" value="'.$search_label.'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" size="6" type="text" name="search_label" value="'.$search_label.'">'; + print '</td>'; } // Date invoice if (! empty($arrayfields['f.datef']['checked'])) { - print '<td class="liste_titre" align="center">'; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.dol_escape_htmltag($day).'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">'; - $formother->select_year($year?$year:-1,'year',1, 20, 5); - print '</td>'; + print '<td class="liste_titre" align="center">'; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.dol_escape_htmltag($day).'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">'; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print '</td>'; } // Date due if (! empty($arrayfields['f.date_lim_reglement']['checked'])) { - print '<td class="liste_titre" align="center">'; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day_lim" value="'.dol_escape_htmltag($day_lim).'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="month_lim" value="'.$month_lim.'">'; - $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); - print '<br><input type="checkbox" name="option" value="late"'.($option == 'late'?' checked':'').'> '.$langs->trans("Late"); - print '</td>'; + print '<td class="liste_titre" align="center">'; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day_lim" value="'.dol_escape_htmltag($day_lim).'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="month_lim" value="'.$month_lim.'">'; + $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); + print '<br><input type="checkbox" name="option" value="late"'.($option == 'late'?' checked':'').'> '.$langs->trans("Late"); + print '</td>'; } // Project if (! empty($arrayfields['p.ref']['checked'])) { - print '<td class="liste_titre" align="left"><input class="flat" type="text" size="6" name="search_project" value="'.$search_project.'"></td>'; + print '<td class="liste_titre" align="left"><input class="flat" type="text" size="6" name="search_project" value="'.$search_project.'"></td>'; } // Thirpdarty if (! empty($arrayfields['s.nom']['checked'])) { - print '<td class="liste_titre" align="left"><input class="flat" type="text" size="6" name="search_societe" value="'.$search_societe.'"></td>'; + print '<td class="liste_titre" align="left"><input class="flat" type="text" size="6" name="search_societe" value="'.$search_societe.'"></td>'; } // Town if (! empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.dol_escape_htmltag($search_town).'"></td>'; @@ -651,98 +651,98 @@ if ($resql) // State if (! empty($arrayfields['state.nom']['checked'])) { - print '<td class="liste_titre">'; - print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; + print '</td>'; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print '<td class="liste_titre" align="center">'; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print '</td>'; + print '<td class="liste_titre" align="center">'; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print '</td>'; } // Company type if (! empty($arrayfields['typent.code']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="center">'; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="center">'; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print '</td>'; } // Payment mode if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) { - print '<td class="liste_titre" align="left">'; - $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); - print '</td>'; + print '<td class="liste_titre" align="left">'; + $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); + print '</td>'; } if (! empty($arrayfields['f.total_ht']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">'; + print '</td>'; } if (! empty($arrayfields['f.total_vat']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">'; + print '</td>'; } if (! empty($arrayfields['f.total_localtax1']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_localtax1" value="'.$search_montant_localtax1.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_localtax1" value="'.$search_montant_localtax1.'">'; + print '</td>'; } if (! empty($arrayfields['f.total_localtax2']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_localtax2" value="'.$search_montant_localtax2.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_localtax2" value="'.$search_montant_localtax2.'">'; + print '</td>'; } if (! empty($arrayfields['f.total_ttc']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">'; + print '</td>'; + } + if (! empty($arrayfields['dynamount_payed']['checked'])) + { + print '<td class="liste_titre" align="right">'; + print '</td>'; + } + if (! empty($arrayfields['rtp']['checked'])) + { + print '<td class="liste_titre" align="right">'; + print '</td>'; } - if (! empty($arrayfields['dynamount_payed']['checked'])) - { - print '<td class="liste_titre" align="right">'; - print '</td>'; - } - if (! empty($arrayfields['rtp']['checked'])) - { - print '<td class="liste_titre" align="right">'; - print '</td>'; - } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } - print '</td>'; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -751,22 +751,22 @@ if ($resql) // Date creation if (! empty($arrayfields['f.datec']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Date modification if (! empty($arrayfields['f.tms']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Status if (! empty($arrayfields['f.fk_statut']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="right">'; - $liststatus=array('0'=>$langs->trans("Draft"),'1'=>$langs->trans("Unpaid"), '2'=>$langs->trans("Paid")); - print $form->selectarray('search_status', $liststatus, $search_status, 1); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="right">'; + $liststatus=array('0'=>$langs->trans("Draft"),'1'=>$langs->trans("Unpaid"), '2'=>$langs->trans("Paid")); + print $form->selectarray('search_status', $liststatus, $search_status, 1); + print '</td>'; } // Action column print '<td class="liste_titre" align="middle">'; @@ -795,21 +795,21 @@ if ($resql) if (! empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'],$_SERVER['PHP_SELF'],'f.localtax1','',$param,'align="right"',$sortfield,$sortorder); if (! empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'],$_SERVER['PHP_SELF'],'f.localtax2','',$param,'align="right"',$sortfield,$sortorder); if (! empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'],$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -821,16 +821,16 @@ if ($resql) print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); print "</tr>\n"; - $facturestatic=new FactureFournisseur($db); + $facturestatic=new FactureFournisseur($db); $supplierstatic=new Fournisseur($db); $projectstatic=new Project($db); if ($num > 0) - { + { $i=0; $var=true; - $totalarray=array(); + $totalarray=array(); while ($i < min($num,$limit)) { $obj = $db->fetch_object($resql); @@ -838,7 +838,7 @@ if ($resql) $datelimit=$db->jdate($obj->datelimite); $facturestatic->id=$obj->facid; $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; + $facturestatic->type=$obj->type; $facturestatic->ref_supplier=$obj->ref_supplier; $facturestatic->date_echeance = $db->jdate($obj->datelimite); $facturestatic->statut = $obj->fk_statut; @@ -849,271 +849,271 @@ if ($resql) $totalpay = $paiement + $totalcreditnotes + $totaldeposits; $remaintopay = $obj->total_ttc - $totalpay; - print '<tr class="oddeven">'; - if (! empty($arrayfields['f.ref']['checked'])) - { - print '<td class="nowrap">'; - - print '<table class="nobordernopadding"><tr class="nocellnopadd">'; - // Picto + Ref - print '<td class="nobordernopadding nowrap">'; - print $facturestatic->getNomUrl(1); - print '</td>'; - // Warning - //print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; - //print '</td>'; - // Other picto tool - print '<td width="16" align="right" class="nobordernopadding hideonsmartphone">'; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->fournisseur->facture->dir_output.'/'.get_exdir($obj->facid,2,0,0,$facturestatic,'invoice_supplier').dol_sanitizeFileName($obj->ref); + print '<tr class="oddeven">'; + if (! empty($arrayfields['f.ref']['checked'])) + { + print '<td class="nowrap">'; + + print '<table class="nobordernopadding"><tr class="nocellnopadd">'; + // Picto + Ref + print '<td class="nobordernopadding nowrap">'; + print $facturestatic->getNomUrl(1); + print '</td>'; + // Warning + //print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; + //print '</td>'; + // Other picto tool + print '<td width="16" align="right" class="nobordernopadding hideonsmartphone">'; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->fournisseur->facture->dir_output.'/'.get_exdir($obj->facid,2,0,0,$facturestatic,'invoice_supplier').dol_sanitizeFileName($obj->ref); $subdir = get_exdir($obj->facid,2,0,0,$facturestatic,'invoice_supplier').dol_sanitizeFileName($obj->ref); print $formfile->getDocumentsLink('facture_fournisseur', $subdir, $filedir); print '</td></tr></table>'; - print "</td>\n"; + print "</td>\n"; if (! $i) $totalarray['nbfield']++; - } + } // Customer ref - if (! empty($arrayfields['f.ref_supplier']['checked'])) - { - print '<td class="nowrap">'; - print $obj->ref_supplier; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['f.ref_supplier']['checked'])) + { + print '<td class="nowrap">'; + print $obj->ref_supplier; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } // Label - if (! empty($arrayfields['f.label']['checked'])) - { - print '<td class="nowrap">'; - print $obj->label; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['f.label']['checked'])) + { + print '<td class="nowrap">'; + print $obj->label; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } // Date - if (! empty($arrayfields['f.datef']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->datef),'day'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Date limit - if (! empty($arrayfields['f.date_lim_reglement']['checked'])) - { - print '<td align="center" class="nowrap">'.dol_print_date($datelimit,'day'); - if ($facturestatic->hasDelay()) - { - print img_warning($langs->trans('Late')); - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Project - if (! empty($arrayfields['p.ref']['checked'])) - { - print '<td class="nowrap">'; - if ($obj->project_id > 0) - { - $projectstatic->id=$obj->project_id; - $projectstatic->ref=$obj->project_ref; - print $projectstatic->getNomUrl(1); - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Third party - if (! empty($arrayfields['s.nom']['checked'])) - { - print '<td class="tdoverflowmax200">'; - $thirdparty=new Societe($db); - $thirdparty->id=$obj->socid; - $thirdparty->name=$obj->name; - $thirdparty->client=$obj->client; - $thirdparty->code_client=$obj->code_client; - print $thirdparty->getNomUrl(1,'supplier'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->town; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->zip; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "<td>".$obj->state_name."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print '<td align="center">'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print '<td align="center">'; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Payment mode - if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) - { - print '<td>'; - $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Amount HT - if (! empty($arrayfields['f.total_ht']['checked'])) - { - print '<td align="right">'.price($obj->total_ht)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['f.total_vat']['checked'])) - { - print '<td align="right">'.price($obj->total_vat)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_vat; - } - // Amount LocalTax1 - if (! empty($arrayfields['f.total_localtax1']['checked'])) - { - print '<td align="right">'.price($obj->total_localtax1)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totallocaltax1field']=$totalarray['nbfield']; - $totalarray['totallocaltax1'] += $obj->total_localtax1; - } - // Amount LocalTax2 - if (! empty($arrayfields['f.total_localtax2']['checked'])) - { - print '<td align="right">'.price($obj->total_localtax2)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totallocaltax2field']=$totalarray['nbfield']; - $totalarray['totallocaltax2'] += $obj->total_localtax2; - } - // Amount TTC - if (! empty($arrayfields['f.total_ttc']['checked'])) - { - print '<td align="right">'.price($obj->total_ttc)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } - - if (! empty($arrayfields['dynamount_payed']['checked'])) - { - print '<td align="right">'.(! empty($totalpay)?price($totalpay,0,$langs):' ').'</td>'; // TODO Use a denormalized field - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalamfield']=$totalarray['nbfield']; - $totalarray['totalam'] += $totalpay; - } - - if (! empty($arrayfields['rtp']['checked'])) - { - print '<td align="right">'.(! empty($remaintopay)?price($remaintopay,0,$langs):' ').'</td>'; // TODO Use a denormalized field - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; - $totalarray['totalrtp'] += $remaintopay; - } - - - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } - } - // 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['f.datec']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['f.tms']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['f.fk_statut']['checked'])) - { - print '<td align="right" class="nowrap">'; - // TODO $paiement is not yet defined - print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5,$paiement,$obj->type); - print "</td>"; - if (! $i) $totalarray['nbfield']++; - } - - // Action column - print '<td class="nowrap" align="center">'; - 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->facid, $arrayofselected)) $selected=1; - print '<input id="cb'.$obj->facid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->facid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! empty($arrayfields['f.datef']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->datef),'day'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Date limit + if (! empty($arrayfields['f.date_lim_reglement']['checked'])) + { + print '<td align="center" class="nowrap">'.dol_print_date($datelimit,'day'); + if ($facturestatic->hasDelay()) + { + print img_warning($langs->trans('Late')); + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Project + if (! empty($arrayfields['p.ref']['checked'])) + { + print '<td class="nowrap">'; + if ($obj->project_id > 0) + { + $projectstatic->id=$obj->project_id; + $projectstatic->ref=$obj->project_ref; + print $projectstatic->getNomUrl(1); + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Third party + if (! empty($arrayfields['s.nom']['checked'])) + { + print '<td class="tdoverflowmax200">'; + $thirdparty=new Societe($db); + $thirdparty->id=$obj->socid; + $thirdparty->name=$obj->name; + $thirdparty->client=$obj->client; + $thirdparty->code_client=$obj->code_client; + print $thirdparty->getNomUrl(1,'supplier'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) + { + print '<td class="nocellnopadd">'; + print $obj->town; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print '<td class="nocellnopadd">'; + print $obj->zip; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "<td>".$obj->state_name."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print '<td align="center">'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print '<td align="center">'; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Payment mode + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) + { + print '<td>'; + $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Amount HT + if (! empty($arrayfields['f.total_ht']['checked'])) + { + print '<td align="right">'.price($obj->total_ht)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['f.total_vat']['checked'])) + { + print '<td align="right">'.price($obj->total_vat)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_vat; + } + // Amount LocalTax1 + if (! empty($arrayfields['f.total_localtax1']['checked'])) + { + print '<td align="right">'.price($obj->total_localtax1)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totallocaltax1field']=$totalarray['nbfield']; + $totalarray['totallocaltax1'] += $obj->total_localtax1; + } + // Amount LocalTax2 + if (! empty($arrayfields['f.total_localtax2']['checked'])) + { + print '<td align="right">'.price($obj->total_localtax2)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totallocaltax2field']=$totalarray['nbfield']; + $totalarray['totallocaltax2'] += $obj->total_localtax2; + } + // Amount TTC + if (! empty($arrayfields['f.total_ttc']['checked'])) + { + print '<td align="right">'.price($obj->total_ttc)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } + + if (! empty($arrayfields['dynamount_payed']['checked'])) + { + print '<td align="right">'.(! empty($totalpay)?price($totalpay,0,$langs):' ').'</td>'; // TODO Use a denormalized field + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalamfield']=$totalarray['nbfield']; + $totalarray['totalam'] += $totalpay; + } + + if (! empty($arrayfields['rtp']['checked'])) + { + print '<td align="right">'.(! empty($remaintopay)?price($remaintopay,0,$langs):' ').'</td>'; // TODO Use a denormalized field + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; + $totalarray['totalrtp'] += $remaintopay; + } + + + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } + } + // 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['f.datec']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['f.tms']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['f.fk_statut']['checked'])) + { + print '<td align="right" class="nowrap">'; + // TODO $paiement is not yet defined + print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5,$paiement,$obj->type); + print "</td>"; + if (! $i) $totalarray['nbfield']++; + } + + // Action column + print '<td class="nowrap" align="center">'; + 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->facid, $arrayofselected)) $selected=1; + print '<input id="cb'.$obj->facid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->facid.'"'.($selected?' checked="checked"':'').'>'; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; print "</tr>\n"; $i++; } - // Show total line - if (isset($totalarray['totalhtfield']) + // Show total line + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totallocaltax1field']) || isset($totalarray['totallocaltax2field']) @@ -1121,29 +1121,29 @@ if ($resql) || isset($totalarray['totalamfield']) || isset($totalarray['totalrtpfield']) ) - { - print '<tr class="liste_total">'; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; - else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; - } - elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; - elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; - elseif ($totalarray['totallocaltax1field'] == $i) print '<td align="right">'.price($totalarray['totallocaltax1']).'</td>'; - elseif ($totalarray['totallocaltax2field'] == $i) print '<td align="right">'.price($totalarray['totallocaltax2']).'</td>'; - elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; - elseif ($totalarray['totalamfield'] == $i) print '<td align="right">'.price($totalarray['totalam']).'</td>'; - elseif ($totalarray['totalrtpfield'] == $i) print '<td align="right">'.price($totalarray['totalrtp']).'</td>'; - else print '<td></td>'; - } - print '</tr>'; - - } + { + print '<tr class="liste_total">'; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; + else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; + } + elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; + elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; + elseif ($totalarray['totallocaltax1field'] == $i) print '<td align="right">'.price($totalarray['totallocaltax1']).'</td>'; + elseif ($totalarray['totallocaltax2field'] == $i) print '<td align="right">'.price($totalarray['totallocaltax2']).'</td>'; + elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; + elseif ($totalarray['totalamfield'] == $i) print '<td align="right">'.price($totalarray['totalam']).'</td>'; + elseif ($totalarray['totalrtpfield'] == $i) print '<td align="right">'.price($totalarray['totalrtp']).'</td>'; + else print '<td></td>'; + } + print '</tr>'; + + } } $db->free($resql); @@ -1153,11 +1153,11 @@ if ($resql) print $hookmanager->resPrint; print "</table>\n"; - print '</div>'; + print '</div>'; print "</form>\n"; - /* + /* if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { // Show list of available documents diff --git a/htdocs/modulebuilder/template/myobject_list.php b/htdocs/modulebuilder/template/myobject_list.php index 07f896d195cbb90cad04d6162ddc0754bd348726..b40f96f669af340f3d96aae3eb04fd99b3afc509 100644 --- a/htdocs/modulebuilder/template/myobject_list.php +++ b/htdocs/modulebuilder/template/myobject_list.php @@ -99,7 +99,7 @@ if (! $sortorder) $sortorder="ASC"; $socid=0; if ($user->societe_id > 0) { - //$socid = $user->societe_id; + //$socid = $user->societe_id; accessforbidden(); } @@ -108,14 +108,14 @@ $search_all=trim(GETPOST("search_all",'alpha')); $search=array(); foreach($object->fields as $key => $val) { - if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha'); + if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha'); } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); foreach($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; + if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; } // Definition of fields for list @@ -123,15 +123,15 @@ $arrayfields=array(); foreach($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled']); + if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled']); } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } @@ -152,32 +152,32 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - foreach($object->fields as $key => $val) - { - $search[$key]=''; - } - $toselect=''; - $search_array_options=array(); - } - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') - || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) - { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation - } - - // Mass actions - $objectclass='MyObject'; - $objectlabel='MyObject'; - $permtoread = $user->rights->mymodule->read; - $permtodelete = $user->rights->mymodule->delete; - $uploaddir = $conf->mymodule->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + foreach($object->fields as $key => $val) + { + $search[$key]=''; + } + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass='MyObject'; + $objectlabel='MyObject'; + $permtoread = $user->rights->mymodule->read; + $permtodelete = $user->rights->mymodule->delete; + $uploaddir = $conf->mymodule->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -202,7 +202,7 @@ $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("MyObjects")); $sql = 'SELECT '; foreach($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql.='t.'.$key.', '; } // Add fields from extrafields foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); @@ -223,16 +223,16 @@ if ($search_all) $sql.= natural_search(array_keys($fieldstosearchall), $search_a // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode_search=0; - if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode_search); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode_search=0; + if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode_search); + } } // Add where from hooks $parameters=array(); @@ -269,8 +269,8 @@ dol_syslog($script_file, LOG_DEBUG); $resql=$db->query($sql); if (! $resql) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($resql); @@ -278,10 +278,10 @@ $num = $db->num_rows($resql); // Direct jump if only one record found if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/mymodule/myobject_card.php?id='.$id); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/mymodule/myobject_card.php?id='.$id); + exit; } @@ -312,21 +312,21 @@ if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&con if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); foreach($search as $key => $val) { - $param.= '&search_'.$key.'='.urlencode($search[$key]); + $param.= '&search_'.$key.'='.urlencode($search[$key]); } if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->mymodule->delete) $arrayofmassactions['delete']=$langs->trans("Delete"); if ($massaction == 'presend') $arrayofmassactions=array(); @@ -346,8 +346,8 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } $moreforfilter = ''; @@ -364,7 +364,7 @@ if (! empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; - print '</div>'; + print '</div>'; } $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; @@ -380,35 +380,35 @@ print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"") print '<tr class="liste_titre">'; foreach($object->fields as $key => $val) { - if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) print '<td class="liste_titre'.($align?' '.$align:'').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>'; + if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print '<td class="liste_titre'.($align?' '.$align:'').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>'; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } - print '</td>'; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -417,12 +417,12 @@ print $hookmanager->resPrint; // Rest of fields search foreach($object->fields as $key => $val) { - if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) print '<td class="liste_titre'.($align?' '.$align:'').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>'; + if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print '<td class="liste_titre'.($align?' '.$align:'').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>'; } // Action column print '<td class="liste_titre" align="right">'; @@ -437,25 +437,25 @@ print '</tr>'."\n"; print '<tr class="liste_titre">'; foreach($object->fields as $key => $val) { - if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; + if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); $sortonfield = "ef.".$key; if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; print getTitleFieldOfList($langs->trans($extralabels[$key]), 0, $_SERVER["PHP_SELF"], $sortonfield, "", $param, ($align?'align="'.$align.'"':''), $sortfield, $sortorder)."\n"; - } + } } } // Hook fields @@ -465,12 +465,12 @@ print $hookmanager->resPrint; // Rest of fields title foreach($object->fields as $key => $val) { - if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; + if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; } print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n"; print '</tr>'."\n"; @@ -480,7 +480,7 @@ print '</tr>'."\n"; $needToFetchEachLine=0; foreach ($extrafields->attribute_computed as $key => $val) { - if (preg_match('/\$object/',$val)) $needToFetchEachLine++; // There is at least one compute field that use $object + if (preg_match('/\$object/',$val)) $needToFetchEachLine++; // There is at least one compute field that use $object } @@ -490,43 +490,43 @@ $i=0; $totalarray=array(); while ($i < min($num, $limit)) { - $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + $obj = $db->fetch_object($resql); + if (empty($obj)) break; // Should not happen - // Store properties in $object + // Store properties in $object $object->id = $obj->rowid; foreach($object->fields as $key => $val) { if (isset($obj->$key)) $object->$key = $obj->$key; } - // Show here line of result - print '<tr class="oddeven">'; - foreach($object->fields as $key => $val) - { - if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; // Discard some field output at end - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) - { - print '<td'.($align?' class="'.$align.'"':'').'>'; - if (in_array($val['type'], array('date'))) print dol_print_date($db->jdate($obj->$key), 'day', 'tzuser'); - elseif (in_array($val['type'], array('datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour', 'tzuser'); - elseif ($key == 'ref') print $object->getNomUrl(1, '', 0, '', 1); - elseif ($key == 'status') print $object->getLibStatut(3); - else print $obj->$key; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) - { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; - $totalarray['val']['t.'.$key] += $obj->$key; - } - } - } - // Extra fields + // Show here line of result + print '<tr class="oddeven">'; + foreach($object->fields as $key => $val) + { + if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; // Discard some field output at end + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) + { + print '<td'.($align?' class="'.$align.'"':'').'>'; + if (in_array($val['type'], array('date'))) print dol_print_date($db->jdate($obj->$key), 'day', 'tzuser'); + elseif (in_array($val['type'], array('datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour', 'tzuser'); + elseif ($key == 'ref') print $object->getNomUrl(1, '', 0, '', 1); + elseif ($key == 'status') print $object->getLibStatut(3); + else print $obj->$key; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + $totalarray['val']['t.'.$key] += $obj->$key; + } + } + } + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) @@ -540,87 +540,87 @@ while ($i < min($num, $limit)) $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print '</td>'; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) - { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='ef.'.$tmpkey; - $totalarray['val']['ef.'.$tmpkey] += $obj->$tmpkey; - } + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='ef.'.$tmpkey; + $totalarray['val']['ef.'.$tmpkey] += $obj->$tmpkey; + } } } } - // Fields from hook + // Fields from hook $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Rest of fields - foreach($object->fields as $key => $val) - { - if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; // Keep only field not yet already output - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) - { - print '<td'.($align?' class="'.$align.'"':'').'>'; - if (in_array($val['type'], array('date'))) print dol_print_date($db->jdate($obj->$key), 'day', 'tzuser'); - elseif (in_array($val['type'], array('datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour', 'tzuser'); - elseif ($key == 'status') print $object->getLibStatut(3); - else print $obj->$key; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) - { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; - $totalarray['val']['t.'.$key] += $obj->$key; - } - } - } - // Action column - print '<td class="nowrap" align="center">'; + print $hookmanager->resPrint; + // Rest of fields + foreach($object->fields as $key => $val) + { + if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; // Keep only field not yet already output + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; + if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) + { + print '<td'.($align?' class="'.$align.'"':'').'>'; + if (in_array($val['type'], array('date'))) print dol_print_date($db->jdate($obj->$key), 'day', 'tzuser'); + elseif (in_array($val['type'], array('datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour', 'tzuser'); + elseif ($key == 'status') print $object->getLibStatut(3); + else print $obj->$key; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + $totalarray['val']['t.'.$key] += $obj->$key; + } + } + } + // Action column + print '<td class="nowrap" align="center">'; 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; + { + $selected=0; if (in_array($obj->rowid, $arrayofselected)) $selected=1; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } + } print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; - print '</tr>'; + print '</tr>'; - $i++; + $i++; } // Show total line if (isset($totalarray['pos'])) { - print '<tr class="liste_total">'; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if (! empty($totalarray['pos'][$i])) print '<td align="right">'.price($totalarray['val'][$totalarray['pos'][$i]]).'</td>'; - else - { - if ($i == 1) - { - if ($num < $limit) print '<td align="left">'.$langs->trans("Total").'</td>'; - else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; - } - else print '<td></td>'; - } - } - print '</tr>'; + print '<tr class="liste_total">'; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if (! empty($totalarray['pos'][$i])) print '<td align="right">'.price($totalarray['val'][$totalarray['pos'][$i]]).'</td>'; + else + { + if ($i == 1) + { + if ($num < $limit) print '<td align="left">'.$langs->trans("Total").'</td>'; + else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; + } + else print '<td></td>'; + } + } + print '</tr>'; } // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } - print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; } @@ -637,25 +637,25 @@ print '</form>'."\n"; if (in_array('builddoc',$arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) - { - require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); - $formfile = new FormFile($db); - - // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); - - $filedir=$diroutputmassaction; - $genallowed=$user->rights->mymodule->read; - $delallowed=$user->rights->mymodule->read; - - print $formfile->showdocuments('massfilesarea_mymodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; - } + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); + + $filedir=$diroutputmassaction; + $genallowed=$user->rights->mymodule->read; + $delallowed=$user->rights->mymodule->read; + + print $formfile->showdocuments('massfilesarea_mymodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; + } } // End of page diff --git a/htdocs/product/list.php b/htdocs/product/list.php index 525bd96ed90df2155cb7e3849067813135652d42..07a9da3bdb0ce645a2ee3f8a051b91781d85f4fb 100644 --- a/htdocs/product/list.php +++ b/htdocs/product/list.php @@ -109,9 +109,9 @@ $canvas=GETPOST("canvas"); $objcanvas=null; if (! empty($canvas)) { - require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; - $objcanvas = new Canvas($db,$action); - $objcanvas->getCanvas('product','list',$canvas); + require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; + $objcanvas = new Canvas($db,$action); + $objcanvas->getCanvas('product','list',$canvas); } // Security check @@ -123,16 +123,16 @@ else $result=restrictedArea($user,'produit|service','','','','','',$objcanvas); $virtualdiffersfromphysical=0; if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { - $virtualdiffersfromphysical=1; // According to increase/decrease stock options, virtual and physical stock may differs. + $virtualdiffersfromphysical=1; // According to increase/decrease stock options, virtual and physical stock may differs. } // List of fields to search into when doing a "search in all" $fieldstosearchall = array( 'p.ref'=>"Ref", - 'pfp.ref_fourn'=>"RefSupplier", + 'pfp.ref_fourn'=>"RefSupplier", 'p.label'=>"ProductLabel", 'p.description'=>"Description", - "p.note"=>"Note", + "p.note"=>"Note", ); // multilang if (! empty($conf->global->MAIN_MULTILANGS)) @@ -156,34 +156,34 @@ if (empty($conf->global->PRODUIT_MULTIPRICES)) // Definition of fields for lists $arrayfields=array( - 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - //'pfp.ref_fourn'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))), - 'p.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), - 'p.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(! empty($conf->produit->enabled) && ! empty($conf->service->enabled))), - 'p.barcode'=>array('label'=>$langs->trans("Gencod"), 'checked'=>($contextpage != 'servicelist'), 'enabled'=>(! empty($conf->barcode->enabled))), - 'p.duration'=>array('label'=>$langs->trans("Duration"), 'checked'=>($contextpage != 'productlist'), 'enabled'=>(! empty($conf->service->enabled))), + 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + //'pfp.ref_fourn'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))), + 'p.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), + 'p.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(! empty($conf->produit->enabled) && ! empty($conf->service->enabled))), + 'p.barcode'=>array('label'=>$langs->trans("Gencod"), 'checked'=>($contextpage != 'servicelist'), 'enabled'=>(! empty($conf->barcode->enabled))), + 'p.duration'=>array('label'=>$langs->trans("Duration"), 'checked'=>($contextpage != 'productlist'), 'enabled'=>(! empty($conf->service->enabled))), 'p.sellprice'=>array('label'=>$langs->trans("SellingPrice"), 'checked'=>1, 'enabled'=>empty($conf->global->PRODUIT_MULTIPRICES)), - 'p.minbuyprice'=>array('label'=>$langs->trans("BuyingPriceMinShort"), 'checked'=>1, 'enabled'=>(! empty($user->rights->fournisseur->lire))), + 'p.minbuyprice'=>array('label'=>$langs->trans("BuyingPriceMinShort"), 'checked'=>1, 'enabled'=>(! empty($user->rights->fournisseur->lire))), 'p.numbuyprice'=>array('label'=>$langs->trans("BuyingPriceNumShort"), 'checked'=>0, 'enabled'=>(! empty($user->rights->fournisseur->lire))), 'p.pmp'=>array('label'=>$langs->trans("PMPValueShort"), 'checked'=>0, 'enabled'=>(! empty($user->rights->fournisseur->lire))), 'p.seuil_stock_alerte'=>array('label'=>$langs->trans("StockLimit"), 'checked'=>0, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical)), - 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(! empty($conf->productbatch->enabled))), + 'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), + 'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), + 'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical)), + 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(! empty($conf->productbatch->enabled))), 'p.accountancy_code_sell'=>array('label'=>$langs->trans("ProductAccountancySellCode"), 'checked'=>0), 'p.accountancy_code_buy'=>array('label'=>$langs->trans("ProductAccountancyBuyCode"), 'checked'=>0), 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'p.tosell'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Sell").')', 'checked'=>1, 'position'=>1000), - 'p.tobuy'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Buy").')', 'checked'=>1, 'position'=>1000) + 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'p.tosell'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Sell").')', 'checked'=>1, 'position'=>1000), + 'p.tobuy'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Buy").')', 'checked'=>1, 'position'=>1000) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + 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'=>$extrafields->attribute_perms[$key]); } } @@ -202,35 +202,35 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $sall=""; - $search_ref=""; - $search_label=""; - $search_barcode=""; - $search_categ=0; - $search_tosell=""; - $search_tobuy=""; - $search_tobatch=''; - $search_type=''; - $search_accountancy_code_sell=''; - $search_accountancy_code_buy=''; - $search_array_options=array(); - } - - // Mass actions - $objectclass='Product'; - if ((string) $search_type == '1') { $objectlabel='Services'; } - if ((string) $search_type == '0') { $objectlabel='Products'; } - - $permtoread = $user->rights->produit->lire; - $permtodelete = $user->rights->produit->supprimer; - $uploaddir = $conf->product->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $sall=""; + $search_ref=""; + $search_label=""; + $search_barcode=""; + $search_categ=0; + $search_tosell=""; + $search_tobuy=""; + $search_tobatch=''; + $search_type=''; + $search_accountancy_code_sell=''; + $search_accountancy_code_buy=''; + $search_array_options=array(); + } + + // Mass actions + $objectclass='Product'; + if ((string) $search_type == '1') { $objectlabel='Services'; } + if ((string) $search_type == '0') { $objectlabel='Products'; } + + $permtoread = $user->rights->produit->lire; + $permtodelete = $user->rights->produit->supprimer; + $uploaddir = $conf->product->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -243,7 +243,7 @@ $htmlother=new FormOther($db); if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { $objcanvas->assign_values($action); // This must contains code to load data (must call LoadListDatas($limit, $offset, $sortfield, $sortorder)) - $objcanvas->display_canvas($action); // This is code to show template + $objcanvas->display_canvas($action); // This is code to show template } else { @@ -265,24 +265,24 @@ else $texte = $langs->trans("ProductsAndServices"); } - $sql = 'SELECT DISTINCT p.rowid, p.ref, p.label, p.fk_product_type, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,'; - $sql.= ' p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,'; - $sql.= ' p.tobatch, p.accountancy_code_sell, p.accountancy_code_buy,'; - $sql.= ' p.datec as date_creation, p.tms as date_update, p.pmp,'; - //$sql.= ' pfp.ref_fourn as ref_supplier, '; - $sql.= ' MIN(pfp.unitprice) as minsellprice'; + $sql = 'SELECT DISTINCT p.rowid, p.ref, p.label, p.fk_product_type, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,'; + $sql.= ' p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,'; + $sql.= ' p.tobatch, p.accountancy_code_sell, p.accountancy_code_buy,'; + $sql.= ' p.datec as date_creation, p.tms as date_update, p.pmp,'; + //$sql.= ' pfp.ref_fourn as ref_supplier, '; + $sql.= ' MIN(pfp.unitprice) as minsellprice'; if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($search_type === 0)) { $sql .= ', pac.rowid prod_comb_id'; } // Add fields from extrafields - foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : ''); + 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.'product as p'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'product as p'; if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields as ef on (p.rowid = ef.fk_object)"; - if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; // We'll need this table joined to the select in order to filter by categ + if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; // We'll need this table joined to the select in order to filter by categ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; // multilang if (! empty($conf->global->MAIN_MULTILANGS)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang = '".$langs->getDefaultLang() ."'"; @@ -292,27 +292,27 @@ else $sql.= ' WHERE p.entity IN ('.getEntity('product').')'; if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); - // if the type is not 1, we show all products (type = 0,2,3) - if (dol_strlen($search_type) && $search_type != '-1') - { - if ($search_type == 1) $sql.= " AND p.fk_product_type = 1"; - else $sql.= " AND p.fk_product_type <> 1"; - } + // if the type is not 1, we show all products (type = 0,2,3) + if (dol_strlen($search_type) && $search_type != '-1') + { + if ($search_type == 1) $sql.= " AND p.fk_product_type = 1"; + else $sql.= " AND p.fk_product_type <> 1"; + } if ($search_ref) $sql .= natural_search('p.ref', $search_ref); if ($search_label) $sql .= natural_search('p.label', $search_label); if ($search_barcode) $sql .= natural_search('p.barcode', $search_barcode); - if (isset($search_tosell) && dol_strlen($search_tosell) > 0 && $search_tosell!=-1) $sql.= " AND p.tosell = ".$db->escape($search_tosell); - if (isset($search_tobuy) && dol_strlen($search_tobuy) > 0 && $search_tobuy!=-1) $sql.= " AND p.tobuy = ".$db->escape($search_tobuy); - if (dol_strlen($canvas) > 0) $sql.= " AND p.canvas = '".$db->escape($canvas)."'"; - if ($catid > 0) $sql.= " AND cp.fk_categorie = ".$catid; - if ($catid == -2) $sql.= " AND cp.fk_categorie IS NULL"; - if ($search_categ > 0) $sql.= " AND cp.fk_categorie = ".$db->escape($search_categ); - if ($search_categ == -2) $sql.= " AND cp.fk_categorie IS NULL"; - if ($fourn_id > 0) $sql.= " AND pfp.fk_soc = ".$fourn_id; - if ($search_tobatch != '' && $search_tobatch >= 0) $sql.= " AND p.tobatch = ".$db->escape($search_tobatch); - if ($search_accountancy_code_sell) $sql.= natural_search('p.accountancy_code_sell', $search_accountancy_code_sell); - if ($search_accountancy_code_buy) $sql.= natural_search('p.accountancy_code_buy', $search_accountancy_code_buy); - // Add where from extra fields + if (isset($search_tosell) && dol_strlen($search_tosell) > 0 && $search_tosell!=-1) $sql.= " AND p.tosell = ".$db->escape($search_tosell); + if (isset($search_tobuy) && dol_strlen($search_tobuy) > 0 && $search_tobuy!=-1) $sql.= " AND p.tobuy = ".$db->escape($search_tobuy); + if (dol_strlen($canvas) > 0) $sql.= " AND p.canvas = '".$db->escape($canvas)."'"; + if ($catid > 0) $sql.= " AND cp.fk_categorie = ".$catid; + if ($catid == -2) $sql.= " AND cp.fk_categorie IS NULL"; + if ($search_categ > 0) $sql.= " AND cp.fk_categorie = ".$db->escape($search_categ); + if ($search_categ == -2) $sql.= " AND cp.fk_categorie IS NULL"; + if ($fourn_id > 0) $sql.= " AND pfp.fk_soc = ".$fourn_id; + if ($search_tobatch != '' && $search_tobatch >= 0) $sql.= " AND p.tobatch = ".$db->escape($search_tobatch); + if ($search_accountancy_code_sell) $sql.= natural_search('p.accountancy_code_sell', $search_accountancy_code_sell); + if ($search_accountancy_code_buy) $sql.= natural_search('p.accountancy_code_buy', $search_accountancy_code_buy); + // Add where from extra fields if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($search_type === 0)) { $sql .= " AND pac.rowid IS NULL"; @@ -321,171 +321,171 @@ else // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // 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; - $sql.= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type,"; - $sql.= " p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,"; - $sql.= ' p.datec, p.tms, p.entity, p.tobatch, p.accountancy_code_sell, p.accountancy_code_buy, p.pmp'; + $sql.= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type,"; + $sql.= " p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,"; + $sql.= ' p.datec, p.tms, p.entity, p.tobatch, p.accountancy_code_sell, p.accountancy_code_buy, p.pmp'; if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($search_type === 0)) { $sql .= ', pac.rowid'; } // Add fields from extrafields - foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); + foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); // Add fields from hooks $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldSelect',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; - //if (GETPOST("toolowstock")) $sql.= " HAVING SUM(s.reel) < p.seuil_stock_alerte"; // Not used yet - $sql.= $db->order($sortfield,$sortorder); + //if (GETPOST("toolowstock")) $sql.= " HAVING SUM(s.reel) < p.seuil_stock_alerte"; // Not used yet + $sql.= $db->order($sortfield,$sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); } - $sql.= $db->plimit($limit + 1, $offset); - - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - - $arrayofselected=is_array($toselect)?$toselect:array(); - - if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/product/card.php?id='.$id); - exit; - } - - $helpurl=''; - if ($search_type != '') - { - if ($search_type == 0) - { - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; - } - else if ($search_type == 1) - { - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; - } - } - - llxHeader('',$title,$helpurl,''); - - // Displays product removal confirmation - if (GETPOST('delprod')) { - setEventMessages($langs->trans("ProductDeleted", GETPOST('delprod')), null, 'mesgs'); - } - - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($sall) $param.="&sall=".urlencode($sall); - if ($search_categ > 0) $param.="&search_categ=".urlencode($search_categ); - if ($search_ref) $param="&search_ref=".urlencode($search_ref); - if ($search_ref_supplier) $param="&search_ref_supplier=".urlencode($search_ref_supplier); - if ($search_barcode) $param.=($search_barcode?"&search_barcode=".urlencode($search_barcode):""); - if ($search_label) $param.="&search_label=".urlencode($search_label); - if ($search_tosell != '') $param.="&search_tosell=".urlencode($search_tosell); - if ($search_tobuy != '') $param.="&search_tobuy=".urlencode($search_tobuy); - if ($fourn_id > 0) $param.=($fourn_id?"&fourn_id=".$fourn_id:""); - if ($seach_categ) $param.=($search_categ?"&search_categ=".urlencode($search_categ):""); - if ($type != '') $param.='&type='.urlencode($type); - if ($search_type != '') $param.='&search_type='.urlencode($search_type); - if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); - if ($search_tobatch) $param="&search_ref_supplier=".urlencode($search_ref_supplier); - if ($search_accountancy_code_sell) $param="&search_accountancy_code_sell=".urlencode($search_accountancy_code_sell); - if ($search_accountancy_code_buy) $param="&search_accountancy_code_buy=".urlencode($search_accountancy_code_buy); - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - // List of mass actions available - $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), - ); - if ($user->rights->produit->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - if ($massaction == 'presend' || $massaction == 'createbills') $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + $sql.= $db->plimit($limit + 1, $offset); + + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + + $arrayofselected=is_array($toselect)?$toselect:array(); + + if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) + { + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/product/card.php?id='.$id); + exit; + } + + $helpurl=''; + if ($search_type != '') + { + if ($search_type == 0) + { + $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + } + else if ($search_type == 1) + { + $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + } + } + + llxHeader('',$title,$helpurl,''); + + // Displays product removal confirmation + if (GETPOST('delprod')) { + setEventMessages($langs->trans("ProductDeleted", GETPOST('delprod')), null, 'mesgs'); + } + + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); + if ($sall) $param.="&sall=".urlencode($sall); + if ($search_categ > 0) $param.="&search_categ=".urlencode($search_categ); + if ($search_ref) $param="&search_ref=".urlencode($search_ref); + if ($search_ref_supplier) $param="&search_ref_supplier=".urlencode($search_ref_supplier); + if ($search_barcode) $param.=($search_barcode?"&search_barcode=".urlencode($search_barcode):""); + if ($search_label) $param.="&search_label=".urlencode($search_label); + if ($search_tosell != '') $param.="&search_tosell=".urlencode($search_tosell); + if ($search_tobuy != '') $param.="&search_tobuy=".urlencode($search_tobuy); + if ($fourn_id > 0) $param.=($fourn_id?"&fourn_id=".$fourn_id:""); + if ($seach_categ) $param.=($search_categ?"&search_categ=".urlencode($search_categ):""); + if ($type != '') $param.='&type='.urlencode($type); + if ($search_type != '') $param.='&search_type='.urlencode($search_type); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + if ($search_tobatch) $param="&search_ref_supplier=".urlencode($search_ref_supplier); + if ($search_accountancy_code_sell) $param="&search_accountancy_code_sell=".urlencode($search_accountancy_code_sell); + if ($search_accountancy_code_buy) $param="&search_accountancy_code_buy=".urlencode($search_accountancy_code_buy); + // Add $param from extra fields + foreach ($search_array_options as $key => $val) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } + + // List of mass actions available + $arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), + ); + if ($user->rights->produit->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + if ($massaction == 'presend' || $massaction == 'createbills') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); print '<form action="'.$_SERVER["PHP_SELF"].'" method="post" name="formulaire">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; - print '<input type="hidden" name="page" value="'.$page.'">'; - print '<input type="hidden" name="type" value="'.$type.'">'; - if (empty($arrayfields['p.fk_product_type']['checked'])) print '<input type="hidden" name="search_type" value="'.dol_escape_htmltag($search_type).'">'; - - print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_products.png', 0, '', '', $limit); - - if (! empty($catid)) - { - print "<div id='ways'>"; - $c = new Categorie($db); - $ways = $c->print_all_ways(' > ','product/list.php'); - print " > ".$ways[0]."<br>\n"; - print "</div><br>"; - } - - if (! empty($canvas) && file_exists(DOL_DOCUMENT_ROOT.'/product/canvas/'.$canvas.'/actions_card_'.$canvas.'.class.php')) - { - $fieldlist = $object->field_list; - $datas = $object->list_datas; - $picto='title.png'; - $title_picto = img_picto('',$picto); - $title_text = $title; - - // Default templates directory - $template_dir = DOL_DOCUMENT_ROOT . '/product/canvas/'.$canvas.'/tpl/'; - // Check if a custom template is present - if (file_exists(DOL_DOCUMENT_ROOT . '/theme/'.$conf->theme.'/tpl/product/'.$canvas.'/list.tpl.php')) - { - $template_dir = DOL_DOCUMENT_ROOT . '/theme/'.$conf->theme.'/tpl/product/'.$canvas.'/'; - } - - include $template_dir.'list.tpl.php'; // Include native PHP templates - } - else - { - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } - - // Filter on categories - $moreforfilter=''; - if (! empty($conf->categorie->enabled)) - { - $moreforfilter.='<div class="divsearchfield">'; - $moreforfilter.=$langs->trans('Categories'). ': '; - $moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT,$search_categ,'search_categ',1); - $moreforfilter.='</div>'; - } + print '<input type="hidden" name="page" value="'.$page.'">'; + print '<input type="hidden" name="type" value="'.$type.'">'; + if (empty($arrayfields['p.fk_product_type']['checked'])) print '<input type="hidden" name="search_type" value="'.dol_escape_htmltag($search_type).'">'; + + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_products.png', 0, '', '', $limit); + + if (! empty($catid)) + { + print "<div id='ways'>"; + $c = new Categorie($db); + $ways = $c->print_all_ways(' > ','product/list.php'); + print " > ".$ways[0]."<br>\n"; + print "</div><br>"; + } + + if (! empty($canvas) && file_exists(DOL_DOCUMENT_ROOT.'/product/canvas/'.$canvas.'/actions_card_'.$canvas.'.class.php')) + { + $fieldlist = $object->field_list; + $datas = $object->list_datas; + $picto='title.png'; + $title_picto = img_picto('',$picto); + $title_text = $title; + + // Default templates directory + $template_dir = DOL_DOCUMENT_ROOT . '/product/canvas/'.$canvas.'/tpl/'; + // Check if a custom template is present + if (file_exists(DOL_DOCUMENT_ROOT . '/theme/'.$conf->theme.'/tpl/product/'.$canvas.'/list.tpl.php')) + { + $template_dir = DOL_DOCUMENT_ROOT . '/theme/'.$conf->theme.'/tpl/product/'.$canvas.'/'; + } + + include $template_dir.'list.tpl.php'; // Include native PHP templates + } + else + { + if ($sall) + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } + + // Filter on categories + $moreforfilter=''; + if (! empty($conf->categorie->enabled)) + { + $moreforfilter.='<div class="divsearchfield">'; + $moreforfilter.=$langs->trans('Categories'). ': '; + $moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT,$search_categ,'search_categ',1); + $moreforfilter.='</div>'; + } //Show/hide child products. Hidden by default if (!empty($conf->variants->enabled) && $search_type === 0) { @@ -495,117 +495,117 @@ else $moreforfilter.='</div>'; } - if ($moreforfilter) - { - print '<div class="liste_titre liste_titre_bydiv centpercent">'; - print $moreforfilter; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - print '</div>'; - } + if ($moreforfilter) + { + print '<div class="liste_titre liste_titre_bydiv centpercent">'; + print $moreforfilter; + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + print '</div>'; + } $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); - - print '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; - - // Lines with input filters - print '<tr class="liste_titre_filter">'; - if (! empty($arrayfields['p.ref']['checked'])) - { - print '<td class="liste_titre" align="left">'; - print '<input class="flat" type="text" name="search_ref" size="8" value="'.dol_escape_htmltag($search_ref).'">'; - print '</td>'; - } - if (! empty($arrayfields['pfp.ref_fourn']['checked'])) - { - print '<td class="liste_titre" align="left">'; - print '<input class="flat" type="text" name="search_ref_supplier" size="8" value="'.dol_escape_htmltag($search_ref_supplier).'">'; - print '</td>'; - } - if (! empty($arrayfields['p.label']['checked'])) - { - print '<td class="liste_titre" align="left">'; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + + print '<div class="div-table-responsive">'; + print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; + + // Lines with input filters + print '<tr class="liste_titre_filter">'; + if (! empty($arrayfields['p.ref']['checked'])) + { + print '<td class="liste_titre" align="left">'; + print '<input class="flat" type="text" name="search_ref" size="8" value="'.dol_escape_htmltag($search_ref).'">'; + print '</td>'; + } + if (! empty($arrayfields['pfp.ref_fourn']['checked'])) + { + print '<td class="liste_titre" align="left">'; + print '<input class="flat" type="text" name="search_ref_supplier" size="8" value="'.dol_escape_htmltag($search_ref_supplier).'">'; + print '</td>'; + } + if (! empty($arrayfields['p.label']['checked'])) + { + print '<td class="liste_titre" align="left">'; print '<input class="flat" type="text" name="search_label" size="12" value="'.dol_escape_htmltag($search_label).'">'; - print '</td>'; - } - // Type - if (! empty($arrayfields['p.fk_product_type']['checked'])) - { - print '<td class="liste_titre" align="left">'; + print '</td>'; + } + // Type + if (! empty($arrayfields['p.fk_product_type']['checked'])) + { + print '<td class="liste_titre" align="left">'; $array=array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); - print $form->selectarray('search_type', $array, $search_type); - print '</td>'; - } - // Barcode - if (! empty($arrayfields['p.barcode']['checked'])) - { - print '<td class="liste_titre">'; - print '<input class="flat" type="text" name="search_barcode" size="6" value="'.dol_escape_htmltag($search_barcode).'">'; - print '</td>'; - } - // Duration + print $form->selectarray('search_type', $array, $search_type); + print '</td>'; + } + // Barcode + if (! empty($arrayfields['p.barcode']['checked'])) + { + print '<td class="liste_titre">'; + print '<input class="flat" type="text" name="search_barcode" size="6" value="'.dol_escape_htmltag($search_barcode).'">'; + print '</td>'; + } + // Duration if (! empty($arrayfields['p.duration']['checked'])) - { - print '<td class="liste_titre">'; - print ' '; - print '</td>'; - } - // Sell price + { + print '<td class="liste_titre">'; + print ' '; + print '</td>'; + } + // Sell price if (! empty($arrayfields['p.sellprice']['checked'])) - { - print '<td class="liste_titre" align="right">'; - print '</td>'; - } - // Minimum buying Price + { + print '<td class="liste_titre" align="right">'; + print '</td>'; + } + // Minimum buying Price if (! empty($arrayfields['p.minbuyprice']['checked'])) - { - print '<td class="liste_titre">'; - print ' '; - print '</td>'; - } + { + print '<td class="liste_titre">'; + print ' '; + print '</td>'; + } // Number buying Price if (! empty($arrayfields['p.numbuyprice']['checked'])) - { - print '<td class="liste_titre">'; - print ' '; - print '</td>'; - } + { + print '<td class="liste_titre">'; + print ' '; + print '</td>'; + } // WAP if (! empty($arrayfields['p.pmp']['checked'])) - { - print '<td class="liste_titre">'; - print ' '; - print '</td>'; - } - // Limit for alert + { + print '<td class="liste_titre">'; + print ' '; + print '</td>'; + } + // Limit for alert if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) - { - print '<td class="liste_titre">'; - print ' '; - print '</td>'; - } - // Desired stock + { + print '<td class="liste_titre">'; + print ' '; + print '</td>'; + } + // Desired stock if (! empty($arrayfields['p.desiredstock']['checked'])) - { - print '<td class="liste_titre">'; - print ' '; - print '</td>'; - } - // Stock + { + print '<td class="liste_titre">'; + print ' '; + print '</td>'; + } + // Stock if (! empty($arrayfields['p.stock']['checked'])) print '<td class="liste_titre"> </td>'; - // Stock + // Stock if (! empty($arrayfields['stock_virtual']['checked'])) print '<td class="liste_titre"> </td>'; // To batch if (! empty($arrayfields['p.tobatch']['checked'])) print '<td class="liste_titre center">'.$form->selectyesno($search_tobatch, '', '', '', 1).'</td>'; // Accountancy code sell - if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" name="search_accountancy_code_sell" size="6" value="'.dol_escape_htmltag($search_accountancy_code_sell).'"></td>'; - // Accountancy code sell - if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" name="search_accountancy_code_buy" size="6" value="'.dol_escape_htmltag($search_accountancy_code_buy).'"></td>'; - // Extra fields + if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" name="search_accountancy_code_sell" size="6" value="'.dol_escape_htmltag($search_accountancy_code_sell).'"></td>'; + // Accountancy code sell + if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" name="search_accountancy_code_buy" size="6" value="'.dol_escape_htmltag($search_accountancy_code_buy).'"></td>'; + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) @@ -632,221 +632,221 @@ else } } } - // Fields from hook + // 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; - // Date creation - if (! empty($arrayfields['p.datec']['checked'])) - { - print '<td class="liste_titre">'; - print '</td>'; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print '<td class="liste_titre">'; - print '</td>'; - } - if (! empty($arrayfields['p.tosell']['checked'])) - { - print '<td class="liste_titre" align="right">'; - print $form->selectarray('search_tosell', array('0'=>$langs->trans('ProductStatusNotOnSellShort'),'1'=>$langs->trans('ProductStatusOnSellShort')),$search_tosell,1); - print '</td >'; - } + $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['p.datec']['checked'])) + { + print '<td class="liste_titre">'; + print '</td>'; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print '<td class="liste_titre">'; + print '</td>'; + } + if (! empty($arrayfields['p.tosell']['checked'])) + { + print '<td class="liste_titre" align="right">'; + print $form->selectarray('search_tosell', array('0'=>$langs->trans('ProductStatusNotOnSellShort'),'1'=>$langs->trans('ProductStatusOnSellShort')),$search_tosell,1); + print '</td >'; + } if (! empty($arrayfields['p.tobuy']['checked'])) - { - print '<td class="liste_titre" align="right">'; - print $form->selectarray('search_tobuy', array('0'=>$langs->trans('ProductStatusNotOnBuyShort'),'1'=>$langs->trans('ProductStatusOnBuyShort')),$search_tobuy,1); - print '</td>'; - } - print '<td class="liste_titre" align="middle">'; - $searchpicto=$form->showFilterButtons(); - print $searchpicto; - print '</td>'; - - print '</tr>'; - - print '<tr class="liste_titre">'; - if (! empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"],"p.ref","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['pfp.ref_fourn']['checked'])) print_liste_field_titre($arrayfields['pfp.ref_fourn']['label'], $_SERVER["PHP_SELF"],"pfp.ref_fourn","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['p.label']['checked'])) print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"],"p.label","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['p.fk_product_type']['checked'])) print_liste_field_titre($arrayfields['p.fk_product_type']['label'], $_SERVER["PHP_SELF"],"p.fk_product_type","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['p.barcode']['checked'])) print_liste_field_titre($arrayfields['p.barcode']['label'], $_SERVER["PHP_SELF"],"p.barcode","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['p.duration']['checked'])) print_liste_field_titre($arrayfields['p.duration']['label'], $_SERVER["PHP_SELF"],"p.duration","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['p.sellprice']['checked'])) print_liste_field_titre($arrayfields['p.sellprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.minbuyprice']['checked'])) print_liste_field_titre($arrayfields['p.minbuyprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.numbuyprice']['checked'])) print_liste_field_titre($arrayfields['p.numbuyprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.pmp']['checked'])) print_liste_field_titre($arrayfields['p.pmp']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) print_liste_field_titre($arrayfields['p.seuil_stock_alerte']['label'], $_SERVER["PHP_SELF"],"p.seuil_stock_alerte","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.desiredstock']['checked'])) print_liste_field_titre($arrayfields['p.desiredstock']['label'], $_SERVER["PHP_SELF"],"p.desiredstock","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.stock']['checked'])) print_liste_field_titre($arrayfields['p.stock']['label'], $_SERVER["PHP_SELF"],"p.stock","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['stock_virtual']['checked'])) print_liste_field_titre($arrayfields['stock_virtual']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.tobatch']['checked'])) print_liste_field_titre($arrayfields['p.tobatch']['label'], $_SERVER["PHP_SELF"],"p.tobatch","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) print_liste_field_titre($arrayfields['p.accountancy_code_sell']['label'], $_SERVER["PHP_SELF"],"p.accountancy_code_sell","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) print_liste_field_titre($arrayfields['p.accountancy_code_buy']['label'], $_SERVER["PHP_SELF"],"p.accountancy_code_buy","",$param,'',$sortfield,$sortorder); - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['p.tosell']['checked'])) print_liste_field_titre($arrayfields['p.tosell']['label'],$_SERVER["PHP_SELF"],"p.tosell","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.tobuy']['checked'])) print_liste_field_titre($arrayfields['p.tobuy']['label'],$_SERVER["PHP_SELF"],"p.tobuy","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "</tr>\n"; - - - $product_static=new Product($db); - $product_fourn =new ProductFournisseur($db); - - $i = 0; - $totalarray=array(); - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); - - // Multilangs - if (! empty($conf->global->MAIN_MULTILANGS)) // si l'option est active - { - $sql = "SELECT label"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sql.= " WHERE fk_product=".$obj->rowid; - $sql.= " AND lang='". $langs->getDefaultLang() ."'"; - $sql.= " LIMIT 1"; - - $result = $db->query($sql); - if ($result) - { - $objtp = $db->fetch_object($result); - if (! empty($objtp->label)) $obj->label = $objtp->label; - } - } - - $product_static->id = $obj->rowid; - $product_static->ref = $obj->ref; - $product_static->ref_fourn = $obj->ref_supplier; - $product_static->label = $obj->label; - $product_static->type = $obj->fk_product_type; - $product_static->status_buy = $obj->tobuy; - $product_static->status = $obj->tosell; + { + print '<td class="liste_titre" align="right">'; + print $form->selectarray('search_tobuy', array('0'=>$langs->trans('ProductStatusNotOnBuyShort'),'1'=>$langs->trans('ProductStatusOnBuyShort')),$search_tobuy,1); + print '</td>'; + } + print '<td class="liste_titre" align="middle">'; + $searchpicto=$form->showFilterButtons(); + print $searchpicto; + print '</td>'; + + print '</tr>'; + + print '<tr class="liste_titre">'; + if (! empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"],"p.ref","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['pfp.ref_fourn']['checked'])) print_liste_field_titre($arrayfields['pfp.ref_fourn']['label'], $_SERVER["PHP_SELF"],"pfp.ref_fourn","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['p.label']['checked'])) print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"],"p.label","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['p.fk_product_type']['checked'])) print_liste_field_titre($arrayfields['p.fk_product_type']['label'], $_SERVER["PHP_SELF"],"p.fk_product_type","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['p.barcode']['checked'])) print_liste_field_titre($arrayfields['p.barcode']['label'], $_SERVER["PHP_SELF"],"p.barcode","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['p.duration']['checked'])) print_liste_field_titre($arrayfields['p.duration']['label'], $_SERVER["PHP_SELF"],"p.duration","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['p.sellprice']['checked'])) print_liste_field_titre($arrayfields['p.sellprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.minbuyprice']['checked'])) print_liste_field_titre($arrayfields['p.minbuyprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.numbuyprice']['checked'])) print_liste_field_titre($arrayfields['p.numbuyprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.pmp']['checked'])) print_liste_field_titre($arrayfields['p.pmp']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) print_liste_field_titre($arrayfields['p.seuil_stock_alerte']['label'], $_SERVER["PHP_SELF"],"p.seuil_stock_alerte","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.desiredstock']['checked'])) print_liste_field_titre($arrayfields['p.desiredstock']['label'], $_SERVER["PHP_SELF"],"p.desiredstock","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.stock']['checked'])) print_liste_field_titre($arrayfields['p.stock']['label'], $_SERVER["PHP_SELF"],"p.stock","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['stock_virtual']['checked'])) print_liste_field_titre($arrayfields['stock_virtual']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.tobatch']['checked'])) print_liste_field_titre($arrayfields['p.tobatch']['label'], $_SERVER["PHP_SELF"],"p.tobatch","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) print_liste_field_titre($arrayfields['p.accountancy_code_sell']['label'], $_SERVER["PHP_SELF"],"p.accountancy_code_sell","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) print_liste_field_titre($arrayfields['p.accountancy_code_buy']['label'], $_SERVER["PHP_SELF"],"p.accountancy_code_buy","",$param,'',$sortfield,$sortorder); + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } + } + // Hook fields + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['p.tosell']['checked'])) print_liste_field_titre($arrayfields['p.tosell']['label'],$_SERVER["PHP_SELF"],"p.tosell","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.tobuy']['checked'])) print_liste_field_titre($arrayfields['p.tobuy']['label'],$_SERVER["PHP_SELF"],"p.tobuy","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); + print "</tr>\n"; + + + $product_static=new Product($db); + $product_fourn =new ProductFournisseur($db); + + $i = 0; + $totalarray=array(); + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); + + // Multilangs + if (! empty($conf->global->MAIN_MULTILANGS)) // si l'option est active + { + $sql = "SELECT label"; + $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql.= " WHERE fk_product=".$obj->rowid; + $sql.= " AND lang='". $langs->getDefaultLang() ."'"; + $sql.= " LIMIT 1"; + + $result = $db->query($sql); + if ($result) + { + $objtp = $db->fetch_object($result); + if (! empty($objtp->label)) $obj->label = $objtp->label; + } + } + + $product_static->id = $obj->rowid; + $product_static->ref = $obj->ref; + $product_static->ref_fourn = $obj->ref_supplier; + $product_static->label = $obj->label; + $product_static->type = $obj->fk_product_type; + $product_static->status_buy = $obj->tobuy; + $product_static->status = $obj->tosell; $product_static->entity = $obj->entity; $product_static->pmp = $obj->pmp; if ((! empty($conf->stock->enabled) && $user->rights->stock->lire && $search_type != 1) || ! empty($conf->global->STOCK_DISABLE_OPTIM_LOAD)) // To optimize call of load_stock { - if ($obj->fk_product_type != 1 || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) // Not a service - { - $product_static->load_stock('nobatch'); // Load stock_reel + stock_warehouse. This also call load_virtual_stock() - } + if ($obj->fk_product_type != 1 || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) // Not a service + { + $product_static->load_stock('nobatch'); // Load stock_reel + stock_warehouse. This also call load_virtual_stock() + } + } + + + print '<tr class="oddeven">'; + + // Ref + if (! empty($arrayfields['p.ref']['checked'])) + { + print '<td class="nowrap">'; + print $product_static->getNomUrl(1,'',24); + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Ref supplier + if (! empty($arrayfields['pfp.ref_fourn']['checked'])) + { + print '<td class="nowrap">'; + print $product_static->getNomUrl(1,'',24); + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Label + if (! empty($arrayfields['p.label']['checked'])) + { + print '<td>'.dol_trunc($obj->label,40).'</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Type + if (! empty($arrayfields['p.fk_product_type']['checked'])) + { + print '<td>'.$obj->fk_product_type.'</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Barcode + if (! empty($arrayfields['p.barcode']['checked'])) + { + print '<td>'.$obj->barcode.'</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Duration + if (! empty($arrayfields['p.duration']['checked'])) + { + print '<td align="center">'; + if (preg_match('/([^a-z]+)[a-z]/i',$obj->duration)) + { + if (preg_match('/([^a-z]+)y/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationYear"); + elseif (preg_match('/([^a-z]+)m/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationMonth"); + elseif (preg_match('/([^a-z]+)w/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationWeek"); + elseif (preg_match('/([^a-z]+)d/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationDay"); + //elseif (preg_match('/([^a-z]+)h/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationHour"); + else print $obj->duration; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; } + // Sell price + if (! empty($arrayfields['p.sellprice']['checked'])) + { + print '<td align="right">'; + if ($obj->tosell) + { + if ($obj->price_base_type == 'TTC') print price($obj->price_ttc).' '.$langs->trans("TTC"); + else print price($obj->price).' '.$langs->trans("HT"); + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } - print '<tr class="oddeven">'; - - // Ref - if (! empty($arrayfields['p.ref']['checked'])) - { - print '<td class="nowrap">'; - print $product_static->getNomUrl(1,'',24); - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Ref supplier - if (! empty($arrayfields['pfp.ref_fourn']['checked'])) - { - print '<td class="nowrap">'; - print $product_static->getNomUrl(1,'',24); - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Label - if (! empty($arrayfields['p.label']['checked'])) - { - print '<td>'.dol_trunc($obj->label,40).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Type - if (! empty($arrayfields['p.fk_product_type']['checked'])) - { - print '<td>'.$obj->fk_product_type.'</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Barcode - if (! empty($arrayfields['p.barcode']['checked'])) - { - print '<td>'.$obj->barcode.'</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Duration - if (! empty($arrayfields['p.duration']['checked'])) - { - print '<td align="center">'; - if (preg_match('/([^a-z]+)[a-z]/i',$obj->duration)) - { - if (preg_match('/([^a-z]+)y/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationYear"); - elseif (preg_match('/([^a-z]+)m/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationMonth"); - elseif (preg_match('/([^a-z]+)w/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationWeek"); - elseif (preg_match('/([^a-z]+)d/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationDay"); - //elseif (preg_match('/([^a-z]+)h/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationHour"); - else print $obj->duration; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Sell price - if (! empty($arrayfields['p.sellprice']['checked'])) - { - print '<td align="right">'; - if ($obj->tosell) - { - if ($obj->price_base_type == 'TTC') print price($obj->price_ttc).' '.$langs->trans("TTC"); - else print price($obj->price).' '.$langs->trans("HT"); - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Better buy price - if (! empty($arrayfields['p.minbuyprice']['checked'])) - { - print '<td align="right">'; - if ($obj->tobuy && $obj->minsellprice != '') - { - //print price($obj->minsellprice).' '.$langs->trans("HT"); - if ($product_fourn->find_min_price_product_fournisseur($obj->rowid) > 0) - { - if ($product_fourn->product_fourn_price_id > 0) - { - if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) - { - $htmltext=$product_fourn->display_price_product_fournisseur(1, 1, 0, 1); - print $form->textwithpicto(price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"),$htmltext); - } - else print price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"); - } - } - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } + // Better buy price + if (! empty($arrayfields['p.minbuyprice']['checked'])) + { + print '<td align="right">'; + if ($obj->tobuy && $obj->minsellprice != '') + { + //print price($obj->minsellprice).' '.$langs->trans("HT"); + if ($product_fourn->find_min_price_product_fournisseur($obj->rowid) > 0) + { + if ($product_fourn->product_fourn_price_id > 0) + { + if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) + { + $htmltext=$product_fourn->display_price_product_fournisseur(1, 1, 0, 1); + print $form->textwithpicto(price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"),$htmltext); + } + else print price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"); + } + } + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } // Number of buy prices if (! empty($arrayfields['p.numbuyprice']['checked'])) @@ -871,73 +871,73 @@ else print '</td>'; } - // Limit alert - if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) - { - print '<td align="right">'; - if ($obj->fk_product_type != 1) - { - print $obj->seuil_stock_alerte; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Desired stock - if (! empty($arrayfields['p.desiredstock']['checked'])) - { - print '<td align="right">'; - if ($obj->fk_product_type != 1) - { - print $obj->desiredstock; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } + // Limit alert + if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) + { + print '<td align="right">'; + if ($obj->fk_product_type != 1) + { + print $obj->seuil_stock_alerte; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Desired stock + if (! empty($arrayfields['p.desiredstock']['checked'])) + { + print '<td align="right">'; + if ($obj->fk_product_type != 1) + { + print $obj->desiredstock; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } // Stock - if (! empty($arrayfields['p.stock']['checked'])) - { + if (! empty($arrayfields['p.stock']['checked'])) + { print '<td align="right">'; - if ($obj->fk_product_type != 1) - { + if ($obj->fk_product_type != 1) + { if ($obj->seuil_stock_alerte != '' && $product_static->stock_reel < (float) $obj->seuil_stock_alerte) print img_warning($langs->trans("StockLowerThanLimit", $obj->seuil_stock_alerte)).' '; - print $product_static->stock_reel; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Stock - if (! empty($arrayfields['stock_virtual']['checked'])) - { + print $product_static->stock_reel; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Stock + if (! empty($arrayfields['stock_virtual']['checked'])) + { print '<td align="right">'; - if ($obj->fk_product_type != 1) - { + if ($obj->fk_product_type != 1) + { if ($obj->seuil_stock_alerte != '' && $product_static->stock_theorique < (float) $obj->seuil_stock_alerte) print img_warning($langs->trans("StockLowerThanLimit", $obj->seuil_stock_alerte)).' '; - print $product_static->stock_theorique; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Lot/Serial - if (! empty($arrayfields['p.tobatch']['checked'])) - { - print '<td align="center">'; - print yn($obj->tobatch); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Accountancy code sell - if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) - { - print '<td>'.$obj->accountancy_code_sell.'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Accountancy code sell - if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) - { - print '<td>'.$obj->accountancy_code_buy.'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Extra fields + print $product_static->stock_theorique; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Lot/Serial + if (! empty($arrayfields['p.tobatch']['checked'])) + { + print '<td align="center">'; + print yn($obj->tobatch); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Accountancy code sell + if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) + { + print '<td>'.$obj->accountancy_code_sell.'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Accountancy code sell + if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) + { + print '<td>'.$obj->accountancy_code_buy.'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) @@ -951,81 +951,81 @@ else $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } } } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + // 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['p.datec']['checked'])) - { - print '<td align="center">'; - print dol_print_date($obj->date_creation, 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print '<td align="center">'; - print dol_print_date($obj->date_update, 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Status (to sell) - if (! empty($arrayfields['p.tosell']['checked'])) - { - print '<td align="right" nowrap="nowrap">'; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - print ajax_object_onoff($product_static, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); - } else { - print $product_static->LibStatut($obj->tosell,5,0); - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status (to buy) - if (! empty($arrayfields['p.tobuy']['checked'])) - { - print '<td align="right" nowrap="nowrap">'; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - print ajax_object_onoff($product_static, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); - } else { - print $product_static->LibStatut($obj->tobuy,5,1); - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Action - print '<td class="nowrap" align="center">'; - 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - - print "</tr>\n"; - $i++; - } - - $db->free($resql); - - print "</table>"; - print "</div>"; - } - print '</form>'; - } - else - { - dol_print_error($db); - } + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['p.datec']['checked'])) + { + print '<td align="center">'; + print dol_print_date($obj->date_creation, 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print '<td align="center">'; + print dol_print_date($obj->date_update, 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Status (to sell) + if (! empty($arrayfields['p.tosell']['checked'])) + { + print '<td align="right" nowrap="nowrap">'; + if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + print ajax_object_onoff($product_static, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); + } else { + print $product_static->LibStatut($obj->tosell,5,0); + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status (to buy) + if (! empty($arrayfields['p.tobuy']['checked'])) + { + print '<td align="right" nowrap="nowrap">'; + if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + print ajax_object_onoff($product_static, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); + } else { + print $product_static->LibStatut($obj->tobuy,5,1); + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Action + print '<td class="nowrap" align="center">'; + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + + print "</tr>\n"; + $i++; + } + + $db->free($resql); + + print "</table>"; + print "</div>"; + } + print '</form>'; + } + else + { + dol_print_error($db); + } } diff --git a/htdocs/product/stock/productlot_list.php b/htdocs/product/stock/productlot_list.php index 7d236c904f598fffda0d1e99a75fd17b34f8108a..7880c262d04ebc4724ef0d3cbb8c147a171b7bca 100644 --- a/htdocs/product/stock/productlot_list.php +++ b/htdocs/product/stock/productlot_list.php @@ -76,7 +76,7 @@ if (! $sortorder) $sortorder="ASC"; $socid=0; if ($user->societe_id > 0) { - $socid = $user->societe_id; + $socid = $user->societe_id; //accessforbidden(); } @@ -90,31 +90,31 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 't.ref'=>'Ref', - 't.note_public'=>'NotePublic', + 't.ref'=>'Ref', + 't.note_public'=>'NotePublic', ); // Definition of fields for list $arrayfields=array( //'t.entity'=>array('label'=>$langs->trans("Fieldentity"), 'checked'=>1), 't.batch'=>array('label'=>$langs->trans("Batch"), 'checked'=>1), - 't.fk_product'=>array('label'=>$langs->trans("Product"), 'checked'=>1), + 't.fk_product'=>array('label'=>$langs->trans("Product"), 'checked'=>1), 't.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>1), 't.sellby'=>array('label'=>$langs->trans("SellByDate"), 'checked'=>1), //'t.import_key'=>array('label'=>$langs->trans("ImportKey"), 'checked'=>1), - //'t.entity'=>array('label'=>$langs->trans("Entity"), 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))), - //'t.fk_user_creat'=>array('label'=>$langs->trans("UserCreationShort"), 'checked'=>0, 'position'=>500), + //'t.entity'=>array('label'=>$langs->trans("Entity"), 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))), + //'t.fk_user_creat'=>array('label'=>$langs->trans("UserCreationShort"), 'checked'=>0, 'position'=>500), //'t.fk_user_modif'=>array('label'=>$langs->trans("UserModificationShort"), 'checked'=>0, 'position'=>500), - 't.datec'=>array('label'=>$langs->trans("DateCreationShort"), 'checked'=>0, 'position'=>500), - 't.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - //'t.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 't.datec'=>array('label'=>$langs->trans("DateCreationShort"), 'checked'=>0, 'position'=>500), + 't.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + //'t.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! 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'=>$extrafields->attribute_perms[$key]); + 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'=>$extrafields->attribute_perms[$key]); } } @@ -122,8 +122,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab $object=new Productlot($db); if (($id > 0 || ! empty($ref)) && $action != 'add') { - $result=$object->fetch($id,$ref); - if ($result < 0) dol_print_error($db); + $result=$object->fetch($id,$ref); + if ($result < 0) dol_print_error($db); } @@ -144,12 +144,12 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_entity=''; - $search_product=''; - $search_batch=''; - $search_fk_user_creat=''; - $search_fk_user_modif=''; - $search_import_key=''; + $search_entity=''; + $search_product=''; + $search_batch=''; + $search_fk_user_creat=''; + $search_fk_user_modif=''; + $search_import_key=''; $search_date_creation=''; $search_date_update=''; $toselect=''; @@ -159,12 +159,12 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', if (empty($reshook)) { - $objectclass='ProductLot'; - $objectlabel='LotSerial'; - $permtoread = $user->rights->stock->read; - $permtodelete = $user->rights->stock->delete; - $uploaddir = $conf->stock->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + $objectclass='ProductLot'; + $objectlabel='LotSerial'; + $permtoread = $user->rights->stock->read; + $permtodelete = $user->rights->stock->delete; + $uploaddir = $conf->stock->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -240,16 +240,16 @@ if ($sall) $sql.= natural_search(array_keys($fieldstosearchall), $sall); // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -273,325 +273,325 @@ dol_syslog($script_file, LOG_DEBUG); $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($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 ($search_entity != '') $param.= '&search_entity='.urlencode($search_entity); - if ($search_product != '') $param.= '&search_product='.urlencode($search_product); - if ($search_batch != '') $param.= '&search_batch='.urlencode($search_batch); - if ($search_fk_user_creat != '') $param.= '&search_fk_user_creat='.urlencode($search_fk_user_creat); - if ($search_fk_user_modif != '') $param.= '&search_fk_user_modif='.urlencode($search_fk_user_modif); - if ($search_import_key != '') $param.= '&search_import_key='.urlencode($search_import_key); - if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), - ); - //if ($user->rights->stock->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - if ($massaction == 'presend') $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + $num = $db->num_rows($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 ($search_entity != '') $param.= '&search_entity='.urlencode($search_entity); + if ($search_product != '') $param.= '&search_product='.urlencode($search_product); + if ($search_batch != '') $param.= '&search_batch='.urlencode($search_batch); + if ($search_fk_user_creat != '') $param.= '&search_fk_user_creat='.urlencode($search_fk_user_creat); + if ($search_fk_user_modif != '') $param.= '&search_fk_user_modif='.urlencode($search_fk_user_modif); + if ($search_import_key != '') $param.= '&search_import_key='.urlencode($search_import_key); + if ($optioncss != '') $param.='&optioncss='.$optioncss; + // Add $param from extra fields + foreach ($search_array_options as $key => $val) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } + + $arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), + ); + //if ($user->rights->stock->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + if ($massaction == 'presend') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; - print '<input type="hidden" name="action" value="list">'; + print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="page" value="'.$page.'">'; - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } - /*$moreforfilter = ''; + /*$moreforfilter = ''; $moreforfilter.='<div class="divsearchfield">'; $moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">'; $moreforfilter.= '</div>';*/ - $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; + $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; - if (! empty($moreforfilter)) + if (! empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; - print '</div>'; + print '</div>'; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - - print '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; - - // Fields title search - print '<tr class="liste_titre_filter">'; - if (! empty($arrayfields['t.entity']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_entity" value="'.$search_entity.'" size="8"></td>'; - if (! empty($arrayfields['t.batch']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_batch" value="'.$search_batch.'" size="8"></td>'; - if (! empty($arrayfields['t.fk_product']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_product" value="'.$search_product.'" size="8"></td>'; - if (! empty($arrayfields['t.eatby']['checked'])) print '<td class="liste_titre"></td>'; - if (! empty($arrayfields['t.sellby']['checked'])) print '<td class="liste_titre"></td>'; - if (! empty($arrayfields['t.fk_user_creat']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_fk_user_creat" value="'.$search_fk_user_creat.'" size="10"></td>'; - if (! empty($arrayfields['t.fk_user_modif']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_fk_user_modif" value="'.$search_fk_user_modif.'" size="10"></td>'; - if (! empty($arrayfields['t.import_key']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_import_key" value="'.$search_import_key.'" size="10"></td>'; - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } - print '</td>'; - } - } - } - // 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; - if (! empty($arrayfields['t.datec']['checked'])) - { - // Date creation - print '<td class="liste_titre">'; - print '</td>'; - } - if (! empty($arrayfields['t.tms']['checked'])) - { - // Date modification - print '<td class="liste_titre">'; - print '</td>'; - } - /*if (! empty($arrayfields['u.statut']['checked'])) + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + + print '<div class="div-table-responsive">'; + print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; + + // Fields title search + print '<tr class="liste_titre_filter">'; + if (! empty($arrayfields['t.entity']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_entity" value="'.$search_entity.'" size="8"></td>'; + if (! empty($arrayfields['t.batch']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_batch" value="'.$search_batch.'" size="8"></td>'; + if (! empty($arrayfields['t.fk_product']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_product" value="'.$search_product.'" size="8"></td>'; + if (! empty($arrayfields['t.eatby']['checked'])) print '<td class="liste_titre"></td>'; + if (! empty($arrayfields['t.sellby']['checked'])) print '<td class="liste_titre"></td>'; + if (! empty($arrayfields['t.fk_user_creat']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_fk_user_creat" value="'.$search_fk_user_creat.'" size="10"></td>'; + if (! empty($arrayfields['t.fk_user_modif']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_fk_user_modif" value="'.$search_fk_user_modif.'" size="10"></td>'; + if (! empty($arrayfields['t.import_key']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_import_key" value="'.$search_import_key.'" size="10"></td>'; + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } + print '</td>'; + } + } + } + // 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; + if (! empty($arrayfields['t.datec']['checked'])) + { + // Date creation + print '<td class="liste_titre">'; + print '</td>'; + } + if (! empty($arrayfields['t.tms']['checked'])) + { + // Date modification + print '<td class="liste_titre">'; + print '</td>'; + } + /*if (! empty($arrayfields['u.statut']['checked'])) { // Status print '<td class="liste_titre" align="center">'; print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut); print '</td>'; }*/ - // Action column - print '<td class="liste_titre" align="right">'; - $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); - print $searchpicto; - print '</td>'; - print '</tr>'."\n"; - - // Fields title - print '<tr class="liste_titre">'; - if (! empty($arrayfields['t.entity']['checked'])) print_liste_field_titre($arrayfields['t.entity']['label'],$_SERVER['PHP_SELF'],'t.entity','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.batch']['checked'])) print_liste_field_titre($arrayfields['t.batch']['label'],$_SERVER['PHP_SELF'],'t.batch','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.fk_product']['checked'])) print_liste_field_titre($arrayfields['t.fk_product']['label'],$_SERVER['PHP_SELF'],'t.fk_product','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.eatby']['checked'])) print_liste_field_titre($arrayfields['t.eatby']['label'],$_SERVER['PHP_SELF'],'t.eatby','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.sellby']['checked'])) print_liste_field_titre($arrayfields['t.sellby']['label'],$_SERVER['PHP_SELF'],'t.sellby','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.fk_user_creat']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_creat']['label'],$_SERVER['PHP_SELF'],'t.fk_user_creat','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.fk_user_modif']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_modif']['label'],$_SERVER['PHP_SELF'],'t.fk_user_modif','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.import_key']['checked'])) print_liste_field_titre($arrayfields['t.import_key']['label'],$_SERVER['PHP_SELF'],'t.import_key','',$param,'',$sortfield,$sortorder); + // Action column + print '<td class="liste_titre" align="right">'; + $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); + print $searchpicto; + print '</td>'; + print '</tr>'."\n"; + + // Fields title + print '<tr class="liste_titre">'; + if (! empty($arrayfields['t.entity']['checked'])) print_liste_field_titre($arrayfields['t.entity']['label'],$_SERVER['PHP_SELF'],'t.entity','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.batch']['checked'])) print_liste_field_titre($arrayfields['t.batch']['label'],$_SERVER['PHP_SELF'],'t.batch','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.fk_product']['checked'])) print_liste_field_titre($arrayfields['t.fk_product']['label'],$_SERVER['PHP_SELF'],'t.fk_product','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.eatby']['checked'])) print_liste_field_titre($arrayfields['t.eatby']['label'],$_SERVER['PHP_SELF'],'t.eatby','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.sellby']['checked'])) print_liste_field_titre($arrayfields['t.sellby']['label'],$_SERVER['PHP_SELF'],'t.sellby','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.fk_user_creat']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_creat']['label'],$_SERVER['PHP_SELF'],'t.fk_user_creat','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.fk_user_modif']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_modif']['label'],$_SERVER['PHP_SELF'],'t.fk_user_modif','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.import_key']['checked'])) print_liste_field_titre($arrayfields['t.import_key']['label'],$_SERVER['PHP_SELF'],'t.import_key','',$param,'',$sortfield,$sortorder); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } - // Hook fields + // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['t.datec']['checked'])) print_liste_field_titre($arrayfields['t.datec']['label'],$_SERVER["PHP_SELF"],"t.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['t.tms']['checked'])) print_liste_field_titre($arrayfields['t.tms']['label'],$_SERVER["PHP_SELF"],"t.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); //if (! empty($arrayfields['t.status']['checked'])) print_liste_field_titre($arrayfields['t.status']['label'],$_SERVER["PHP_SELF"],"t.status","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print '</tr>'."\n"; + print '</tr>'."\n"; $productlot = new Productlot($db); $i=0; $var=true; $totalarray=array(); - while ($i < min($num, $limit)) - { - $obj = $db->fetch_object($resql); - if ($obj) - { - $var = !$var; - - $productlot->id = $obj->rowid; - $productlot->batch = $obj->batch; - - // You can use here results - print '<tr class="oddeven">'; - if (! empty($arrayfields['t.entity']['checked'])) - { - print '<td>'.$obj->entity.'</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.batch']['checked'])) - { - print '<td>'.$productlot->getNomUrl(1).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.fk_product']['checked'])) - { - $productstatic->id=$obj->fk_product; - $productstatic->type=$obj->product_type; - $productstatic->ref=$obj->product_ref; - $productstatic->label=$obj->product_label; - print '<td>'.$productstatic->getNomUrl(1).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.eatby']['checked'])) - { - print '<td>'.dol_print_date($db->jdate($obj->eatby), 'day').'</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.sellby']['checked'])) - { - print '<td>'.dol_print_date($db->jdate($obj->sellby), 'day').'</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.fk_user_creat']['checked'])) - { - print '<td>'.$obj->fk_user_creat.'</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.fk_user_modif']['checked'])) - { - print '<td>'.$obj->fk_user_modif.'</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.import_key']['checked'])) - { - print '<td>'.$obj->import_key.'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } - } - // 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['t.datec']['checked'])) - { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['t.tms']['checked'])) - { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - /* + while ($i < min($num, $limit)) + { + $obj = $db->fetch_object($resql); + if ($obj) + { + $var = !$var; + + $productlot->id = $obj->rowid; + $productlot->batch = $obj->batch; + + // You can use here results + print '<tr class="oddeven">'; + if (! empty($arrayfields['t.entity']['checked'])) + { + print '<td>'.$obj->entity.'</td>'; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.batch']['checked'])) + { + print '<td>'.$productlot->getNomUrl(1).'</td>'; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.fk_product']['checked'])) + { + $productstatic->id=$obj->fk_product; + $productstatic->type=$obj->product_type; + $productstatic->ref=$obj->product_ref; + $productstatic->label=$obj->product_label; + print '<td>'.$productstatic->getNomUrl(1).'</td>'; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.eatby']['checked'])) + { + print '<td>'.dol_print_date($db->jdate($obj->eatby), 'day').'</td>'; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.sellby']['checked'])) + { + print '<td>'.dol_print_date($db->jdate($obj->sellby), 'day').'</td>'; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.fk_user_creat']['checked'])) + { + print '<td>'.$obj->fk_user_creat.'</td>'; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.fk_user_modif']['checked'])) + { + print '<td>'.$obj->fk_user_modif.'</td>'; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.import_key']['checked'])) + { + print '<td>'.$obj->import_key.'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } + } + // 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['t.datec']['checked'])) + { + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['t.tms']['checked'])) + { + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + /* if (! empty($arrayfields['u.statut']['checked'])) { $userstatic->statut=$obj->statut; print '<td align="center">'.$userstatic->getLibStatut(3).'</td>'; }*/ - // Action column - print '<td class="nowrap" align="center">'; - 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - - print '</tr>'; - } - $i++; - } - - // Show total line - if (isset($totalarray['totalhtfield'])) - { - print '<tr class="liste_total">'; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; - else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; - } - elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; - elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; - elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; - else print '<td></td>'; - } - print '</tr>'; - } - - $db->free($resql); + // Action column + print '<td class="nowrap" align="center">'; + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + + print '</tr>'; + } + $i++; + } + + // Show total line + if (isset($totalarray['totalhtfield'])) + { + print '<tr class="liste_total">'; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; + else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; + } + elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; + elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; + elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; + else print '<td></td>'; + } + print '</tr>'; + } + + $db->free($resql); $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); $reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '</table>'."\n"; - print '</div>'; + print '</div>'; print '</form>'."\n"; @@ -616,8 +616,8 @@ if ($resql) } else { - $error++; - dol_print_error($db); + $error++; + dol_print_error($db); } diff --git a/htdocs/projet/tasks/list.php b/htdocs/projet/tasks/list.php index ccc2c12584e51e4355f60ea5989a618c4e8c54a3..12c8eb2038eb3fabd503e159488bd1a7642f3f23 100644 --- a/htdocs/projet/tasks/list.php +++ b/htdocs/projet/tasks/list.php @@ -45,8 +45,8 @@ $search_categ=GETPOST("search_categ",'alpha'); $search_project=GETPOST('search_project'); if (! isset($_GET['search_projectstatus']) && ! isset($_POST['search_projectstatus'])) { - if ($search_all != '') $search_projectstatus=-1; - else $search_projectstatus=1; + if ($search_all != '') $search_projectstatus=-1; + else $search_projectstatus=1; } else $search_projectstatus=GETPOST('search_projectstatus'); $search_project_ref=GETPOST('search_project_ref'); @@ -99,36 +99,36 @@ if (! $sortorder) $sortorder='DESC'; // List of fields to search into when doing a "search in all" $fieldstosearchall = array( 't.ref'=>"Ref", - 't.label'=>"Label", - 't.description'=>"Description", - 't.note_public'=>"NotePublic", + 't.label'=>"Label", + 't.description'=>"Description", + 't.note_public'=>"NotePublic", ); if (empty($user->socid)) $fieldstosearchall['t.note_private']="NotePrivate"; $arrayfields=array( - 't.ref'=>array('label'=>$langs->trans("RefTask"), 'checked'=>1, 'position'=>80), - 't.label'=>array('label'=>$langs->trans("LabelTask"), 'checked'=>1, 'position'=>80), - 't.dateo'=>array('label'=>$langs->trans("DateStart"), 'checked'=>1, 'position'=>100), - 't.datee'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1, 'position'=>101), - 'p.ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>1), - 'p.title'=>array('label'=>$langs->trans("ProjectLabel"), 'checked'=>0), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>0), - 'p.fk_statut'=>array('label'=>$langs->trans("ProjectStatus"), 'checked'=>1), - 't.planned_workload'=>array('label'=>$langs->trans("PlannedWorkload"), 'checked'=>1, 'position'=>102), - 't.duration_effective'=>array('label'=>$langs->trans("TimeSpent"), 'checked'=>1, 'position'=>103), - 't.progress_calculated'=>array('label'=>$langs->trans("ProgressCalculated"), 'checked'=>1, 'position'=>104), - 't.progress'=>array('label'=>$langs->trans("ProgressDeclared"), 'checked'=>1, 'position'=>105), - 't.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 't.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - //'t.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 't.ref'=>array('label'=>$langs->trans("RefTask"), 'checked'=>1, 'position'=>80), + 't.label'=>array('label'=>$langs->trans("LabelTask"), 'checked'=>1, 'position'=>80), + 't.dateo'=>array('label'=>$langs->trans("DateStart"), 'checked'=>1, 'position'=>100), + 't.datee'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1, 'position'=>101), + 'p.ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>1), + 'p.title'=>array('label'=>$langs->trans("ProjectLabel"), 'checked'=>0), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>0), + 'p.fk_statut'=>array('label'=>$langs->trans("ProjectStatus"), 'checked'=>1), + 't.planned_workload'=>array('label'=>$langs->trans("PlannedWorkload"), 'checked'=>1, 'position'=>102), + 't.duration_effective'=>array('label'=>$langs->trans("TimeSpent"), 'checked'=>1, 'position'=>103), + 't.progress_calculated'=>array('label'=>$langs->trans("ProgressCalculated"), 'checked'=>1, 'position'=>104), + 't.progress'=>array('label'=>$langs->trans("ProgressDeclared"), 'checked'=>1, 'position'=>105), + 't.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 't.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + //'t.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! 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'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } $object = new Task($db); @@ -147,40 +147,40 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $search_all=""; - $search_categ=""; - $search_project=""; - $search_projectstatus=-1; - $search_project_ref=""; - $search_project_title=""; - $search_task_ref=""; - $search_task_label=""; - $search_task_description=""; - $search_task_user=-1; - $search_project_user=-1; - $search_sday=''; - $search_smonth=''; - $search_syear=''; - $search_eday=''; - $search_emonth=''; - $search_eyear=''; - $toselect=''; - $search_array_options=array(); - } - - // Mass actions - $objectclass='Task'; - $objectlabel='Tasks'; - $permtoread = $user->rights->projet->lire; - $permtodelete = $user->rights->projet->supprimer; - $uploaddir = $conf->projet->dir_output.'/tasks'; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search_all=""; + $search_categ=""; + $search_project=""; + $search_projectstatus=-1; + $search_project_ref=""; + $search_project_title=""; + $search_task_ref=""; + $search_task_label=""; + $search_task_description=""; + $search_task_user=-1; + $search_project_user=-1; + $search_sday=''; + $search_smonth=''; + $search_syear=''; + $search_eday=''; + $search_emonth=''; + $search_eyear=''; + $toselect=''; + $search_array_options=array(); + } + + // Mass actions + $objectclass='Task'; + $objectlabel='Tasks'; + $permtoread = $user->rights->projet->lire; + $permtodelete = $user->rights->projet->supprimer; + $uploaddir = $conf->projet->dir_output.'/tasks'; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } if (empty($search_projectstatus) && $search_projectstatus == '') $search_projectstatus=1; @@ -223,10 +223,10 @@ $sql.= " AND ctc.source = 'internal'"; $resql = $db->query($sql); if ($resql) { - while($obj = $db->fetch_object($resql)) - { - $listofprojectcontacttype[$obj->rowid]=$obj->code; - } + while($obj = $db->fetch_object($resql)) + { + $listofprojectcontacttype[$obj->rowid]=$obj->code; + } } else dol_print_error($db); if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0]='0'; // To avoid sql syntax error if not found @@ -238,10 +238,10 @@ $sql.= " AND ctc.source = 'internal'"; $resql = $db->query($sql); if ($resql) { - while($obj = $db->fetch_object($resql)) - { - $listoftaskcontacttype[$obj->rowid]=$obj->code; - } + while($obj = $db->fetch_object($resql)) + { + $listoftaskcontacttype[$obj->rowid]=$obj->code; + } } else dol_print_error($db); if (count($listoftaskcontacttype) == 0) $listoftaskcontacttype[0]='0'; // To avoid sql syntax error if not found @@ -281,35 +281,35 @@ if ($search_task_label) $sql .= natural_search('t.label', $search_task_label) if ($search_societe) $sql .= natural_search('s.nom', $search_societe); if ($search_smonth > 0) { - if ($search_syear > 0 && empty($search_sday)) - $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,$search_smonth,false))."' AND '".$db->idate(dol_get_last_day($search_syear,$search_smonth,false))."'"; - else if ($search_syear > 0 && ! empty($search_sday)) - $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_smonth, $search_sday, $search_syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_smonth, $search_sday, $search_syear))."'"; - else - $sql.= " AND date_format(t.dateo, '%m') = '".$search_smonth."'"; + if ($search_syear > 0 && empty($search_sday)) + $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,$search_smonth,false))."' AND '".$db->idate(dol_get_last_day($search_syear,$search_smonth,false))."'"; + else if ($search_syear > 0 && ! empty($search_sday)) + $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_smonth, $search_sday, $search_syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_smonth, $search_sday, $search_syear))."'"; + else + $sql.= " AND date_format(t.dateo, '%m') = '".$search_smonth."'"; } else if ($search_syear > 0) { - $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,1,false))."' AND '".$db->idate(dol_get_last_day($search_syear,12,false))."'"; + $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,1,false))."' AND '".$db->idate(dol_get_last_day($search_syear,12,false))."'"; } if ($search_emonth > 0) { - if ($search_eyear > 0 && empty($search_eday)) - $sql.= " AND t.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,$search_emonth,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,$search_emonth,false))."'"; - else if ($search_eyear > 0 && ! empty($search_eday)) - $sql.= " AND t.datee BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_emonth, $search_eday, $search_eyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_emonth, $search_eday, $search_eyear))."'"; - else - $sql.= " AND date_format(t.datee, '%m') = '".$search_emonth."'"; + if ($search_eyear > 0 && empty($search_eday)) + $sql.= " AND t.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,$search_emonth,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,$search_emonth,false))."'"; + else if ($search_eyear > 0 && ! empty($search_eday)) + $sql.= " AND t.datee BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_emonth, $search_eday, $search_eyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_emonth, $search_eday, $search_eyear))."'"; + else + $sql.= " AND date_format(t.datee, '%m') = '".$search_emonth."'"; } else if ($search_eyear > 0) { - $sql.= " AND t.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,12,false))."'"; + $sql.= " AND t.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,12,false))."'"; } if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); if ($search_projectstatus >= 0) { - if ($search_projectstatus == 99) $sql .= " AND p.fk_statut <> 2"; - else $sql .= " AND p.fk_statut = ".$db->escape($search_projectstatus); + if ($search_projectstatus == 99) $sql .= " AND p.fk_statut <> 2"; + else $sql .= " AND p.fk_statut = ".$db->escape($search_projectstatus); } if ($search_public!='') $sql .= " AND p.public = ".$db->escape($search_public); if ($search_project_user > 0) $sql.= " AND ecp.fk_c_type_contact IN (".join(',',array_keys($listofprojectcontacttype)).") AND ecp.element_id = p.rowid AND ecp.fk_socpeople = ".$search_project_user; @@ -317,16 +317,16 @@ if ($search_task_user > 0) $sql.= " AND ect.fk_c_type_contact IN (".join(',',arr // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -337,8 +337,8 @@ $sql.= $db->order($sortfield,$sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit + 1,$offset); @@ -349,8 +349,8 @@ dol_syslog("list allowed project", LOG_DEBUG); $resql = $db->query($sql); if (! $resql) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($resql); @@ -359,10 +359,10 @@ $arrayofselected=is_array($toselect)?$toselect:array(); if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { - $obj = $db->fetch_object($resql); - $id = $obj->id; - header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1'); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->id; + header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1'); + exit; } $help_url="EN:Module_Projects|FR:Module_Projets|ES:Módulo_Proyectos"; @@ -393,9 +393,9 @@ if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available @@ -425,14 +425,14 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorde if ($search_task_user == $user->id) print $langs->trans("MyTasksDesc").'<br><br>'; else { - if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("TasksOnProjectsDesc").'<br><br>'; - else print $langs->trans("TasksOnProjectsPublicDesc").'<br><br>'; + if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("TasksOnProjectsDesc").'<br><br>'; + else print $langs->trans("TasksOnProjectsPublicDesc").'<br><br>'; } if ($search_all) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); } $morehtmlfilter = ''; @@ -440,11 +440,11 @@ $morehtmlfilter = ''; // Filter on categories if (! empty($conf->categorie->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='<div class="divsearchfield">'; - $moreforfilter.=$langs->trans('ProjectCategories'). ': '; - $moreforfilter.=$formother->select_categories('project', $search_categ, 'search_categ', 1, 'maxwidth300'); - $moreforfilter.='</div>'; + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='<div class="divsearchfield">'; + $moreforfilter.=$langs->trans('ProjectCategories'). ': '; + $moreforfilter.=$formother->select_categories('project', $search_categ, 'search_categ', 1, 'maxwidth300'); + $moreforfilter.='</div>'; } // If the user can view users @@ -483,60 +483,60 @@ print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"") print '<tr class="liste_titre_filter">'; if (! empty($arrayfields['t.ref']['checked'])) { - print '<td class="liste_titre">'; - print '<input type="text" class="flat" name="search_task_ref" value="'.dol_escape_htmltag($search_task_ref).'" size="4">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input type="text" class="flat" name="search_task_ref" value="'.dol_escape_htmltag($search_task_ref).'" size="4">'; + print '</td>'; } if (! empty($arrayfields['t.label']['checked'])) { - print '<td class="liste_titre">'; - print '<input type="text" class="flat" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'" size="8">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input type="text" class="flat" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'" size="8">'; + print '</td>'; } // Start date if (! empty($arrayfields['t.dateo']['checked'])) { - print '<td class="liste_titre center">'; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_sday" value="'.$search_sday.'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="search_smonth" value="'.$search_smonth.'">'; - $formother->select_year($search_syear?$search_syear:-1,'search_syear',1, 20, 5); - print '</td>'; + print '<td class="liste_titre center">'; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_sday" value="'.$search_sday.'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="search_smonth" value="'.$search_smonth.'">'; + $formother->select_year($search_syear?$search_syear:-1,'search_syear',1, 20, 5); + print '</td>'; } // End date if (! empty($arrayfields['t.datee']['checked'])) { - print '<td class="liste_titre center">'; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_eday" value="'.$search_eday.'">'; - print '<input class="flat" type="text" size="1" maxlength="2" name="search_emonth" value="'.$search_emonth.'">'; - $formother->select_year($search_eyear?$search_eyear:-1,'search_eyear',1, 20, 5); - print '</td>'; + print '<td class="liste_titre center">'; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_eday" value="'.$search_eday.'">'; + print '<input class="flat" type="text" size="1" maxlength="2" name="search_emonth" value="'.$search_emonth.'">'; + $formother->select_year($search_eyear?$search_eyear:-1,'search_eyear',1, 20, 5); + print '</td>'; } if (! empty($arrayfields['p.ref']['checked'])) { - print '<td class="liste_titre">'; - print '<input type="text" class="flat" name="search_project_ref" value="'.$search_project_ref.'" size="4">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input type="text" class="flat" name="search_project_ref" value="'.$search_project_ref.'" size="4">'; + print '</td>'; } if (! empty($arrayfields['p.title']['checked'])) { - print '<td class="liste_titre">'; - print '<input type="text" class="flat" name="search_project_title" value="'.$search_project_title.'" size="6">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input type="text" class="flat" name="search_project_title" value="'.$search_project_title.'" size="6">'; + print '</td>'; } if (! empty($arrayfields['s.nom']['checked'])) { - print '<td class="liste_titre">'; - print '<input type="text" class="flat" name="search_societe" value="'.dol_escape_htmltag($search_societe).'" size="4">'; - print '</td>'; + print '<td class="liste_titre">'; + print '<input type="text" class="flat" name="search_societe" value="'.dol_escape_htmltag($search_societe).'" size="4">'; + print '</td>'; } if (! empty($arrayfields['p.fk_statut']['checked'])) { - print '<td class="liste_titre center">'; - $arrayofstatus = array(); - foreach($projectstatic->statuts_short as $key => $val) $arrayofstatus[$key]=$langs->trans($val); - $arrayofstatus['99']=$langs->trans("NotClosed").' ('.$langs->trans('Draft').'+'.$langs->trans('Opened').')'; + print '<td class="liste_titre center">'; + $arrayofstatus = array(); + foreach($projectstatic->statuts_short as $key => $val) $arrayofstatus[$key]=$langs->trans($val); + $arrayofstatus['99']=$langs->trans("NotClosed").' ('.$langs->trans('Draft').'+'.$langs->trans('Opened').')'; print $form->selectarray('search_projectstatus', $arrayofstatus, $search_projectstatus, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100'); - print '</td>'; + print '</td>'; } if (! empty($arrayfields['t.planned_workload']['checked'])) print '<td class="liste_titre"></td>'; if (! empty($arrayfields['t.duration_effective']['checked'])) print '<td class="liste_titre"></td>'; @@ -545,25 +545,25 @@ if (! empty($arrayfields['t.progress']['checked'])) print '<td class="liste_titr // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { - $crit=$val; + $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); $searchclass=''; if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; } - print '</td>'; - } - } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -571,15 +571,15 @@ $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // N print $hookmanager->resPrint; if (! empty($arrayfields['t.datec']['checked'])) { - // Date creation - print '<td class="liste_titre">'; - print '</td>'; + // Date creation + print '<td class="liste_titre">'; + print '</td>'; } if (! empty($arrayfields['t.tms']['checked'])) { - // Date modification - print '<td class="liste_titre">'; - print '</td>'; + // Date modification + print '<td class="liste_titre">'; + print '</td>'; } // Action column print '<td class="liste_titre" align="right">'; @@ -604,16 +604,16 @@ if (! empty($arrayfields['t.progress']['checked'])) print_liste_field_titre // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -656,157 +656,157 @@ while ($i < min($num,$limit)) { print '<tr class="oddeven">'; - // Ref - if (! empty($arrayfields['t.ref']['checked'])) - { - print '<td>'; - print $object->getNomUrl(1,'withproject'); - if ($object->hasDelay()) print img_warning("Late"); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Label - if (! empty($arrayfields['t.label']['checked'])) - { - print '<td>'; - print $object->label; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date start - if (! empty($arrayfields['t.dateo']['checked'])) - { + // Ref + if (! empty($arrayfields['t.ref']['checked'])) + { + print '<td>'; + print $object->getNomUrl(1,'withproject'); + if ($object->hasDelay()) print img_warning("Late"); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Label + if (! empty($arrayfields['t.label']['checked'])) + { + print '<td>'; + print $object->label; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date start + if (! empty($arrayfields['t.dateo']['checked'])) + { print '<td class="center">'; - print dol_print_date($db->jdate($obj->date_start),'day'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } + print dol_print_date($db->jdate($obj->date_start),'day'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } // Date end - if (! empty($arrayfields['t.datee']['checked'])) - { + if (! empty($arrayfields['t.datee']['checked'])) + { + print '<td class="center">'; + print dol_print_date($db->jdate($obj->date_end),'day'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Project ref + if (! empty($arrayfields['p.ref']['checked'])) + { + print '<td class="nowrap">'; + print $projectstatic->getNomUrl(1, 'task'); + if ($projectstatic->hasDelay()) print img_warning("Late"); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Project title + if (! empty($arrayfields['p.title']['checked'])) + { + print '<td>'; + print dol_trunc($obj->projecttitle,80); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Third party + if (! empty($arrayfields['s.nom']['checked'])) + { + print '<td>'; + if ($obj->socid) + { + $socstatic->id=$obj->socid; + $socstatic->name=$obj->name; + print $socstatic->getNomUrl(1); + } + else + { + print ' '; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Project status + if (! empty($arrayfields['p.fk_statut']['checked'])) + { + print '<td align="center">'; + print $projectstatic->getLibStatut(1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + // Planned workload + if (! empty($arrayfields['t.planned_workload']['checked'])) + { + print '<td class="center">'; + $fullhour=convertSecondToTime($obj->planned_workload,$plannedworkloadoutputformat); + $workingdelay=convertSecondToTime($obj->planned_workload,'all',86400,7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks + if ($obj->planned_workload != '') + { + print $fullhour; + // TODO Add delay taking account of working hours per day and working day per week + //if ($workingdelay != $fullhour) print '<br>('.$workingdelay.')'; + } + //else print '--:--'; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalplannedworkloadfield']=$totalarray['nbfield']; + $totalarray['totalplannedworkload'] += $obj->planned_workload; + } + // Time spent + if (! empty($arrayfields['t.duration_effective']['checked'])) + { + $showlineingray=0;$showproject=1; print '<td class="center">'; - print dol_print_date($db->jdate($obj->date_end),'day'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Project ref - if (! empty($arrayfields['p.ref']['checked'])) - { - print '<td class="nowrap">'; - print $projectstatic->getNomUrl(1, 'task'); - if ($projectstatic->hasDelay()) print img_warning("Late"); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Project title - if (! empty($arrayfields['p.title']['checked'])) - { - print '<td>'; - print dol_trunc($obj->projecttitle,80); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Third party - if (! empty($arrayfields['s.nom']['checked'])) - { - print '<td>'; - if ($obj->socid) - { - $socstatic->id=$obj->socid; - $socstatic->name=$obj->name; - print $socstatic->getNomUrl(1); - } - else - { - print ' '; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Project status - if (! empty($arrayfields['p.fk_statut']['checked'])) - { - print '<td align="center">'; - print $projectstatic->getLibStatut(1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - // Planned workload - if (! empty($arrayfields['t.planned_workload']['checked'])) - { - print '<td class="center">'; - $fullhour=convertSecondToTime($obj->planned_workload,$plannedworkloadoutputformat); - $workingdelay=convertSecondToTime($obj->planned_workload,'all',86400,7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks - if ($obj->planned_workload != '') - { - print $fullhour; - // TODO Add delay taking account of working hours per day and working day per week - //if ($workingdelay != $fullhour) print '<br>('.$workingdelay.')'; - } - //else print '--:--'; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalplannedworkloadfield']=$totalarray['nbfield']; - $totalarray['totalplannedworkload'] += $obj->planned_workload; - } - // Time spent - if (! empty($arrayfields['t.duration_effective']['checked'])) - { - $showlineingray=0;$showproject=1; - print '<td class="center">'; if ($showlineingray) print '<i>'; else print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$lines[$i]->id.($showproject?'':'&withproject=1').'">'; if ($obj->duration_effective) print convertSecondToTime($obj->duration_effective,$timespentoutputformat); else print '--:--'; if ($showlineingray) print '</i>'; else print '</a>'; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totaldurationeffectivefield']=$totalarray['nbfield']; - $totalarray['totaldurationeffective'] += $obj->duration_effective; - } - // Calculated progress - if (! empty($arrayfields['t.progress_calculated']['checked'])) - { + print '</td>'; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totaldurationeffectivefield']=$totalarray['nbfield']; + $totalarray['totaldurationeffective'] += $obj->duration_effective; + } + // Calculated progress + if (! empty($arrayfields['t.progress_calculated']['checked'])) + { print '<td class="center">'; - if ($obj->planned_workload || $obj->duration_effective) + if ($obj->planned_workload || $obj->duration_effective) { if ($obj->planned_workload) print round(100 * $obj->duration_effective / $obj->planned_workload,2).' %'; else print $form->textwithpicto('',$langs->trans('WorkloadNotDefined'), 1, 'help'); } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalprogress_calculated']=$totalarray['nbfield']; - } - // Declared progress - if (! empty($arrayfields['t.progress']['checked'])) - { + print '</td>'; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalprogress_calculated']=$totalarray['nbfield']; + } + // Declared progress + if (! empty($arrayfields['t.progress']['checked'])) + { print '<td class="center">'; - if ($obj->progress != '') + if ($obj->progress != '') { print $obj->progress.' %'; } - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); @@ -815,18 +815,18 @@ while ($i < min($num,$limit)) // Date creation if (! empty($arrayfields['t.datec']['checked'])) { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['t.tms']['checked'])) { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; } // Status /*if (! empty($arrayfields['p.fk_statut']['checked'])) @@ -834,16 +834,16 @@ while ($i < min($num,$limit)) $projectstatic->statut = $obj->fk_statut; print '<td align="right">'.$projectstatic->getLibStatut(5).'</td>'; }*/ - // Action column - print '<td class="nowrap" align="center">'; - 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->id, $arrayofselected)) $selected=1; - print '<input id="cb'.$obj->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->id.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + // Action column + print '<td class="nowrap" align="center">'; + 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->id, $arrayofselected)) $selected=1; + print '<input id="cb'.$obj->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->id.'"'.($selected?' checked="checked"':'').'>'; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; print "</tr>\n"; @@ -856,22 +856,22 @@ while ($i < min($num,$limit)) // Show total line if (isset($totalarray['totaldurationeffectivefield']) || isset($totalarray['totalplannedworkloadfield'])) { - print '<tr class="liste_total">'; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; - else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; - } - elseif ($totalarray['totalplannedworkloadfield'] == $i) print '<td align="center">'.convertSecondToTime($totalarray['totalplannedworkload'],$plannedworkloadoutputformat).'</td>'; - elseif ($totalarray['totaldurationeffectivefield'] == $i) print '<td align="center">'.convertSecondToTime($totalarray['totaldurationeffective'],$timespentoutputformat).'</td>'; - elseif ($totalarray['totalprogress_calculated'] == $i) print '<td align="center">'.($totalarray['totalplannedworkload'] > 0 ? round(100 * $totalarray['totaldurationeffective'] / $totalarray['totalplannedworkload'], 2).' %' : '').'</td>'; - else print '<td></td>'; - } - print '</tr>'; + print '<tr class="liste_total">'; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; + else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; + } + elseif ($totalarray['totalplannedworkloadfield'] == $i) print '<td align="center">'.convertSecondToTime($totalarray['totalplannedworkload'],$plannedworkloadoutputformat).'</td>'; + elseif ($totalarray['totaldurationeffectivefield'] == $i) print '<td align="center">'.convertSecondToTime($totalarray['totaldurationeffective'],$timespentoutputformat).'</td>'; + elseif ($totalarray['totalprogress_calculated'] == $i) print '<td align="center">'.($totalarray['totalplannedworkload'] > 0 ? round(100 * $totalarray['totaldurationeffective'] / $totalarray['totalplannedworkload'], 2).' %' : '').'</td>'; + else print '<td></td>'; + } + print '</tr>'; } $db->free($resql); diff --git a/htdocs/public/payment/newpayment.php b/htdocs/public/payment/newpayment.php index 5e3428019d60c5f999b6d760466f75a8a8e8f08b..175f3e1510ecf972f6d7a6ff0adb1e9847561ceb 100644 --- a/htdocs/public/payment/newpayment.php +++ b/htdocs/public/payment/newpayment.php @@ -71,21 +71,21 @@ $download = GETPOST('d','int')?GETPOST('d','int'):GETPOST('download','int'); if (! $action) { - if (! GETPOST("amount",'alpha') && ! $source) - { - print $langs->trans('ErrorBadParameters')." - amount or source"; - exit; - } - if (is_numeric($amount) && ! GETPOST("tag",'alpha') && ! $source) - { - print $langs->trans('ErrorBadParameters')." - tag or source"; - exit; - } - if ($source && ! GETPOST("ref",'alpha')) - { - print $langs->trans('ErrorBadParameters')." - ref"; - exit; - } + if (! GETPOST("amount",'alpha') && ! $source) + { + print $langs->trans('ErrorBadParameters')." - amount or source"; + exit; + } + if (is_numeric($amount) && ! GETPOST("tag",'alpha') && ! $source) + { + print $langs->trans('ErrorBadParameters')." - tag or source"; + exit; + } + if ($source && ! GETPOST("ref",'alpha')) + { + print $langs->trans('ErrorBadParameters')." - ref"; + exit; + } } @@ -95,11 +95,11 @@ $validpaymentmethod=array(); // Detect $paymentmethod foreach($_POST as $key => $val) { - if (preg_match('/^dopayment_(.*)$/', $key, $reg)) - { - $paymentmethod=$reg[1]; - break; - } + if (preg_match('/^dopayment_(.*)$/', $key, $reg)) + { + $paymentmethod=$reg[1]; + break; + } } @@ -125,28 +125,28 @@ if (! empty($suffix)) } if ($source) { - $urlok.='s='.urlencode($source).'&'; - $urlko.='s='.urlencode($source).'&'; + $urlok.='s='.urlencode($source).'&'; + $urlko.='s='.urlencode($source).'&'; } if (! empty($REF)) { - $urlok.='ref='.urlencode($REF).'&'; - $urlko.='ref='.urlencode($REF).'&'; + $urlok.='ref='.urlencode($REF).'&'; + $urlko.='ref='.urlencode($REF).'&'; } if (! empty($TAG)) { - $urlok.='tag='.urlencode($TAG).'&'; - $urlko.='tag='.urlencode($TAG).'&'; + $urlok.='tag='.urlencode($TAG).'&'; + $urlko.='tag='.urlencode($TAG).'&'; } if (! empty($FULLTAG)) { - $urlok.='fulltag='.urlencode($FULLTAG).'&'; - $urlko.='fulltag='.urlencode($FULLTAG).'&'; + $urlok.='fulltag='.urlencode($FULLTAG).'&'; + $urlko.='fulltag='.urlencode($FULLTAG).'&'; } if (! empty($SECUREKEY)) { - $urlok.='securekey='.urlencode($SECUREKEY).'&'; - $urlko.='securekey='.urlencode($SECUREKEY).'&'; + $urlok.='securekey='.urlencode($SECUREKEY).'&'; + $urlko.='securekey='.urlencode($SECUREKEY).'&'; } if (! empty($entity)) { @@ -174,21 +174,21 @@ if (! empty($conf->paypal->enabled)) if ($urlko) $PAYPAL_API_KO=$urlko; if (empty($PAYPAL_API_USER)) { - dol_print_error('',"Paypal setup param PAYPAL_API_USER not defined"); - return -1; + 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; + 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; + dol_print_error('',"Paypal setup param PAYPAL_API_SIGNATURE not defined"); + return -1; } - $validpaymentmethod['paypal']='valid'; + $validpaymentmethod['paypal']='valid'; } if (! empty($conf->paybox->enabled)) @@ -221,23 +221,23 @@ if (! empty($conf->stripe->enabled)) $valid=true; if (! empty($conf->global->PAYMENT_SECURITY_TOKEN)) { - if (! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { - if ($source && $REF) $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . $source . $REF, 2); // Use the source in the hash to avoid duplicates if the references are identical - else $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); - } - else - { - $token = $conf->global->PAYMENT_SECURITY_TOKEN; - } - if ($SECUREKEY != $token) $valid=false; - - if (! $valid) - { - print '<div class="error">Bad value for key.</div>'; - //print 'SECUREKEY='.$SECUREKEY.' token='.$token.' valid='.$valid; - exit; - } + if (! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) + { + if ($source && $REF) $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . $source . $REF, 2); // Use the source in the hash to avoid duplicates if the references are identical + else $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + } + else + { + $token = $conf->global->PAYMENT_SECURITY_TOKEN; + } + if ($SECUREKEY != $token) $valid=false; + + if (! $valid) + { + print '<div class="error">Bad value for key.</div>'; + //print 'SECUREKEY='.$SECUREKEY.' token='.$token.' valid='.$valid; + exit; + } } @@ -265,19 +265,19 @@ if ($action == 'dopayment') if ($paymentmethod == 'paypal') { $PAYPAL_API_PRICE=price2num(GETPOST("newamount"),'MT'); - $PAYPAL_PAYMENT_TYPE='Sale'; - - $origfulltag=GETPOST("fulltag",'alpha'); - $shipToName=GETPOST("shipToName"); - $shipToStreet=GETPOST("shipToStreet"); - $shipToCity=GETPOST("shipToCity"); - $shipToState=GETPOST("shipToState"); - $shipToCountryCode=GETPOST("shipToCountryCode"); - $shipToZip=GETPOST("shipToZip"); - $shipToStreet2=GETPOST("shipToStreet2"); - $phoneNum=GETPOST("phoneNum"); - $email=GETPOST("email"); - $desc=GETPOST("desc",'alpha'); + $PAYPAL_PAYMENT_TYPE='Sale'; + + $origfulltag=GETPOST("fulltag",'alpha'); + $shipToName=GETPOST("shipToName"); + $shipToStreet=GETPOST("shipToStreet"); + $shipToCity=GETPOST("shipToCity"); + $shipToState=GETPOST("shipToState"); + $shipToCountryCode=GETPOST("shipToCountryCode"); + $shipToZip=GETPOST("shipToZip"); + $shipToStreet2=GETPOST("shipToStreet2"); + $phoneNum=GETPOST("phoneNum"); + $email=GETPOST("email"); + $desc=GETPOST("desc",'alpha'); $mesg=''; if (empty($PAYPAL_API_PRICE) || ! is_numeric($PAYPAL_API_PRICE)) $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Amount")); @@ -285,7 +285,7 @@ if ($action == 'dopayment') //elseif (! isValidEMail($EMAIL)) $mesg=$langs->trans("ErrorBadEMail",$EMAIL); elseif (! $origfulltag) $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("PaymentCode")); - //var_dump($_POST); + //var_dump($_POST); if (empty($mesg)) { dol_syslog("newpayment.php call paypal api and do redirect", LOG_DEBUG); @@ -294,35 +294,35 @@ if ($action == 'dopayment') $PAYPAL_API_DEVISE="USD"; //if ($currency == 'EUR') $PAYPAL_API_DEVISE="EUR"; //if ($currency == 'USD') $PAYPAL_API_DEVISE="USD"; - if (! empty($currency)) $PAYPAL_API_DEVISE=$currency; - - dol_syslog("Submit Paypal form", LOG_DEBUG); - dol_syslog("PAYPAL_API_USER: $PAYPAL_API_USER", LOG_DEBUG); - //dol_syslog("PAYPAL_API_PASSWORD: $PAYPAL_API_PASSWORD", LOG_DEBUG); // No password into log files - dol_syslog("PAYPAL_API_SIGNATURE: $PAYPAL_API_SIGNATURE", LOG_DEBUG); - dol_syslog("PAYPAL_API_SANDBOX: $PAYPAL_API_SANDBOX", LOG_DEBUG); - dol_syslog("PAYPAL_API_OK: $PAYPAL_API_OK", LOG_DEBUG); - dol_syslog("PAYPAL_API_KO: $PAYPAL_API_KO", LOG_DEBUG); - dol_syslog("PAYPAL_API_PRICE: $PAYPAL_API_PRICE", LOG_DEBUG); - dol_syslog("PAYPAL_API_DEVISE: $PAYPAL_API_DEVISE", LOG_DEBUG); - dol_syslog("shipToName: $shipToName", LOG_DEBUG); - dol_syslog("shipToStreet: $shipToStreet", LOG_DEBUG); - dol_syslog("shipToCity: $shipToCity", LOG_DEBUG); - dol_syslog("shipToState: $shipToState", LOG_DEBUG); - dol_syslog("shipToCountryCode: $shipToCountryCode", LOG_DEBUG); - dol_syslog("shipToZip: $shipToZip", LOG_DEBUG); - dol_syslog("shipToStreet2: $shipToStreet2", LOG_DEBUG); - dol_syslog("phoneNum: $phoneNum", LOG_DEBUG); - dol_syslog("email: $email", LOG_DEBUG); - dol_syslog("desc: $desc", LOG_DEBUG); - - dol_syslog("SCRIPT_URI: ".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG); // If defined script uri must match domain of PAYPAL_API_OK and PAYPAL_API_KO - //$_SESSION["PaymentType"]=$PAYPAL_PAYMENT_TYPE; - //$_SESSION["currencyCodeType"]=$PAYPAL_API_DEVISE; - //$_SESSION["FinalPaymentAmt"]=$PAYPAL_API_PRICE; - - // A redirect is added if API call successfull - print_paypal_redirect($PAYPAL_API_PRICE,$PAYPAL_API_DEVISE,$PAYPAL_PAYMENT_TYPE,$PAYPAL_API_OK,$PAYPAL_API_KO, $FULLTAG); + if (! empty($currency)) $PAYPAL_API_DEVISE=$currency; + + dol_syslog("Submit Paypal form", LOG_DEBUG); + dol_syslog("PAYPAL_API_USER: $PAYPAL_API_USER", LOG_DEBUG); + //dol_syslog("PAYPAL_API_PASSWORD: $PAYPAL_API_PASSWORD", LOG_DEBUG); // No password into log files + dol_syslog("PAYPAL_API_SIGNATURE: $PAYPAL_API_SIGNATURE", LOG_DEBUG); + dol_syslog("PAYPAL_API_SANDBOX: $PAYPAL_API_SANDBOX", LOG_DEBUG); + dol_syslog("PAYPAL_API_OK: $PAYPAL_API_OK", LOG_DEBUG); + dol_syslog("PAYPAL_API_KO: $PAYPAL_API_KO", LOG_DEBUG); + dol_syslog("PAYPAL_API_PRICE: $PAYPAL_API_PRICE", LOG_DEBUG); + dol_syslog("PAYPAL_API_DEVISE: $PAYPAL_API_DEVISE", LOG_DEBUG); + dol_syslog("shipToName: $shipToName", LOG_DEBUG); + dol_syslog("shipToStreet: $shipToStreet", LOG_DEBUG); + dol_syslog("shipToCity: $shipToCity", LOG_DEBUG); + dol_syslog("shipToState: $shipToState", LOG_DEBUG); + dol_syslog("shipToCountryCode: $shipToCountryCode", LOG_DEBUG); + dol_syslog("shipToZip: $shipToZip", LOG_DEBUG); + dol_syslog("shipToStreet2: $shipToStreet2", LOG_DEBUG); + dol_syslog("phoneNum: $phoneNum", LOG_DEBUG); + dol_syslog("email: $email", LOG_DEBUG); + dol_syslog("desc: $desc", LOG_DEBUG); + + dol_syslog("SCRIPT_URI: ".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG); // If defined script uri must match domain of PAYPAL_API_OK and PAYPAL_API_KO + //$_SESSION["PaymentType"]=$PAYPAL_PAYMENT_TYPE; + //$_SESSION["currencyCodeType"]=$PAYPAL_API_DEVISE; + //$_SESSION["FinalPaymentAmt"]=$PAYPAL_API_PRICE; + + // A redirect is added if API call successfull + print_paypal_redirect($PAYPAL_API_PRICE,$PAYPAL_API_DEVISE,$PAYPAL_PAYMENT_TYPE,$PAYPAL_API_OK,$PAYPAL_API_KO, $FULLTAG); exit; } @@ -506,11 +506,11 @@ llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'online // Check link validity if ($source && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) { - $langs->load("errors"); - dol_print_error_email('BADREFINPAYMENTFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref)); - llxFooter(); - $db->close(); - exit; + $langs->load("errors"); + dol_print_error_email('BADREFINPAYMENTFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref)); + llxFooter(); + $db->close(); + exit; } @@ -592,15 +592,15 @@ if ($urllogo) $text=''; if (! empty($conf->global->PAYMENT_NEWFORM_TEXT)) { - $langs->load("members"); - if (preg_match('/^\((.*)\)$/',$conf->global->PAYMENT_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."<br>\n"; - else $text.=$conf->global->PAYMENT_NEWFORM_TEXT."<br>\n"; - $text='<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n"; + $langs->load("members"); + if (preg_match('/^\((.*)\)$/',$conf->global->PAYMENT_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."<br>\n"; + else $text.=$conf->global->PAYMENT_NEWFORM_TEXT."<br>\n"; + $text='<tr><td align="center"><br>'.$text.'<br></td></tr>'."\n"; } if (empty($text)) { - $text.='<tr><td class="textpublicpayment"><br><strong>'.$langs->trans("WelcomeOnPaymentPage").'</strong></td></tr>'."\n"; - $text.='<tr><td class="textpublicpayment">'.$langs->trans("ThisScreenAllowsYouToPay",$creditor).'<br><br></td></tr>'."\n"; + $text.='<tr><td class="textpublicpayment"><br><strong>'.$langs->trans("WelcomeOnPaymentPage").'</strong></td></tr>'."\n"; + $text.='<tr><td class="textpublicpayment">'.$langs->trans("ThisScreenAllowsYouToPay",$creditor).'<br><br></td></tr>'."\n"; } print $text; @@ -626,9 +626,9 @@ if (! $source) // Creditor print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor"); - print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>'; - print '<input type="hidden" name="creditor" value="'.$creditor.'">'; - print '</td></tr>'."\n"; + print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>'; + print '<input type="hidden" name="creditor" value="'.$creditor.'">'; + print '</td></tr>'."\n"; // Amount @@ -637,12 +637,12 @@ if (! $source) print '</td><td class="CTableRow'.($var?'1':'2').'">'; if (empty($amount) || ! is_numeric($amount)) { - print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">'; - print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">'; + print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">'; + print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">'; } else { print '<b>'.price($amount).'</b>'; - print '<input type="hidden" name="amount" value="'.$amount.'">'; + print '<input type="hidden" name="amount" value="'.$amount.'">'; print '<input type="hidden" name="newamount" value="'.$amount.'">'; } // Currency @@ -658,8 +658,8 @@ if (! $source) print '<input type="hidden" name="fulltag" value="'.$fulltag.'">'; print '</td></tr>'."\n"; - // We do not add fields shipToName, shipToStreet, shipToCity, shipToState, shipToCountryCode, shipToZip, shipToStreet2, phoneNum - // as they don't exists (buyer is unknown, tag is free). + // We do not add fields shipToName, shipToStreet, shipToCity, shipToState, shipToCountryCode, shipToZip, shipToStreet2, phoneNum + // as they don't exists (buyer is unknown, tag is free). } @@ -685,12 +685,12 @@ if ($source == 'order') $object = $order; } - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { - $amount=$order->total_ttc; - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } + if ($action != 'dopayment') // Do not change amount if we just click on first dopayment + { + $amount=$order->total_ttc; + if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); + $amount=price2num($amount); + } $fulltag='ORD='.$order->ref.'.CUS='.$order->thirdparty->id; //$fulltag.='.NAM='.strtr($order->thirdparty->name,"-"," "); @@ -700,9 +700,9 @@ if ($source == 'order') // Creditor print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor"); - print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>'; - print '<input type="hidden" name="creditor" value="'.$creditor.'">'; - print '</td></tr>'."\n"; + print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>'; + print '<input type="hidden" name="creditor" value="'.$creditor.'">'; + print '</td></tr>'."\n"; // Debitor @@ -726,12 +726,12 @@ if ($source == 'order') print '</td><td class="CTableRow'.($var?'1':'2').'">'; if (empty($amount) || ! is_numeric($amount)) { - print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">'; - print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">'; + print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">'; + print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">'; } else { print '<b>'.price($amount).'</b>'; - print '<input type="hidden" name="amount" value="'.$amount.'">'; + print '<input type="hidden" name="amount" value="'.$amount.'">'; print '<input type="hidden" name="newamount" value="'.$amount.'">'; } // Currency @@ -749,32 +749,32 @@ if ($source == 'order') // Shipping address $shipToName=$order->thirdparty->name; - $shipToStreet=$order->thirdparty->address; - $shipToCity=$order->thirdparty->town; - $shipToState=$order->thirdparty->state_code; - $shipToCountryCode=$order->thirdparty->country_code; - $shipToZip=$order->thirdparty->zip; - $shipToStreet2=''; - $phoneNum=$order->thirdparty->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { - print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; - print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; - print '<input type="hidden" name="shipToCity" value="'.$shipToCity.'">'."\n"; - print '<input type="hidden" name="shipToState" value="'.$shipToState.'">'."\n"; - print '<input type="hidden" name="shipToCountryCode" value="'.$shipToCountryCode.'">'."\n"; - print '<input type="hidden" name="shipToZip" value="'.$shipToZip.'">'."\n"; - print '<input type="hidden" name="shipToStreet2" value="'.$shipToStreet2.'">'."\n"; - print '<input type="hidden" name="phoneNum" value="'.$phoneNum.'">'."\n"; - } - else - { - print '<!-- Shipping address not complete, so we don t use it -->'."\n"; - } - print '<input type="hidden" name="email" value="'.$order->thirdparty->email.'">'."\n"; - $labeldesc=$langs->trans("Order").' '.$order->ref; - if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); - print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; + $shipToStreet=$order->thirdparty->address; + $shipToCity=$order->thirdparty->town; + $shipToState=$order->thirdparty->state_code; + $shipToCountryCode=$order->thirdparty->country_code; + $shipToZip=$order->thirdparty->zip; + $shipToStreet2=''; + $phoneNum=$order->thirdparty->phone; + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) + { + print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; + print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; + print '<input type="hidden" name="shipToCity" value="'.$shipToCity.'">'."\n"; + print '<input type="hidden" name="shipToState" value="'.$shipToState.'">'."\n"; + print '<input type="hidden" name="shipToCountryCode" value="'.$shipToCountryCode.'">'."\n"; + print '<input type="hidden" name="shipToZip" value="'.$shipToZip.'">'."\n"; + print '<input type="hidden" name="shipToStreet2" value="'.$shipToStreet2.'">'."\n"; + print '<input type="hidden" name="phoneNum" value="'.$phoneNum.'">'."\n"; + } + else + { + print '<!-- Shipping address not complete, so we don t use it -->'."\n"; + } + print '<input type="hidden" name="email" value="'.$order->thirdparty->email.'">'."\n"; + $labeldesc=$langs->trans("Order").' '.$order->ref; + if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); + print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; } @@ -800,12 +800,12 @@ if ($source == 'invoice') $object = $invoice; } - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { - $amount=price2num($invoice->total_ttc - $invoice->getSommePaiement()); - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } + if ($action != 'dopayment') // Do not change amount if we just click on first dopayment + { + $amount=price2num($invoice->total_ttc - $invoice->getSommePaiement()); + if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); + $amount=price2num($amount); + } $fulltag='INV='.$invoice->ref.'.CUS='.$invoice->thirdparty->id; //$fulltag.='.NAM='.strtr($invoice->thirdparty->name,"-"," "); @@ -815,9 +815,9 @@ if ($source == 'invoice') // Creditor print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor"); - print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>'; - print '<input type="hidden" name="creditor" value="'.dol_escape_htmltag($creditor).'">'; - print '</td></tr>'."\n"; + print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>'; + print '<input type="hidden" name="creditor" value="'.dol_escape_htmltag($creditor).'">'; + print '</td></tr>'."\n"; // Debitor @@ -841,12 +841,12 @@ if ($source == 'invoice') print '</td><td class="CTableRow'.($var?'1':'2').'">'; if (empty($amount) || ! is_numeric($amount)) { - print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">'; - print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">'; + print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">'; + print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">'; } else { print '<b>'.price($amount).'</b>'; - print '<input type="hidden" name="amount" value="'.$amount.'">'; + print '<input type="hidden" name="amount" value="'.$amount.'">'; print '<input type="hidden" name="newamount" value="'.$amount.'">'; } // Currency @@ -870,34 +870,34 @@ if ($source == 'invoice') print '</td></tr>'."\n"; } - // Shipping address - $shipToName=$invoice->thirdparty->name; - $shipToStreet=$invoice->thirdparty->address; - $shipToCity=$invoice->thirdparty->town; - $shipToState=$invoice->thirdparty->state_code; - $shipToCountryCode=$invoice->thirdparty->country_code; - $shipToZip=$invoice->thirdparty->zip; - $shipToStreet2=''; - $phoneNum=$invoice->thirdparty->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { - print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; - print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; - print '<input type="hidden" name="shipToCity" value="'.$shipToCity.'">'."\n"; - print '<input type="hidden" name="shipToState" value="'.$shipToState.'">'."\n"; - print '<input type="hidden" name="shipToCountryCode" value="'.$shipToCountryCode.'">'."\n"; - print '<input type="hidden" name="shipToZip" value="'.$shipToZip.'">'."\n"; - print '<input type="hidden" name="shipToStreet2" value="'.$shipToStreet2.'">'."\n"; - print '<input type="hidden" name="phoneNum" value="'.$phoneNum.'">'."\n"; - } - else - { - print '<!-- Shipping address not complete, so we don t use it -->'."\n"; - } - print '<input type="hidden" name="email" value="'.$invoice->thirdparty->email.'">'."\n"; - $labeldesc=$langs->trans("Invoice").' '.$invoice->ref; - if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); - print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; + // Shipping address + $shipToName=$invoice->thirdparty->name; + $shipToStreet=$invoice->thirdparty->address; + $shipToCity=$invoice->thirdparty->town; + $shipToState=$invoice->thirdparty->state_code; + $shipToCountryCode=$invoice->thirdparty->country_code; + $shipToZip=$invoice->thirdparty->zip; + $shipToStreet2=''; + $phoneNum=$invoice->thirdparty->phone; + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) + { + print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; + print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; + print '<input type="hidden" name="shipToCity" value="'.$shipToCity.'">'."\n"; + print '<input type="hidden" name="shipToState" value="'.$shipToState.'">'."\n"; + print '<input type="hidden" name="shipToCountryCode" value="'.$shipToCountryCode.'">'."\n"; + print '<input type="hidden" name="shipToZip" value="'.$shipToZip.'">'."\n"; + print '<input type="hidden" name="shipToStreet2" value="'.$shipToStreet2.'">'."\n"; + print '<input type="hidden" name="phoneNum" value="'.$phoneNum.'">'."\n"; + } + else + { + print '<!-- Shipping address not complete, so we don t use it -->'."\n"; + } + print '<input type="hidden" name="email" value="'.$invoice->thirdparty->email.'">'."\n"; + $labeldesc=$langs->trans("Invoice").' '.$invoice->ref; + if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); + print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; } // Payment on contract line @@ -941,40 +941,40 @@ if ($source == 'contractline') } } - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { - $amount=$contractline->total_ttc; - - if ($contractline->fk_product && ! empty($conf->global->PAYMENT_USE_NEW_PRICE_FOR_CONTRACTLINES)) - { - $product=new Product($db); - $result=$product->fetch($contractline->fk_product); - - // We define price for product (TODO Put this in a method in product class) - if (! empty($conf->global->PRODUIT_MULTIPRICES)) - { - $pu_ht = $product->multiprices[$contract->thirdparty->price_level]; - $pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level]; - $price_base_type = $product->multiprices_base_type[$contract->thirdparty->price_level]; - } - else - { - $pu_ht = $product->price; - $pu_ttc = $product->price_ttc; - $price_base_type = $product->price_base_type; - } - - $amount=$pu_ttc; - if (empty($amount)) - { - dol_print_error('','ErrorNoPriceDefinedForThisProduct'); - exit; - } - } - - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } + if ($action != 'dopayment') // Do not change amount if we just click on first dopayment + { + $amount=$contractline->total_ttc; + + if ($contractline->fk_product && ! empty($conf->global->PAYMENT_USE_NEW_PRICE_FOR_CONTRACTLINES)) + { + $product=new Product($db); + $result=$product->fetch($contractline->fk_product); + + // We define price for product (TODO Put this in a method in product class) + if (! empty($conf->global->PRODUIT_MULTIPRICES)) + { + $pu_ht = $product->multiprices[$contract->thirdparty->price_level]; + $pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level]; + $price_base_type = $product->multiprices_base_type[$contract->thirdparty->price_level]; + } + else + { + $pu_ht = $product->price; + $pu_ttc = $product->price_ttc; + $price_base_type = $product->price_base_type; + } + + $amount=$pu_ttc; + if (empty($amount)) + { + dol_print_error('','ErrorNoPriceDefinedForThisProduct'); + exit; + } + } + + if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); + $amount=price2num($amount); + } $fulltag='COL='.$contractline->ref.'.CON='.$contract->ref.'.CUS='.$contract->thirdparty->id.'.DAT='.dol_print_date(dol_now(),'%Y%m%d%H%M'); //$fulltag.='.NAM='.strtr($contract->thirdparty->name,"-"," "); @@ -988,7 +988,7 @@ if ($source == 'contractline') print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor"); print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>'; - print '<input type="hidden" name="creditor" value="'.$creditor.'">'; + print '<input type="hidden" name="creditor" value="'.$creditor.'">'; print '</td></tr>'."\n"; // Debitor @@ -1054,12 +1054,12 @@ if ($source == 'contractline') print '</td><td class="CTableRow'.($var?'1':'2').'">'; if (empty($amount) || ! is_numeric($amount)) { - print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">'; - print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">'; + print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">'; + print '<input class="flat" size=8 type="text" name="newamount" value="'.GETPOST("newamount","int").'">'; } else { print '<b>'.price($amount).'</b>'; - print '<input type="hidden" name="amount" value="'.$amount.'">'; + print '<input type="hidden" name="amount" value="'.$amount.'">'; print '<input type="hidden" name="newamount" value="'.$amount.'">'; } // Currency @@ -1075,34 +1075,34 @@ if ($source == 'contractline') print '<input type="hidden" name="fulltag" value="'.$fulltag.'">'; print '</td></tr>'."\n"; - // Shipping address - $shipToName=$contract->thirdparty->name; - $shipToStreet=$contract->thirdparty->address; - $shipToCity=$contract->thirdparty->town; - $shipToState=$contract->thirdparty->state_code; - $shipToCountryCode=$contract->thirdparty->country_code; - $shipToZip=$contract->thirdparty->zip; - $shipToStreet2=''; - $phoneNum=$contract->thirdparty->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { - print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; - print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; - print '<input type="hidden" name="shipToCity" value="'.$shipToCity.'">'."\n"; - print '<input type="hidden" name="shipToState" value="'.$shipToState.'">'."\n"; - print '<input type="hidden" name="shipToCountryCode" value="'.$shipToCountryCode.'">'."\n"; - print '<input type="hidden" name="shipToZip" value="'.$shipToZip.'">'."\n"; - print '<input type="hidden" name="shipToStreet2" value="'.$shipToStreet2.'">'."\n"; - print '<input type="hidden" name="phoneNum" value="'.$phoneNum.'">'."\n"; - } - else - { - print '<!-- Shipping address not complete, so we don t use it -->'."\n"; - } - print '<input type="hidden" name="email" value="'.$contract->thirdparty->email.'">'."\n"; - $labeldesc=$langs->trans("Contract").' '.$contract->ref; - if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); - print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; + // Shipping address + $shipToName=$contract->thirdparty->name; + $shipToStreet=$contract->thirdparty->address; + $shipToCity=$contract->thirdparty->town; + $shipToState=$contract->thirdparty->state_code; + $shipToCountryCode=$contract->thirdparty->country_code; + $shipToZip=$contract->thirdparty->zip; + $shipToStreet2=''; + $phoneNum=$contract->thirdparty->phone; + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) + { + print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; + print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; + print '<input type="hidden" name="shipToCity" value="'.$shipToCity.'">'."\n"; + print '<input type="hidden" name="shipToState" value="'.$shipToState.'">'."\n"; + print '<input type="hidden" name="shipToCountryCode" value="'.$shipToCountryCode.'">'."\n"; + print '<input type="hidden" name="shipToZip" value="'.$shipToZip.'">'."\n"; + print '<input type="hidden" name="shipToStreet2" value="'.$shipToStreet2.'">'."\n"; + print '<input type="hidden" name="phoneNum" value="'.$phoneNum.'">'."\n"; + } + else + { + print '<!-- Shipping address not complete, so we don t use it -->'."\n"; + } + print '<input type="hidden" name="email" value="'.$contract->thirdparty->email.'">'."\n"; + $labeldesc=$langs->trans("Contract").' '.$contract->ref; + if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); + print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; } // Payment on member subscription @@ -1128,12 +1128,12 @@ if ($source == 'membersubscription') $subscription=new Subscription($db); } - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { - $amount=$subscription->total_ttc; - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } + if ($action != 'dopayment') // Do not change amount if we just click on first dopayment + { + $amount=$subscription->total_ttc; + if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); + $amount=price2num($amount); + } $fulltag='MEM='.$member->id.'.DAT='.dol_print_date(dol_now(),'%Y%m%d%H%M'); if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; } @@ -1142,9 +1142,9 @@ if ($source == 'membersubscription') // Creditor print '<tr class="CTableRow'.($var?'1':'2').'"><td class="CTableRow'.($var?'1':'2').'">'.$langs->trans("Creditor"); - print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>'; - print '<input type="hidden" name="creditor" value="'.$creditor.'">'; - print '</td></tr>'."\n"; + print '</td><td class="CTableRow'.($var?'1':'2').'"><b>'.$creditor.'</b>'; + print '<input type="hidden" name="creditor" value="'.$creditor.'">'; + print '</td></tr>'."\n"; // Debitor @@ -1195,7 +1195,7 @@ if ($source == 'membersubscription') { $valtoshow=GETPOST("newamount",'int'); // force default subscription amount to value defined into constant... - if (! empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { + if (! empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { if (! empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { $valtoshow = $conf->global->MEMBER_NEWFORM_AMOUNT; } @@ -1203,21 +1203,21 @@ if ($source == 'membersubscription') else { if (! empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { $amount = $conf->global->MEMBER_NEWFORM_AMOUNT; - } - } + } + } } if (empty($amount) || ! is_numeric($amount)) { - //$valtoshow=GETPOST("newamount",'int'); - if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow); - print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">'; - print '<input class="flat" size="8" type="text" name="newamount" value="'.$valtoshow.'">'; + //$valtoshow=GETPOST("newamount",'int'); + if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow); + print '<input type="hidden" name="amount" value="'.GETPOST("amount",'int').'">'; + print '<input class="flat" size="8" type="text" name="newamount" value="'.$valtoshow.'">'; } else { - $valtoshow=$amount; - if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow); - print '<b>'.price($valtoshow).'</b>'; - print '<input type="hidden" name="amount" value="'.$valtoshow.'">'; + $valtoshow=$amount; + if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow); + print '<b>'.price($valtoshow).'</b>'; + print '<input type="hidden" name="amount" value="'.$valtoshow.'">'; print '<input type="hidden" name="newamount" value="'.$valtoshow.'">'; } // Currency @@ -1233,34 +1233,34 @@ if ($source == 'membersubscription') print '<input type="hidden" name="fulltag" value="'.$fulltag.'">'; print '</td></tr>'."\n"; - // Shipping address - $shipToName=$member->getFullName($langs); - $shipToStreet=$member->address; - $shipToCity=$member->town; - $shipToState=$member->state_code; - $shipToCountryCode=$member->country_code; - $shipToZip=$member->zip; - $shipToStreet2=''; - $phoneNum=$member->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { - print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; - print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; - print '<input type="hidden" name="shipToCity" value="'.$shipToCity.'">'."\n"; - print '<input type="hidden" name="shipToState" value="'.$shipToState.'">'."\n"; - print '<input type="hidden" name="shipToCountryCode" value="'.$shipToCountryCode.'">'."\n"; - print '<input type="hidden" name="shipToZip" value="'.$shipToZip.'">'."\n"; - print '<input type="hidden" name="shipToStreet2" value="'.$shipToStreet2.'">'."\n"; - print '<input type="hidden" name="phoneNum" value="'.$phoneNum.'">'."\n"; - } - else - { - print '<!-- Shipping address not complete, so we don t use it -->'."\n"; - } - print '<input type="hidden" name="email" value="'.$member->email.'">'."\n"; - $labeldesc = $langs->trans("PaymentSubscription"); - if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); - print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; + // Shipping address + $shipToName=$member->getFullName($langs); + $shipToStreet=$member->address; + $shipToCity=$member->town; + $shipToState=$member->state_code; + $shipToCountryCode=$member->country_code; + $shipToZip=$member->zip; + $shipToStreet2=''; + $phoneNum=$member->phone; + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) + { + print '<input type="hidden" name="shipToName" value="'.$shipToName.'">'."\n"; + print '<input type="hidden" name="shipToStreet" value="'.$shipToStreet.'">'."\n"; + print '<input type="hidden" name="shipToCity" value="'.$shipToCity.'">'."\n"; + print '<input type="hidden" name="shipToState" value="'.$shipToState.'">'."\n"; + print '<input type="hidden" name="shipToCountryCode" value="'.$shipToCountryCode.'">'."\n"; + print '<input type="hidden" name="shipToZip" value="'.$shipToZip.'">'."\n"; + print '<input type="hidden" name="shipToStreet2" value="'.$shipToStreet2.'">'."\n"; + print '<input type="hidden" name="phoneNum" value="'.$phoneNum.'">'."\n"; + } + else + { + print '<!-- Shipping address not complete, so we don t use it -->'."\n"; + } + print '<input type="hidden" name="email" value="'.$member->email.'">'."\n"; + $labeldesc = $langs->trans("PaymentSubscription"); + if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); + print '<input type="hidden" name="desc" value="'.dol_escape_htmltag($labeldesc).'">'."\n"; } @@ -1275,44 +1275,44 @@ print "\n"; if ($action != 'dopayment') { - if ($found && ! $error) // We are in a management option and no error - { - // Buttons for all payments registration methods - - if (! empty($conf->paybox->enabled)) - { - // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of paybox - print '<br><input class="button buttonpayment buttonpayment'.(empty($conf->global->PAYBOX_PICTO_FOR_PAYMENT)?'paybox':$conf->global->PAYBOX_PICTO_FOR_PAYMENT).'" type="submit" name="dopayment_paybox" value="'.$langs->trans("PayBoxDoPayment").'">'; - } - - if (! empty($conf->stripe->enabled)) - { - // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of stripe - print '<br><input class="button buttonpayment buttonpayment'.(empty($conf->global->STRIPE_PICTO_FOR_PAYMENT)?'stripe':$conf->global->STRIPE_PICTO_FOR_PAYMENT).'" type="submit" name="dopayment_stripe" value="'.$langs->trans("StripeDoPayment").'">'; - } - - if (! empty($conf->paypal->enabled)) - { - if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY='integral'; - - if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') - { - print '<br><input class="button buttonpayment buttonpaymentpaypal" type="submit" name="dopayment_paypal" value="'.$langs->trans("PaypalOrCBDoPayment").'">'; - } - if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') - { - print '<br><input class="button buttonpayment buttonpaymentpaypal" type="submit" name="dopayment_paypal" value="'.$langs->trans("PaypalDoPayment").'">'; - } - } - } - else - { - dol_print_error_email('ERRORNEWPAYMENT'); - } + if ($found && ! $error) // We are in a management option and no error + { + // Buttons for all payments registration methods + + if (! empty($conf->paybox->enabled)) + { + // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of paybox + print '<br><input class="button buttonpayment buttonpayment'.(empty($conf->global->PAYBOX_PICTO_FOR_PAYMENT)?'paybox':$conf->global->PAYBOX_PICTO_FOR_PAYMENT).'" type="submit" name="dopayment_paybox" value="'.$langs->trans("PayBoxDoPayment").'">'; + } + + if (! empty($conf->stripe->enabled)) + { + // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of stripe + print '<br><input class="button buttonpayment buttonpayment'.(empty($conf->global->STRIPE_PICTO_FOR_PAYMENT)?'stripe':$conf->global->STRIPE_PICTO_FOR_PAYMENT).'" type="submit" name="dopayment_stripe" value="'.$langs->trans("StripeDoPayment").'">'; + } + + if (! empty($conf->paypal->enabled)) + { + if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY='integral'; + + if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') + { + print '<br><input class="button buttonpayment buttonpaymentpaypal" type="submit" name="dopayment_paypal" value="'.$langs->trans("PaypalOrCBDoPayment").'">'; + } + if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') + { + print '<br><input class="button buttonpayment buttonpaymentpaypal" type="submit" name="dopayment_paypal" value="'.$langs->trans("PaypalDoPayment").'">'; + } + } + } + else + { + dol_print_error_email('ERRORNEWPAYMENT'); + } } else { - // Print + // Print } print '</td></tr>'."\n"; @@ -1495,7 +1495,7 @@ if (preg_match('/^dopayment/',$action)) } <?php - print '</script>'; + print '</script>'; } } diff --git a/htdocs/societe/class/companybankaccount.class.php b/htdocs/societe/class/companybankaccount.class.php index 4853c54fdd9b1587ce95f2a6ce80a786d5f97ae6..428f5b96f42113878cae809f62585ebd60039b83 100644 --- a/htdocs/societe/class/companybankaccount.class.php +++ b/htdocs/societe/class/companybankaccount.class.php @@ -33,65 +33,65 @@ require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php'; */ class CompanyBankAccount extends Account { - var $socid; + var $socid; - var $default_rib; - var $frstrecur; - var $rum; - var $date_rum; + var $default_rib; + var $frstrecur; + var $rum; + var $date_rum; - var $datec; - var $datem; + var $datec; + var $datem; - /** + /** * Constructor * * @param DoliDB $db Database handler - */ - public function __construct(DoliDB $db) - { - $this->db = $db; - - $this->socid = 0; - $this->solde = 0; - $this->error_number = 0; - $this->default_rib = 0; - } - - - /** - * Create bank information record - * - * @param User $user User - * @param int $notrigger 1=Disable triggers - * @return int <0 if KO, >= 0 if OK - */ - function create(User $user = null, $notrigger=0) - { - $now = dol_now(); + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + + $this->socid = 0; + $this->solde = 0; + $this->error_number = 0; + $this->default_rib = 0; + } + + + /** + * Create bank information record + * + * @param User $user User + * @param int $notrigger 1=Disable triggers + * @return int <0 if KO, >= 0 if OK + */ + function create(User $user = null, $notrigger=0) + { + $now = dol_now(); $error = 0; - // Correct default_rib to be sure to have always one default + // Correct default_rib to be sure to have always one default $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib where fk_soc = ".$this->socid." AND default_rib = 1"; $result = $this->db->query($sql); - if ($result) - { - $numrows=$this->db->num_rows($result); - if ($this->default_rib && $numrows > 0) $this->default_rib = 0; - if (empty($this->default_rib) && $numrows == 0) $this->default_rib = 1; - } - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_rib (fk_soc, datec)"; - $sql.= " VALUES (".$this->socid.", '".$this->db->idate($now)."')"; - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->affected_rows($resql)) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe_rib"); - - if (! $notrigger) - { + if ($result) + { + $numrows=$this->db->num_rows($result); + if ($this->default_rib && $numrows > 0) $this->default_rib = 0; + if (empty($this->default_rib) && $numrows == 0) $this->default_rib = 1; + } + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_rib (fk_soc, datec)"; + $sql.= " VALUES (".$this->socid.", '".$this->db->idate($now)."')"; + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->affected_rows($resql)) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe_rib"); + + if (! $notrigger) + { // Call trigger $result=$this->call_trigger('COMPANY_RIB_CREATE',$user); if ($result < 0) $error++; @@ -105,64 +105,64 @@ class CompanyBankAccount extends Account { return 0; } - } - else - { - return 1; - } - } - } - else - { - print $this->db->error(); - return 0; - } - } - - /** - * Update bank account - * - * @param User $user Object user - * @param int $notrigger 1=Disable triggers - * @return int <=0 if KO, >0 if OK - */ - function update(User $user = null, $notrigger = 0) - { - global $conf; - $error = 0; - - if (! $this->id) return -1; - - if (dol_strlen($this->domiciliation) > 255) $this->domiciliation = dol_trunc($this->domiciliation, 254, 'right', 'UTF-8', 1); + } + else + { + return 1; + } + } + } + else + { + print $this->db->error(); + return 0; + } + } + + /** + * Update bank account + * + * @param User $user Object user + * @param int $notrigger 1=Disable triggers + * @return int <=0 if KO, >0 if OK + */ + function update(User $user = null, $notrigger = 0) + { + global $conf; + $error = 0; + + if (! $this->id) return -1; + + if (dol_strlen($this->domiciliation) > 255) $this->domiciliation = dol_trunc($this->domiciliation, 254, 'right', 'UTF-8', 1); if (dol_strlen($this->owner_address) > 255) $this->owner_address = dol_trunc($this->owner_address, 254, 'right', 'UTF-8', 1); - $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET"; - $sql.= " bank = '" .$this->db->escape($this->bank)."'"; - $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; - $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; - $sql.= ",number='".$this->db->escape($this->number)."'"; - $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; - $sql.= ",bic='".$this->db->escape($this->bic)."'"; - $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; - $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; - $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; - $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; - $sql.= ",default_rib = ".$this->default_rib; - if ($conf->prelevement->enabled) - { - $sql.= ",frstrecur = '".$this->db->escape($this->frstrecur)."'"; - $sql.= ",rum = '".$this->db->escape($this->rum)."'"; - $sql.= ",date_rum = ".($this->date_rum ? "'".$this->db->idate($this->date_rum)."'" : "null"); - } - if (trim($this->label) != '') - $sql.= ",label = '".$this->db->escape($this->label)."'"; - else - $sql.= ",label = NULL"; - $sql.= " WHERE rowid = ".$this->id; - - $result = $this->db->query($sql); - if ($result) - { + $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET"; + $sql.= " bank = '" .$this->db->escape($this->bank)."'"; + $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; + $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; + $sql.= ",number='".$this->db->escape($this->number)."'"; + $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; + $sql.= ",bic='".$this->db->escape($this->bic)."'"; + $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; + $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; + $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; + $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; + $sql.= ",default_rib = ".$this->default_rib; + if ($conf->prelevement->enabled) + { + $sql.= ",frstrecur = '".$this->db->escape($this->frstrecur)."'"; + $sql.= ",rum = '".$this->db->escape($this->rum)."'"; + $sql.= ",date_rum = ".($this->date_rum ? "'".$this->db->idate($this->date_rum)."'" : "null"); + } + if (trim($this->label) != '') + $sql.= ",label = '".$this->db->escape($this->label)."'"; + else + $sql.= ",label = NULL"; + $sql.= " WHERE rowid = ".$this->id; + + $result = $this->db->query($sql); + if ($result) + { if (! $notrigger) @@ -185,118 +185,118 @@ class CompanyBankAccount extends Account return 1; } - } - else - { - dol_print_error($this->db); - return -1; - } - } - - /** - * Load record from database - * - * @param int $id Id of record - * @param int $socid Id of company. If this is filled, function will return the default RIB of company - * @return int <0 if KO, >0 if OK - */ - function fetch($id, $socid=0) - { - if (empty($id) && empty($socid)) return -1; - - $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; - $sql.= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib"; - if ($id) $sql.= " WHERE rowid = ".$id; - if ($socid) $sql.= " WHERE fk_soc = ".$socid." AND default_rib = 1"; - - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->ref = $obj->fk_soc.'-'.$obj->label; // Generate an artificial ref - - $this->id = $obj->rowid; - $this->socid = $obj->fk_soc; - $this->bank = $obj->bank; - $this->code_banque = $obj->code_banque; - $this->code_guichet = $obj->code_guichet; - $this->number = $obj->number; - $this->cle_rib = $obj->cle_rib; - $this->bic = $obj->bic; - $this->iban = $obj->iban; - $this->domiciliation = $obj->domiciliation; - $this->proprio = $obj->proprio; - $this->owner_address = $obj->owner_address; - $this->label = $obj->label; - $this->default_rib = $obj->default_rib; - $this->datec = $this->db->jdate($obj->datec); - $this->datem = $this->db->jdate($obj->datem); - $this->rum = $obj->rum; - $this->frstrecur = $obj->frstrecur; - } - $this->db->free($resql); - - return 1; - } - else - { - dol_print_error($this->db); - return -1; - } - } - - /** - * Delete a rib from database - * - * @param User $user User deleting - * @param int $notrigger 1=Disable triggers - * @return int <0 if KO, >0 if OK - */ - function delete(User $user = null, $notrigger=0) - { - global $conf; - - $error = 0; - - dol_syslog(get_class($this) . "::delete ".$this->id, LOG_DEBUG); - - $this->db->begin(); - - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('COMPANY_RIB_DELETE',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $sql = "DELETE FROM " . MAIN_DB_PREFIX . "societe_rib"; - $sql .= " WHERE rowid = " . $this->id; - - if (! $this->db->query($sql)) - { - $error++; - $this->errors[]=$this->db->lasterror(); - } - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1*$error; - } - } + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Load record from database + * + * @param int $id Id of record + * @param int $socid Id of company. If this is filled, function will return the default RIB of company + * @return int <0 if KO, >0 if OK + */ + function fetch($id, $socid=0) + { + if (empty($id) && empty($socid)) return -1; + + $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; + $sql.= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib"; + if ($id) $sql.= " WHERE rowid = ".$id; + if ($socid) $sql.= " WHERE fk_soc = ".$socid." AND default_rib = 1"; + + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->ref = $obj->fk_soc.'-'.$obj->label; // Generate an artificial ref + + $this->id = $obj->rowid; + $this->socid = $obj->fk_soc; + $this->bank = $obj->bank; + $this->code_banque = $obj->code_banque; + $this->code_guichet = $obj->code_guichet; + $this->number = $obj->number; + $this->cle_rib = $obj->cle_rib; + $this->bic = $obj->bic; + $this->iban = $obj->iban; + $this->domiciliation = $obj->domiciliation; + $this->proprio = $obj->proprio; + $this->owner_address = $obj->owner_address; + $this->label = $obj->label; + $this->default_rib = $obj->default_rib; + $this->datec = $this->db->jdate($obj->datec); + $this->datem = $this->db->jdate($obj->datem); + $this->rum = $obj->rum; + $this->frstrecur = $obj->frstrecur; + } + $this->db->free($resql); + + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Delete a rib from database + * + * @param User $user User deleting + * @param int $notrigger 1=Disable triggers + * @return int <0 if KO, >0 if OK + */ + function delete(User $user = null, $notrigger=0) + { + global $conf; + + $error = 0; + + dol_syslog(get_class($this) . "::delete ".$this->id, LOG_DEBUG); + + $this->db->begin(); + + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('COMPANY_RIB_DELETE',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "societe_rib"; + $sql .= " WHERE rowid = " . $this->id; + + if (! $this->db->query($sql)) + { + $error++; + $this->errors[]=$this->db->lasterror(); + } + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1*$error; + } + } /** * Return RIB @@ -320,93 +320,93 @@ class CompanyBankAccount extends Account return $rib; } - /** - * Set RIB as Default - * - * @param int $rib RIB id - * @return int 0 if KO, 1 if OK - */ - function setAsDefault($rib=0) - { - $sql1 = "SELECT rowid as id, fk_soc FROM ".MAIN_DB_PREFIX."societe_rib"; - $sql1.= " WHERE rowid = ".($rib?$rib:$this->id); - - dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); - $result1 = $this->db->query($sql1); - if ($result1) - { - if ($this->db->num_rows($result1) == 0) - { - return 0; - } - else - { - $obj = $this->db->fetch_object($result1); - - $this->db->begin(); - - $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0 "; - $sql2.= "WHERE fk_soc = ".$obj->fk_soc; - dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); - $result2 = $this->db->query($sql2); - - $sql3 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 1 "; - $sql3.= "WHERE rowid = ".$obj->id; - dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); - $result3 = $this->db->query($sql3); - - if (!$result2 || !$result3) - { - dol_print_error($this->db); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - } - else - { - dol_print_error($this->db); - return -1; - } - } - - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - function initAsSpecimen() - { - $this->specimen = 1; - $this->ref = 'CBA'; - $this->label = 'CustomerCorp Bank account'; - $this->bank = 'CustomerCorp Bank'; - $this->courant = Account::TYPE_CURRENT; - $this->clos = Account::STATUS_OPEN; - $this->code_banque = '123'; - $this->code_guichet = '456'; - $this->number = 'CUST12345'; - $this->cle_rib = 50; - $this->bic = 'CC12'; - $this->iban = 'FR999999999'; - $this->domiciliation = 'Bank address of customer corp'; - $this->proprio = 'Owner'; - $this->owner_address = 'Owner address'; - $this->country_id = 1; - - $this->rum = 'UMR-CU1212-0007-5-1475405262'; - $this->date_rum =dol_now() - 10000; - $this->frstrecur = 'FRST'; - - $this->socid = 0; - } + /** + * Set RIB as Default + * + * @param int $rib RIB id + * @return int 0 if KO, 1 if OK + */ + function setAsDefault($rib=0) + { + $sql1 = "SELECT rowid as id, fk_soc FROM ".MAIN_DB_PREFIX."societe_rib"; + $sql1.= " WHERE rowid = ".($rib?$rib:$this->id); + + dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); + $result1 = $this->db->query($sql1); + if ($result1) + { + if ($this->db->num_rows($result1) == 0) + { + return 0; + } + else + { + $obj = $this->db->fetch_object($result1); + + $this->db->begin(); + + $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0 "; + $sql2.= "WHERE fk_soc = ".$obj->fk_soc; + dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); + $result2 = $this->db->query($sql2); + + $sql3 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 1 "; + $sql3.= "WHERE rowid = ".$obj->id; + dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); + $result3 = $this->db->query($sql3); + + if (!$result2 || !$result3) + { + dol_print_error($this->db); + $this->db->rollback(); + return -1; + } + else + { + $this->db->commit(); + return 1; + } + } + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + $this->specimen = 1; + $this->ref = 'CBA'; + $this->label = 'CustomerCorp Bank account'; + $this->bank = 'CustomerCorp Bank'; + $this->courant = Account::TYPE_CURRENT; + $this->clos = Account::STATUS_OPEN; + $this->code_banque = '123'; + $this->code_guichet = '456'; + $this->number = 'CUST12345'; + $this->cle_rib = 50; + $this->bic = 'CC12'; + $this->iban = 'FR999999999'; + $this->domiciliation = 'Bank address of customer corp'; + $this->proprio = 'Owner'; + $this->owner_address = 'Owner address'; + $this->country_id = 1; + + $this->rum = 'UMR-CU1212-0007-5-1475405262'; + $this->date_rum =dol_now() - 10000; + $this->frstrecur = 'FRST'; + + $this->socid = 0; + } } diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index d1d218a00614274f666dccc156ea7b52ff60f798..ed0cd57ba760f23a6942dd074cb1594fd9d6ce28 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -40,28 +40,28 @@ require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; */ class Societe extends CommonObject { - public $element='societe'; - public $table_element = 'societe'; + public $element='societe'; + public $table_element = 'societe'; public $fk_element='fk_soc'; - protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord'); // To test if we can delete object + protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord'); // To test if we can delete object protected $childtablesoncascade=array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm"); /** - * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - * @var int - */ - protected $ismultientitymanaged = 1; + * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + * @var int + */ + protected $ismultientitymanaged = 1; - public $entity; + public $entity; - /** - * Thirdparty name - * @var string - * @deprecated Use $name instead - * @see name - */ - public $nom; + /** + * Thirdparty name + * @var string + * @deprecated Use $name instead + * @see name + */ + public $nom; /** * Alias names (commercial, trademark or alias names) @@ -69,46 +69,46 @@ class Societe extends CommonObject */ public $name_alias; - public $particulier; - public $address; - public $zip; - public $town; - - /** - * Thirdparty status : 0=activity ceased, 1= in activity - * @var int - */ - var $status; - - /** - * Id of department - * @var int - */ - var $state_id; - var $state_code; - var $state; - - /** - * State code - * @var string - * @deprecated Use state_code instead - * @see state_code - */ - var $departement_code; - - /** - * @var string - * @deprecated Use state instead - * @see state - */ - var $departement; - - /** - * @var string - * @deprecated Use country instead - * @see country - */ - var $pays; + public $particulier; + public $address; + public $zip; + public $town; + + /** + * Thirdparty status : 0=activity ceased, 1= in activity + * @var int + */ + var $status; + + /** + * Id of department + * @var int + */ + var $state_id; + var $state_code; + var $state; + + /** + * State code + * @var string + * @deprecated Use state_code instead + * @see state_code + */ + var $departement_code; + + /** + * @var string + * @deprecated Use state instead + * @see state + */ + var $departement; + + /** + * @var string + * @deprecated Use country instead + * @see country + */ + var $pays; /** * Phone number @@ -137,77 +137,77 @@ class Societe extends CommonObject var $url; //! barcode - /** - * Barcode value - * @var string - */ - var $barcode; - - // 6 professional id (usage depends on country) - - /** - * Professional ID 1 (Ex: Siren in France) - * @var string - */ - var $idprof1; - - /** - * Professional ID 2 (Ex: Siret in France) - * @var string - */ - var $idprof2; - - /** - * Professional ID 3 (Ex: Ape in France) - * @var string - */ - var $idprof3; - - /** - * Professional ID 4 (Ex: RCS in France) - * @var string - */ - var $idprof4; - - /** - * Professional ID 5 - * @var string - */ - var $idprof5; - - /** - * Professional ID 6 - * @var string - */ - var $idprof6; - - var $prefix_comm; - - var $tva_assuj; - /** - * Intracommunitary VAT ID - * @var string - */ - var $tva_intra; - - // Local taxes - var $localtax1_assuj; - var $localtax1_value; - var $localtax2_assuj; - var $localtax2_value; - - var $managers; - var $capital; - var $typent_id; - var $typent_code; - var $effectif; - var $effectif_id; - var $forme_juridique_code; - var $forme_juridique; - - var $remise_percent; - var $mode_reglement_supplier_id; - var $cond_reglement_supplier_id; + /** + * Barcode value + * @var string + */ + var $barcode; + + // 6 professional id (usage depends on country) + + /** + * Professional ID 1 (Ex: Siren in France) + * @var string + */ + var $idprof1; + + /** + * Professional ID 2 (Ex: Siret in France) + * @var string + */ + var $idprof2; + + /** + * Professional ID 3 (Ex: Ape in France) + * @var string + */ + var $idprof3; + + /** + * Professional ID 4 (Ex: RCS in France) + * @var string + */ + var $idprof4; + + /** + * Professional ID 5 + * @var string + */ + var $idprof5; + + /** + * Professional ID 6 + * @var string + */ + var $idprof6; + + var $prefix_comm; + + var $tva_assuj; + /** + * Intracommunitary VAT ID + * @var string + */ + var $tva_intra; + + // Local taxes + var $localtax1_assuj; + var $localtax1_value; + var $localtax2_assuj; + var $localtax2_value; + + var $managers; + var $capital; + var $typent_id; + var $typent_code; + var $effectif; + var $effectif_id; + var $forme_juridique_code; + var $forme_juridique; + + var $remise_percent; + var $mode_reglement_supplier_id; + var $cond_reglement_supplier_id; var $fk_prospectlevel; var $name_bis; @@ -215,541 +215,206 @@ class Societe extends CommonObject /** * Date of last update - * @var string + * @var string */ var $date_modification; /** * User that made last update - * @var string + * @var string */ var $user_modification; /** * Date of creation - * @var string + * @var string */ var $date_creation; /** * User that created the thirdparty - * @var User + * @var User */ var $user_creation; - var $specimen; - - /** - * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect - * @var int - */ - var $client; - /** - * 0=no prospect, 1=prospect - * @var int - */ - var $prospect; - /** - * 0=no supplier, 1=supplier - * @var int - */ - var $fournisseur; - - /** - * Client code. E.g: CU2014-003 - * @var string - */ - var $code_client; - - /** - * Supplier code. E.g: SU2014-003 - * @var string - */ - var $code_fournisseur; - - /** - * Accounting code for client - * @var string - */ - var $code_compta; - - /** - * Accounting code for suppliers - * @var string - */ - var $code_compta_fournisseur; - - /** - * @var string - * @deprecated Note is split in public and private notes - * @see note_public, note_private - */ - var $note; - - /** - * Private note - * @var string - */ - var $note_private; - - /** - * Public note - * @var string - */ - var $note_public; - - //! code statut prospect - var $stcomm_id; - var $statut_commercial; - - /** - * Assigned price level - * @var int - */ - var $price_level; - var $outstanding_limit; - - /** - * Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives. - * @var int - */ - var $commercial_id; - /** - * Id of parent thirdparty (if one) - * @var int - */ - var $parent; - /** - * Default language code of thirdparty (en_US, ...) - * @var string - */ - var $default_lang; - - var $ref; - var $ref_int; - /** - * External user reference. - * This is to allow external systems to store their id and make self-developed synchronizing functions easier to - * build. - * @var string - */ - var $ref_ext; - - /** - * Import key. - * Set when the thirdparty has been created through an import process. This is to relate those created thirdparties - * to an import process - * @var string - */ - var $import_key; - - /** - * Supplier WebServices URL - * @var string - */ - var $webservices_url; - - /** - * Supplier WebServices Key - * @var string - */ - var $webservices_key; - - var $logo; - var $logo_small; - var $logo_mini; - - var $array_options; + var $specimen; - // Incoterms - var $fk_incoterms; - var $location_incoterms; - var $libelle_incoterms; //Used into tooltip + /** + * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect + * @var int + */ + var $client; + /** + * 0=no prospect, 1=prospect + * @var int + */ + var $prospect; + /** + * 0=no supplier, 1=supplier + * @var int + */ + var $fournisseur; - // Multicurrency - var $fk_multicurrency; - var $multicurrency_code; + /** + * Client code. E.g: CU2014-003 + * @var string + */ + var $code_client; - /** - * To contains a clone of this when we need to save old properties of object - * @var Societe - */ - var $oldcopy; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - - $this->client = 0; - $this->prospect = 0; - $this->fournisseur = 0; - $this->typent_id = 0; - $this->effectif_id = 0; - $this->forme_juridique_code = 0; - $this->tva_assuj = 1; - $this->status = 1; - } - - - /** - * Create third party in database. - * $this->code_client = -1 and $this->code_fournisseur = -1 means automatic assignement. - * - * @param User $user Object of user that ask creation - * @return int >= 0 if OK, < 0 if KO - */ - function create($user) - { - global $langs,$conf,$mysoc; + /** + * Supplier code. E.g: SU2014-003 + * @var string + */ + var $code_fournisseur; - $error=0; + /** + * Accounting code for client + * @var string + */ + var $code_compta; - // Clean parameters - if (empty($this->status)) $this->status=0; - $this->name=$this->name?trim($this->name):trim($this->nom); - if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name); - $this->nom=$this->name; // For backward compatibility - if (empty($this->client)) $this->client=0; - if (empty($this->fournisseur)) $this->fournisseur=0; - $this->import_key = trim($this->import_key); + /** + * Accounting code for suppliers + * @var string + */ + var $code_compta_fournisseur; - if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); - if (empty($this->fk_multicurrency)) - { - $this->multicurrency_code = ''; - $this->fk_multicurrency = 0; - } + /** + * @var string + * @deprecated Note is split in public and private notes + * @see note_public, note_private + */ + var $note; - dol_syslog(get_class($this)."::create ".$this->name); + /** + * Private note + * @var string + */ + var $note_private; - $now=dol_now(); + /** + * Public note + * @var string + */ + var $note_public; - $this->db->begin(); + //! code statut prospect + var $stcomm_id; + var $statut_commercial; - // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts) - if ($this->code_client == -1) $this->get_codeclient($this,0); - if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1); + /** + * Assigned price level + * @var int + */ + var $price_level; + var $outstanding_limit; - // Check more parameters (including mandatory setup - // If error, this->errors[] is filled - $result = $this->verify(); + /** + * Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives. + * @var int + */ + var $commercial_id; + /** + * Id of parent thirdparty (if one) + * @var int + */ + var $parent; + /** + * Default language code of thirdparty (en_US, ...) + * @var string + */ + var $default_lang; - if ($result >= 0) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)"; - $sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$conf->entity.", '".$this->db->idate($now)."'"; - $sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null"); - $sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null"); - $sql.= ", ".$this->status; - $sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null"); - $sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null"); - $sql.= ", 0"; - $sql.= ", ".(int) $this->fk_incoterms; - $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; - $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null"); - $sql.= ", ".(int) $this->fk_multicurrency; - $sql.= ", '".$this->db->escape($this->multicurrency_code)."')"; - - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe"); - - $ret = $this->update($this->id,$user,0,1,1,'add'); - - // Ajout du commercial affecte - if ($this->commercial_id != '' && $this->commercial_id != -1) - { - $this->add_commercial($user, $this->commercial_id); - } - // si un commercial cree un client il lui est affecte automatiquement - else if (empty($user->rights->societe->client->voir)) - { - $this->add_commercial($user, $user->id); - } - - if ($ret >= 0) - { - // Call trigger - $result=$this->call_trigger('COMPANY_CREATE',$user); - if ($result < 0) $error++; - // End call triggers - } - else $error++; - - if (! $error) - { - dol_syslog(get_class($this)."::Create success id=".$this->id); - $this->db->commit(); - return $this->id; - } - else - { - dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',',$this->errors), LOG_ERR); - $this->db->rollback(); - return -4; - } - } - else - { - if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name); // duplicate on a field (code or profid or ...) - $result=-1; - } - else - { - $this->error=$this->db->lasterror(); - $result=-2; - } - $this->db->rollback(); - return $result; - } + var $ref; + var $ref_int; + /** + * External user reference. + * This is to allow external systems to store their id and make self-developed synchronizing functions easier to + * build. + * @var string + */ + var $ref_ext; - } - else - { - $this->db->rollback(); - dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING); - return -3; - } - } - - - /** - * Create a contact/address from thirdparty - * - * @param User $user Object user - * @return int <0 if KO, >0 if OK - */ - function create_individual(User $user) - { - require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - $contact=new Contact($this->db); - - $contact->name = $this->name_bis; - $contact->firstname = $this->firstname; - $contact->civility_id = $this->civility_id; - $contact->socid = $this->id; // fk_soc - $contact->statut = 1; - $contact->priv = 0; - $contact->country_id = $this->country_id; - $contact->state_id = $this->state_id; - $contact->address = $this->address; - $contact->email = $this->email; - $contact->zip = $this->zip; - $contact->town = $this->town; - $contact->phone_pro = $this->phone; - - $result = $contact->create($user); - if ($result < 0) - { - $this->error = $contact->error; - $this->errors = $contact->errors; - dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR); - } + /** + * Import key. + * Set when the thirdparty has been created through an import process. This is to relate those created thirdparties + * to an import process + * @var string + */ + var $import_key; - return $result; - } - - /** - * Check properties of third party are ok (like name, third party codes, ...) - * Used before an add or update. - * - * @return int 0 if OK, <0 if KO - */ - function verify() - { - global $conf, $langs, $mysoc; - - $error = 0; - $this->errors=array(); - - $result = 0; - $this->name = trim($this->name); - $this->nom=$this->name; // For backward compatibility - - if (! $this->name) - { - $this->errors[] = 'ErrorBadThirdPartyName'; - $result = -2; - } + /** + * Supplier WebServices URL + * @var string + */ + var $webservices_url; - if ($this->client) - { - $rescode = $this->check_codeclient(); - if ($rescode <> 0) - { - if ($rescode == -1) - { - $this->errors[] = 'ErrorBadCustomerCodeSyntax'; - } - if ($rescode == -2) - { - $this->errors[] = 'ErrorCustomerCodeRequired'; - } - if ($rescode == -3) - { - $this->errors[] = 'ErrorCustomerCodeAlreadyUsed'; - } - if ($rescode == -4) - { - $this->errors[] = 'ErrorPrefixRequired'; - } - $result = -3; - } - } + /** + * Supplier WebServices Key + * @var string + */ + var $webservices_key; - if ($this->fournisseur) - { - $rescode = $this->check_codefournisseur(); - if ($rescode <> 0) - { - if ($rescode == -1) - { - $this->errors[] = 'ErrorBadSupplierCodeSyntax'; - } - if ($rescode == -2) - { - $this->errors[] = 'ErrorSupplierCodeRequired'; - } - if ($rescode == -3) - { - $this->errors[] = 'ErrorSupplierCodeAlreadyUsed'; - } - if ($rescode == -5) - { - $this->errors[] = 'ErrorprefixRequired'; - } - $result = -3; - } - } + var $logo; + var $logo_small; + var $logo_mini; + + var $array_options; + + // Incoterms + var $fk_incoterms; + var $location_incoterms; + var $libelle_incoterms; //Used into tooltip + + // Multicurrency + var $fk_multicurrency; + var $multicurrency_code; + + /** + * To contains a clone of this when we need to save old properties of object + * @var Societe + */ + var $oldcopy; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + + $this->client = 0; + $this->prospect = 0; + $this->fournisseur = 0; + $this->typent_id = 0; + $this->effectif_id = 0; + $this->forme_juridique_code = 0; + $this->tva_assuj = 1; + $this->status = 1; + } - // Check for duplicate or mandatory fields defined into setup - $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL'); - foreach($array_to_check as $key) - { - $keymin=strtolower($key); - $i=(int) preg_replace('/[^0-9]/','',$key); - $vallabel=$this->$keymin; - - if ($i > 0) - { - if ($this->isACompany()) - { - // Check for unicity - if ($vallabel && $this->id_prof_verifiable($i)) - { - if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) - { - $langs->load("errors"); - $error++; $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')'; - } - } - - // Check for mandatory prof id (but only if country is other than ours) - if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) - { - $idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY'; - if (! $vallabel && ! empty($conf->global->$idprof_mandatory)) - { - $langs->load("errors"); - $error++; - $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')'; - } - } - } - } - else - { - //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY); - if ($key == 'EMAIL') - { - // Check for unicity - if ($vallabel) - { - if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) - { - $langs->load("errors"); - $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')'; - } - } - - // Check for mandatory - if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email)) - { - $langs->load("errors"); - $error++; - $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')'; - } - } - } - } - if ($error) $result = -4; - - return $result; - } - - /** - * Update parameters of third party - * - * @param int $id id societe - * @param User $user Utilisateur qui demande la mise a jour - * @param int $call_trigger 0=non, 1=oui - * @param int $allowmodcodeclient Inclut modif code client et code compta - * @param int $allowmodcodefournisseur Inclut modif code fournisseur et code compta fournisseur - * @param string $action 'add' or 'update' - * @param int $nosyncmember Do not synchronize info of linked member - * @return int <0 if KO, >=0 if OK - */ - function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1) - { - global $langs,$conf,$hookmanager; - require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + /** + * Create third party in database. + * $this->code_client = -1 and $this->code_fournisseur = -1 means automatic assignement. + * + * @param User $user Object of user that ask creation + * @return int >= 0 if OK, < 0 if KO + */ + function create($user) + { + global $langs,$conf,$mysoc; $error=0; - dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur); - - $now=dol_now(); - - // Clean parameters - $this->id = $id; - $this->name = $this->name?trim($this->name):trim($this->nom); - $this->nom = $this->name; // For backward compatibility - $this->name_alias = trim($this->name_alias); - $this->ref_ext = trim($this->ref_ext); - $this->address = $this->address?trim($this->address):trim($this->address); - $this->zip = $this->zip?trim($this->zip):trim($this->zip); - $this->town = $this->town?trim($this->town):trim($this->town); - $this->state_id = trim($this->state_id); - $this->country_id = ($this->country_id > 0)?$this->country_id:0; - $this->phone = trim($this->phone); - $this->phone = preg_replace("/\s/","",$this->phone); - $this->phone = preg_replace("/\./","",$this->phone); - $this->fax = trim($this->fax); - $this->fax = preg_replace("/\s/","",$this->fax); - $this->fax = preg_replace("/\./","",$this->fax); - $this->email = trim($this->email); - $this->skype = trim($this->skype); - $this->url = $this->url?clean_url($this->url,0):''; - $this->idprof1 = trim($this->idprof1); - $this->idprof2 = trim($this->idprof2); - $this->idprof3 = trim($this->idprof3); - $this->idprof4 = trim($this->idprof4); - $this->idprof5 = (! empty($this->idprof5)?trim($this->idprof5):''); - $this->idprof6 = (! empty($this->idprof6)?trim($this->idprof6):''); - $this->prefix_comm = trim($this->prefix_comm); - $this->outstanding_limit = price2num($this->outstanding_limit); - - $this->tva_assuj = trim($this->tva_assuj); - $this->tva_intra = dol_sanitizeFileName($this->tva_intra,''); - if (empty($this->status)) $this->status = 0; + // Clean parameters + if (empty($this->status)) $this->status=0; + $this->name=$this->name?trim($this->name):trim($this->nom); + if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name); + $this->nom=$this->name; // For backward compatibility + if (empty($this->client)) $this->client=0; + if (empty($this->fournisseur)) $this->fournisseur=0; + $this->import_key = trim($this->import_key); if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); if (empty($this->fk_multicurrency)) @@ -758,2321 +423,2656 @@ class Societe extends CommonObject $this->fk_multicurrency = 0; } - // Local taxes - $this->localtax1_assuj=trim($this->localtax1_assuj); - $this->localtax2_assuj=trim($this->localtax2_assuj); + dol_syslog(get_class($this)."::create ".$this->name); - $this->localtax1_value=trim($this->localtax1_value); - $this->localtax2_value=trim($this->localtax2_value); + $now=dol_now(); - if ($this->capital != '') $this->capital=price2num(trim($this->capital)); - if (! is_numeric($this->capital)) $this->capital = ''; // '' = undef + $this->db->begin(); - $this->effectif_id=trim($this->effectif_id); - $this->forme_juridique_code=trim($this->forme_juridique_code); + // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts) + if ($this->code_client == -1) $this->get_codeclient($this,0); + if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1); - //Gencod - $this->barcode=trim($this->barcode); - - // For automatic creation - if ($this->code_client == -1) $this->get_codeclient($this,0); - if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1); - - $this->code_compta=trim($this->code_compta); - $this->code_compta_fournisseur=trim($this->code_compta_fournisseur); - - // Check parameters. More tests are done later in the ->verify() - if (! is_numeric($this->client) && ! is_numeric($this->fournisseur)) - { - $langs->load("errors"); - $this->error = $langs->trans("BadValueForParameterClientOrSupplier"); - return -1; - } - - $customer=false; - if (! empty($allowmodcodeclient) && ! empty($this->client)) - { - // Attention get_codecompta peut modifier le code suivant le module utilise - if (empty($this->code_compta)) - { - $ret=$this->get_codecompta('customer'); - if ($ret < 0) return -1; - } - - $customer=true; - } - - $supplier=false; - if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur)) - { - // Attention get_codecompta peut modifier le code suivant le module utilise - if (empty($this->code_compta_fournisseur)) - { - $ret=$this->get_codecompta('supplier'); - if ($ret < 0) return -1; - } - - $supplier=true; - } + // Check more parameters (including mandatory setup + // If error, this->errors[] is filled + $result = $this->verify(); - //Web services - $this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):''; - $this->webservices_key = trim($this->webservices_key); + if ($result >= 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)"; + $sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$conf->entity.", '".$this->db->idate($now)."'"; + $sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null"); + $sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null"); + $sql.= ", ".$this->status; + $sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null"); + $sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null"); + $sql.= ", 0"; + $sql.= ", ".(int) $this->fk_incoterms; + $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null"); + $sql.= ", ".(int) $this->fk_multicurrency; + $sql.= ", '".$this->db->escape($this->multicurrency_code)."')"; - //Incoterms - $this->fk_incoterms = (int) $this->fk_incoterms; - $this->location_incoterms = trim($this->location_incoterms); + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe"); - $this->db->begin(); - - // Check name is required and codes are ok or unique. - // If error, this->errors[] is filled - $result = 0; - if ($action != 'add') $result = $this->verify(); // We don't check when update called during a create because verify was already done - - if ($result >= 0) - { - dol_syslog(get_class($this)."::update verify ok or not done"); - - $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET "; - $sql .= "nom = '" . $this->db->escape($this->name) ."'"; // Required - $sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'"; - $sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null"); - $sql .= ",address = '" . $this->db->escape($this->address) ."'"; - - $sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null"); - $sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null"); - - $sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'"; - $sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'"; - - $sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null"); - $sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null"); - $sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null"); - $sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null"); - $sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null"); - - $sql .= ",siren = '". $this->db->escape($this->idprof1) ."'"; - $sql .= ",siret = '". $this->db->escape($this->idprof2) ."'"; - $sql .= ",ape = '". $this->db->escape($this->idprof3) ."'"; - $sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'"; - $sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'"; - $sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'"; - - $sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null"); - $sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'"; - $sql .= ",status = " .$this->status; - - // Local taxes - $sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null"); - $sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null"); - if($this->localtax1_assuj==1) - { - if($this->localtax1_value!='') - { - $sql .=",localtax1_value =".$this->localtax1_value; - } - else $sql .=",localtax1_value =0.000"; - - } - else $sql .=",localtax1_value =0.000"; - - if($this->localtax2_assuj==1) - { - if($this->localtax2_value!='') - { - $sql .=",localtax2_value =".$this->localtax2_value; - } - else $sql .=",localtax2_value =0.000"; - - } - else $sql .=",localtax2_value =0.000"; - - $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital); - - $sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null"); - - $sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null"); - if (isset($this->stcomm_id)) - { - $sql .= ",fk_stcomm=".($this->stcomm_id > 0 ? $this->stcomm_id : "0"); - } - $sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0"); - - $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null"); - - $sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null"); - $sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null"); - $sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null"); - $sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null"); - $sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null"); - - $sql .= ",client = " . (! empty($this->client)?$this->client:0); - $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0); - $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null"); - $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null"); - $sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null"); - $sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null'); - $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'"; - - $sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null"); - $sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null"); + $ret = $this->update($this->id,$user,0,1,1,'add'); - //Incoterms - $sql.= ", fk_incoterms = ".$this->fk_incoterms; - $sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null"); + // Ajout du commercial affecte + if ($this->commercial_id != '' && $this->commercial_id != -1) + { + $this->add_commercial($user, $this->commercial_id); + } + // si un commercial cree un client il lui est affecte automatiquement + else if (empty($user->rights->societe->client->voir)) + { + $this->add_commercial($user, $user->id); + } - if ($customer) - { - $sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null"); - $sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null"); - } - - if ($supplier) - { - $sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null"); - $sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null"); - } - $sql .= ", fk_user_modif = ".(! empty($user->id)?"'".$user->id."'":"null"); - $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency; - $sql .= ', multicurrency_code = \''.$this->db->escape($this->multicurrency_code)."'"; - $sql .= " WHERE rowid = '" . $id ."'"; - - $resql=$this->db->query($sql); - if ($resql) - { - unset($this->country_code); // We clean this because it may have been changed after an update of country_id - unset($this->country); - unset($this->state_code); - unset($this->state); - - $nbrowsaffected = $this->db->affected_rows($resql); - - if (! $error && $nbrowsaffected) - { - // Update information on linked member if it is an update - if (! $nosyncmember && ! empty($conf->adherent->enabled)) - { - require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - - dol_syslog(get_class($this)."::update update linked member"); - - $lmember=new Adherent($this->db); - $result=$lmember->fetch(0, 0, $this->id); - - if ($result > 0) - { - $lmember->societe=$this->name; - //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged - //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged - $lmember->address=$this->address; - $lmember->email=$this->email; - $lmember->skype=$this->skype; - $lmember->phone=$this->phone; - - $result=$lmember->update($user,0,1,1,1); // Use nosync to 1 to avoid cyclic updates - if ($result < 0) - { - $this->error=$lmember->error; - dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR); - $error++; - } - } - else if ($result < 0) - { - $this->error=$lmember->error; - $error++; - } - } - } - - $action='update'; - - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('thirdpartydao')); - $parameters=array('socid'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - else if ($reshook < 0) $error++; - - if (! $error && $call_trigger) - { - // Call trigger - $result=$this->call_trigger('COMPANY_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - dol_syslog(get_class($this)."::Update success"); - $this->db->commit(); - return 1; - } - else + if ($ret >= 0) { - $this->db->rollback(); - return -1; - } - } - else - { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - // Doublon - $this->error = $langs->trans("ErrorDuplicateField"); - $result = -1; - } - else - { - $this->error = $this->db->lasterror(); - $result = -2; - } - $this->db->rollback(); - return $result; - } - } - else - { - $this->db->rollback(); - dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING); - return -3; - } - } - - /** - * Load a third party from database into memory - * - * @param int $rowid Id of third party to load - * @param string $ref Reference of third party, name (Warning, this can return several records) - * @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr) - * @param string $ref_int Internal reference of third party (not used by dolibarr) - * @param string $idprof1 Prof id 1 of third party (Warning, this can return several records) - * @param string $idprof2 Prof id 2 of third party (Warning, this can return several records) - * @param string $idprof3 Prof id 3 of third party (Warning, this can return several records) - * @param string $idprof4 Prof id 4 of third party (Warning, this can return several records) - * @param string $idprof5 Prof id 5 of third party (Warning, this can return several records) - * @param string $idprof6 Prof id 6 of third party (Warning, this can return several records) - * @param string $email Email (Warning, this can return several records) - * @return int >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found. - */ - function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='', $email='') - { - global $langs; - global $conf; - - if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1; - - $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm'; - $sql .= ', s.status'; - $sql .= ', s.price_level'; - $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif'; - $sql .= ', s.phone, s.fax, s.email, s.skype, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur'; - $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6'; - $sql .= ', s.capital, s.tva_intra'; - $sql .= ', s.fk_typent as typent_id'; - $sql .= ', s.fk_effectif as effectif_id'; - $sql .= ', s.fk_forme_juridique as forme_juridique_code'; - $sql .= ', s.webservices_url, s.webservices_key'; - $sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode'; - $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj'; - $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo'; - $sql .= ', s.fk_shipping_method'; - $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms'; - $sql .= ', s.fk_multicurrency, s.multicurrency_code'; - $sql .= ', fj.libelle as forme_juridique'; - $sql .= ', e.libelle as effectif'; - $sql .= ', c.code as country_code, c.label as country'; - $sql .= ', d.code_departement as state_code, d.nom as state'; - $sql .= ', st.libelle as stcomm'; - $sql .= ', te.code as typent_code'; - $sql .= ', i.libelle as libelle_incoterms'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid'; - $sql .= ' WHERE s.entity IN ('.getEntity($this->element, 1).')'; - if ($rowid) $sql .= ' AND s.rowid = '.$rowid; - if ($ref) $sql .= " AND s.nom = '".$this->db->escape($ref)."'"; - if ($ref_ext) $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'"; - if ($ref_int) $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'"; - if ($idprof1) $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'"; - if ($idprof2) $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'"; - if ($idprof3) $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'"; - if ($idprof4) $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'"; - if ($idprof5) $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'"; - if ($idprof6) $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'"; - if ($email) $sql .= " AND email = '".$this->db->escape($email)."'"; - - $resql=$this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - if ($num > 1) - { - $this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.'; - dol_syslog($this->error, LOG_ERR); - $result = -2; - } - elseif ($num) // $num = 1 - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->entity = $obj->entity; - $this->canvas = $obj->canvas; - - $this->ref = $obj->rowid; - $this->name = $obj->name; - $this->nom = $obj->name; // deprecated - $this->name_alias = $obj->name_alias; - $this->ref_ext = $obj->ref_ext; - $this->ref_int = $obj->ref_int; - - $this->date_creation = $this->db->jdate($obj->date_creation); - $this->date_modification = $this->db->jdate($obj->date_modification); - $this->user_creation = $obj->fk_user_creat; - $this->user_modification = $obj->fk_user_modif; - - $this->address = $obj->address; - $this->zip = $obj->zip; - $this->town = $obj->town; - - $this->country_id = $obj->country_id; - $this->country_code = $obj->country_id?$obj->country_code:''; - $this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):''; - - $this->state_id = $obj->fk_departement; - $this->state_code = $obj->state_code; - $this->state = ($obj->state!='-'?$obj->state:''); - - $transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm); - $libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm); - $this->stcomm_id = $obj->fk_stcomm; // id statut commercial - $this->statut_commercial = $libelle; // libelle statut commercial - - $this->email = $obj->email; - $this->skype = $obj->skype; - $this->url = $obj->url; - $this->phone = $obj->phone; - $this->fax = $obj->fax; - - $this->parent = $obj->parent; - - $this->idprof1 = $obj->idprof1; - $this->idprof2 = $obj->idprof2; - $this->idprof3 = $obj->idprof3; - $this->idprof4 = $obj->idprof4; - $this->idprof5 = $obj->idprof5; - $this->idprof6 = $obj->idprof6; - - $this->capital = $obj->capital; - - $this->code_client = $obj->code_client; - $this->code_fournisseur = $obj->code_fournisseur; - - $this->code_compta = $obj->code_compta; - $this->code_compta_fournisseur = $obj->code_compta_fournisseur; - - $this->barcode = $obj->barcode; - - $this->tva_assuj = $obj->tva_assuj; - $this->tva_intra = $obj->tva_intra; - $this->status = $obj->status; - - // Local Taxes - $this->localtax1_assuj = $obj->localtax1_assuj; - $this->localtax2_assuj = $obj->localtax2_assuj; - - $this->localtax1_value = $obj->localtax1_value; - $this->localtax2_value = $obj->localtax2_value; - - $this->typent_id = $obj->typent_id; - $this->typent_code = $obj->typent_code; - - $this->effectif_id = $obj->effectif_id; - $this->effectif = $obj->effectif_id?$obj->effectif:''; - - $this->forme_juridique_code= $obj->forme_juridique_code; - $this->forme_juridique = $obj->forme_juridique_code?$obj->forme_juridique:''; - - $this->fk_prospectlevel = $obj->fk_prospectlevel; - - $this->prefix_comm = $obj->prefix_comm; - - $this->remise_percent = $obj->remise_client; - $this->mode_reglement_id = $obj->mode_reglement; - $this->cond_reglement_id = $obj->cond_reglement; - $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier; - $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier; - $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; - $this->fk_account = $obj->fk_account; + // Call trigger + $result=$this->call_trigger('COMPANY_CREATE',$user); + if ($result < 0) $error++; + // End call triggers + } + else $error++; - $this->client = $obj->client; - $this->fournisseur = $obj->fournisseur; + if (! $error) + { + dol_syslog(get_class($this)."::Create success id=".$this->id); + $this->db->commit(); + return $this->id; + } + else + { + dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',',$this->errors), LOG_ERR); + $this->db->rollback(); + return -4; + } + } + else + { + if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name); // duplicate on a field (code or profid or ...) + $result=-1; + } + else + { + $this->error=$this->db->lasterror(); + $result=-2; + } + $this->db->rollback(); + return $result; + } - $this->note = $obj->note_private; // TODO Deprecated for backward comtability - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->modelpdf = $obj->model_pdf; - $this->default_lang = $obj->default_lang; - $this->logo = $obj->logo; + } + else + { + $this->db->rollback(); + dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING); + return -3; + } + } - $this->webservices_url = $obj->webservices_url; - $this->webservices_key = $obj->webservices_key; - $this->outstanding_limit = $obj->outstanding_limit; + /** + * Create a contact/address from thirdparty + * + * @param User $user Object user + * @return int <0 if KO, >0 if OK + */ + function create_individual(User $user) + { + require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; + $contact=new Contact($this->db); + + $contact->name = $this->name_bis; + $contact->firstname = $this->firstname; + $contact->civility_id = $this->civility_id; + $contact->socid = $this->id; // fk_soc + $contact->statut = 1; + $contact->priv = 0; + $contact->country_id = $this->country_id; + $contact->state_id = $this->state_id; + $contact->address = $this->address; + $contact->email = $this->email; + $contact->zip = $this->zip; + $contact->town = $this->town; + $contact->phone_pro = $this->phone; + + $result = $contact->create($user); + if ($result < 0) + { + $this->error = $contact->error; + $this->errors = $contact->errors; + dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR); + } - // multiprix - $this->price_level = $obj->price_level; + return $result; + } - $this->import_key = $obj->import_key; + /** + * Check properties of third party are ok (like name, third party codes, ...) + * Used before an add or update. + * + * @return int 0 if OK, <0 if KO + */ + function verify() + { + global $conf, $langs, $mysoc; - //Incoterms - $this->fk_incoterms = $obj->fk_incoterms; - $this->location_incoterms = $obj->location_incoterms; - $this->libelle_incoterms = $obj->libelle_incoterms; + $error = 0; + $this->errors=array(); - // multicurrency - $this->fk_multicurrency = $obj->fk_multicurrency; - $this->multicurrency_code = $obj->multicurrency_code; + $result = 0; + $this->name = trim($this->name); + $this->nom=$this->name; // For backward compatibility - $result = 1; + if (! $this->name) + { + $this->errors[] = 'ErrorBadThirdPartyName'; + $result = -2; + } - // Retreive all extrafield for thirdparty - $this->fetch_optionals(); - } - else + if ($this->client) + { + $rescode = $this->check_codeclient(); + if ($rescode <> 0) { - $result = 0; - } + if ($rescode == -1) + { + $this->errors[] = 'ErrorBadCustomerCodeSyntax'; + } + if ($rescode == -2) + { + $this->errors[] = 'ErrorCustomerCodeRequired'; + } + if ($rescode == -3) + { + $this->errors[] = 'ErrorCustomerCodeAlreadyUsed'; + } + if ($rescode == -4) + { + $this->errors[] = 'ErrorPrefixRequired'; + } + $result = -3; + } + } - $this->db->free($resql); - } - else + if ($this->fournisseur) { - $this->error=$this->db->lasterror(); - $result = -3; - } + $rescode = $this->check_codefournisseur(); + if ($rescode <> 0) + { + if ($rescode == -1) + { + $this->errors[] = 'ErrorBadSupplierCodeSyntax'; + } + if ($rescode == -2) + { + $this->errors[] = 'ErrorSupplierCodeRequired'; + } + if ($rescode == -3) + { + $this->errors[] = 'ErrorSupplierCodeAlreadyUsed'; + } + if ($rescode == -5) + { + $this->errors[] = 'ErrorprefixRequired'; + } + $result = -3; + } + } - // Use first price level if level not defined for third party - if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1; - - return $result; - } - - /** - * Search and fetch thirparties by name - * - * @param string $name Name - * @param int $type Type of thirdparties (0=any, 1=customer, 2=prospect, 3=supplier) - * @param array $filters Array of couple field name/value to filter the companies with the same name - * @param boolean $exact Exact string search (true/false) - * @param boolean $case Case sensitive (true/false) - * @param boolean $similar Add test if string inside name into database, or name into database inside string. Do not use this: Not compatible with other database. - * @param string $clause Clause for filters - * @return array|int <0 if KO, array of thirdparties object if OK - */ - function searchByName($name, $type='0', $filters = array(), $exact = false, $case = false, $similar = false, $clause = 'AND') - { - $thirdparties = array(); - - dol_syslog("searchByName name=".$name." type=".$type." exact=".$exact); - - // Check parameter - if (empty($name)) - { - $this->errors[]='ErrorBadValueForParameter'; - return -1; - } - - // Generation requete recherche - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe"; - $sql.= " WHERE entity IN (".getEntity('category').")"; - if (! empty($type)) - { - if ($type == 1 || $type == 2) - $sql.= " AND client = ".$type; - elseif ($type == 3) - $sql.= " AND fournisseur = 1"; - } - if (! empty($name)) - { - if (! $exact) - { - if (preg_match('/^([\*])?[^*]+([\*])?$/', $name, $regs) && count($regs) > 1) - { - $name = str_replace('*', '%', $name); - } - else - { - $name = '%'.$name.'%'; - } - } - $sql.= " AND "; - if (is_array($filters) && ! empty($filters)) - $sql.= "("; - if ($similar) - { - // For test similitude (string inside name into database, or name into database inside string) - // Do not use this. Not compatible with other database. - $sql.= "(LOCATE('".$this->db->escape($name)."', nom) > 0 OR LOCATE(nom, '".$this->db->escape($name)."') > 0)"; - } - else - { - if (! $case) - $sql.= "nom LIKE '".$this->db->escape($name)."'"; - else - $sql.= "nom LIKE BINARY '".$this->db->escape($name)."'"; - } - } - if (is_array($filters) && ! empty($filters)) - { - foreach($filters as $field => $value) - { - if (! $exact) - { - if (preg_match('/^([\*])?[^*]+([\*])?$/', $value, $regs) && count($regs) > 1) - { - $value = str_replace('*', '%', $value); - } - else - { - $value = '%'.$value.'%'; - } - } - if (! $case) - $sql.= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'"; - else - $sql.= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'"; - } - if (! empty($name)) - $sql.= ")"; - } - - $res = $this->db->query($sql); - if ($res) - { - while ($rec = $this->db->fetch_array($res)) - { - $soc = new Societe($this->db); - $soc->fetch($rec['rowid']); - $thirdparties[] = $soc; - } - - return $thirdparties; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } - - /** - * Delete a third party from database and all its dependencies (contacts, rib...) - * - * @param int $id Id of third party to delete - * @param User $fuser User who ask to delete thirparty - * @param int $call_trigger 0=No, 1=yes - * @return int <0 if KO, 0 if nothing done, >0 if OK - */ - function delete($id, User $fuser=null, $call_trigger=1) - { - global $langs, $conf, $user; - - if (empty($fuser)) $fuser=$user; - - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - $entity=isset($this->entity)?$this->entity:$conf->entity; - - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $error = 0; - - // Test if child exists - $objectisused = $this->isObjectUsed($id); - if (empty($objectisused)) + // Check for duplicate or mandatory fields defined into setup + $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL'); + foreach($array_to_check as $key) { - $this->db->begin(); + $keymin=strtolower($key); + $i=(int) preg_replace('/[^0-9]/','',$key); + $vallabel=$this->$keymin; + + if ($i > 0) + { + if ($this->isACompany()) + { + // Check for unicity + if ($vallabel && $this->id_prof_verifiable($i)) + { + if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) + { + $langs->load("errors"); + $error++; $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')'; + } + } + + // Check for mandatory prof id (but only if country is other than ours) + if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) + { + $idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY'; + if (! $vallabel && ! empty($conf->global->$idprof_mandatory)) + { + $langs->load("errors"); + $error++; + $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')'; + } + } + } + } + else + { + //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY); + if ($key == 'EMAIL') + { + // Check for unicity + if ($vallabel) + { + if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) + { + $langs->load("errors"); + $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')'; + } + } + + // Check for mandatory + if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email)) + { + $langs->load("errors"); + $error++; + $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')'; + } + } + } + } + + if ($error) $result = -4; + + return $result; + } + + /** + * Update parameters of third party + * + * @param int $id id societe + * @param User $user Utilisateur qui demande la mise a jour + * @param int $call_trigger 0=non, 1=oui + * @param int $allowmodcodeclient Inclut modif code client et code compta + * @param int $allowmodcodefournisseur Inclut modif code fournisseur et code compta fournisseur + * @param string $action 'add' or 'update' + * @param int $nosyncmember Do not synchronize info of linked member + * @return int <0 if KO, >=0 if OK + */ + function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1) + { + global $langs,$conf,$hookmanager; + require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + + $error=0; + + dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur); + + $now=dol_now(); + + // Clean parameters + $this->id = $id; + $this->name = $this->name?trim($this->name):trim($this->nom); + $this->nom = $this->name; // For backward compatibility + $this->name_alias = trim($this->name_alias); + $this->ref_ext = trim($this->ref_ext); + $this->address = $this->address?trim($this->address):trim($this->address); + $this->zip = $this->zip?trim($this->zip):trim($this->zip); + $this->town = $this->town?trim($this->town):trim($this->town); + $this->state_id = trim($this->state_id); + $this->country_id = ($this->country_id > 0)?$this->country_id:0; + $this->phone = trim($this->phone); + $this->phone = preg_replace("/\s/","",$this->phone); + $this->phone = preg_replace("/\./","",$this->phone); + $this->fax = trim($this->fax); + $this->fax = preg_replace("/\s/","",$this->fax); + $this->fax = preg_replace("/\./","",$this->fax); + $this->email = trim($this->email); + $this->skype = trim($this->skype); + $this->url = $this->url?clean_url($this->url,0):''; + $this->idprof1 = trim($this->idprof1); + $this->idprof2 = trim($this->idprof2); + $this->idprof3 = trim($this->idprof3); + $this->idprof4 = trim($this->idprof4); + $this->idprof5 = (! empty($this->idprof5)?trim($this->idprof5):''); + $this->idprof6 = (! empty($this->idprof6)?trim($this->idprof6):''); + $this->prefix_comm = trim($this->prefix_comm); + $this->outstanding_limit = price2num($this->outstanding_limit); + + $this->tva_assuj = trim($this->tva_assuj); + $this->tva_intra = dol_sanitizeFileName($this->tva_intra,''); + if (empty($this->status)) $this->status = 0; + + if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); + if (empty($this->fk_multicurrency)) + { + $this->multicurrency_code = ''; + $this->fk_multicurrency = 0; + } + + // Local taxes + $this->localtax1_assuj=trim($this->localtax1_assuj); + $this->localtax2_assuj=trim($this->localtax2_assuj); + + $this->localtax1_value=trim($this->localtax1_value); + $this->localtax2_value=trim($this->localtax2_value); + + if ($this->capital != '') $this->capital=price2num(trim($this->capital)); + if (! is_numeric($this->capital)) $this->capital = ''; // '' = undef + + $this->effectif_id=trim($this->effectif_id); + $this->forme_juridique_code=trim($this->forme_juridique_code); + + //Gencod + $this->barcode=trim($this->barcode); + + // For automatic creation + if ($this->code_client == -1) $this->get_codeclient($this,0); + if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1); + + $this->code_compta=trim($this->code_compta); + $this->code_compta_fournisseur=trim($this->code_compta_fournisseur); + + // Check parameters. More tests are done later in the ->verify() + if (! is_numeric($this->client) && ! is_numeric($this->fournisseur)) + { + $langs->load("errors"); + $this->error = $langs->trans("BadValueForParameterClientOrSupplier"); + return -1; + } + + $customer=false; + if (! empty($allowmodcodeclient) && ! empty($this->client)) + { + // Attention get_codecompta peut modifier le code suivant le module utilise + if (empty($this->code_compta)) + { + $ret=$this->get_codecompta('customer'); + if ($ret < 0) return -1; + } + + $customer=true; + } + + $supplier=false; + if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur)) + { + // Attention get_codecompta peut modifier le code suivant le module utilise + if (empty($this->code_compta_fournisseur)) + { + $ret=$this->get_codecompta('supplier'); + if ($ret < 0) return -1; + } + + $supplier=true; + } + + //Web services + $this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):''; + $this->webservices_key = trim($this->webservices_key); + + //Incoterms + $this->fk_incoterms = (int) $this->fk_incoterms; + $this->location_incoterms = trim($this->location_incoterms); + + $this->db->begin(); + + // Check name is required and codes are ok or unique. + // If error, this->errors[] is filled + $result = 0; + if ($action != 'add') $result = $this->verify(); // We don't check when update called during a create because verify was already done + + if ($result >= 0) + { + dol_syslog(get_class($this)."::update verify ok or not done"); + + $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET "; + $sql .= "nom = '" . $this->db->escape($this->name) ."'"; // Required + $sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'"; + $sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null"); + $sql .= ",address = '" . $this->db->escape($this->address) ."'"; + + $sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null"); + $sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null"); + + $sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'"; + $sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'"; + + $sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null"); + $sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null"); + $sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null"); + $sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null"); + $sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null"); + + $sql .= ",siren = '". $this->db->escape($this->idprof1) ."'"; + $sql .= ",siret = '". $this->db->escape($this->idprof2) ."'"; + $sql .= ",ape = '". $this->db->escape($this->idprof3) ."'"; + $sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'"; + $sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'"; + $sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'"; + + $sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null"); + $sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'"; + $sql .= ",status = " .$this->status; + + // Local taxes + $sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null"); + $sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null"); + if($this->localtax1_assuj==1) + { + if($this->localtax1_value!='') + { + $sql .=",localtax1_value =".$this->localtax1_value; + } + else $sql .=",localtax1_value =0.000"; + + } + else $sql .=",localtax1_value =0.000"; + + if($this->localtax2_assuj==1) + { + if($this->localtax2_value!='') + { + $sql .=",localtax2_value =".$this->localtax2_value; + } + else $sql .=",localtax2_value =0.000"; + + } + else $sql .=",localtax2_value =0.000"; + + $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital); + + $sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null"); + + $sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null"); + if (isset($this->stcomm_id)) + { + $sql .= ",fk_stcomm=".($this->stcomm_id > 0 ? $this->stcomm_id : "0"); + } + $sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0"); + + $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null"); + + $sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null"); + $sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null"); + $sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null"); + $sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null"); + $sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null"); + + $sql .= ",client = " . (! empty($this->client)?$this->client:0); + $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0); + $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null"); + $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null"); + $sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null"); + $sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null'); + $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'"; + + $sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null"); + $sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null"); + + //Incoterms + $sql.= ", fk_incoterms = ".$this->fk_incoterms; + $sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null"); + + if ($customer) + { + $sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null"); + $sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null"); + } + + if ($supplier) + { + $sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null"); + $sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null"); + } + $sql .= ", fk_user_modif = ".(! empty($user->id)?"'".$user->id."'":"null"); + $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency; + $sql .= ', multicurrency_code = \''.$this->db->escape($this->multicurrency_code)."'"; + $sql .= " WHERE rowid = '" . $id ."'"; + + $resql=$this->db->query($sql); + if ($resql) + { + unset($this->country_code); // We clean this because it may have been changed after an update of country_id + unset($this->country); + unset($this->state_code); + unset($this->state); + + $nbrowsaffected = $this->db->affected_rows($resql); + + if (! $error && $nbrowsaffected) + { + // Update information on linked member if it is an update + if (! $nosyncmember && ! empty($conf->adherent->enabled)) + { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + + dol_syslog(get_class($this)."::update update linked member"); + + $lmember=new Adherent($this->db); + $result=$lmember->fetch(0, 0, $this->id); + + if ($result > 0) + { + $lmember->societe=$this->name; + //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged + //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged + $lmember->address=$this->address; + $lmember->email=$this->email; + $lmember->skype=$this->skype; + $lmember->phone=$this->phone; + + $result=$lmember->update($user,0,1,1,1); // Use nosync to 1 to avoid cyclic updates + if ($result < 0) + { + $this->error=$lmember->error; + dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR); + $error++; + } + } + else if ($result < 0) + { + $this->error=$lmember->error; + $error++; + } + } + } + + $action='update'; + + // Actions on extra fields (by external module or standard code) + // TODO le hook fait double emploi avec le trigger !! + $hookmanager->initHooks(array('thirdpartydao')); + $parameters=array('socid'=>$this->id); + $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if (empty($reshook)) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + } + else if ($reshook < 0) $error++; + + if (! $error && $call_trigger) + { + // Call trigger + $result=$this->call_trigger('COMPANY_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + dol_syslog(get_class($this)."::Update success"); + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } + else + { + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + // Doublon + $this->error = $langs->trans("ErrorDuplicateField"); + $result = -1; + } + else + { + $this->error = $this->db->lasterror(); + $result = -2; + } + $this->db->rollback(); + return $result; + } + } + else + { + $this->db->rollback(); + dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING); + return -3; + } + } + + /** + * Load a third party from database into memory + * + * @param int $rowid Id of third party to load + * @param string $ref Reference of third party, name (Warning, this can return several records) + * @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr) + * @param string $ref_int Internal reference of third party (not used by dolibarr) + * @param string $idprof1 Prof id 1 of third party (Warning, this can return several records) + * @param string $idprof2 Prof id 2 of third party (Warning, this can return several records) + * @param string $idprof3 Prof id 3 of third party (Warning, this can return several records) + * @param string $idprof4 Prof id 4 of third party (Warning, this can return several records) + * @param string $idprof5 Prof id 5 of third party (Warning, this can return several records) + * @param string $idprof6 Prof id 6 of third party (Warning, this can return several records) + * @param string $email Email (Warning, this can return several records) + * @return int >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found. + */ + function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='', $email='') + { + global $langs; + global $conf; + + if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1; + + $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm'; + $sql .= ', s.status'; + $sql .= ', s.price_level'; + $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif'; + $sql .= ', s.phone, s.fax, s.email, s.skype, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur'; + $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6'; + $sql .= ', s.capital, s.tva_intra'; + $sql .= ', s.fk_typent as typent_id'; + $sql .= ', s.fk_effectif as effectif_id'; + $sql .= ', s.fk_forme_juridique as forme_juridique_code'; + $sql .= ', s.webservices_url, s.webservices_key'; + $sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode'; + $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj'; + $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo'; + $sql .= ', s.fk_shipping_method'; + $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms'; + $sql .= ', s.fk_multicurrency, s.multicurrency_code'; + $sql .= ', fj.libelle as forme_juridique'; + $sql .= ', e.libelle as effectif'; + $sql .= ', c.code as country_code, c.label as country'; + $sql .= ', d.code_departement as state_code, d.nom as state'; + $sql .= ', st.libelle as stcomm'; + $sql .= ', te.code as typent_code'; + $sql .= ', i.libelle as libelle_incoterms'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid'; + $sql .= ' WHERE s.entity IN ('.getEntity($this->element, 1).')'; + if ($rowid) $sql .= ' AND s.rowid = '.$rowid; + if ($ref) $sql .= " AND s.nom = '".$this->db->escape($ref)."'"; + if ($ref_ext) $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'"; + if ($ref_int) $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'"; + if ($idprof1) $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'"; + if ($idprof2) $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'"; + if ($idprof3) $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'"; + if ($idprof4) $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'"; + if ($idprof5) $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'"; + if ($idprof6) $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'"; + if ($email) $sql .= " AND email = '".$this->db->escape($email)."'"; + + $resql=$this->db->query($sql); + if ($resql) + { + $num=$this->db->num_rows($resql); + if ($num > 1) + { + $this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.'; + dol_syslog($this->error, LOG_ERR); + $result = -2; + } + elseif ($num) // $num = 1 + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->entity = $obj->entity; + $this->canvas = $obj->canvas; + + $this->ref = $obj->rowid; + $this->name = $obj->name; + $this->nom = $obj->name; // deprecated + $this->name_alias = $obj->name_alias; + $this->ref_ext = $obj->ref_ext; + $this->ref_int = $obj->ref_int; + + $this->date_creation = $this->db->jdate($obj->date_creation); + $this->date_modification = $this->db->jdate($obj->date_modification); + $this->user_creation = $obj->fk_user_creat; + $this->user_modification = $obj->fk_user_modif; + + $this->address = $obj->address; + $this->zip = $obj->zip; + $this->town = $obj->town; + + $this->country_id = $obj->country_id; + $this->country_code = $obj->country_id?$obj->country_code:''; + $this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):''; + + $this->state_id = $obj->fk_departement; + $this->state_code = $obj->state_code; + $this->state = ($obj->state!='-'?$obj->state:''); + + $transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm); + $libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm); + $this->stcomm_id = $obj->fk_stcomm; // id statut commercial + $this->statut_commercial = $libelle; // libelle statut commercial + + $this->email = $obj->email; + $this->skype = $obj->skype; + $this->url = $obj->url; + $this->phone = $obj->phone; + $this->fax = $obj->fax; + + $this->parent = $obj->parent; + + $this->idprof1 = $obj->idprof1; + $this->idprof2 = $obj->idprof2; + $this->idprof3 = $obj->idprof3; + $this->idprof4 = $obj->idprof4; + $this->idprof5 = $obj->idprof5; + $this->idprof6 = $obj->idprof6; + + $this->capital = $obj->capital; + + $this->code_client = $obj->code_client; + $this->code_fournisseur = $obj->code_fournisseur; + + $this->code_compta = $obj->code_compta; + $this->code_compta_fournisseur = $obj->code_compta_fournisseur; + + $this->barcode = $obj->barcode; + + $this->tva_assuj = $obj->tva_assuj; + $this->tva_intra = $obj->tva_intra; + $this->status = $obj->status; + + // Local Taxes + $this->localtax1_assuj = $obj->localtax1_assuj; + $this->localtax2_assuj = $obj->localtax2_assuj; + + $this->localtax1_value = $obj->localtax1_value; + $this->localtax2_value = $obj->localtax2_value; + + $this->typent_id = $obj->typent_id; + $this->typent_code = $obj->typent_code; + + $this->effectif_id = $obj->effectif_id; + $this->effectif = $obj->effectif_id?$obj->effectif:''; + + $this->forme_juridique_code= $obj->forme_juridique_code; + $this->forme_juridique = $obj->forme_juridique_code?$obj->forme_juridique:''; + + $this->fk_prospectlevel = $obj->fk_prospectlevel; + + $this->prefix_comm = $obj->prefix_comm; + + $this->remise_percent = $obj->remise_client; + $this->mode_reglement_id = $obj->mode_reglement; + $this->cond_reglement_id = $obj->cond_reglement; + $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier; + $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier; + $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; + $this->fk_account = $obj->fk_account; + + $this->client = $obj->client; + $this->fournisseur = $obj->fournisseur; + + $this->note = $obj->note_private; // TODO Deprecated for backward comtability + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->modelpdf = $obj->model_pdf; + $this->default_lang = $obj->default_lang; + $this->logo = $obj->logo; + + $this->webservices_url = $obj->webservices_url; + $this->webservices_key = $obj->webservices_key; + + $this->outstanding_limit = $obj->outstanding_limit; + + // multiprix + $this->price_level = $obj->price_level; + + $this->import_key = $obj->import_key; + + //Incoterms + $this->fk_incoterms = $obj->fk_incoterms; + $this->location_incoterms = $obj->location_incoterms; + $this->libelle_incoterms = $obj->libelle_incoterms; + + // multicurrency + $this->fk_multicurrency = $obj->fk_multicurrency; + $this->multicurrency_code = $obj->multicurrency_code; + + $result = 1; + + // Retreive all extrafield for thirdparty + $this->fetch_optionals(); + } + else + { + $result = 0; + } + + $this->db->free($resql); + } + else + { + $this->error=$this->db->lasterror(); + $result = -3; + } + + // Use first price level if level not defined for third party + if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1; + + return $result; + } + + /** + * Search and fetch thirparties by name + * + * @param string $name Name + * @param int $type Type of thirdparties (0=any, 1=customer, 2=prospect, 3=supplier) + * @param array $filters Array of couple field name/value to filter the companies with the same name + * @param boolean $exact Exact string search (true/false) + * @param boolean $case Case sensitive (true/false) + * @param boolean $similar Add test if string inside name into database, or name into database inside string. Do not use this: Not compatible with other database. + * @param string $clause Clause for filters + * @return array|int <0 if KO, array of thirdparties object if OK + */ + function searchByName($name, $type='0', $filters = array(), $exact = false, $case = false, $similar = false, $clause = 'AND') + { + $thirdparties = array(); + + dol_syslog("searchByName name=".$name." type=".$type." exact=".$exact); + + // Check parameter + if (empty($name)) + { + $this->errors[]='ErrorBadValueForParameter'; + return -1; + } + + // Generation requete recherche + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe"; + $sql.= " WHERE entity IN (".getEntity('category').")"; + if (! empty($type)) + { + if ($type == 1 || $type == 2) + $sql.= " AND client = ".$type; + elseif ($type == 3) + $sql.= " AND fournisseur = 1"; + } + if (! empty($name)) + { + if (! $exact) + { + if (preg_match('/^([\*])?[^*]+([\*])?$/', $name, $regs) && count($regs) > 1) + { + $name = str_replace('*', '%', $name); + } + else + { + $name = '%'.$name.'%'; + } + } + $sql.= " AND "; + if (is_array($filters) && ! empty($filters)) + $sql.= "("; + if ($similar) + { + // For test similitude (string inside name into database, or name into database inside string) + // Do not use this. Not compatible with other database. + $sql.= "(LOCATE('".$this->db->escape($name)."', nom) > 0 OR LOCATE(nom, '".$this->db->escape($name)."') > 0)"; + } + else + { + if (! $case) + $sql.= "nom LIKE '".$this->db->escape($name)."'"; + else + $sql.= "nom LIKE BINARY '".$this->db->escape($name)."'"; + } + } + if (is_array($filters) && ! empty($filters)) + { + foreach($filters as $field => $value) + { + if (! $exact) + { + if (preg_match('/^([\*])?[^*]+([\*])?$/', $value, $regs) && count($regs) > 1) + { + $value = str_replace('*', '%', $value); + } + else + { + $value = '%'.$value.'%'; + } + } + if (! $case) + $sql.= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'"; + else + $sql.= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'"; + } + if (! empty($name)) + $sql.= ")"; + } + + $res = $this->db->query($sql); + if ($res) + { + while ($rec = $this->db->fetch_array($res)) + { + $soc = new Societe($this->db); + $soc->fetch($rec['rowid']); + $thirdparties[] = $soc; + } + + return $thirdparties; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + + /** + * Delete a third party from database and all its dependencies (contacts, rib...) + * + * @param int $id Id of third party to delete + * @param User $fuser User who ask to delete thirparty + * @param int $call_trigger 0=No, 1=yes + * @return int <0 if KO, 0 if nothing done, >0 if OK + */ + function delete($id, User $fuser=null, $call_trigger=1) + { + global $langs, $conf, $user; + + if (empty($fuser)) $fuser=$user; + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + $entity=isset($this->entity)?$this->entity:$conf->entity; + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $error = 0; + + // Test if child exists + $objectisused = $this->isObjectUsed($id); + if (empty($objectisused)) + { + $this->db->begin(); + + // User is mandatory for trigger call + if (! $error && $call_trigger) + { + // Call trigger + $result=$this->call_trigger('COMPANY_DELETE',$fuser); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $static_cat = new Categorie($this->db); + $toute_categs = array(); + + // Fill $toute_categs array with an array of (type => array of ("Categorie" instance)) + if ($this->client || $this->prospect) + { + $toute_categs['societe'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER); + } + if ($this->fournisseur) + { + $toute_categs['fournisseur'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER); + } + + // Remove each "Categorie" + foreach ($toute_categs as $type => $categs_type) + { + foreach ($categs_type as $cat) + { + $cat->del_type($this, $type); + } + } + } + + foreach ($this->childtablesoncascade as $tabletodelete) + { + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete; + $sql.= " WHERE fk_soc = " . $id; + if (! $this->db->query($sql)) + { + $error++; + $this->errors[] = $this->db->lasterror(); + } + } + } + + // Removed extrafields + if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + { + $result=$this->deleteExtraFields(); + if ($result < 0) + { + $error++; + dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR); + } + } + + // Remove third party + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe"; + $sql.= " WHERE rowid = " . $id; + if (! $this->db->query($sql)) + { + $error++; + $this->errors[] = $this->db->lasterror(); + } + } + + if (! $error) + { + $this->db->commit(); + + // Delete directory + if (! empty($conf->societe->multidir_output[$entity])) + { + $docdir = $conf->societe->multidir_output[$entity] . "/" . $id; + if (dol_is_dir($docdir)) + { + dol_delete_dir_recursive($docdir); + } + } + + return 1; + } + else + { + dol_syslog($this->error, LOG_ERR); + $this->db->rollback(); + return -1; + } + } + else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING); + return 0; + } + + /** + * Define third party as a customer + * + * @return int <0 if KO, >0 if OK + */ + function set_as_client() + { + if ($this->id) + { + $newclient=1; + if ($this->client == 2 || $this->client == 3) $newclient=3; //If prospect, we keep prospect tag + $sql = "UPDATE ".MAIN_DB_PREFIX."societe"; + $sql.= " SET client = ".$newclient; + $sql.= " WHERE rowid = " . $this->id; + + $resql=$this->db->query($sql); + if ($resql) + { + $this->client = $newclient; + return 1; + } + else return -1; + } + return 0; + } + + /** + * Definit la societe comme un client + * + * @param float $remise Valeur en % de la remise + * @param string $note Note/Motif de modification de la remise + * @param User $user Utilisateur qui definie la remise + * @return int <0 if KO, >0 if OK + */ + function set_remise_client($remise, $note, User $user) + { + global $conf, $langs; + + // Nettoyage parametres + $note=trim($note); + if (! $note) + { + $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason")); + return -2; + } + + dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id); + + if ($this->id) + { + $this->db->begin(); + + $now=dol_now(); + + // Positionne remise courante + $sql = "UPDATE ".MAIN_DB_PREFIX."societe "; + $sql.= " SET remise_client = '".$this->db->escape($remise)."'"; + $sql.= " WHERE rowid = " . $this->id; + $resql=$this->db->query($sql); + if (! $resql) + { + $this->db->rollback(); + $this->error=$this->db->error(); + return -1; + } + + // Ecrit trace dans historique des remises + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise"; + $sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)"; + $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',"; + $sql.= " '".$this->db->escape($note)."',"; + $sql.= " ".$user->id; + $sql.= ")"; + + $resql=$this->db->query($sql); + if (! $resql) + { + $this->db->rollback(); + $this->error=$this->db->lasterror(); + return -1; + } + + $this->db->commit(); + return 1; + } + } + + /** + * Add a discount for third party + * + * @param float $remise Amount of discount + * @param User $user User adding discount + * @param string $desc Reason of discount + * @param float $tva_tx VAT rate + * @return int <0 if KO, id of discount record if OK + */ + function set_remise_except($remise, User $user, $desc, $tva_tx=0) + { + global $langs; + + // Clean parameters + $remise = price2num($remise); + $desc = trim($desc); + + // Check parameters + if (! $remise > 0) + { + $this->error=$langs->trans("ErrorWrongValueForParameter","1"); + return -1; + } + if (! $desc) + { + $this->error=$langs->trans("ErrorWrongValueForParameter","3"); + return -2; + } + + if ($this->id) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + + $discount = new DiscountAbsolute($this->db); + $discount->fk_soc=$this->id; + $discount->amount_ht=price2num($remise,'MT'); + $discount->amount_tva=price2num($remise*$tva_tx/100,'MT'); + $discount->amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT'); + $discount->tva_tx=price2num($tva_tx,'MT'); + $discount->description=$desc; + $result=$discount->create($user); + if ($result > 0) + { + return $result; + } + else + { + $this->error=$discount->error; + return -3; + } + } + else return 0; + } + + /** + * Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe + * + * @param User $user Filtre sur un user auteur des remises + * @param string $filter Filtre autre + * @param integer $maxvalue Filter on max value for discount + * @return int <0 if KO, Credit note amount otherwise + */ + function getAvailableDiscounts($user='',$filter='',$maxvalue=0) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + + $discountstatic=new DiscountAbsolute($this->db); + $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue); + if ($result >= 0) + { + return $result; + } + else + { + $this->error=$discountstatic->error; + return -1; + } + } + + /** + * Return array of sales representatives + * + * @param User $user Object user + * @return array Array of sales representatives of third party + */ + function getSalesRepresentatives(User $user) + { + global $conf; + + $reparray=array(); + + $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u"; + if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; + $sql.= " WHERE ((ug.fk_user = sc.fk_user"; + $sql.= " AND ug.entity = ".$conf->entity.")"; + $sql.= " OR u.admin = 1)"; + } + else + $sql.= " WHERE entity in (0, ".$conf->entity.")"; + + $sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id; + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i=0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $reparray[$i]['id']=$obj->rowid; + $reparray[$i]['lastname']=$obj->lastname; + $reparray[$i]['firstname']=$obj->firstname; + $reparray[$i]['email']=$obj->email; + $reparray[$i]['statut']=$obj->statut; + $reparray[$i]['entity']=$obj->entity; + $reparray[$i]['login']=$obj->login; + $reparray[$i]['photo']=$obj->photo; + $i++; + } + return $reparray; + } + else { + dol_print_error($this->db); + return -1; + } + } + + /** + * Set the price level + * + * @param int $price_level Level of price + * @param User $user Use making change + * @return int <0 if KO, >0 if OK + */ + function set_price_level($price_level, User $user) + { + if ($this->id) + { + $now=dol_now(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."societe"; + $sql .= " SET price_level = '".$this->db->escape($price_level)."'"; + $sql .= " WHERE rowid = " . $this->id; + + if (! $this->db->query($sql)) + { + dol_print_error($this->db); + return -1; + } + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices"; + $sql .= " (datec, fk_soc, price_level, fk_user_author)"; + $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")"; + + if (! $this->db->query($sql)) + { + dol_print_error($this->db); + return -1; + } + return 1; + } + return -1; + } + + /** + * Add link to sales representative + * + * @param User $user Object user + * @param int $commid Id of user + * @return void + */ + function add_commercial(User $user, $commid) + { + if ($this->id > 0 && $commid > 0) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux"; + $sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid; + + $this->db->query($sql); + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux"; + $sql.= " ( fk_soc, fk_user )"; + $sql.= " VALUES (".$this->id.",".$commid.")"; + + if (! $this->db->query($sql) ) + { + dol_syslog(get_class($this)."::add_commercial Erreur"); + } + } + } + + /** + * Add link to sales representative + * + * @param User $user Object user + * @param int $commid Id of user + * @return void + */ + function del_commercial(User $user, $commid) + { + if ($this->id > 0 && $commid > 0) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux "; + $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid; + + if (! $this->db->query($sql) ) + { + dol_syslog(get_class($this)."::del_commercial Erreur"); + } + } + } + + + /** + * Return a link on thirdparty (with picto) + * + * @param int $withpicto Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only) + * @param string $option Target of link ('', 'customer', 'prospect', 'supplier', 'project') + * @param int $maxlen Max length of name + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1) + { + global $conf, $langs, $hookmanager; + + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + + $name=$this->name?$this->name:$this->nom; + + if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) + { + if (($this->client) && (! empty ( $this->code_client )) + && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 + || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2 + ) + ) + $code = $this->code_client . ' - '; + + if (($this->fournisseur) && (! empty ( $this->code_fournisseur )) + && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 + || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3 + ) + ) + $code .= $this->code_fournisseur . ' - '; + + if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) + $name =$code.' '.$name; + else + $name =$code; + } + + if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')'; + + $result=''; $label=''; + $linkstart=''; $linkend=''; + + if (! empty($this->logo) && class_exists('Form')) + { + $label.= '<div class="photointooltip">'; + $label.= Form::showphoto('societe', $this, 80, 0, 0, 'photowithmargin', 'mini'); + $label.= '</div><div style="clear: both;"></div>'; + } + + $label.= '<div class="centpercent">'; + + if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier') + { + $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>'; + $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id; + } + else if ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) + { + $label.= '<u>' . $langs->trans("ShowProspect") . '</u>'; + $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id; + } + else if ($option == 'supplier') + { + $label.= '<u>' . $langs->trans("ShowSupplier") . '</u>'; + $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id; + } + else if ($option == 'agenda') + { + $label.= '<u>' . $langs->trans("ShowAgenda") . '</u>'; + $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id; + } + else if ($option == 'project') + { + $label.= '<u>' . $langs->trans("ShowProject") . '</u>'; + $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id; + } + else if ($option == 'margin') + { + $label.= '<u>' . $langs->trans("ShowMargin") . '</u>'; + $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1'; + } + else if ($option == 'contact') + { + $label.= '<u>' . $langs->trans("ShowContacts") . '</u>'; + $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id; + } + else if ($option == 'ban') + { + $label.= '<u>' . $langs->trans("ShowBan") . '</u>'; + $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/rib.php?socid='.$this->id; + } + + // By default + if (empty($linkstart)) + { + $label.= '<u>' . $langs->trans("ShowCompany") . '</u>'; + $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id; + } + + if (! empty($this->name)) + { + $label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name; + if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')'; + $label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email; + } + if (! empty($this->country_code)) + $label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code; + if (! empty($this->tva_intra)) + $label.= '<br><b>' . $langs->trans('VATNumber') . ':</b> '. $this->tva_intra; + if (! empty($this->code_client) && $this->client) + $label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client; + if (! empty($this->code_fournisseur) && $this->fournisseur) + $label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur; + if (! empty($conf->accounting->enabled) && $this->client) + $label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. $this->code_compta_client; + if (! empty($conf->accounting->enabled) && $this->fournisseur) + $label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur; + + $label.= '</div>'; + + // Add type of canvas + $linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:''); + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1'; + $linkstart.='"'; + + $linkclose=''; + if (empty($notooltip)) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowCompany"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; + + if (! is_object($hookmanager)) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager=new HookManager($this->db); + } + $hookmanager->initHooks(array('societedao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + } + $linkstart.=$linkclose.'>'; + $linkend='</a>'; + + global $user; + if (! $user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id) + { + $linkstart=''; + $linkend=''; + } + + if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1).$linkend); + if ($withpicto && $withpicto != 2) $result.=' '; + if ($withpicto != 2) $result.=$linkstart.($maxlen?dol_trunc($name,$maxlen):$name).$linkend; + + return $result; + } + + /** + * Return label of status (activity, closed) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long + * @return string Libelle + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->status,$mode); + } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $statut Id statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle du statut + */ + function LibStatut($statut,$mode=0) + { + global $langs; + $langs->load('companies'); + + if ($mode == 0) + { + if ($statut==0) return $langs->trans("ActivityCeased"); + if ($statut==1) return $langs->trans("InActivity"); + } + if ($mode == 1) + { + if ($statut==0) return $langs->trans("ActivityCeased"); + if ($statut==1) return $langs->trans("InActivity"); + } + if ($mode == 2) + { + if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased"); + if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity"); + } + if ($mode == 3) + { + if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"'); + if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"'); + } + if ($mode == 4) + { + if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased"); + if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity"); + } + if ($mode == 5) + { + if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"'); + if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"'); + } + } + + /** + * Return list of contacts emails existing for third party + * + * @param int $addthirdparty 1=Add also a record for thirdparty email + * @return array Array of contacts emails + */ + function thirdparty_and_contact_email_array($addthirdparty=0) + { + global $langs; + + $contact_emails = $this->contact_property_array('email',1); + if ($this->email && $addthirdparty) + { + if (empty($this->name)) $this->name=$this->nom; + $contact_emails['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->email.">"; + } + //var_dump($contact_emails) + return $contact_emails; + } + + /** + * Return list of contacts mobile phone existing for third party + * + * @return array Array of contacts emails + */ + function thirdparty_and_contact_phone_array() + { + global $langs; + + $contact_phone = $this->contact_property_array('mobile'); + + if (! empty($this->phone)) // If a phone of thirdparty is defined, we add it ot mobile of contacts + { + if (empty($this->name)) $this->name=$this->nom; + // TODO: Tester si tel non deja present dans tableau contact + $contact_phone['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->phone.">"; + } + return $contact_phone; + } + + /** + * Return list of contacts emails or mobile existing for third party + * + * @param string $mode 'email' or 'mobile' + * @param int $hidedisabled 1=Hide contact if disabled + * @return array Array of contacts emails or mobile array(id=>'Name <email>') + */ + function contact_property_array($mode='email', $hidedisabled=0) + { + global $langs; + + $contact_property = array(); + + + $sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname"; + $sql.= " FROM ".MAIN_DB_PREFIX."socpeople"; + $sql.= " WHERE fk_soc = ".$this->id; + + $resql=$this->db->query($sql); + if ($resql) + { + $nump = $this->db->num_rows($resql); + if ($nump) + { + $sepa="("; $sepb=")"; + if ($mode == 'email') + { + $sepa="<"; $sepb=">"; + } + $i = 0; + while ($i < $nump) + { + $obj = $this->db->fetch_object($resql); + if ($mode == 'email') $property=$obj->email; + else if ($mode == 'mobile') $property=$obj->phone_mobile; + else $property=$obj->$mode; + + // Show all contact. If hidedisabled is 1, showonly contacts with status = 1 + if ($obj->statut == 1 || empty($hidedisabled)) + { + if (empty($property)) + { + if ($mode == 'email') $property=$langs->trans("NoEMail"); + else if ($mode == 'mobile') $property=$langs->trans("NoMobilePhone"); + } + + if (!empty($obj->poste)) + { + $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:''); + } + else + { + $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:''); + } + } + $i++; + } + } + } + else + { + dol_print_error($this->db); + } + return $contact_property; + } + + + /** + * Renvoie la liste des contacts de cette societe + * + * @return array tableau des contacts + */ + function contact_array() + { + $contacts = array(); + + $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id; + $resql=$this->db->query($sql); + if ($resql) + { + $nump = $this->db->num_rows($resql); + if ($nump) + { + $i = 0; + while ($i < $nump) + { + $obj = $this->db->fetch_object($resql); + $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname); + $i++; + } + } + } + else + { + dol_print_error($this->db); + } + return $contacts; + } + + /** + * Renvoie la liste des contacts de cette societe + * + * @return array $contacts tableau des contacts + */ + function contact_array_objects() + { + require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; + $contacts = array(); + + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id; + $resql=$this->db->query($sql); + if ($resql) + { + $nump = $this->db->num_rows($resql); + if ($nump) + { + $i = 0; + while ($i < $nump) + { + $obj = $this->db->fetch_object($resql); + $contact = new Contact($this->db); + $contact->fetch($obj->rowid); + $contacts[] = $contact; + $i++; + } + } + } + else + { + dol_print_error($this->db); + } + return $contacts; + } + + /** + * Return property of contact from its id + * + * @param int $rowid id of contact + * @param string $mode 'email' or 'mobile' + * @return string Email of contact with format: "Full name <email>" + */ + function contact_get_property($rowid,$mode) + { + $contact_property=''; + + if (empty($rowid)) return ''; + + $sql = "SELECT rowid, email, phone_mobile, lastname, firstname"; + $sql.= " FROM ".MAIN_DB_PREFIX."socpeople"; + $sql.= " WHERE rowid = '".$rowid."'"; + + $resql=$this->db->query($sql); + if ($resql) + { + $nump = $this->db->num_rows($resql); + + if ($nump) + { + $obj = $this->db->fetch_object($resql); + + if ($mode == 'email') $contact_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">"; + else if ($mode == 'mobile') $contact_property = $obj->phone_mobile; + } + return $contact_property; + } + else + { + dol_print_error($this->db); + } + + } + + + /** + * Return bank number property of thirdparty (label or rum) + * + * @param string $mode 'label' or 'rum' or 'format' + * @return string Bank number + */ + function display_rib($mode='label') + { + require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + + $bac = new CompanyBankAccount($this->db); + $bac->fetch(0,$this->id); + + if ($mode == 'label') + { + return $bac->getRibLabel(true); + } + elseif ($mode == 'rum') + { + if (empty($bac->rum)) + { + require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php'; + $prelevement = new BonPrelevement($this->db); + $bac->fetch_thirdparty(); + $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id); + } + return $bac->rum; + } + elseif ($mode == 'format') + { + return $bac->frstrecur; + } + + return 'BadParameterToFunctionDisplayRib'; + } + + /** + * Return Array of RIB + * + * @return array|int 0 if KO, Array of CompanyBanckAccount if OK + */ + function get_all_rib() + { + require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc = ".$this->id; + $result = $this->db->query($sql); + if (!$result) { + $this->error++; + $this->errors[] = $this->db->lasterror; + return 0; + } else { + $num_rows = $this->db->num_rows($result); + $rib_array = array(); + if ($num_rows) { + while ($obj = $this->db->fetch_object($result)) { + $rib = new CompanyBankAccount($this->db); + $rib->fetch($obj->rowid); + $rib_array[] = $rib; + } + } + return $rib_array; + } + } + + /** + * Attribut un code client a partir du module de controle des codes. + * Return value is stored into this->code_client + * + * @param Societe $objsoc Object thirdparty + * @param int $type Should be 0 to say customer + * @return void + */ + function get_codeclient($objsoc=0,$type=0) + { + global $conf; + if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + { + $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + + $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); + foreach ($dirsociete as $dirroot) + { + $res=dol_include_once($dirroot.$module.'.php'); + if ($res) break; + } + $mod = new $module(); + + $this->code_client = $mod->getNextValue($objsoc,$type); + $this->prefixCustomerIsRequired = $mod->prefixIsRequired; + + dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module); + } + } + + /** + * Attribut un code fournisseur a partir du module de controle des codes. + * Return value is stored into this->code_fournisseur + * + * @param Societe $objsoc Object thirdparty + * @param int $type Should be 1 to say supplier + * @return void + */ + function get_codefournisseur($objsoc=0,$type=1) + { + global $conf; + if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + { + $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + + $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); + foreach ($dirsociete as $dirroot) + { + $res=dol_include_once($dirroot.$module.'.php'); + if ($res) break; + } + $mod = new $module(); + + $this->code_fournisseur = $mod->getNextValue($objsoc,$type); + + dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module); + } + } + + /** + * Verifie si un code client est modifiable en fonction des parametres + * du module de controle des codes. + * + * @return int 0=No, 1=Yes + */ + function codeclient_modifiable() + { + global $conf; + if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + { + $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + + $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); + foreach ($dirsociete as $dirroot) + { + $res=dol_include_once($dirroot.$module.'.php'); + if ($res) break; + } + + $mod = new $module(); + + dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module); + if ($mod->code_modifiable_null && ! $this->code_client) return 1; + if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1; + if ($mod->code_modifiable) return 1; // A mettre en dernier + return 0; + } + else + { + return 0; + } + } + + + /** + * Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes + * + * @return int 0=No, 1=Yes + */ + function codefournisseur_modifiable() + { + global $conf; + if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + { + $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + + $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); + foreach ($dirsociete as $dirroot) + { + $res=dol_include_once($dirroot.$module.'.php'); + if ($res) break; + } + + $mod = new $module(); + + dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module); + if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1; + if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1; + if ($mod->code_modifiable) return 1; // A mettre en dernier + return 0; + } + else + { + return 0; + } + } + + + /** + * Check customer code + * + * @return int 0 if OK + * -1 ErrorBadCustomerCodeSyntax + * -2 ErrorCustomerCodeRequired + * -3 ErrorCustomerCodeAlreadyUsed + * -4 ErrorPrefixRequired + */ + function check_codeclient() + { + global $conf; + if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + { + $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + + $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); + foreach ($dirsociete as $dirroot) + { + $res=dol_include_once($dirroot.$module.'.php'); + if ($res) break; + } + + $mod = new $module(); + + dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module); + $result = $mod->verif($this->db, $this->code_client, $this, 0); + return $result; + } + else + { + return 0; + } + } + + /** + * Check supplier code + * + * @return int 0 if OK + * -1 ErrorBadCustomerCodeSyntax + * -2 ErrorCustomerCodeRequired + * -3 ErrorCustomerCodeAlreadyUsed + * -4 ErrorPrefixRequired + */ + function check_codefournisseur() + { + global $conf; + if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + { + $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + + $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); + foreach ($dirsociete as $dirroot) + { + $res=dol_include_once($dirroot.$module.'.php'); + if ($res) break; + } + + $mod = new $module(); + + dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module); + $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1); + return $result; + } + else + { + return 0; + } + } + + /** + * Renvoie un code compta, suivant le module de code compta. + * Peut etre identique a celui saisit ou genere automatiquement. + * A ce jour seule la generation automatique est implementee + * + * @param string $type Type of thirdparty ('customer' or 'supplier') + * @return string Code compta si ok, 0 si aucun, <0 si ko + */ + function get_codecompta($type) + { + global $conf; + + if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) + { + $file=''; + $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + foreach ($dirsociete as $dirroot) + { + if (file_exists(DOL_DOCUMENT_ROOT.'/'.$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php")) + { + $file=$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php"; + break; + } + } + + if (! empty($file)) + { + dol_include_once($file); + + $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON; + $mod = new $classname; + + // Defini code compta dans $mod->code + $result = $mod->get_code($this->db, $this, $type); + + if ($type == 'customer') $this->code_compta = $mod->code; + else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code; + + return $result; + } + else + { + $this->error = 'ErrorAccountancyCodeNotDefined'; + return -1; + } + } + else + { + if ($type == 'customer') $this->code_compta = ''; + else if ($type == 'supplier') $this->code_compta_fournisseur = ''; + + return 0; + } + } + + /** + * Define parent commany of current company + * + * @param int $id Id of thirdparty to set or '' to remove + * @return int <0 if KO, >0 if OK + */ + function set_parent($id) + { + if ($this->id) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."societe"; + $sql.= " SET parent = ".($id > 0 ? $id : "null"); + $sql.= " WHERE rowid = " . $this->id; + dol_syslog(get_class($this).'::set_parent', LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->parent = $id; + return 1; + } + else + { + return -1; + } + } + else return -1; + } + + /** + * Returns if a profid sould be verified + * + * @param int $idprof 1,2,3,4,5,6 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm,5=idprof5,6=idprof6) + * @return boolean true , false + */ + function id_prof_verifiable($idprof) + { + global $conf; + + switch($idprof) + { + case 1: + $ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true); + break; + case 2: + $ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true); + break; + case 3: + $ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true); + break; + case 4: + $ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true); + break; + case 5: + $ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true); + break; + case 6: + $ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true); + break; + default: + $ret=false; + } + + return $ret; + } + + /** + * Verify if a profid exists into database for others thirds + * + * @param string $idprof 'idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','email' (Example: idprof1=siren, idprof2=siret, idprof3=naf, idprof4=rcs/rm) + * @param string $value Value of profid + * @param int $socid Id of thirdparty to exclude (if update) + * @return boolean True if exists, False if not + */ + function id_prof_exists($idprof, $value, $socid=0) + { + $field = $idprof; + + switch($idprof) // For backward compatibility + { + case '1': + case 'idprof1': + $field="siren"; + break; + case '2': + case 'idprof2': + $field="siret"; + break; + case '3': + case 'idprof3': + $field="ape"; + break; + case '4': + case 'idprof4': + $field="idprof4"; + break; + case '5': + $field="idprof5"; + break; + case '6': + $field="idprof6"; + break; + } + + //Verify duplicate entries + $sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")"; + if($socid) $sql .= " AND rowid <> ".$socid; + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + $count = $obj->idprof; + } + else + { + $count = 0; + print $this->db->error(); + } + $this->db->free($resql); + + if ($count > 0) return true; + else return false; + } + + /** + * Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...) + * + * @param int $idprof 1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm) + * @param Societe $soc Objet societe + * @return int <=0 if KO, >0 if OK + * TODO better to have this in a lib than into a business class + */ + function id_prof_check($idprof,$soc) + { + global $conf; + + $ok=1; + + if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1; + + // Verifie SIREN si pays FR + if ($idprof == 1 && $soc->country_code == 'FR') + { + $chaine=trim($this->idprof1); + $chaine=preg_replace('/(\s)/','',$chaine); + + if (dol_strlen($chaine) != 9) return -1; + + $sum = 0; + + for ($i = 0 ; $i < 10 ; $i = $i+2) + { + $sum = $sum + substr($this->idprof1, (8 - $i), 1); + } + + for ($i = 1 ; $i < 9 ; $i = $i+2) + { + $ps = 2 * substr($this->idprof1, (8 - $i), 1); + + if ($ps > 9) + { + $ps = substr($ps, 0,1) + substr($ps, 1, 1); + } + $sum = $sum + $ps; + } + + if (substr($sum, -1) != 0) return -1; + } + + // Verifie SIRET si pays FR + if ($idprof == 2 && $soc->country_code == 'FR') + { + $chaine=trim($this->idprof2); + $chaine=preg_replace('/(\s)/','',$chaine); + + if (dol_strlen($chaine) != 14) return -1; + } + + //Verify CIF/NIF/NIE if pays ES + //Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad + if ($idprof == 1 && $soc->country_code == 'ES') + { + $string=trim($this->idprof1); + $string=preg_replace('/(\s)/','',$string); + $string = strtoupper($string); + + for ($i = 0; $i < 9; $i ++) + $num[$i] = substr($string, $i, 1); + + //Check format + if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string)) + return 0; + + //Check NIF + if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) + if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) + return 1; + else + return -1; + + //algorithm checking type code CIF + $sum = $num[2] + $num[4] + $num[6]; + for ($i = 1; $i < 8; $i += 2) + $sum += substr((2 * $num[$i]),0,1) + substr((2 * $num[$i]),1,1); + $n = 10 - substr($sum, strlen($sum) - 1, 1); + + //Chek special NIF + if (preg_match('/^[KLM]{1}/', $string)) + if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) + return 1; + else + return -1; + + //Check CIF + if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) + if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) + return 2; + else + return -2; + + //Check NIE T + if (preg_match('/^[T]{1}/', $string)) + if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) + return 3; + else + return -3; + + //Check NIE XYZ + if (preg_match('/^[XYZ]{1}/', $string)) + if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1)) + return 3; + else + return -3; + + //Can not be verified + return -4; + } - // User is mandatory for trigger call - if (! $error && $call_trigger) - { - // Call trigger - $result=$this->call_trigger('COMPANY_DELETE',$fuser); - if ($result < 0) $error++; - // End call triggers - } + return $ok; + } - if (! $error) - { - require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $static_cat = new Categorie($this->db); - $toute_categs = array(); - - // Fill $toute_categs array with an array of (type => array of ("Categorie" instance)) - if ($this->client || $this->prospect) - { - $toute_categs['societe'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER); - } - if ($this->fournisseur) - { - $toute_categs['fournisseur'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER); - } - - // Remove each "Categorie" - foreach ($toute_categs as $type => $categs_type) - { - foreach ($categs_type as $cat) - { - $cat->del_type($this, $type); - } - } - } + /** + * Return an url to check online a professional id or empty string + * + * @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm) + * @param Societe $thirdparty Object thirdparty + * @return string Url or empty string if no URL known + * TODO better in a lib than into business class + */ + function id_prof_url($idprof,$thirdparty) + { + global $conf,$langs,$hookmanager; - foreach ($this->childtablesoncascade as $tabletodelete) - { - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete; - $sql.= " WHERE fk_soc = " . $id; - if (! $this->db->query($sql)) - { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } - } + $url=''; + $action = ''; - // Removed extrafields - if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used - { - $result=$this->deleteExtraFields(); - if ($result < 0) - { - $error++; - dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR); - } - } - - // Remove third party - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe"; - $sql.= " WHERE rowid = " . $id; - if (! $this->db->query($sql)) - { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } - - if (! $error) - { - $this->db->commit(); - - // Delete directory - if (! empty($conf->societe->multidir_output[$entity])) - { - $docdir = $conf->societe->multidir_output[$entity] . "/" . $id; - if (dol_is_dir($docdir)) - { - dol_delete_dir_recursive($docdir); - } - } - - return 1; - } - else - { - dol_syslog($this->error, LOG_ERR); - $this->db->rollback(); - return -1; - } - } - else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING); - return 0; - } - - /** - * Define third party as a customer - * - * @return int <0 if KO, >0 if OK - */ - function set_as_client() - { - if ($this->id) - { - $newclient=1; - if ($this->client == 2 || $this->client == 3) $newclient=3; //If prospect, we keep prospect tag - $sql = "UPDATE ".MAIN_DB_PREFIX."societe"; - $sql.= " SET client = ".$newclient; - $sql.= " WHERE rowid = " . $this->id; - - $resql=$this->db->query($sql); - if ($resql) - { - $this->client = $newclient; - return 1; - } - else return -1; - } - return 0; - } - - /** - * Definit la societe comme un client - * - * @param float $remise Valeur en % de la remise - * @param string $note Note/Motif de modification de la remise - * @param User $user Utilisateur qui definie la remise - * @return int <0 if KO, >0 if OK - */ - function set_remise_client($remise, $note, User $user) - { - global $conf, $langs; - - // Nettoyage parametres - $note=trim($note); - if (! $note) - { - $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason")); - return -2; - } + $hookmanager->initHooks(array('idprofurl')); + $parameters=array('idprof'=>$idprof, 'company'=>$thirdparty); + $reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if (empty($reshook)) + { + if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return ''; - dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id); - - if ($this->id) - { - $this->db->begin(); - - $now=dol_now(); - - // Positionne remise courante - $sql = "UPDATE ".MAIN_DB_PREFIX."societe "; - $sql.= " SET remise_client = '".$this->db->escape($remise)."'"; - $sql.= " WHERE rowid = " . $this->id; - $resql=$this->db->query($sql); - if (! $resql) - { - $this->db->rollback(); - $this->error=$this->db->error(); - return -1; - } - - // Ecrit trace dans historique des remises - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise"; - $sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)"; - $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',"; - $sql.= " '".$this->db->escape($note)."',"; - $sql.= " ".$user->id; - $sql.= ")"; - - $resql=$this->db->query($sql); - if (! $resql) - { - $this->db->rollback(); - $this->error=$this->db->lasterror(); - return -1; - } - - $this->db->commit(); - return 1; - } - } - - /** - * Add a discount for third party - * - * @param float $remise Amount of discount - * @param User $user User adding discount - * @param string $desc Reason of discount - * @param float $tva_tx VAT rate - * @return int <0 if KO, id of discount record if OK - */ - function set_remise_except($remise, User $user, $desc, $tva_tx=0) - { - global $langs; - - // Clean parameters - $remise = price2num($remise); - $desc = trim($desc); - - // Check parameters - if (! $remise > 0) - { - $this->error=$langs->trans("ErrorWrongValueForParameter","1"); - return -1; - } - if (! $desc) - { - $this->error=$langs->trans("ErrorWrongValueForParameter","3"); - return -2; - } + // TODO Move links to validate professional ID into a dictionary table "country" + "link" + if ($idprof == 1 && $thirdparty->country_code == 'FR') $url='http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1; // See also http://avis-situation-sirene.insee.fr/ + //if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) $url='http://www.companieshouse.gov.uk/WebCHeck/findinfolink/'; // Link no more valid + if ($idprof == 1 && $thirdparty->country_code == 'ES') $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1; + if ($idprof == 1 && $thirdparty->country_code == 'IN') $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp'; - if ($this->id) - { - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - - $discount = new DiscountAbsolute($this->db); - $discount->fk_soc=$this->id; - $discount->amount_ht=price2num($remise,'MT'); - $discount->amount_tva=price2num($remise*$tva_tx/100,'MT'); - $discount->amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT'); - $discount->tva_tx=price2num($tva_tx,'MT'); - $discount->description=$desc; - $result=$discount->create($user); - if ($result > 0) - { - return $result; - } - else - { - $this->error=$discount->error; - return -3; - } - } - else return 0; - } - - /** - * Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe - * - * @param User $user Filtre sur un user auteur des remises - * @param string $filter Filtre autre - * @param integer $maxvalue Filter on max value for discount - * @return int <0 if KO, Credit note amount otherwise - */ - function getAvailableDiscounts($user='',$filter='',$maxvalue=0) - { - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - - $discountstatic=new DiscountAbsolute($this->db); - $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue); - if ($result >= 0) - { - return $result; - } - else - { - $this->error=$discountstatic->error; - return -1; - } - } - - /** - * Return array of sales representatives - * - * @param User $user Object user - * @return array Array of sales representatives of third party - */ - function getSalesRepresentatives(User $user) - { - global $conf; - - $reparray=array(); - - $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u"; - if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; - $sql.= " WHERE ((ug.fk_user = sc.fk_user"; - $sql.= " AND ug.entity = ".$conf->entity.")"; - $sql.= " OR u.admin = 1)"; - } - else - $sql.= " WHERE entity in (0, ".$conf->entity.")"; - - $sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id; - - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $reparray[$i]['id']=$obj->rowid; - $reparray[$i]['lastname']=$obj->lastname; - $reparray[$i]['firstname']=$obj->firstname; - $reparray[$i]['email']=$obj->email; - $reparray[$i]['statut']=$obj->statut; - $reparray[$i]['entity']=$obj->entity; - $reparray[$i]['login']=$obj->login; - $reparray[$i]['photo']=$obj->photo; - $i++; - } - return $reparray; - } - else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Set the price level - * - * @param int $price_level Level of price - * @param User $user Use making change - * @return int <0 if KO, >0 if OK - */ - function set_price_level($price_level, User $user) - { - if ($this->id) - { - $now=dol_now(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."societe"; - $sql .= " SET price_level = '".$this->db->escape($price_level)."'"; - $sql .= " WHERE rowid = " . $this->id; - - if (! $this->db->query($sql)) - { - dol_print_error($this->db); - return -1; - } - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices"; - $sql .= " (datec, fk_soc, price_level, fk_user_author)"; - $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")"; - - if (! $this->db->query($sql)) - { - dol_print_error($this->db); - return -1; - } - return 1; - } - return -1; - } - - /** - * Add link to sales representative - * - * @param User $user Object user - * @param int $commid Id of user - * @return void - */ - function add_commercial(User $user, $commid) - { - if ($this->id > 0 && $commid > 0) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux"; - $sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid; - - $this->db->query($sql); - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux"; - $sql.= " ( fk_soc, fk_user )"; - $sql.= " VALUES (".$this->id.",".$commid.")"; - - if (! $this->db->query($sql) ) - { - dol_syslog(get_class($this)."::add_commercial Erreur"); - } - } - } - - /** - * Add link to sales representative - * - * @param User $user Object user - * @param int $commid Id of user - * @return void - */ - function del_commercial(User $user, $commid) - { - if ($this->id > 0 && $commid > 0) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux "; - $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid; - - if (! $this->db->query($sql) ) - { - dol_syslog(get_class($this)."::del_commercial Erreur"); - } - } - } - - - /** - * Return a link on thirdparty (with picto) - * - * @param int $withpicto Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only) - * @param string $option Target of link ('', 'customer', 'prospect', 'supplier', 'project') - * @param int $maxlen Max length of name - * @param int $notooltip 1=Disable tooltip - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string String with URL - */ - function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1) - { - global $conf, $langs, $hookmanager; - - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips - - $name=$this->name?$this->name:$this->nom; - - if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) - { - if (($this->client) && (! empty ( $this->code_client )) - && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 - || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2 - ) - ) - $code = $this->code_client . ' - '; - - if (($this->fournisseur) && (! empty ( $this->code_fournisseur )) - && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 - || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3 - ) - ) - $code .= $this->code_fournisseur . ' - '; - - if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) - $name =$code.' '.$name; - else - $name =$code; - } - - if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')'; - - $result=''; $label=''; - $linkstart=''; $linkend=''; - - if (! empty($this->logo) && class_exists('Form')) - { - $label.= '<div class="photointooltip">'; - $label.= Form::showphoto('societe', $this, 80, 0, 0, 'photowithmargin', 'mini'); - $label.= '</div><div style="clear: both;"></div>'; - } + if ($url) return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>'; + } + else + { + return $hookmanager->resPrint; + } - $label.= '<div class="centpercent">'; + return ''; + } - if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier') - { - $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>'; - $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id; - } - else if ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) - { - $label.= '<u>' . $langs->trans("ShowProspect") . '</u>'; - $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id; - } - else if ($option == 'supplier') - { - $label.= '<u>' . $langs->trans("ShowSupplier") . '</u>'; - $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id; - } - else if ($option == 'agenda') - { - $label.= '<u>' . $langs->trans("ShowAgenda") . '</u>'; - $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id; - } - else if ($option == 'project') - { - $label.= '<u>' . $langs->trans("ShowProject") . '</u>'; - $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id; - } - else if ($option == 'margin') - { - $label.= '<u>' . $langs->trans("ShowMargin") . '</u>'; - $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1'; - } - else if ($option == 'contact') - { - $label.= '<u>' . $langs->trans("ShowContacts") . '</u>'; - $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id; - } - else if ($option == 'ban') - { - $label.= '<u>' . $langs->trans("ShowBan") . '</u>'; - $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/rib.php?socid='.$this->id; - } + /** + * Indique si la societe a des projets + * + * @return bool true si la societe a des projets, false sinon + */ + function has_projects() + { + $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id; + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + $count = $obj->numproj; + } + else + { + $count = 0; + print $this->db->error(); + } + $this->db->free($resql); + return ($count > 0); + } - // By default - if (empty($linkstart)) - { - $label.= '<u>' . $langs->trans("ShowCompany") . '</u>'; - $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id; - } - if (! empty($this->name)) - { - $label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name; - if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')'; - $label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email; - } - if (! empty($this->country_code)) - $label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code; - if (! empty($this->tva_intra)) - $label.= '<br><b>' . $langs->trans('VATNumber') . ':</b> '. $this->tva_intra; - if (! empty($this->code_client) && $this->client) - $label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client; - if (! empty($this->code_fournisseur) && $this->fournisseur) - $label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur; - if (! empty($conf->accounting->enabled) && $this->client) - $label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. $this->code_compta_client; - if (! empty($conf->accounting->enabled) && $this->fournisseur) - $label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur; - - $label.= '</div>'; - - // Add type of canvas - $linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:''); - // Add param to save lastsearch_values or not - $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; - if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1'; - $linkstart.='"'; - - $linkclose=''; - if (empty($notooltip)) - { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label=$langs->trans("ShowCompany"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip"'; - - if (! is_object($hookmanager)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); - } - $hookmanager->initHooks(array('societedao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - } - $linkstart.=$linkclose.'>'; - $linkend='</a>'; - - global $user; - if (! $user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id) - { - $linkstart=''; - $linkend=''; - } + /** + * Load information for tab info + * + * @param int $id Id of thirdparty to load + * @return void + */ + function info($id) + { + $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,"; + $sql.= " fk_user_creat, fk_user_modif"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql.= " WHERE s.rowid = ".$id; - if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$linkstart.($maxlen?dol_trunc($name,$maxlen):$name).$linkend; - - return $result; - } - - /** - * Return label of status (activity, closed) - * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long - * @return string Libelle - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->status,$mode); - } - - /** - * Renvoi le libelle d'un statut donne - * - * @param int $statut Id statut - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle du statut - */ - function LibStatut($statut,$mode=0) - { - global $langs; - $langs->load('companies'); - - if ($mode == 0) - { - if ($statut==0) return $langs->trans("ActivityCeased"); - if ($statut==1) return $langs->trans("InActivity"); - } - if ($mode == 1) - { - if ($statut==0) return $langs->trans("ActivityCeased"); - if ($statut==1) return $langs->trans("InActivity"); - } - if ($mode == 2) - { - if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased"); - if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity"); - } - if ($mode == 3) - { - if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"'); - if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"'); - } - if ($mode == 4) - { - if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased"); - if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity"); - } - if ($mode == 5) - { - if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"'); - if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"'); - } - } - - /** - * Return list of contacts emails existing for third party - * - * @param int $addthirdparty 1=Add also a record for thirdparty email - * @return array Array of contacts emails - */ - function thirdparty_and_contact_email_array($addthirdparty=0) - { - global $langs; - - $contact_emails = $this->contact_property_array('email',1); - if ($this->email && $addthirdparty) - { - if (empty($this->name)) $this->name=$this->nom; - $contact_emails['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->email.">"; - } - //var_dump($contact_emails) - return $contact_emails; - } - - /** - * Return list of contacts mobile phone existing for third party - * - * @return array Array of contacts emails - */ - function thirdparty_and_contact_phone_array() - { - global $langs; - - $contact_phone = $this->contact_property_array('mobile'); - - if (! empty($this->phone)) // If a phone of thirdparty is defined, we add it ot mobile of contacts - { - if (empty($this->name)) $this->name=$this->nom; - // TODO: Tester si tel non deja present dans tableau contact - $contact_phone['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->phone.">"; - } - return $contact_phone; - } + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); - /** - * Return list of contacts emails or mobile existing for third party - * - * @param string $mode 'email' or 'mobile' - * @param int $hidedisabled 1=Hide contact if disabled - * @return array Array of contacts emails or mobile array(id=>'Name <email>') - */ - function contact_property_array($mode='email', $hidedisabled=0) - { - global $langs; - - $contact_property = array(); - - - $sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname"; - $sql.= " FROM ".MAIN_DB_PREFIX."socpeople"; - $sql.= " WHERE fk_soc = ".$this->id; - - $resql=$this->db->query($sql); - if ($resql) - { - $nump = $this->db->num_rows($resql); - if ($nump) - { - $sepa="("; $sepb=")"; - if ($mode == 'email') - { - $sepa="<"; $sepb=">"; - } - $i = 0; - while ($i < $nump) - { - $obj = $this->db->fetch_object($resql); - if ($mode == 'email') $property=$obj->email; - else if ($mode == 'mobile') $property=$obj->phone_mobile; - else $property=$obj->$mode; + $this->id = $obj->rowid; - // Show all contact. If hidedisabled is 1, showonly contacts with status = 1 - if ($obj->statut == 1 || empty($hidedisabled)) - { - if (empty($property)) - { - if ($mode == 'email') $property=$langs->trans("NoEMail"); - else if ($mode == 'mobile') $property=$langs->trans("NoMobilePhone"); - } - - if (!empty($obj->poste)) - { - $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:''); - } - else - { - $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:''); - } - } - $i++; - } - } - } - else - { - dol_print_error($this->db); - } - return $contact_property; - } - - - /** - * Renvoie la liste des contacts de cette societe - * - * @return array tableau des contacts - */ - function contact_array() - { - $contacts = array(); - - $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id; - $resql=$this->db->query($sql); - if ($resql) - { - $nump = $this->db->num_rows($resql); - if ($nump) - { - $i = 0; - while ($i < $nump) - { - $obj = $this->db->fetch_object($resql); - $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname); - $i++; - } - } - } - else - { - dol_print_error($this->db); - } - return $contacts; - } - - /** - * Renvoie la liste des contacts de cette societe - * - * @return array $contacts tableau des contacts - */ - function contact_array_objects() - { - require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; - $contacts = array(); - - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id; - $resql=$this->db->query($sql); - if ($resql) - { - $nump = $this->db->num_rows($resql); - if ($nump) - { - $i = 0; - while ($i < $nump) - { - $obj = $this->db->fetch_object($resql); - $contact = new Contact($this->db); - $contact->fetch($obj->rowid); - $contacts[] = $contact; - $i++; - } - } - } - else - { - dol_print_error($this->db); - } - return $contacts; - } - - /** - * Return property of contact from its id - * - * @param int $rowid id of contact - * @param string $mode 'email' or 'mobile' - * @return string Email of contact with format: "Full name <email>" - */ - function contact_get_property($rowid,$mode) - { - $contact_property=''; - - if (empty($rowid)) return ''; - - $sql = "SELECT rowid, email, phone_mobile, lastname, firstname"; - $sql.= " FROM ".MAIN_DB_PREFIX."socpeople"; - $sql.= " WHERE rowid = '".$rowid."'"; - - $resql=$this->db->query($sql); - if ($resql) - { - $nump = $this->db->num_rows($resql); - - if ($nump) - { - $obj = $this->db->fetch_object($resql); - - if ($mode == 'email') $contact_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">"; - else if ($mode == 'mobile') $contact_property = $obj->phone_mobile; - } - return $contact_property; - } - else - { - dol_print_error($this->db); - } + if ($obj->fk_user_creat) { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_creat); + $this->user_creation = $cuser; + } - } + if ($obj->fk_user_modif) { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_modif); + $this->user_modification = $muser; + } + $this->ref = $obj->name; + $this->date_creation = $this->db->jdate($obj->date_creation); + $this->date_modification = $this->db->jdate($obj->date_modification); + } - /** - * Return bank number property of thirdparty (label or rum) - * - * @param string $mode 'label' or 'rum' or 'format' - * @return string Bank number - */ - function display_rib($mode='label') - { - require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + $this->db->free($result); - $bac = new CompanyBankAccount($this->db); - $bac->fetch(0,$this->id); + } + else + { + dol_print_error($this->db); + } + } - if ($mode == 'label') - { - return $bac->getRibLabel(true); - } - elseif ($mode == 'rum') - { - if (empty($bac->rum)) - { - require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php'; - $prelevement = new BonPrelevement($this->db); - $bac->fetch_thirdparty(); - $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id); - } - return $bac->rum; - } - elseif ($mode == 'format') - { - return $bac->frstrecur; - } + /** + * Return if third party is a company (Business) or an end user (Consumer) + * + * @return boolean true=is a company, false=a and user + */ + function isACompany() + { + global $conf; - return 'BadParameterToFunctionDisplayRib'; - } - - /** - * Return Array of RIB - * - * @return array|int 0 if KO, Array of CompanyBanckAccount if OK - */ - function get_all_rib() - { - require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc = ".$this->id; - $result = $this->db->query($sql); - if (!$result) { - $this->error++; - $this->errors[] = $this->db->lasterror; - return 0; - } else { - $num_rows = $this->db->num_rows($result); - $rib_array = array(); - if ($num_rows) { - while ($obj = $this->db->fetch_object($result)) { - $rib = new CompanyBankAccount($this->db); - $rib->fetch($obj->rowid); - $rib_array[] = $rib; - } - } - return $rib_array; - } - } - - /** - * Attribut un code client a partir du module de controle des codes. - * Return value is stored into this->code_client - * - * @param Societe $objsoc Object thirdparty - * @param int $type Should be 0 to say customer - * @return void - */ - function get_codeclient($objsoc=0,$type=0) - { - global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) - { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; - - $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { - $res=dol_include_once($dirroot.$module.'.php'); - if ($res) break; - } - $mod = new $module(); - - $this->code_client = $mod->getNextValue($objsoc,$type); - $this->prefixCustomerIsRequired = $mod->prefixIsRequired; - - dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module); - } - } - - /** - * Attribut un code fournisseur a partir du module de controle des codes. - * Return value is stored into this->code_fournisseur - * - * @param Societe $objsoc Object thirdparty - * @param int $type Should be 1 to say supplier - * @return void - */ - function get_codefournisseur($objsoc=0,$type=1) - { - global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) - { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + // Define if third party is treated as company (or not) when nature is unknown + $isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default + if (! empty($this->tva_intra)) $isacompany=1; + else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_PRIVATE'))) $isacompany=0; + else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_SMALL','TE_MEDIUM','TE_LARGE','TE_GROUP'))) $isacompany=1; - $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { - $res=dol_include_once($dirroot.$module.'.php'); - if ($res) break; - } - $mod = new $module(); + return $isacompany; + } - $this->code_fournisseur = $mod->getNextValue($objsoc,$type); + /** + * Charge la liste des categories fournisseurs + * + * @return int 0 if success, <> 0 if error + */ + function LoadSupplierCateg() + { + $this->SupplierCategories = array(); + $sql = "SELECT rowid, label"; + $sql.= " FROM ".MAIN_DB_PREFIX."categorie"; + $sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER; - dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module); - } - } - - /** - * Verifie si un code client est modifiable en fonction des parametres - * du module de controle des codes. - * - * @return int 0=No, 1=Yes - */ - function codeclient_modifiable() - { - global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) - { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; - - $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { - $res=dol_include_once($dirroot.$module.'.php'); - if ($res) break; - } - - $mod = new $module(); - - dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module); - if ($mod->code_modifiable_null && ! $this->code_client) return 1; - if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1; - if ($mod->code_modifiable) return 1; // A mettre en dernier - return 0; - } - else - { - return 0; - } - } - - - /** - * Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes - * - * @return int 0=No, 1=Yes - */ - function codefournisseur_modifiable() - { - global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) - { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; - - $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { - $res=dol_include_once($dirroot.$module.'.php'); - if ($res) break; - } - - $mod = new $module(); - - dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module); - if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1; - if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1; - if ($mod->code_modifiable) return 1; // A mettre en dernier - return 0; - } - else - { - return 0; - } - } - - - /** - * Check customer code - * - * @return int 0 if OK - * -1 ErrorBadCustomerCodeSyntax - * -2 ErrorCustomerCodeRequired - * -3 ErrorCustomerCodeAlreadyUsed - * -4 ErrorPrefixRequired - */ - function check_codeclient() - { - global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) - { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; - - $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { - $res=dol_include_once($dirroot.$module.'.php'); - if ($res) break; - } - - $mod = new $module(); - - dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module); - $result = $mod->verif($this->db, $this->code_client, $this, 0); - return $result; - } - else + $resql=$this->db->query($sql); + if ($resql) { - return 0; - } - } - - /** - * Check supplier code - * - * @return int 0 if OK - * -1 ErrorBadCustomerCodeSyntax - * -2 ErrorCustomerCodeRequired - * -3 ErrorCustomerCodeAlreadyUsed - * -4 ErrorPrefixRequired - */ - function check_codefournisseur() - { - global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) - { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; - - $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { - $res=dol_include_once($dirroot.$module.'.php'); - if ($res) break; - } - - $mod = new $module(); - - dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module); - $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1); - return $result; - } - else + while ($obj = $this->db->fetch_object($resql) ) + { + $this->SupplierCategories[$obj->rowid] = $obj->label; + } + return 0; + } + else { - return 0; - } - } - - /** - * Renvoie un code compta, suivant le module de code compta. - * Peut etre identique a celui saisit ou genere automatiquement. - * A ce jour seule la generation automatique est implementee - * - * @param string $type Type of thirdparty ('customer' or 'supplier') - * @return string Code compta si ok, 0 si aucun, <0 si ko - */ - function get_codecompta($type) - { - global $conf; - - if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) - { - $file=''; - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); - foreach ($dirsociete as $dirroot) - { - if (file_exists(DOL_DOCUMENT_ROOT.'/'.$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php")) - { - $file=$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php"; - break; - } - } - - if (! empty($file)) - { - dol_include_once($file); - - $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON; - $mod = new $classname; - - // Defini code compta dans $mod->code - $result = $mod->get_code($this->db, $this, $type); - - if ($type == 'customer') $this->code_compta = $mod->code; - else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code; - - return $result; - } - else - { - $this->error = 'ErrorAccountancyCodeNotDefined'; - return -1; - } - } - else - { - if ($type == 'customer') $this->code_compta = ''; - else if ($type == 'supplier') $this->code_compta_fournisseur = ''; - - return 0; - } - } - - /** - * Define parent commany of current company - * - * @param int $id Id of thirdparty to set or '' to remove - * @return int <0 if KO, >0 if OK - */ - function set_parent($id) - { - if ($this->id) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."societe"; - $sql.= " SET parent = ".($id > 0 ? $id : "null"); - $sql.= " WHERE rowid = " . $this->id; - dol_syslog(get_class($this).'::set_parent', LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->parent = $id; - return 1; - } - else - { - return -1; - } - } - else return -1; - } - - /** - * Returns if a profid sould be verified - * - * @param int $idprof 1,2,3,4,5,6 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm,5=idprof5,6=idprof6) - * @return boolean true , false - */ - function id_prof_verifiable($idprof) - { - global $conf; - - switch($idprof) - { - case 1: - $ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true); - break; - case 2: - $ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true); - break; - case 3: - $ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true); - break; - case 4: - $ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true); - break; - case 5: - $ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true); - break; - case 6: - $ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true); - break; - default: - $ret=false; - } + return -1; + } + } - return $ret; - } - - /** - * Verify if a profid exists into database for others thirds - * - * @param string $idprof 'idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','email' (Example: idprof1=siren, idprof2=siret, idprof3=naf, idprof4=rcs/rm) - * @param string $value Value of profid - * @param int $socid Id of thirdparty to exclude (if update) - * @return boolean True if exists, False if not - */ - function id_prof_exists($idprof, $value, $socid=0) - { - $field = $idprof; - - switch($idprof) // For backward compatibility - { - case '1': - case 'idprof1': - $field="siren"; - break; - case '2': - case 'idprof2': - $field="siret"; - break; - case '3': - case 'idprof3': - $field="ape"; - break; - case '4': - case 'idprof4': - $field="idprof4"; - break; - case '5': - $field="idprof5"; - break; - case '6': - $field="idprof6"; - break; - } - - //Verify duplicate entries - $sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")"; - if($socid) $sql .= " AND rowid <> ".$socid; - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $count = $obj->idprof; - } - else - { - $count = 0; - print $this->db->error(); - } - $this->db->free($resql); + /** + * Insert link supplier - category + * + * @param int $categorie_id Id of category + * @return int 0 if success, <> 0 if error + */ + function AddFournisseurInCategory($categorie_id) + { + if ($categorie_id > 0 && $this->id > 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) "; + $sql.= " VALUES (".$categorie_id.", ".$this->id.")"; - if ($count > 0) return true; - else return false; - } - - /** - * Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...) - * - * @param int $idprof 1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm) - * @param Societe $soc Objet societe - * @return int <=0 if KO, >0 if OK - * TODO better to have this in a lib than into a business class - */ - function id_prof_check($idprof,$soc) - { - global $conf; - - $ok=1; - - if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1; - - // Verifie SIREN si pays FR - if ($idprof == 1 && $soc->country_code == 'FR') - { - $chaine=trim($this->idprof1); - $chaine=preg_replace('/(\s)/','',$chaine); - - if (dol_strlen($chaine) != 9) return -1; - - $sum = 0; - - for ($i = 0 ; $i < 10 ; $i = $i+2) - { - $sum = $sum + substr($this->idprof1, (8 - $i), 1); - } - - for ($i = 1 ; $i < 9 ; $i = $i+2) - { - $ps = 2 * substr($this->idprof1, (8 - $i), 1); - - if ($ps > 9) - { - $ps = substr($ps, 0,1) + substr($ps, 1, 1); - } - $sum = $sum + $ps; - } - - if (substr($sum, -1) != 0) return -1; - } + if ($resql=$this->db->query($sql)) return 0; + } + else + { + return 0; + } + return -1; + } - // Verifie SIRET si pays FR - if ($idprof == 2 && $soc->country_code == 'FR') - { - $chaine=trim($this->idprof2); - $chaine=preg_replace('/(\s)/','',$chaine); - if (dol_strlen($chaine) != 14) return -1; - } + /** + * Create a third party into database from a member object + * + * @param Adherent $member Object member + * @param string $socname Name of third party to force + * @param string $socalias Alias name of third party to force + * @return int <0 if KO, id of created account if OK + */ + function create_from_member(Adherent $member, $socname='', $socalias='') + { + global $user,$langs; + + $name = $socname?$socname:$member->societe; + if (empty($name)) $name=$member->getFullName($langs); + + $alias = $socalias?$socalias:''; + + // Positionne parametres + $this->nom=$name; // TODO deprecated + $this->name=$name; + $this->name_alias=$alias; + $this->address=$member->address; + $this->zip=$member->zip; + $this->town=$member->town; + $this->country_code=$member->country_code; + $this->country_id=$member->country_id; + $this->phone=$member->phone; // Prof phone + $this->email=$member->email; + $this->skype=$member->skype; + + $this->client = 1; // A member is a customer by default + $this->code_client = -1; + $this->code_fournisseur = -1; + + $this->db->begin(); + + // Cree et positionne $this->id + $result=$this->create($user); + if ($result >= 0) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."adherent"; + $sql.= " SET fk_soc=".$this->id; + $sql.= " WHERE rowid=".$member->id; - //Verify CIF/NIF/NIE if pays ES - //Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad - if ($idprof == 1 && $soc->country_code == 'ES') - { - $string=trim($this->idprof1); - $string=preg_replace('/(\s)/','',$string); - $string = strtoupper($string); - - for ($i = 0; $i < 9; $i ++) - $num[$i] = substr($string, $i, 1); - - //Check format - if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string)) - return 0; - - //Check NIF - if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) - if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) - return 1; - else - return -1; - - //algorithm checking type code CIF - $sum = $num[2] + $num[4] + $num[6]; - for ($i = 1; $i < 8; $i += 2) - $sum += substr((2 * $num[$i]),0,1) + substr((2 * $num[$i]),1,1); - $n = 10 - substr($sum, strlen($sum) - 1, 1); - - //Chek special NIF - if (preg_match('/^[KLM]{1}/', $string)) - if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) - return 1; - else - return -1; - - //Check CIF - if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) - if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) - return 2; - else - return -2; - - //Check NIE T - if (preg_match('/^[T]{1}/', $string)) - if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) - return 3; - else - return -3; - - //Check NIE XYZ - if (preg_match('/^[XYZ]{1}/', $string)) - if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1)) - return 3; - else - return -3; - - //Can not be verified - return -4; - } + dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->error=$this->db->error(); - return $ok; - } - - /** - * Return an url to check online a professional id or empty string - * - * @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm) - * @param Societe $thirdparty Object thirdparty - * @return string Url or empty string if no URL known - * TODO better in a lib than into business class - */ - function id_prof_url($idprof,$thirdparty) - { - global $conf,$langs,$hookmanager; - - $url=''; - $action = ''; - - $hookmanager->initHooks(array('idprofurl')); - $parameters=array('idprof'=>$idprof, 'company'=>$thirdparty); - $reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return ''; - - // TODO Move links to validate professional ID into a dictionary table "country" + "link" - if ($idprof == 1 && $thirdparty->country_code == 'FR') $url='http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1; // See also http://avis-situation-sirene.insee.fr/ - //if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) $url='http://www.companieshouse.gov.uk/WebCHeck/findinfolink/'; // Link no more valid - if ($idprof == 1 && $thirdparty->country_code == 'ES') $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1; - if ($idprof == 1 && $thirdparty->country_code == 'IN') $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp'; - - if ($url) return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>'; - } - else - { - return $hookmanager->resPrint; - } + $this->db->rollback(); + return -1; + } + } + else + { + // $this->error deja positionne + dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR); - return ''; - } - - /** - * Indique si la societe a des projets - * - * @return bool true si la societe a des projets, false sinon - */ - function has_projects() - { - $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id; - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $count = $obj->numproj; - } - else - { - $count = 0; - print $this->db->error(); - } - $this->db->free($resql); - return ($count > 0); - } - - - /** - * Load information for tab info - * - * @param int $id Id of thirdparty to load - * @return void - */ - function info($id) - { - $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,"; - $sql.= " fk_user_creat, fk_user_modif"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= " WHERE s.rowid = ".$id; - - $result=$this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - - $this->id = $obj->rowid; - - if ($obj->fk_user_creat) { - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_creat); - $this->user_creation = $cuser; - } - - if ($obj->fk_user_modif) { - $muser = new User($this->db); - $muser->fetch($obj->fk_user_modif); - $this->user_modification = $muser; - } - - $this->ref = $obj->name; - $this->date_creation = $this->db->jdate($obj->date_creation); - $this->date_modification = $this->db->jdate($obj->date_modification); - } - - $this->db->free($result); + $this->db->rollback(); + return $result; + } + } - } - else - { - dol_print_error($this->db); - } - } - - /** - * Return if third party is a company (Business) or an end user (Consumer) - * - * @return boolean true=is a company, false=a and user - */ - function isACompany() - { - global $conf; - - // Define if third party is treated as company (or not) when nature is unknown - $isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default - if (! empty($this->tva_intra)) $isacompany=1; - else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_PRIVATE'))) $isacompany=0; - else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_SMALL','TE_MEDIUM','TE_LARGE','TE_GROUP'))) $isacompany=1; - - return $isacompany; - } - - /** - * Charge la liste des categories fournisseurs - * - * @return int 0 if success, <> 0 if error - */ - function LoadSupplierCateg() - { - $this->SupplierCategories = array(); - $sql = "SELECT rowid, label"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie"; - $sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER; - - $resql=$this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql) ) - { - $this->SupplierCategories[$obj->rowid] = $obj->label; - } - return 0; - } - else - { - return -1; - } - } - - /** - * Insert link supplier - category - * - * @param int $categorie_id Id of category - * @return int 0 if success, <> 0 if error - */ - function AddFournisseurInCategory($categorie_id) - { - if ($categorie_id > 0 && $this->id > 0) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) "; - $sql.= " VALUES (".$categorie_id.", ".$this->id.")"; - - if ($resql=$this->db->query($sql)) return 0; - } - else - { - return 0; - } - return -1; - } - - - /** - * Create a third party into database from a member object - * - * @param Adherent $member Object member - * @param string $socname Name of third party to force - * @param string $socalias Alias name of third party to force - * @return int <0 if KO, id of created account if OK - */ - function create_from_member(Adherent $member, $socname='', $socalias='') - { - global $user,$langs; - - $name = $socname?$socname:$member->societe; - if (empty($name)) $name=$member->getFullName($langs); - - $alias = $socalias?$socalias:''; - - // Positionne parametres - $this->nom=$name; // TODO deprecated - $this->name=$name; - $this->name_alias=$alias; - $this->address=$member->address; - $this->zip=$member->zip; - $this->town=$member->town; - $this->country_code=$member->country_code; - $this->country_id=$member->country_id; - $this->phone=$member->phone; // Prof phone - $this->email=$member->email; - $this->skype=$member->skype; - - $this->client = 1; // A member is a customer by default - $this->code_client = -1; - $this->code_fournisseur = -1; - - $this->db->begin(); - - // Cree et positionne $this->id - $result=$this->create($user); - if ($result >= 0) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."adherent"; - $sql.= " SET fk_soc=".$this->id; - $sql.= " WHERE rowid=".$member->id; - - dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->db->commit(); - return $this->id; - } - else - { - $this->error=$this->db->error(); - - $this->db->rollback(); - return -1; - } - } - else - { - // $this->error deja positionne - dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR); + /** + * Set properties with value into $conf + * + * @param Conf $conf Conf object (possibility to use another entity) + * @return void + */ + function setMysoc(Conf $conf) + { + global $langs; - $this->db->rollback(); - return $result; - } - } - - /** - * Set properties with value into $conf - * - * @param Conf $conf Conf object (possibility to use another entity) - * @return void - */ - function setMysoc(Conf $conf) - { - global $langs; - - $this->id=0; - $this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM; - $this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS; - $this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP; - $this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN; + $this->id=0; + $this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM; + $this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS; + $this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP; + $this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN; $this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE; - /* Disabled: we don't want any SQL request into method setMySoc. This method set object from env only. + /* Disabled: we don't want any SQL request into method setMySoc. This method set object from env only. If we need label, label must be loaded by output that need it from id (label depends on output language) require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) { @@ -3081,165 +3081,165 @@ class Societe extends CommonObject } */ - $this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE; - - $this->nom=$this->name; // deprecated - - // We define country_id, country_code and country - $country_id=$country_code=$country_label=''; - if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) - { - $tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY); - $country_id=$tmp[0]; - if (! empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label" - { - $country_code=$tmp[1]; - $country_label=$tmp[2]; - } - else // For backward compatibility - { - dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR); - include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - $country_code=getCountry($country_id,2,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore - $country_label=getCountry($country_id,0,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore - } - } - $this->country_id=$country_id; - $this->country_code=$country_code; - $this->country=$country_label; - if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label; - - $this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL; - $this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX; - $this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB; - // Id prof generiques - $this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN; - $this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET; - $this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE; - $this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS; - $this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5; - $this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6; - $this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA. - $this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS; - $this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL; - $this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE; - $this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL; - $this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO; - $this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL; - $this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI; - - // Define if company use vat or not - $this->tva_assuj=$conf->global->FACTURE_TVAOPTION; - - // Define if company use local taxes - $this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0); - $this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0); - } - - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - function initAsSpecimen() - { - $now=dol_now(); - - // Initialize parameters - $this->id=0; - $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog'); - $this->nom = $this->name; // For backward compatibility - $this->ref_ext = 'Ref ext'; - $this->specimen=1; - $this->address='21 jump street'; - $this->zip='99999'; - $this->town='MyTown'; - $this->state_id=1; - $this->state_code='AA'; - $this->state='MyState'; - $this->country_id=1; - $this->country_code='FR'; - $this->email='specimen@specimen.com'; - $this->skype='tom.hanson'; - $this->url='http://www.specimen.com'; - - $this->phone='0909090901'; - $this->fax='0909090909'; - - $this->code_client='CC-'.dol_print_date($now,'dayhourlog'); - $this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog'); - $this->capital=10000; - $this->client=1; - $this->prospect=1; - $this->fournisseur=1; - $this->tva_assuj=1; - $this->tva_intra='EU1234567'; - $this->note_public='This is a comment (public)'; - $this->note_private='This is a comment (private)'; - - $this->idprof1='idprof1'; - $this->idprof2='idprof2'; - $this->idprof3='idprof3'; - $this->idprof4='idprof4'; - $this->idprof5='idprof5'; - $this->idprof6='idprof6'; - } - - /** - * Check if we must use localtax feature or not according to country (country of $mysoc in most cases). - * - * @param int $localTaxNum To get info for only localtax1 or localtax2 - * @return boolean true or false - */ - function useLocalTax($localTaxNum=0) - { - $sql = "SELECT t.localtax1, t.localtax2"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'"; - $sql .= " AND t.active = 1"; - if (empty($localTaxNum)) $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')"; - elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'"; - elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'"; - - dol_syslog("useLocalTax", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { + $this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE; + + $this->nom=$this->name; // deprecated + + // We define country_id, country_code and country + $country_id=$country_code=$country_label=''; + if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) + { + $tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY); + $country_id=$tmp[0]; + if (! empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label" + { + $country_code=$tmp[1]; + $country_label=$tmp[2]; + } + else // For backward compatibility + { + dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR); + include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + $country_code=getCountry($country_id,2,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore + $country_label=getCountry($country_id,0,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore + } + } + $this->country_id=$country_id; + $this->country_code=$country_code; + $this->country=$country_label; + if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label; + + $this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL; + $this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX; + $this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB; + // Id prof generiques + $this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN; + $this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET; + $this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE; + $this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS; + $this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5; + $this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6; + $this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA. + $this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS; + $this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL; + $this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE; + $this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL; + $this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO; + $this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL; + $this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI; + + // Define if company use vat or not + $this->tva_assuj=$conf->global->FACTURE_TVAOPTION; + + // Define if company use local taxes + $this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0); + $this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0); + } + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + $now=dol_now(); + + // Initialize parameters + $this->id=0; + $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog'); + $this->nom = $this->name; // For backward compatibility + $this->ref_ext = 'Ref ext'; + $this->specimen=1; + $this->address='21 jump street'; + $this->zip='99999'; + $this->town='MyTown'; + $this->state_id=1; + $this->state_code='AA'; + $this->state='MyState'; + $this->country_id=1; + $this->country_code='FR'; + $this->email='specimen@specimen.com'; + $this->skype='tom.hanson'; + $this->url='http://www.specimen.com'; + + $this->phone='0909090901'; + $this->fax='0909090909'; + + $this->code_client='CC-'.dol_print_date($now,'dayhourlog'); + $this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog'); + $this->capital=10000; + $this->client=1; + $this->prospect=1; + $this->fournisseur=1; + $this->tva_assuj=1; + $this->tva_intra='EU1234567'; + $this->note_public='This is a comment (public)'; + $this->note_private='This is a comment (private)'; + + $this->idprof1='idprof1'; + $this->idprof2='idprof2'; + $this->idprof3='idprof3'; + $this->idprof4='idprof4'; + $this->idprof5='idprof5'; + $this->idprof6='idprof6'; + } + + /** + * Check if we must use localtax feature or not according to country (country of $mysoc in most cases). + * + * @param int $localTaxNum To get info for only localtax1 or localtax2 + * @return boolean true or false + */ + function useLocalTax($localTaxNum=0) + { + $sql = "SELECT t.localtax1, t.localtax2"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'"; + $sql .= " AND t.active = 1"; + if (empty($localTaxNum)) $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')"; + elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'"; + elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'"; + + dol_syslog("useLocalTax", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { return ($this->db->num_rows($resql) > 0); - } - else return false; - } - - /** - * Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases). - * - * @return boolean true or false - */ - function useNPR() - { - $sql = "SELECT t.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'"; - $sql .= " AND t.active = 1 AND t.recuperableonly = 1"; - - dol_syslog("useNPR", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - return ($this->db->num_rows($resql) > 0); - } - else return false; - } - - /** - * Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases). - * - * @return boolean true or false - */ - function useRevenueStamp() - { + } + else return false; + } + + /** + * Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases). + * + * @return boolean true or false + */ + function useNPR() + { + $sql = "SELECT t.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'"; + $sql .= " AND t.active = 1 AND t.recuperableonly = 1"; + + dol_syslog("useNPR", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + return ($this->db->num_rows($resql) > 0); + } + else return false; + } + + /** + * Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases). + * + * @return boolean true or false + */ + function useRevenueStamp() + { $sql = "SELECT COUNT(*) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c"; $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'"; @@ -3294,11 +3294,11 @@ class Societe extends CommonObject * * @param User $user Utilisateur qui definie la remise * @return int <0 if KO, >0 if OK - * @deprecated Use update function instead + * @deprecated Use update function instead */ function set_prospect_level(User $user) { - return $this->update($this->id, $user); + return $this->update($this->id, $user); } /** @@ -3371,11 +3371,11 @@ class Societe extends CommonObject * * @param User $user User making change * @return int <0 if KO, >0 if OK - * @deprecated Use update function instead + * @deprecated Use update function instead */ function set_OutstandingBill(User $user) { - return $this->update($this->id, $user); + return $this->update($this->id, $user); } /** @@ -3539,39 +3539,39 @@ class Societe extends CommonObject */ function get_OutstandingBill() { - /* Accurate value of remain to pay is to sum remaintopay for each invoice + /* Accurate value of remain to pay is to sum remaintopay for each invoice $paiement = $invoice->getSommePaiement(); $creditnotes=$invoice->getSumCreditNotesUsed(); $deposits=$invoice->getSumDepositsUsed(); $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT'); $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); */ - $sql = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f"; - $sql .= " WHERE fk_soc = ". $this->id; - $sql .= " AND paye = 0"; - $sql .= " AND fk_statut <> 0"; // Not a draft - //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason - $sql .= " AND fk_statut <> 3"; // Not abandonned - $sql .= " AND fk_statut <> 2"; // Not clasified as paid - - dol_syslog("get_OutstandingBill", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $outstandingAmount = 0; - require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $tmpobject=new Facture($this->db); - while($obj=$this->db->fetch_object($resql)) { - $tmpobject->id=$obj->rowid; - $paiement = $tmpobject->getSommePaiement(); - $creditnotes = $tmpobject->getSumCreditNotesUsed(); - $deposits = $tmpobject->getSumDepositsUsed(); - $outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits; - } - return $outstandingAmount; - } - else - return 0; + $sql = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f"; + $sql .= " WHERE fk_soc = ". $this->id; + $sql .= " AND paye = 0"; + $sql .= " AND fk_statut <> 0"; // Not a draft + //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason + $sql .= " AND fk_statut <> 3"; // Not abandonned + $sql .= " AND fk_statut <> 2"; // Not clasified as paid + + dol_syslog("get_OutstandingBill", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $outstandingAmount = 0; + require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $tmpobject=new Facture($this->db); + while($obj=$this->db->fetch_object($resql)) { + $tmpobject->id=$obj->rowid; + $paiement = $tmpobject->getSommePaiement(); + $creditnotes = $tmpobject->getSumCreditNotesUsed(); + $deposits = $tmpobject->getSumDepositsUsed(); + $outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits; + } + return $outstandingAmount; + } + else + return 0; } /** @@ -3620,33 +3620,33 @@ class Societe extends CommonObject if (! empty($moreparams) && ! empty($moreparams['use_companybankid'])) { - $modelpath = "core/modules/bank/doc/"; + $modelpath = "core/modules/bank/doc/"; - include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; - $companybankaccount = new CompanyBankAccount($this->db); - $result = $companybankaccount->fetch($moreparams['use_companybankid']); - if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors); - $result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; + $companybankaccount = new CompanyBankAccount($this->db); + $result = $companybankaccount->fetch($moreparams['use_companybankid']); + if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors); + $result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } else { - // Positionne le modele sur le nom du modele a utiliser - if (! dol_strlen($modele)) - { - if (! empty($conf->global->COMPANY_ADDON_PDF)) - { - $modele = $conf->global->COMPANY_ADDON_PDF; - } - else - { - print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined"); - return 0; - } - } + // Positionne le modele sur le nom du modele a utiliser + if (! dol_strlen($modele)) + { + if (! empty($conf->global->COMPANY_ADDON_PDF)) + { + $modele = $conf->global->COMPANY_ADDON_PDF; + } + else + { + print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined"); + return 0; + } + } - $modelpath = "core/modules/societe/doc/"; + $modelpath = "core/modules/societe/doc/"; - $result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + $result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } return $result; @@ -3667,7 +3667,7 @@ class Societe extends CommonObject { require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - // Decode type + // Decode type if ($type == 'customer') { $type_id = Categorie::TYPE_CUSTOMER; $type_text = 'customer'; diff --git a/htdocs/societe/list.php b/htdocs/societe/list.php index f9e10667ccd8284fc78be4f1dd981cf9b72f7ba3..2478990241112f8f0a235aea6aeb128cec65fc8b 100644 --- a/htdocs/societe/list.php +++ b/htdocs/societe/list.php @@ -127,15 +127,15 @@ $fieldstosearchall = array( 's.nom'=>"ThirdPartyName", 's.name_alias'=>"AliasNameShort", 's.code_client'=>"CustomerCode", - 's.code_fournisseur'=>"SupplierCode", + 's.code_fournisseur'=>"SupplierCode", 's.code_compta'=>"CustomerAccountancyCodeShort", 's.code_compta_fournisseur'=>"SupplierAccountancyCodeShort", 's.email'=>"EMail", 's.url'=>"URL", - 's.tva_intra'=>"VATIntra", - 's.siren'=>"ProfId1", - 's.siret'=>"ProfId2", - 's.ape'=>"ProfId3", + 's.tva_intra'=>"VATIntra", + 's.siren'=>"ProfId1", + 's.siret'=>"ProfId2", + 's.ape'=>"ProfId3", ); if (($tmp = $langs->transnoentities("ProfId4".$mysoc->country_code)) && $tmp != "ProfId4".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof4']='ProfId4'; if (($tmp = $langs->transnoentities("ProfId5".$mysoc->country_code)) && $tmp != "ProfId5".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof5']='ProfId5'; @@ -161,35 +161,35 @@ $checkprospectlevel=(in_array($contextpage, array('prospectlist')) ? 1 : 0); $checkstcomm=(in_array($contextpage, array('prospectlist')) ? 1 : 0); $arrayfields=array( 's.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0)), - 's.nom'=>array('label'=>"ThirdPartyName", 'checked'=>1), - 's.name_alias'=>array('label'=>"AliasNameShort", 'checked'=>1), - 's.barcode'=>array('label'=>"Gencod", 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))), - 's.code_client'=>array('label'=>"CustomerCodeShort", 'checked'=>$checkedcustomercode), - 's.code_fournisseur'=>array('label'=>"SupplierCodeShort", 'checked'=>$checkedsuppliercode, 'enabled'=>(! empty($conf->fournisseur->enabled))), - 's.code_compta'=>array('label'=>"CustomerAccountancyCodeShort", 'checked'=>$checkedcustomeraccountcode), - 's.code_compta_fournisseur'=>array('label'=>"SupplierAccountancyCodeShort", 'checked'=>$checkedsupplieraccountcode, 'enabled'=>(! empty($conf->fournisseur->enabled))), - 's.town'=>array('label'=>"Town", 'checked'=>1), - 's.zip'=>array('label'=>"Zip", 'checked'=>1), - 'state.nom'=>array('label'=>"State", 'checked'=>0), - 'region.nom'=>array('label'=>"Region", 'checked'=>0), + 's.nom'=>array('label'=>"ThirdPartyName", 'checked'=>1), + 's.name_alias'=>array('label'=>"AliasNameShort", 'checked'=>1), + 's.barcode'=>array('label'=>"Gencod", 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))), + 's.code_client'=>array('label'=>"CustomerCodeShort", 'checked'=>$checkedcustomercode), + 's.code_fournisseur'=>array('label'=>"SupplierCodeShort", 'checked'=>$checkedsuppliercode, 'enabled'=>(! empty($conf->fournisseur->enabled))), + 's.code_compta'=>array('label'=>"CustomerAccountancyCodeShort", 'checked'=>$checkedcustomeraccountcode), + 's.code_compta_fournisseur'=>array('label'=>"SupplierAccountancyCodeShort", 'checked'=>$checkedsupplieraccountcode, 'enabled'=>(! empty($conf->fournisseur->enabled))), + 's.town'=>array('label'=>"Town", 'checked'=>1), + 's.zip'=>array('label'=>"Zip", 'checked'=>1), + 'state.nom'=>array('label'=>"State", 'checked'=>0), + 'region.nom'=>array('label'=>"Region", 'checked'=>0), 'country.code_iso'=>array('label'=>"Country", 'checked'=>0), - 's.email'=>array('label'=>"Email", 'checked'=>0), - 's.url'=>array('label'=>"Url", 'checked'=>0), - 's.phone'=>array('label'=>"Phone", 'checked'=>1), - 'typent.code'=>array('label'=>"ThirdPartyType", 'checked'=>$checkedtypetiers), - 's.siren'=>array('label'=>"ProfId1Short", 'checked'=>$checkedprofid1), - 's.siret'=>array('label'=>"ProfId2Short", 'checked'=>$checkedprofid2), - 's.ape'=>array('label'=>"ProfId3Short", 'checked'=>$checkedprofid3), - 's.idprof4'=>array('label'=>"ProfId4Short", 'checked'=>$checkedprofid4), - 's.idprof5'=>array('label'=>"ProfId5Short", 'checked'=>$checkedprofid5), - 's.idprof6'=>array('label'=>"ProfId6Short", 'checked'=>$checkedprofid6), + 's.email'=>array('label'=>"Email", 'checked'=>0), + 's.url'=>array('label'=>"Url", 'checked'=>0), + 's.phone'=>array('label'=>"Phone", 'checked'=>1), + 'typent.code'=>array('label'=>"ThirdPartyType", 'checked'=>$checkedtypetiers), + 's.siren'=>array('label'=>"ProfId1Short", 'checked'=>$checkedprofid1), + 's.siret'=>array('label'=>"ProfId2Short", 'checked'=>$checkedprofid2), + 's.ape'=>array('label'=>"ProfId3Short", 'checked'=>$checkedprofid3), + 's.idprof4'=>array('label'=>"ProfId4Short", 'checked'=>$checkedprofid4), + 's.idprof5'=>array('label'=>"ProfId5Short", 'checked'=>$checkedprofid5), + 's.idprof6'=>array('label'=>"ProfId6Short", 'checked'=>$checkedprofid6), 's.tva_intra'=>array('label'=>"VATIntra", 'checked'=>0), 'customerorsupplier'=>array('label'=>'Nature', 'checked'=>1), 's.fk_prospectlevel'=>array('label'=>"ProspectLevelShort", 'checked'=>$checkprospectlevel), 's.fk_stcomm'=>array('label'=>"StatusProsp", 'checked'=>$checkstcomm), - 's.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), - 's.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), - 's.status'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), + 's.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), + 's.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), + 's.status'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), 's.import_key'=>array('label'=>"ImportId", 'checked'=>0, 'position'=>1100), ); // Extra fields @@ -197,7 +197,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { 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'=>$extrafields->attribute_perms[$key]); + 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'=>$extrafields->attribute_perms[$key]); } } @@ -220,44 +220,44 @@ if (empty($reshook)) // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Did we click on purge search criteria ? - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $search_id=''; - $search_nom=''; - $search_alias=''; - $search_categ_cus=0; - $search_categ_sup=0; - $search_sale=''; - $search_barcode=""; - $search_customer_code=''; - $search_supplier_code=''; - $search_account_customer_code=''; - $search_account_supplier_code=''; - $search_town=""; - $search_zip=""; - $search_state=""; - $search_country=''; - $search_email=''; - $search_phone=''; - $search_url=''; - $search_idprof1=''; - $search_idprof2=''; - $search_idprof3=''; - $search_idprof4=''; - $search_idprof5=''; - $search_idprof6=''; - $search_vat=''; - $search_type=''; - $search_type_thirdparty=''; - $search_status=-1; - $search_stcomm=''; - $search_level_from=''; - $search_level_to=''; - $search_import_key=''; - $toselect=''; - $search_array_options=array(); - } + // Did we click on purge search criteria ? + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search_id=''; + $search_nom=''; + $search_alias=''; + $search_categ_cus=0; + $search_categ_sup=0; + $search_sale=''; + $search_barcode=""; + $search_customer_code=''; + $search_supplier_code=''; + $search_account_customer_code=''; + $search_account_supplier_code=''; + $search_town=""; + $search_zip=""; + $search_state=""; + $search_country=''; + $search_email=''; + $search_phone=''; + $search_url=''; + $search_idprof1=''; + $search_idprof2=''; + $search_idprof3=''; + $search_idprof4=''; + $search_idprof5=''; + $search_idprof6=''; + $search_vat=''; + $search_type=''; + $search_type_thirdparty=''; + $search_status=-1; + $search_stcomm=''; + $search_level_from=''; + $search_level_to=''; + $search_import_key=''; + $toselect=''; + $search_array_options=array(); + } // Mass actions $objectclass='Societe'; @@ -469,16 +469,16 @@ if ($search_import_key) $sql.= natural_search("s.import_key",$search_import_k // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks @@ -501,8 +501,8 @@ $sql.= $db->plimit($limit+1, $offset); $resql = $db->query($sql); if (! $resql) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($resql); @@ -511,10 +511,10 @@ $arrayofselected=is_array($toselect)?$toselect:array(); if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && ($search_all != '' || $search_cti != '') && $action != 'list') { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/societe/card.php?socid='.$id); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/societe/card.php?socid='.$id); + exit; } $help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; @@ -562,20 +562,20 @@ if ($type != '') $param.='&type='.urlencode($type); // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // Show delete result message if (GETPOST('delsoc')) { - setEventMessages($langs->trans("CompanyDeleted",GETPOST('delsoc')), null, 'mesgs'); + setEventMessages($langs->trans("CompanyDeleted",GETPOST('delsoc')), null, 'mesgs'); } // List of mass actions available $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), + 'presend'=>$langs->trans("SendByMail"), // 'builddoc'=>$langs->trans("PDFMerge"), ); //if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); @@ -618,8 +618,8 @@ if ($massaction == 'presend') if ($search_all) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); } // Filter on categories @@ -637,14 +637,14 @@ if (empty($type) || $type == 'c' || $type == 'p') } if (empty($type) || $type == 'f') { - if (! empty($conf->categorie->enabled)) - { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='<div class="divsearchfield">'; - $moreforfilter.=$langs->trans('SuppliersCategoriesShort').': '; - $moreforfilter.=$formother->select_categories('supplier',$search_categ_sup,'search_categ_sup',1); - $moreforfilter.='</div>'; - } + if (! empty($conf->categorie->enabled)) + { + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='<div class="divsearchfield">'; + $moreforfilter.=$langs->trans('SuppliersCategoriesShort').': '; + $moreforfilter.=$formother->select_categories('supplier',$search_categ_sup,'search_categ_sup',1); + $moreforfilter.='</div>'; + } } // If the user can view prospects other than his' @@ -661,8 +661,8 @@ if ($moreforfilter) print $moreforfilter; $parameters=array('type'=>$type); $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - print '</div>'; + print $hookmanager->resPrint; + print '</div>'; } $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; @@ -705,125 +705,125 @@ if (! empty($arrayfields['s.barcode']['checked'])) // Customer code if (! empty($arrayfields['s.code_client']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input class="flat searchstring" size="8" type="text" name="search_customer_code" value="'.dol_escape_htmltag($search_customer_code).'">'; print '</td>'; } // Supplier code if (! empty($arrayfields['s.code_fournisseur']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input class="flat searchstring" size="8" type="text" name="search_supplier_code" value="'.dol_escape_htmltag($search_supplier_code).'">'; print '</td>'; } // Account Customer code if (! empty($arrayfields['s.code_compta']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input class="flat searchstring" size="8" type="text" name="search_account_customer_code" value="'.dol_escape_htmltag($search_account_customer_code).'">'; print '</td>'; } // Account Supplier code if (! empty($arrayfields['s.code_compta_fournisseur']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input class="flat" size="8" type="text" name="search_account_supplier_code" value="'.dol_escape_htmltag($search_account_supplier_code).'">'; print '</td>'; } // Town if (! empty($arrayfields['s.town']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input class="flat searchstring" size="6" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'">'; print '</td>'; } // Zip if (! empty($arrayfields['s.zip']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input class="flat searchstring" size="4" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'">'; print '</td>'; } // State if (! empty($arrayfields['state.nom']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input class="flat searchstring" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; print '</td>'; } // Region if (! empty($arrayfields['region.nom']['checked'])) { - print '<td class="liste_titre">'; + print '<td class="liste_titre">'; print '<input class="flat searchstring" size="4" type="text" name="search_region" value="'.dol_escape_htmltag($search_region).'">'; print '</td>'; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print '<td class="liste_titre" align="center">'; + print '<td class="liste_titre" align="center">'; print $form->select_country($search_country,'search_country','',0,'maxwidth100'); print '</td>'; } // Company type if (! empty($arrayfields['typent.code']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="center">'; + print '<td class="liste_titre maxwidthonsmartphone" align="center">'; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); print '</td>'; } if (! empty($arrayfields['s.email']['checked'])) { - // Email + // Email print '<td class="liste_titre">'; print '<input class="flat searchemail" size="4" type="text" name="search_email" value="'.dol_escape_htmltag($search_email).'">'; print '</td>'; } if (! empty($arrayfields['s.phone']['checked'])) { - // Phone + // Phone print '<td class="liste_titre">'; print '<input class="flat searchstring" size="4" type="text" name="search_phone" value="'.dol_escape_htmltag($search_phone).'">'; print '</td>'; } if (! empty($arrayfields['s.url']['checked'])) { - // Url + // Url print '<td class="liste_titre">'; print '<input class="flat searchstring" size="4" type="text" name="search_url" value="'.dol_escape_htmltag($search_url).'">'; print '</td>'; } if (! empty($arrayfields['s.siren']['checked'])) { - // IdProf1 + // IdProf1 print '<td class="liste_titre">'; print '<input class="flat searchstring" size="4" type="text" name="search_idprof1" value="'.dol_escape_htmltag($search_idprof1).'">'; print '</td>'; } if (! empty($arrayfields['s.siret']['checked'])) { - // IdProf2 + // IdProf2 print '<td class="liste_titre">'; print '<input class="flat searchstring" size="4" type="text" name="search_idprof2" value="'.dol_escape_htmltag($search_idprof2).'">'; print '</td>'; } if (! empty($arrayfields['s.ape']['checked'])) { - // IdProf3 + // IdProf3 print '<td class="liste_titre">'; print '<input class="flat searchstring" size="4" type="text" name="search_idprof3" value="'.dol_escape_htmltag($search_idprof3).'">'; print '</td>'; } if (! empty($arrayfields['s.idprof4']['checked'])) { - // IdProf4 + // IdProf4 print '<td class="liste_titre">'; print '<input class="flat searchstring" size="4" type="text" name="search_idprof4" value="'.dol_escape_htmltag($search_idprof4).'">'; print '</td>'; } if (! empty($arrayfields['s.idprof5']['checked'])) { - // IdProf5 + // IdProf5 print '<td class="liste_titre">'; print '<input class="flat searchstring" size="4" type="text" name="search_idprof5" value="'.dol_escape_htmltag($search_idprof5).'">'; print '</td>'; @@ -846,20 +846,20 @@ if (! empty($arrayfields['s.tva_intra']['checked'])) // Type (customer/prospect/supplier) if (! empty($arrayfields['customerorsupplier']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone" align="middle">'; - if ($type != '') print '<input type="hidden" name="type" value="'.$type.'">'; - print '<select class="flat" name="search_type">'; - print '<option value="-1"'.($search_type==''?' selected':'').'> </option>'; - if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print '<option value="1,3"'.($search_type=='1,3'?' selected':'').'>'.$langs->trans('Customer').'</option>'; - if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="2,3"'.($search_type=='2,3'?' selected':'').'>'.$langs->trans('Prospect').'</option>'; - //if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="3"'.($search_type=='3'?' selected':'').'>'.$langs->trans('ProspectCustomer').'</option>'; - print '<option value="4"'.($search_type=='4'?' selected':'').'>'.$langs->trans('Supplier').'</option>'; - print '<option value="0"'.($search_type=='0'?' selected':'').'>'.$langs->trans('Others').'</option>'; - print '</select></td>'; + print '<td class="liste_titre maxwidthonsmartphone" align="middle">'; + if ($type != '') print '<input type="hidden" name="type" value="'.$type.'">'; + print '<select class="flat" name="search_type">'; + print '<option value="-1"'.($search_type==''?' selected':'').'> </option>'; + if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print '<option value="1,3"'.($search_type=='1,3'?' selected':'').'>'.$langs->trans('Customer').'</option>'; + if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="2,3"'.($search_type=='2,3'?' selected':'').'>'.$langs->trans('Prospect').'</option>'; + //if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="3"'.($search_type=='3'?' selected':'').'>'.$langs->trans('ProspectCustomer').'</option>'; + print '<option value="4"'.($search_type=='4'?' selected':'').'>'.$langs->trans('Supplier').'</option>'; + print '<option value="0"'.($search_type=='0'?' selected':'').'>'.$langs->trans('Others').'</option>'; + print '</select></td>'; } if (! empty($arrayfields['s.fk_prospectlevel']['checked'])) { - // Prospect level + // Prospect level print '<td class="liste_titre" align="center">'; $options_from = '<option value=""> </option>'; // Generate in $options_from the list of each option sorted foreach ($tab_level as $tab_level_sortorder => $tab_level_label) @@ -877,25 +877,25 @@ if (! empty($arrayfields['s.fk_prospectlevel']['checked'])) $options_to .= '</option>'; } - // Print these two select + // Print these two select print $langs->trans("From").' <select class="flat" name="search_level_from">'.$options_from.'</select>'; print ' '; print $langs->trans("to").' <select class="flat" name="search_level_to">'.$options_to.'</select>'; - print '</td>'; + print '</td>'; } if (! empty($arrayfields['s.fk_stcomm']['checked'])) { - // Prospect status - print '<td class="liste_titre maxwidthonsmartphone" align="center">'; - $arraystcomm=array(); + // Prospect status + print '<td class="liste_titre maxwidthonsmartphone" align="center">'; + $arraystcomm=array(); foreach($prospectstatic->cacheprospectstatus as $key => $val) { - $arraystcomm[$val['id']]=($langs->trans("StatusProspect".$val['id']) != "StatusProspect".$val['id'] ? $langs->trans("StatusProspect".$val['id']) : $val['label']); + $arraystcomm[$val['id']]=($langs->trans("StatusProspect".$val['id']) != "StatusProspect".$val['id'] ? $langs->trans("StatusProspect".$val['id']) : $val['label']); } - print $form->selectarray('search_stcomm', $arraystcomm, $search_stcomm, -2); - print '</td>'; + print $form->selectarray('search_stcomm', $arraystcomm, $search_stcomm, -2); + print '</td>'; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) @@ -904,12 +904,12 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { if (! empty($arrayfields["ef.".$key]['checked'])) { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { - $crit=$val; + $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); $searchclass=''; if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; @@ -932,21 +932,21 @@ print $hookmanager->resPrint; // Date creation if (! empty($arrayfields['s.datec']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Date modification if (! empty($arrayfields['s.tms']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Status if (! empty($arrayfields['s.status']['checked'])) { - print '<td class="liste_titre maxwidthonsmartphone center">'; - print $form->selectarray('search_status', array('0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')), $search_status, 1); - print '</td>'; + print '<td class="liste_titre maxwidthonsmartphone center">'; + print $form->selectarray('search_status', array('0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')), $search_status, 1); + print '</td>'; } if (! empty($arrayfields['s.import_key']['checked'])) { @@ -993,16 +993,16 @@ if (! empty($arrayfields['s.fk_stcomm']['checked'])) print_liste_f // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); @@ -1043,186 +1043,186 @@ while ($i < min($num, $limit)) print '<td class="tdoverflowmax50">'; print $obj->rowid; print "</td>\n"; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['s.nom']['checked'])) { print '<td class="tdoverflowmax200">'; print $companystatic->getNomUrl(1,'',100); print "</td>\n"; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['s.name_alias']['checked'])) { - print '<td class="tdoverflowmax200">'; - print $companystatic->name_alias; - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; + print '<td class="tdoverflowmax200">'; + print $companystatic->name_alias; + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; } // Barcode - if (! empty($arrayfields['s.barcode']['checked'])) + if (! empty($arrayfields['s.barcode']['checked'])) { print '<td>'.$obj->barcode.'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } // Customer code - if (! empty($arrayfields['s.code_client']['checked'])) + if (! empty($arrayfields['s.code_client']['checked'])) { print '<td>'.$obj->code_client.'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - // Supplier code - if (! empty($arrayfields['s.code_fournisseur']['checked'])) + // Supplier code + if (! empty($arrayfields['s.code_fournisseur']['checked'])) { print '<td>'.$obj->code_fournisseur.'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } // Account customer code - if (! empty($arrayfields['s.code_compta']['checked'])) + if (! empty($arrayfields['s.code_compta']['checked'])) { print '<td>'.$obj->code_compta.'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - // Account supplier code - if (! empty($arrayfields['s.code_compta_fournisseur']['checked'])) + // Account supplier code + if (! empty($arrayfields['s.code_compta_fournisseur']['checked'])) { print '<td>'.$obj->code_compta_fournisseur.'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print "<td>".$obj->town."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print "<td>".$obj->zip."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "<td>".$obj->state_name."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Region - if (! empty($arrayfields['region.nom']['checked'])) - { - print "<td>".$obj->region_name."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print '<td align="center">'; + if (! empty($arrayfields['s.town']['checked'])) + { + print "<td>".$obj->town."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print "<td>".$obj->zip."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "<td>".$obj->state_name."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Region + if (! empty($arrayfields['region.nom']['checked'])) + { + print "<td>".$obj->region_name."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print '<td align="center">'; $tmparray=getCountry($obj->fk_pays,'all'); print $tmparray['label']; print '</td>'; - if (! $i) $totalarray['nbfield']++; - } + if (! $i) $totalarray['nbfield']++; + } // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print '<td align="center">'; + if (! empty($arrayfields['typent.code']['checked'])) + { + print '<td align="center">'; if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); print $typenArray[$obj->typent_code]; print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.email']['checked'])) - { - print "<td>".$obj->email."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.phone']['checked'])) - { - print "<td>".$obj->phone."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.url']['checked'])) - { - print "<td>".$obj->url."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.siren']['checked'])) - { - print "<td>".$obj->idprof1."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.siret']['checked'])) - { - print "<td>".$obj->idprof2."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.ape']['checked'])) - { - print "<td>".$obj->idprof3."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.idprof4']['checked'])) - { - print "<td>".$obj->idprof4."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.idprof5']['checked'])) - { - print "<td>".$obj->idprof5."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.idprof6']['checked'])) - { - print "<td>".$obj->idprof6."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.tva_intra']['checked'])) - { - print "<td>".$obj->tva_intra."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Type - if (! empty($arrayfields['customerorsupplier']['checked'])) - { - print '<td align="center">'; - $s=''; - if (($obj->client==1 || $obj->client==3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) - { - $companystatic->name=$langs->trans("Customer"); - $companystatic->name_alias=''; - $s.=$companystatic->getNomUrl(0,'customer'); - } - if (($obj->client==2 || $obj->client==3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) - { - if ($s) $s.=" / "; - $companystatic->name=$langs->trans("Prospect"); - $companystatic->name_alias=''; - $s.=$companystatic->getNomUrl(0,'prospect'); - } - if (! empty($conf->fournisseur->enabled) && $obj->fournisseur) - { - if ($s) $s.=" / "; - $companystatic->name=$langs->trans("Supplier"); - $companystatic->name_alias=''; - $s.=$companystatic->getNomUrl(0,'supplier'); - } - print $s; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - - if (! empty($arrayfields['s.fk_prospectlevel']['checked'])) - { + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.email']['checked'])) + { + print "<td>".$obj->email."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.phone']['checked'])) + { + print "<td>".$obj->phone."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.url']['checked'])) + { + print "<td>".$obj->url."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.siren']['checked'])) + { + print "<td>".$obj->idprof1."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.siret']['checked'])) + { + print "<td>".$obj->idprof2."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.ape']['checked'])) + { + print "<td>".$obj->idprof3."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.idprof4']['checked'])) + { + print "<td>".$obj->idprof4."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.idprof5']['checked'])) + { + print "<td>".$obj->idprof5."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.idprof6']['checked'])) + { + print "<td>".$obj->idprof6."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.tva_intra']['checked'])) + { + print "<td>".$obj->tva_intra."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Type + if (! empty($arrayfields['customerorsupplier']['checked'])) + { + print '<td align="center">'; + $s=''; + if (($obj->client==1 || $obj->client==3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) + { + $companystatic->name=$langs->trans("Customer"); + $companystatic->name_alias=''; + $s.=$companystatic->getNomUrl(0,'customer'); + } + if (($obj->client==2 || $obj->client==3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) + { + if ($s) $s.=" / "; + $companystatic->name=$langs->trans("Prospect"); + $companystatic->name_alias=''; + $s.=$companystatic->getNomUrl(0,'prospect'); + } + if (! empty($conf->fournisseur->enabled) && $obj->fournisseur) + { + if ($s) $s.=" / "; + $companystatic->name=$langs->trans("Supplier"); + $companystatic->name_alias=''; + $s.=$companystatic->getNomUrl(0,'supplier'); + } + print $s; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + + if (! empty($arrayfields['s.fk_prospectlevel']['checked'])) + { // Prospect level print '<td align="center">'; print $companystatic->getLibProspLevel(); print "</td>"; - if (! $i) $totalarray['nbfield']++; - } + if (! $i) $totalarray['nbfield']++; + } - if (! empty($arrayfields['s.fk_stcomm']['checked'])) - { - // Prospect status + if (! empty($arrayfields['s.fk_stcomm']['checked'])) + { + // Prospect status print '<td align="center" class="nowrap"><div class="nowrap">'; print '<div class="inline-block">'.$companystatic->LibProspCommStatut($obj->stcomm_id,2,$prospectstatic->cacheprospectstatus[$obj->stcomm_id]['label']); print '</div> - <div class="inline-block">'; @@ -1233,8 +1233,8 @@ while ($i < min($num, $limit)) if ($obj->stcomm_id != $val['id']) print '<a class="pictosubstatus" href="'.$_SERVER["PHP_SELF"].'?stcommsocid='.$obj->rowid.'&stcomm='.$val['code'].'&action=setstcomm'.$param.($page?'&page='.urlencode($page):'').'">'.img_action($titlealt,$val['code']).'</a>'; } print '</div></div></td>'; - if (! $i) $totalarray['nbfield']++; - } + if (! $i) $totalarray['nbfield']++; + } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { @@ -1249,54 +1249,54 @@ while ($i < min($num, $limit)) $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } } } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + // 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['s.datec']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['s.tms']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['s.status']['checked'])) - { - print '<td align="center" class="nowrap">'.$companystatic->getLibStatut(3).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['s.import_key']['checked'])) - { - print '<td class="tdoverflowmax100">'; - print $obj->import_key; - print "</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - - // Action column - print '<td class="nowrap" align="center">'; - 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; + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['s.datec']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['s.tms']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['s.status']['checked'])) + { + print '<td align="center" class="nowrap">'.$companystatic->getLibStatut(3).'</td>'; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.import_key']['checked'])) + { + print '<td class="tdoverflowmax100">'; + print $obj->import_key; + print "</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + + // Action column + print '<td class="nowrap" align="center">'; + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; print '</tr>'."\n"; $i++; diff --git a/htdocs/societe/rib.php b/htdocs/societe/rib.php index 7bfc5a482fe80f82b496c869836d5065fe25fdee..5b5a10b598b1e827a8bc65752e885ac3598387d4 100644 --- a/htdocs/societe/rib.php +++ b/htdocs/societe/rib.php @@ -78,255 +78,255 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if ($cancel) - { - $action=''; - if (! empty($backtopage)) - { - header("Location: ".$backtopage); - exit; - } - } + if ($cancel) + { + $action=''; + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + } - if ($action == 'update' && ! $_POST["cancel"]) - { - // Modification - if (! GETPOST('label')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $action='edit'; - $error++; - } - if (! GETPOST('bank')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); - $action='edit'; - $error++; - } - if ($account->needIBAN() == 1) - { - if (! GETPOST('iban')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); - $action='edit'; - $error++; - } - if (! GETPOST('bic')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); - $action='edit'; - $error++; - } - } - - $account->fetch($id); - if (! $error) - { - $account->socid = $object->id; - - $account->bank = GETPOST('bank','alpha'); - $account->label = GETPOST('label','alpha'); - $account->courant = GETPOST('courant','alpha'); - $account->clos = GETPOST('clos','alpha'); - $account->code_banque = GETPOST('code_banque','alpha'); - $account->code_guichet = GETPOST('code_guichet','alpha'); - $account->number = GETPOST('number','alpha'); - $account->cle_rib = GETPOST('cle_rib','alpha'); - $account->bic = GETPOST('bic','alpha'); - $account->iban = GETPOST('iban','alpha'); - $account->domiciliation = GETPOST('domiciliation','alpha'); - $account->proprio = GETPOST('proprio','alpha'); - $account->owner_address = GETPOST('owner_address','alpha'); - $account->frstrecur = GETPOST('frstrecur','alpha'); - $account->rum = GETPOST('rum','alpha'); - if (empty($account->rum)) - { - $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - $account->date_rum = dol_now(); - } - - $result = $account->update($user); - if (! $result) - { - setEventMessages($account->error, $account->errors, 'errors'); - } - else - { - // If this account is the default bank account, we disable others - if ($account->default_rib) - { - $account->setAsDefault($id); // This will make sure there is only one default rib - } - - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - } - } + if ($action == 'update' && ! $_POST["cancel"]) + { + // Modification + if (! GETPOST('label')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + $action='edit'; + $error++; + } + if (! GETPOST('bank')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + $action='edit'; + $error++; + } + if ($account->needIBAN() == 1) + { + if (! GETPOST('iban')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); + $action='edit'; + $error++; + } + if (! GETPOST('bic')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); + $action='edit'; + $error++; + } + } - if ($action == 'add' && ! $_POST["cancel"]) - { - $error=0; - - if (! GETPOST('label')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $action='create'; - $error++; - } - if (! GETPOST('bank')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); - $action='create'; - $error++; - } - - if (! $error) - { - // Ajout - $account = new CompanyBankAccount($db); - - $account->socid = $object->id; - - $account->bank = GETPOST('bank','alpha'); - $account->label = GETPOST('label','alpha'); - $account->courant = GETPOST('courant','alpha'); - $account->clos = GETPOST('clos','alpha'); - $account->code_banque = GETPOST('code_banque','alpha'); - $account->code_guichet = GETPOST('code_guichet','alpha'); - $account->number = GETPOST('number','alpha'); - $account->cle_rib = GETPOST('cle_rib','alpha'); - $account->bic = GETPOST('bic','alpha'); - $account->iban = GETPOST('iban','alpha'); - $account->domiciliation = GETPOST('domiciliation','alpha'); - $account->proprio = GETPOST('proprio','alpha'); - $account->owner_address = GETPOST('owner_address','alpha'); - $account->frstrecur = GETPOST('frstrecur'); - $account->rum = GETPOST('rum','alpha'); - $account->datec = dol_now(); - - $db->begin(); - - // This test can be done only once properties were set - if ($account->needIBAN() == 1) - { - if (! GETPOST('iban')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); - $action='create'; - $error++; - } - if (! GETPOST('bic')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); - $action='create'; - $error++; - } - } - - if (! $error) - { - $result = $account->create($user); - if ($result < 0) - { - $error++; - setEventMessages($account->error, $account->errors, 'errors'); - $action='create'; // Force chargement page création - } - - if (empty($account->rum)) - { - $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - $account->date_rum = dol_now(); - } - } - - if (! $error) - { - $result = $account->update($user); // This will set the UMR number. - if ($result < 0) - { - $error++; - setEventMessages($account->error, $account->errors, 'errors'); - $action='create'; - } - } - - if (! $error) - { - $db->commit(); - - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - else - { - $db->rollback(); - } - } - } + $account->fetch($id); + if (! $error) + { + $account->socid = $object->id; + + $account->bank = GETPOST('bank','alpha'); + $account->label = GETPOST('label','alpha'); + $account->courant = GETPOST('courant','alpha'); + $account->clos = GETPOST('clos','alpha'); + $account->code_banque = GETPOST('code_banque','alpha'); + $account->code_guichet = GETPOST('code_guichet','alpha'); + $account->number = GETPOST('number','alpha'); + $account->cle_rib = GETPOST('cle_rib','alpha'); + $account->bic = GETPOST('bic','alpha'); + $account->iban = GETPOST('iban','alpha'); + $account->domiciliation = GETPOST('domiciliation','alpha'); + $account->proprio = GETPOST('proprio','alpha'); + $account->owner_address = GETPOST('owner_address','alpha'); + $account->frstrecur = GETPOST('frstrecur','alpha'); + $account->rum = GETPOST('rum','alpha'); + if (empty($account->rum)) + { + $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); + $account->date_rum = dol_now(); + } - if ($action == 'setasdefault') - { - $account = new CompanyBankAccount($db); - $res = $account->setAsDefault(GETPOST('ribid','int')); - if ($res) - { - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - else - { - setEventMessages($db->lasterror, null, 'errors'); - } - } + $result = $account->update($user); + if (! $result) + { + setEventMessages($account->error, $account->errors, 'errors'); + } + else + { + // If this account is the default bank account, we disable others + if ($account->default_rib) + { + $account->setAsDefault($id); // This will make sure there is only one default rib + } - if ($action == 'confirm_delete' && $_GET['confirm'] == 'yes') - { - $account = new CompanyBankAccount($db); - if ($account->fetch($ribid?$ribid:$id)) - { - $result = $account->delete($user); - if ($result > 0) - { - $url = $_SERVER['PHP_SELF']."?socid=".$object->id; - header('Location: '.$url); - exit; - } - else - { - setEventMessages($account->error, $account->errors, 'errors'); - } - } - else - { - setEventMessages($account->error, $account->errors, 'errors'); - } - } + $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + } + } - $savid=$id; + if ($action == 'add' && ! $_POST["cancel"]) + { + $error=0; - // Actions to build doc - if ($action == 'builddocrib') - { - $action = 'builddoc'; - $moreparams = array( - 'use_companybankid'=>GETPOST('companybankid'), - 'force_dir_output'=>$conf->societe->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->id) - ); - $_POST['lang_id'] = GETPOST('lang_idrib'.GETPOST('companybankid')); - $_POST['model'] = GETPOST('modelrib'.GETPOST('companybankid')); - } - $id = $socid; - $upload_dir = $conf->societe->multidir_output[$object->entity]; - $permissioncreate=$user->rights->societe->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + if (! GETPOST('label')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + $action='create'; + $error++; + } + if (! GETPOST('bank')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + $action='create'; + $error++; + } + + if (! $error) + { + // Ajout + $account = new CompanyBankAccount($db); + + $account->socid = $object->id; + + $account->bank = GETPOST('bank','alpha'); + $account->label = GETPOST('label','alpha'); + $account->courant = GETPOST('courant','alpha'); + $account->clos = GETPOST('clos','alpha'); + $account->code_banque = GETPOST('code_banque','alpha'); + $account->code_guichet = GETPOST('code_guichet','alpha'); + $account->number = GETPOST('number','alpha'); + $account->cle_rib = GETPOST('cle_rib','alpha'); + $account->bic = GETPOST('bic','alpha'); + $account->iban = GETPOST('iban','alpha'); + $account->domiciliation = GETPOST('domiciliation','alpha'); + $account->proprio = GETPOST('proprio','alpha'); + $account->owner_address = GETPOST('owner_address','alpha'); + $account->frstrecur = GETPOST('frstrecur'); + $account->rum = GETPOST('rum','alpha'); + $account->datec = dol_now(); + + $db->begin(); + + // This test can be done only once properties were set + if ($account->needIBAN() == 1) + { + if (! GETPOST('iban')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); + $action='create'; + $error++; + } + if (! GETPOST('bic')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); + $action='create'; + $error++; + } + } + + if (! $error) + { + $result = $account->create($user); + if ($result < 0) + { + $error++; + setEventMessages($account->error, $account->errors, 'errors'); + $action='create'; // Force chargement page création + } + + if (empty($account->rum)) + { + $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); + $account->date_rum = dol_now(); + } + } + + if (! $error) + { + $result = $account->update($user); // This will set the UMR number. + if ($result < 0) + { + $error++; + setEventMessages($account->error, $account->errors, 'errors'); + $action='create'; + } + } + + if (! $error) + { + $db->commit(); + + $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + else + { + $db->rollback(); + } + } + } - $id = $savid; + if ($action == 'setasdefault') + { + $account = new CompanyBankAccount($db); + $res = $account->setAsDefault(GETPOST('ribid','int')); + if ($res) + { + $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + else + { + setEventMessages($db->lasterror, null, 'errors'); + } + } + + if ($action == 'confirm_delete' && $_GET['confirm'] == 'yes') + { + $account = new CompanyBankAccount($db); + if ($account->fetch($ribid?$ribid:$id)) + { + $result = $account->delete($user); + if ($result > 0) + { + $url = $_SERVER['PHP_SELF']."?socid=".$object->id; + header('Location: '.$url); + exit; + } + else + { + setEventMessages($account->error, $account->errors, 'errors'); + } + } + else + { + setEventMessages($account->error, $account->errors, 'errors'); + } + } + + $savid=$id; + + // Actions to build doc + if ($action == 'builddocrib') + { + $action = 'builddoc'; + $moreparams = array( + 'use_companybankid'=>GETPOST('companybankid'), + 'force_dir_output'=>$conf->societe->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->id) + ); + $_POST['lang_id'] = GETPOST('lang_idrib'.GETPOST('companybankid')); + $_POST['model'] = GETPOST('modelrib'.GETPOST('companybankid')); + } + $id = $socid; + $upload_dir = $conf->societe->multidir_output[$object->entity]; + $permissioncreate=$user->rights->societe->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + + $id = $savid; } @@ -347,22 +347,22 @@ if (! $id) } else { - $account->fetch($id); + $account->fetch($id); } if (empty($account->socid)) $account->socid=$object->id; if ($socid && $action == 'edit' && $user->rights->societe->creer) { - print '<form action="rib.php?socid='.$object->id.'" method="post">'; - print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; - print '<input type="hidden" name="action" value="update">'; - print '<input type="hidden" name="id" value="'.GETPOST("id","int").'">'; + print '<form action="rib.php?socid='.$object->id.'" method="post">'; + print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; + print '<input type="hidden" name="action" value="update">'; + print '<input type="hidden" name="id" value="'.GETPOST("id","int").'">'; } if ($socid && $action == 'create' && $user->rights->societe->creer) { - print '<form action="rib.php?socid='.$object->id.'" method="post">'; - print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; - print '<input type="hidden" name="action" value="add">'; + print '<form action="rib.php?socid='.$object->id.'" method="post">'; + print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; + print '<input type="hidden" name="action" value="add">'; } @@ -372,25 +372,25 @@ if ($socid && $action != 'edit' && $action != "create") dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"), -1, 'company'); // Confirm delete third party - if ($action == 'delete') - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $account->getRibLabel()), "confirm_delete", '', 0, 1); - } + if ($action == 'delete') + { + print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $account->getRibLabel()), "confirm_delete", '', 0, 1); + } - $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; + $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; - dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); - print load_fiche_titre($langs->trans("DefaultRIB"), '', ''); + print load_fiche_titre($langs->trans("DefaultRIB"), '', ''); - print '<div class="fichecenter">'; - print '<div class="underbanner clearboth"></div>'; + print '<div class="fichecenter">'; + print '<div class="underbanner clearboth"></div>'; - print '<table class="border centpercent">'; + print '<table class="border centpercent">'; - print '<tr><td class="titlefield">'.$langs->trans("LabelRIB").'</td>'; - print '<td>'.$account->label.'</td></tr>'; + print '<tr><td class="titlefield">'.$langs->trans("LabelRIB").'</td>'; + print '<td>'.$account->label.'</td></tr>'; print '<tr><td>'.$langs->trans("BankName").'</td>'; print '<td>'.$account->bank.'</td></tr>'; @@ -405,11 +405,11 @@ if ($socid && $action != 'edit' && $action != "create") } elseif ($val == 'BankAccountNumber') { $content = $account->number; if (! empty($account->label) && $account->number) { - if (! checkBanForAccount($account)) { - $content.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); - } else { - $content.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); - } + if (! checkBanForAccount($account)) { + $content.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); + } else { + $content.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); + } } } elseif ($val == 'BankAccountNumberKey') { $content = $account->cle_rib; @@ -451,78 +451,78 @@ if ($socid && $action != 'edit' && $action != "create") print "</td></tr>\n"; print '</table>'; - print '</div>'; + print '</div>'; print '<br>'; - /* + /* * List of bank accounts */ - print load_fiche_titre($langs->trans("AllRIB"), '', ''); + print load_fiche_titre($langs->trans("AllRIB"), '', ''); - $rib_list = $object->get_all_rib(); - $var = false; - if (is_array($rib_list)) - { + $rib_list = $object->get_all_rib(); + $var = false; + if (is_array($rib_list)) + { print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print '<table class="liste" width="100%">'; - - print '<tr class="liste_titre">'; - print_liste_field_titre("LabelRIB"); - print_liste_field_titre("Bank"); - print_liste_field_titre("RIB"); - print_liste_field_titre("IBAN"); - print_liste_field_titre("BIC"); - if (! empty($conf->prelevement->enabled)) - { + print '<table class="liste" width="100%">'; + + print '<tr class="liste_titre">'; + print_liste_field_titre("LabelRIB"); + print_liste_field_titre("Bank"); + print_liste_field_titre("RIB"); + print_liste_field_titre("IBAN"); + print_liste_field_titre("BIC"); + if (! empty($conf->prelevement->enabled)) + { print print_liste_field_titre("RUM"); print print_liste_field_titre("WithdrawMode"); - } - print_liste_field_titre("DefaultRIB", '', '', '', '', 'align="center"'); - print_liste_field_titre('', '', '', '', '', 'align="center"'); - print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch '); + } + print_liste_field_titre("DefaultRIB", '', '', '', '', 'align="center"'); + print_liste_field_titre('', '', '', '', '', 'align="center"'); + print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch '); print "</tr>\n"; - foreach ($rib_list as $rib) - { - print '<tr class="oddeven">'; - // Label - print '<td>'.$rib->label.'</td>'; - // Bank name - print '<td>'.$rib->bank.'</td>'; - // Account number - print '<td>'; - $string=''; - foreach ($rib->getFieldsToShow() as $val) { - - if ($val == 'BankCode') { - $string .= $rib->code_banque.' '; - } elseif ($val == 'BankAccountNumber') { - $string .= $rib->number.' '; - } elseif ($val == 'DeskCode') { - $string .= $rib->code_guichet.' '; - } elseif ($val == 'BankAccountNumberKey') { - $string .= $rib->cle_rib.' '; - /* Already output after + foreach ($rib_list as $rib) + { + print '<tr class="oddeven">'; + // Label + print '<td>'.$rib->label.'</td>'; + // Bank name + print '<td>'.$rib->bank.'</td>'; + // Account number + print '<td>'; + $string=''; + foreach ($rib->getFieldsToShow() as $val) { + + if ($val == 'BankCode') { + $string .= $rib->code_banque.' '; + } elseif ($val == 'BankAccountNumber') { + $string .= $rib->number.' '; + } elseif ($val == 'DeskCode') { + $string .= $rib->code_guichet.' '; + } elseif ($val == 'BankAccountNumberKey') { + $string .= $rib->cle_rib.' '; + /* Already output after }elseif ($val == 'BIC') { $string .= $rib->bic.' '; }elseif ($val == 'IBAN') { $string .= $rib->iban.' ';*/ - } - } - if (! empty($rib->label) && $rib->number) { - if (! checkBanForAccount($rib)) { - $string.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); - } else { - $string.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); - } + } + } + if (! empty($rib->label) && $rib->number) { + if (! checkBanForAccount($rib)) { + $string.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); + } else { + $string.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); + } } - print $string; - print '</td>'; - // IBAN - print '<td>'.$rib->iban; + print $string; + print '</td>'; + // IBAN + print '<td>'.$rib->iban; if (! empty($rib->iban)) { if (! checkIbanForAccount($rib)) { print ' '.img_picto($langs->trans("IbanNotValid"),'warning'); @@ -530,9 +530,9 @@ if ($socid && $action != 'edit' && $action != "create") print ' '.img_picto($langs->trans("IbanValid"),'info'); } } - print '</td>'; - // BIC - print '<td>'.$rib->bic; + print '</td>'; + // BIC + print '<td>'.$rib->bic; if (! empty($rib->bic)) { if (! checkSwiftForAccount($rib)) { print ' '.img_picto($langs->trans("SwiftNotValid"),'warning'); @@ -723,20 +723,20 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) { dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); - $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php">'.$langs->trans("BackToList").'</a>'; + $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php">'.$langs->trans("BackToList").'</a>'; - dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); - print '<div class="fichecenter">'; + print '<div class="fichecenter">'; - print '<div class="underbanner clearboth"></div>'; + print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent">'; - print '<tr><td class="titlefield fieldrequired">'.$langs->trans("LabelRIB").'</td>'; - print '<td><input size="30" type="text" name="label" value="'.$account->label.'"></td></tr>'; + print '<tr><td class="titlefield fieldrequired">'.$langs->trans("LabelRIB").'</td>'; + print '<td><input size="30" type="text" name="label" value="'.$account->label.'"></td></tr>'; - print '<tr><td class="fieldrequired">'.$langs->trans("BankName").'</td>'; - print '<td><input size="30" type="text" name="bank" value="'.$account->bank.'"></td></tr>'; + print '<tr><td class="fieldrequired">'.$langs->trans("BankName").'</td>'; + print '<td><input size="30" type="text" name="bank" value="'.$account->bank.'"></td></tr>'; // Show fields of bank account foreach ($account->getFieldsToShow(1) as $val) { @@ -775,51 +775,51 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) print '</tr>'; } - print '<tr><td>'.$langs->trans("BankAccountDomiciliation").'</td><td>'; - print '<textarea name="domiciliation" rows="4" cols="40" maxlength="255">'; - print $account->domiciliation; - print "</textarea></td></tr>"; + print '<tr><td>'.$langs->trans("BankAccountDomiciliation").'</td><td>'; + print '<textarea name="domiciliation" rows="4" cols="40" maxlength="255">'; + print $account->domiciliation; + print "</textarea></td></tr>"; - print '<tr><td>'.$langs->trans("BankAccountOwner").'</td>'; - print '<td><input size="30" type="text" name="proprio" value="'.$account->proprio.'"></td></tr>'; - print "</td></tr>\n"; + print '<tr><td>'.$langs->trans("BankAccountOwner").'</td>'; + print '<td><input size="30" type="text" name="proprio" value="'.$account->proprio.'"></td></tr>'; + print "</td></tr>\n"; - print '<tr><td>'.$langs->trans("BankAccountOwnerAddress").'</td><td>'; - print '<textarea name="owner_address" rows="'.ROWS_4.'" cols="40" maxlength="255">'; - print $account->owner_address; - print "</textarea></td></tr>"; + print '<tr><td>'.$langs->trans("BankAccountOwnerAddress").'</td><td>'; + print '<textarea name="owner_address" rows="'.ROWS_4.'" cols="40" maxlength="255">'; + print $account->owner_address; + print "</textarea></td></tr>"; - print '</table>'; + print '</table>'; - if ($conf->prelevement->enabled) - { + if ($conf->prelevement->enabled) + { print '<br>'; - print '<table class="border" width="100%">'; + print '<table class="border" width="100%">'; - if (empty($account->rum)) $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); + if (empty($account->rum)) $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); - // RUM - print '<tr><td class="titlefield">'.$langs->trans("RUM").'</td>'; - print '<td><input class="minwidth300" type="text" name="rum" value="'.dol_escape_htmltag($account->rum).'"></td></tr>'; + // RUM + print '<tr><td class="titlefield">'.$langs->trans("RUM").'</td>'; + print '<td><input class="minwidth300" type="text" name="rum" value="'.dol_escape_htmltag($account->rum).'"></td></tr>'; - print '<tr><td>'.$langs->trans("WithdrawMode").'</td><td>'; - $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); - print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur')?GETPOST('frstrecur'):$account->frstrecur), 0); - print '</td></tr>'; + print '<tr><td>'.$langs->trans("WithdrawMode").'</td><td>'; + $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); + print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur')?GETPOST('frstrecur'):$account->frstrecur), 0); + print '</td></tr>'; - print '</table>'; - } + print '</table>'; + } - print '</div>'; + print '</div>'; - dol_fiche_end(); + dol_fiche_end(); print '<div align="center">'; print '<input class="button" value="'.$langs->trans("Modify").'" type="submit">'; - print ' '; + print ' '; print '<input class="button" name="cancel" value="'.$langs->trans("Cancel").'" type="submit">'; - print '</div>'; + print '</div>'; } @@ -828,95 +828,95 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) { dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); - $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php">'.$langs->trans("BackToList").'</a>'; + $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php">'.$langs->trans("BackToList").'</a>'; - dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); - print '<div class="nofichecenter">'; + print '<div class="nofichecenter">'; - print '<div class="underbanner clearboth"></div>'; + print '<div class="underbanner clearboth"></div>'; print '<table class="border centpercent">'; - print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("LabelRIB").'</td>'; - print '<td><input size="30" type="text" name="label" value="'.GETPOST('label').'"></td></tr>'; - - print '<tr><td class="fieldrequired">'.$langs->trans("Bank").'</td>'; - print '<td><input size="30" type="text" name="bank" value="'.GETPOST('bank').'"></td></tr>'; - - // Show fields of bank account - foreach ($account->getFieldsToShow(1) as $val) { - - $require=false; - if ($val == 'BankCode') { - $name = 'code_banque'; - $size = 8; - } elseif ($val == 'DeskCode') { - $name = 'code_guichet'; - $size = 8; - } elseif ($val == 'BankAccountNumber') { - $name = 'number'; - $size = 18; - } elseif ($val == 'BankAccountNumberKey') { - $name = 'cle_rib'; - $size = 3; - } elseif ($val == 'IBAN') { - $name = 'iban'; - $size = 30; - if ($account->needIBAN()) $require=true; - } elseif ($val == 'BIC') { - $name = 'bic'; - $size = 12; - if ($account->needIBAN()) $require=true; - } + print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("LabelRIB").'</td>'; + print '<td><input size="30" type="text" name="label" value="'.GETPOST('label').'"></td></tr>'; - print '<tr><td'.($require?' class="fieldrequired" ':'').'>'.$langs->trans($val).'</td>'; - print '<td><input size="'.$size.'" type="text" class="flat" name="'.$name.'" value="'.GETPOST($name).'"></td>'; - print '</tr>'; - } + print '<tr><td class="fieldrequired">'.$langs->trans("Bank").'</td>'; + print '<td><input size="30" type="text" name="bank" value="'.GETPOST('bank').'"></td></tr>'; - print '<tr><td>'.$langs->trans("BankAccountDomiciliation").'</td><td>'; - print '<textarea name="domiciliation" rows="'.ROWS_4.'" class="quatrevingtpercent" maxlength="255">'; - print GETPOST('domiciliation'); - print "</textarea></td></tr>"; + // Show fields of bank account + foreach ($account->getFieldsToShow(1) as $val) { - print '<tr><td>'.$langs->trans("BankAccountOwner").'</td>'; - print '<td><input size="30" type="text" name="proprio" value="'.GETPOST('proprio').'"></td></tr>'; - print "</td></tr>\n"; + $require=false; + if ($val == 'BankCode') { + $name = 'code_banque'; + $size = 8; + } elseif ($val == 'DeskCode') { + $name = 'code_guichet'; + $size = 8; + } elseif ($val == 'BankAccountNumber') { + $name = 'number'; + $size = 18; + } elseif ($val == 'BankAccountNumberKey') { + $name = 'cle_rib'; + $size = 3; + } elseif ($val == 'IBAN') { + $name = 'iban'; + $size = 30; + if ($account->needIBAN()) $require=true; + } elseif ($val == 'BIC') { + $name = 'bic'; + $size = 12; + if ($account->needIBAN()) $require=true; + } - print '<tr><td>'.$langs->trans("BankAccountOwnerAddress").'</td><td>'; - print '<textarea name="owner_address" rows="'.ROWS_4.'" class="quatrevingtpercent" maxlength="255">'; - print GETPOST('owner_address'); - print "</textarea></td></tr>"; + print '<tr><td'.($require?' class="fieldrequired" ':'').'>'.$langs->trans($val).'</td>'; + print '<td><input size="'.$size.'" type="text" class="flat" name="'.$name.'" value="'.GETPOST($name).'"></td>'; + print '</tr>'; + } - print '</table>'; + print '<tr><td>'.$langs->trans("BankAccountDomiciliation").'</td><td>'; + print '<textarea name="domiciliation" rows="'.ROWS_4.'" class="quatrevingtpercent" maxlength="255">'; + print GETPOST('domiciliation'); + print "</textarea></td></tr>"; - if ($conf->prelevement->enabled) - { - print '<br>'; + print '<tr><td>'.$langs->trans("BankAccountOwner").'</td>'; + print '<td><input size="30" type="text" name="proprio" value="'.GETPOST('proprio').'"></td></tr>'; + print "</td></tr>\n"; - print '<table class="border" width="100%">'; + print '<tr><td>'.$langs->trans("BankAccountOwnerAddress").'</td><td>'; + print '<textarea name="owner_address" rows="'.ROWS_4.'" class="quatrevingtpercent" maxlength="255">'; + print GETPOST('owner_address'); + print "</textarea></td></tr>"; - // RUM - print '<tr><td class="titlefieldcreate">'.$langs->trans("RUM").'</td>'; - print '<td colspan="4"><input type="text" class="minwidth300" name="rum" value="'.GETPOST('rum','alpha').'"><br>'.$langs->trans("RUMWillBeGenerated").'</td></tr>'; + print '</table>'; - print '<tr><td>'.$langs->trans("WithdrawMode").'</td><td>'; - $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); - print $form->selectarray("frstrecur", $tblArraychoice, (isset($_POST['frstrecur'])?GETPOST('frstrecur'):'FRST'), 0); - print '</td></tr>'; + if ($conf->prelevement->enabled) + { + print '<br>'; - print '</table>'; - } + print '<table class="border" width="100%">'; + + // RUM + print '<tr><td class="titlefieldcreate">'.$langs->trans("RUM").'</td>'; + print '<td colspan="4"><input type="text" class="minwidth300" name="rum" value="'.GETPOST('rum','alpha').'"><br>'.$langs->trans("RUMWillBeGenerated").'</td></tr>'; + + print '<tr><td>'.$langs->trans("WithdrawMode").'</td><td>'; + $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); + print $form->selectarray("frstrecur", $tblArraychoice, (isset($_POST['frstrecur'])?GETPOST('frstrecur'):'FRST'), 0); + print '</td></tr>'; + + print '</table>'; + } - print '</div>'; + print '</div>'; dol_fiche_end(); print '<div class="center">'; print '<input class="button" value="'.$langs->trans("Add").'" type="submit">'; - print ' '; + print ' '; print '<input name="cancel" class="button" value="'.$langs->trans("Cancel").'" type="submit">'; - print '</div>'; + print '</div>'; } if ($socid && $action == 'edit' && $user->rights->societe->creer) diff --git a/htdocs/supplier_proposal/list.php b/htdocs/supplier_proposal/list.php index 9b345827a8ed976586de1f0f27aced465a74182f..85798a8a80f89d06b62f2d8c975a5f3c350962f2 100644 --- a/htdocs/supplier_proposal/list.php +++ b/htdocs/supplier_proposal/list.php @@ -126,39 +126,39 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'p.ref'=>'Ref', - 's.nom'=>'Supplier', - 'pd.description'=>'Description', - 'p.note_public'=>'NotePublic', + 'p.ref'=>'Ref', + 's.nom'=>'Supplier', + 'pd.description'=>'Description', + 'p.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["p.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'sp.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("Supplier"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'sp.date_valid'=>array('label'=>$langs->trans("Date"), 'checked'=>1), - 'sp.date_livraison'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), - 'sp.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'sp.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'sp.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'u.login'=>array('label'=>$langs->trans("Author"), 'checked'=>1, 'position'=>10), - 'sp.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'sp.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'sp.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'sp.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("Supplier"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'sp.date_valid'=>array('label'=>$langs->trans("Date"), 'checked'=>1), + 'sp.date_livraison'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), + 'sp.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'sp.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'sp.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'u.login'=>array('label'=>$langs->trans("Author"), 'checked'=>1, 'position'=>10), + 'sp.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'sp.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'sp.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! 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'=>$extrafields->attribute_perms[$key]); - } + 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'=>$extrafields->attribute_perms[$key]); + } } @@ -180,38 +180,38 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_ref=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_login=''; - $search_product_category=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $search_author=''; - $yearvalid=''; - $monthvalid=''; - $year=''; - $month=''; - $search_status=''; - $object_statut=''; + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_ref=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $search_login=''; + $search_product_category=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $search_author=''; + $yearvalid=''; + $monthvalid=''; + $year=''; + $month=''; + $search_status=''; + $object_statut=''; } if (empty($reshook)) { - $objectclass='SupplierProposal'; - $objectlabel='SupplierProposals'; - $permtoread = $user->rights->supplier_proposal->lire; - $permtodelete = $user->rights->supplier_proposal->supprimer; - $uploaddir = $conf->supplier_proposal->dir_output; + $objectclass='SupplierProposal'; + $objectlabel='SupplierProposals'; + $permtoread = $user->rights->supplier_proposal->lire; + $permtodelete = $user->rights->supplier_proposal->supprimer; + $uploaddir = $conf->supplier_proposal->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -263,8 +263,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = sp.fk_projet"; if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as c"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as c"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE sp.fk_soc = s.rowid'; $sql.= ' AND sp.entity IN ('.getEntity('supplier_proposal').')'; @@ -288,12 +288,12 @@ if ($socid) $sql.= ' AND s.rowid = '.$socid; if ($search_status >= 0 && $search_status != '') $sql.= ' AND sp.fk_statut IN ('.$db->escape($search_status).')'; if ($month > 0) { - if ($year > 0 && empty($day)) - $sql.= " AND sp.date_livraison BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND sp.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(sp.date_livraison, '%m') = '".$month."'"; + if ($year > 0 && empty($day)) + $sql.= " AND sp.date_livraison BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND sp.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(sp.date_livraison, '%m') = '".$month."'"; } else if ($year > 0) { @@ -301,12 +301,12 @@ else if ($year > 0) } if ($monthvalid > 0) { - if ($yearvalid > 0 && empty($dayvalid)) - $sql.= " AND sp.date_valid BETWEEN '".$db->idate(dol_get_first_day($yearvalid,$monthvalid,false))."' AND '".$db->idate(dol_get_last_day($yearvalid,$monthvalid,false))."'"; - else if ($yearvalid > 0 && ! empty($dayvalid)) - $sql.= " AND sp.date_valid BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $monthvalid, $dayvalid, $yearvalid))."' AND '".$db->idate(dol_mktime(23, 59, 59, $monthvalid, $dayvalid, $yearvalid))."'"; - else - $sql.= " AND date_format(sp.date_valid, '%m') = '".$monthvalid."'"; + if ($yearvalid > 0 && empty($dayvalid)) + $sql.= " AND sp.date_valid BETWEEN '".$db->idate(dol_get_first_day($yearvalid,$monthvalid,false))."' AND '".$db->idate(dol_get_last_day($yearvalid,$monthvalid,false))."'"; + else if ($yearvalid > 0 && ! empty($dayvalid)) + $sql.= " AND sp.date_valid BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $monthvalid, $dayvalid, $yearvalid))."' AND '".$db->idate(dol_mktime(23, 59, 59, $monthvalid, $dayvalid, $yearvalid))."'"; + else + $sql.= " AND date_format(sp.date_valid, '%m') = '".$monthvalid."'"; } else if ($yearvalid > 0) { @@ -315,21 +315,21 @@ else if ($yearvalid > 0) if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; if ($search_user > 0) { - $sql.= " AND c.fk_c_type_contact = tc.rowid AND tc.element='supplier_proposal' AND tc.source='internal' AND c.element_id = sp.rowid AND c.fk_socpeople = ".$search_user; + $sql.= " AND c.fk_c_type_contact = tc.rowid AND tc.element='supplier_proposal' AND tc.source='internal' AND c.element_id = sp.rowid AND c.fk_socpeople = ".$search_user; } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -357,13 +357,13 @@ if ($resql) if ($socid > 0) { - $soc = new Societe($db); - $soc->fetch($socid); - $title = $langs->trans('ListOfSupplierProposals') . ' - '.$soc->name; + $soc = new Societe($db); + $soc->fetch($socid); + $title = $langs->trans('ListOfSupplierProposals') . ' - '.$soc->name; } else { - $title = $langs->trans('ListOfSupplierProposals'); + $title = $langs->trans('ListOfSupplierProposals'); } $num = $db->num_rows($resql); @@ -371,13 +371,13 @@ if ($resql) $arrayofselected=is_array($toselect)?$toselect:array(); $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + 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 ($month) $param.='&month='.$month; if ($year) $param.='&year='.$year; - if ($search_ref) $param.='&search_ref=' .$search_ref; - if ($search_societe) $param.='&search_societe=' .$search_societe; + if ($search_ref) $param.='&search_ref=' .$search_ref; + if ($search_societe) $param.='&search_societe=' .$search_societe; if ($search_user > 0) $param.='&search_user='.$search_user; if ($search_sale > 0) $param.='&search_sale='.$search_sale; if ($search_montant_ht) $param.='&search_montant_ht='.$search_montant_ht; @@ -390,15 +390,15 @@ if ($resql) // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + //'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->supplier_proposal->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); if ($massaction == 'presend') $arrayofmassactions=array(); @@ -428,8 +428,8 @@ if ($resql) if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } $i = 0; @@ -448,20 +448,20 @@ if ($resql) // If the user can view prospects other than his' if ($user->rights->societe->client->voir || $socid) { - $moreforfilter.='<div class="divsearchfield">'; - $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); - $moreforfilter.='</div>'; + $moreforfilter.='<div class="divsearchfield">'; + $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); + $moreforfilter.='</div>'; } // If the user can view products if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { - include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $moreforfilter.='<div class="divsearchfield">'; - $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter.='</div>'; + include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter.='<div class="divsearchfield">'; + $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); + $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); + $moreforfilter.='</div>'; } $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook @@ -469,18 +469,18 @@ if ($resql) else $moreforfilter = $hookmanager->resPrint; if (! empty($moreforfilter)) - { - print '<div class="liste_titre liste_titre_bydiv centpercent">'; - print $moreforfilter; - print '</div>'; - } + { + print '<div class="liste_titre liste_titre_bydiv centpercent">'; + print $moreforfilter; + print '</div>'; + } - $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); + $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); - print '<div class="div-table-responsive">'; - print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; + print '<div class="div-table-responsive">'; + print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; print '<tr class="liste_titre_filter">'; if (! empty($arrayfields['sp.ref']['checked'])) @@ -498,26 +498,26 @@ if ($resql) if (! empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; if (! empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="4" name="search_zip" value="'.$search_zip.'"></td>'; // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print '<td class="liste_titre">'; - print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; - print '</td>'; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print '<td class="liste_titre" align="center">'; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print '</td>'; - } + if (! empty($arrayfields['state.nom']['checked'])) + { + print '<td class="liste_titre">'; + print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; + print '</td>'; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print '<td class="liste_titre" align="center">'; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print '</td>'; + } // Company type - if (! empty($arrayfields['typent.code']['checked'])) - { - print '<td class="liste_titre maxwidthonsmartphone" align="center">'; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print '</td>'; - } + if (! empty($arrayfields['typent.code']['checked'])) + { + print '<td class="liste_titre maxwidthonsmartphone" align="center">'; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print '</td>'; + } // Date if (! empty($arrayfields['sp.date_valid']['checked'])) { @@ -543,54 +543,54 @@ if ($resql) if (! empty($arrayfields['sp.total_ht']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.$search_montant_ht.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.$search_montant_ht.'">'; + print '</td>'; } if (! empty($arrayfields['sp.total_vat']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.$search_montant_vat.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.$search_montant_vat.'">'; + print '</td>'; } if (! empty($arrayfields['sp.total_ttc']['checked'])) { - // Amount - print '<td class="liste_titre" align="right">'; - print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.$search_montant_ttc.'">'; - print '</td>'; + // Amount + print '<td class="liste_titre" align="right">'; + print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.$search_montant_ttc.'">'; + print '</td>'; } if (! empty($arrayfields['u.login']['checked'])) { - // Author - print '<td class="liste_titre" align="center">'; - print '<input class="flat" size="4" type="text" name="search_login" value="'.$search_author.'">'; - print '</td>'; + // Author + print '<td class="liste_titre" align="center">'; + print '<input class="flat" size="4" type="text" name="search_login" value="'.$search_author.'">'; + print '</td>'; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; - } - print '</td>'; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print '<input class="flat'.($searchclass?' '.$searchclass:'').'" size="4" type="text" name="search_options_'.$tmpkey.'" value="'.dol_escape_htmltag($search_array_options['search_options_'.$tmpkey]).'">'; + } + print '</td>'; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -599,14 +599,14 @@ if ($resql) // Date creation if (! empty($arrayfields['sp.datec']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Date modification if (! empty($arrayfields['sp.tms']['checked'])) { - print '<td class="liste_titre">'; - print '</td>'; + print '<td class="liste_titre">'; + print '</td>'; } // Status if (! empty($arrayfields['sp.fk_statut']['checked'])) @@ -643,19 +643,19 @@ if ($resql) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['sp.datec']['checked'])) print_liste_field_titre($arrayfields['sp.datec']['label'],$_SERVER["PHP_SELF"],"sp.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['sp.tms']['checked'])) print_liste_field_titre($arrayfields['sp.tms']['label'],$_SERVER["PHP_SELF"],"sp.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['sp.fk_statut']['checked'])) print_liste_field_titre($arrayfields['sp.fk_statut']['label'],$_SERVER["PHP_SELF"],"sp.fk_statut","",$param,'align="right"',$sortfield,$sortorder); @@ -724,164 +724,164 @@ if ($resql) // Thirdparty if (! empty($arrayfields['s.nom']['checked'])) { - print '<td class="tdoverflowmax200">'; + print '<td class="tdoverflowmax200">'; print $companystatic->getNomUrl(1,'customer'); print '</td>'; if (! $i) $totalarray['nbfield']++; } // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->town; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print '<td class="nocellnopadd">'; - print $obj->zip; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "<td>".$obj->state_name."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print '<td align="center">'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print '<td align="center">'; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['s.town']['checked'])) + { + print '<td class="nocellnopadd">'; + print $obj->town; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print '<td class="nocellnopadd">'; + print $obj->zip; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "<td>".$obj->state_name."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print '<td align="center">'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print '<td align="center">'; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } // Date proposal - if (! empty($arrayfields['sp.date_valid']['checked'])) - { - print '<td align="center">'; + if (! empty($arrayfields['sp.date_valid']['checked'])) + { + print '<td align="center">'; print dol_print_date($db->jdate($obj->date_valid), 'day'); print "</td>\n"; if (! $i) $totalarray['nbfield']++; - } + } // Date delivery - if (! empty($arrayfields['sp.date_livraison']['checked'])) - { - print '<td align="center">'; + if (! empty($arrayfields['sp.date_livraison']['checked'])) + { + print '<td align="center">'; print dol_print_date($db->jdate($obj->dp), 'day'); print "</td>\n"; if (! $i) $totalarray['nbfield']++; - } - - // Amount HT - if (! empty($arrayfields['sp.total_ht']['checked'])) - { - print '<td align="right">'.price($obj->total_ht)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['sp.total_vat']['checked'])) - { - print '<td align="right">'.price($obj->total_vat)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_vat; - } - // Amount TTC - if (! empty($arrayfields['sp.total_ttc']['checked'])) - { - print '<td align="right">'.price($obj->total_ttc)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } + } + + // Amount HT + if (! empty($arrayfields['sp.total_ht']['checked'])) + { + print '<td align="right">'.price($obj->total_ht)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['sp.total_vat']['checked'])) + { + print '<td align="right">'.price($obj->total_vat)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_vat; + } + // Amount TTC + if (! empty($arrayfields['sp.total_ttc']['checked'])) + { + print '<td align="right">'.price($obj->total_ttc)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } $userstatic->id=$obj->fk_user_author; $userstatic->login=$obj->login; - // Author - if (! empty($arrayfields['u.login']['checked'])) - { + // Author + if (! empty($arrayfields['u.login']['checked'])) + { print '<td align="center">'; if ($userstatic->id) print $userstatic->getLoginUrl(1); else print ' '; print "</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print '<td'; - $align=$extrafields->getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - } - } - // 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['sp.datec']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['sp.tms']['checked'])) - { - print '<td align="center" class="nowrap">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['sp.fk_statut']['checked'])) - { - print '<td align="right">'.$objectstatic->LibStatut($obj->fk_statut,5)."</td>\n"; - if (! $i) $totalarray['nbfield']++; - } - - // Action column - print '<td class="nowrap" align="center">'; - 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; + } + + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print '<td'; + $align=$extrafields->getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + } + } + // 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['sp.datec']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['sp.tms']['checked'])) + { + print '<td align="center" class="nowrap">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['sp.fk_statut']['checked'])) + { + print '<td align="right">'.$objectstatic->LibStatut($obj->fk_statut,5)."</td>\n"; + if (! $i) $totalarray['nbfield']++; + } + + // Action column + print '<td class="nowrap" align="center">'; + 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 '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>'; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; print "</tr>\n"; @@ -893,28 +893,28 @@ if ($resql) // Show total line if (isset($totalarray['totalhtfield']) - || isset($totalarray['totalvatfield']) - || isset($totalarray['totalttcfield']) - || isset($totalarray['totalamfield']) - || isset($totalarray['totalrtpfield']) - ) + || isset($totalarray['totalvatfield']) + || isset($totalarray['totalttcfield']) + || isset($totalarray['totalamfield']) + || isset($totalarray['totalrtpfield']) + ) { - print '<tr class="liste_total">'; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; - else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; - } - elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; - elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; - elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; - else print '<td></td>'; - } - print '</tr>'; + print '<tr class="liste_total">'; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>'; + else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>'; + } + elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>'; + elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>'; + elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>'; + else print '<td></td>'; + } + print '</tr>'; } $db->free($resql); @@ -924,28 +924,28 @@ if ($resql) print $hookmanager->resPrint; print '</table>'."\n"; - print '</div>'."\n"; + print '</div>'."\n"; print '</form>'."\n"; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; + $filedir=$diroutputmassaction; - $genallowed=$user->rights->supplier_proposal->lire; - $delallowed=$user->rights->supplier_proposal->lire; + $genallowed=$user->rights->supplier_proposal->lire; + $delallowed=$user->rights->supplier_proposal->lire; - print $formfile->showdocuments('massfilesarea_supplier_proposal','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); + print $formfile->showdocuments('massfilesarea_supplier_proposal','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); } else { - print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; + print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>'; } } diff --git a/htdocs/user/index.php b/htdocs/user/index.php index 1557175594423c486b3d9c0f877965c9dfb98346..981704de6ae7d80fd2c5b906d0a6227200270489 100644 --- a/htdocs/user/index.php +++ b/htdocs/user/index.php @@ -72,37 +72,37 @@ $form = new Form($db); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( 'u.login'=>"Login", - 'u.lastname'=>"Lastname", - 'u.firstname'=>"Firstname", + 'u.lastname'=>"Lastname", + 'u.firstname'=>"Firstname", 'u.accountancy_code'=>"AccountancyCode", 'u.email'=>"EMail", - 'u.note'=>"Note" + 'u.note'=>"Note" ); // Definition of fields for list $arrayfields=array( - 'u.login'=>array('label'=>$langs->trans("Login"), 'checked'=>1), - 'u.lastname'=>array('label'=>$langs->trans("Lastname"), 'checked'=>1), - 'u.firstname'=>array('label'=>$langs->trans("Firstname"), 'checked'=>1), - 'u.gender'=>array('label'=>$langs->trans("Gender"), 'checked'=>0), - 'u.employee'=>array('label'=>$langs->trans("Employee"), 'checked'=>($mode=='employee'?1:0)), - 'u.accountancy_code'=>array('label'=>$langs->trans("AccountancyCode"), 'checked'=>0), - 'u.email'=>array('label'=>$langs->trans("EMail"), 'checked'=>1), - 'u.fk_soc'=>array('label'=>$langs->trans("Company"), 'checked'=>1), - 'u.entity'=>array('label'=>$langs->trans("Entity"), 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))), - 'u.fk_user'=>array('label'=>$langs->trans("HierarchicalResponsible"), 'checked'=>1), - 'u.datelastlogin'=>array('label'=>$langs->trans("LastConnexion"), 'checked'=>1, 'position'=>100), - 'u.datepreviouslogin'=>array('label'=>$langs->trans("PreviousConnexion"), 'checked'=>0, 'position'=>110), - 'u.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'u.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'u.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'u.login'=>array('label'=>$langs->trans("Login"), 'checked'=>1), + 'u.lastname'=>array('label'=>$langs->trans("Lastname"), 'checked'=>1), + 'u.firstname'=>array('label'=>$langs->trans("Firstname"), 'checked'=>1), + 'u.gender'=>array('label'=>$langs->trans("Gender"), 'checked'=>0), + 'u.employee'=>array('label'=>$langs->trans("Employee"), 'checked'=>($mode=='employee'?1:0)), + 'u.accountancy_code'=>array('label'=>$langs->trans("AccountancyCode"), 'checked'=>0), + 'u.email'=>array('label'=>$langs->trans("EMail"), 'checked'=>1), + 'u.fk_soc'=>array('label'=>$langs->trans("Company"), 'checked'=>1), + 'u.entity'=>array('label'=>$langs->trans("Entity"), 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))), + 'u.fk_user'=>array('label'=>$langs->trans("HierarchicalResponsible"), 'checked'=>1), + 'u.datelastlogin'=>array('label'=>$langs->trans("LastConnexion"), 'checked'=>1, 'position'=>100), + 'u.datepreviouslogin'=>array('label'=>$langs->trans("PreviousConnexion"), 'checked'=>0, 'position'=>110), + 'u.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'u.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'u.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! 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'=>$extrafields->attribute_perms[$key]); + 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'=>$extrafields->attribute_perms[$key]); } } @@ -141,29 +141,29 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $search_user=""; - $search_login=""; - $search_lastname=""; - $search_firstname=""; - $search_gender=""; - $search_employee=""; - $search_accountancy_code=""; - $search_email=""; - $search_statut=""; - $search_thirdparty=""; - $search_supervisor=""; - $search_datelastlogin=""; - $search_datepreviouslogin=""; - $search_date_creation=""; - $search_date_update=""; - $search_array_options=array(); - } + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search_user=""; + $search_login=""; + $search_lastname=""; + $search_firstname=""; + $search_gender=""; + $search_employee=""; + $search_accountancy_code=""; + $search_email=""; + $search_statut=""; + $search_thirdparty=""; + $search_supervisor=""; + $search_datelastlogin=""; + $search_datepreviouslogin=""; + $search_date_creation=""; + $search_date_update=""; + $search_array_options=array(); + } } @@ -217,16 +217,16 @@ if ($sall) $sql.= natural_search(array_keys($fieldstos // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -238,7 +238,7 @@ $nbtotalofrecords=0; $result=$db->query($sql); if ($result) { - $nbtotalofrecords = $db->num_rows($result); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1, $offset); @@ -246,18 +246,18 @@ $sql.= $db->plimit($limit+1, $offset); $result = $db->query($sql); if (! $result) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($result); if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/user/card.php?id='.$id); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/user/card.php?id='.$id); + exit; } llxHeader('',$langs->trans("ListOfUsers")); @@ -281,9 +281,9 @@ if ($mode != '') $param.='&mode='.$mode; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } $text = $langs->trans("ListOfUsers"); @@ -302,8 +302,8 @@ print_barre_liste($text, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sorto if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } $moreforfilter=''; @@ -319,59 +319,59 @@ print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"") print '<tr class="liste_titre_filter">'; if (! empty($arrayfields['u.login']['checked'])) { - print '<td class="liste_titre"><input type="text" name="search_login" size="6" value="'.$search_login.'"></td>'; + print '<td class="liste_titre"><input type="text" name="search_login" size="6" value="'.$search_login.'"></td>'; } if (! empty($arrayfields['u.lastname']['checked'])) { - print '<td class="liste_titre"><input type="text" name="search_lastname" size="6" value="'.$search_lastname.'"></td>'; + print '<td class="liste_titre"><input type="text" name="search_lastname" size="6" value="'.$search_lastname.'"></td>'; } if (! empty($arrayfields['u.firstname']['checked'])) { - print '<td class="liste_titre"><input type="text" name="search_firstname" size="6" value="'.$search_firstname.'"></td>'; + print '<td class="liste_titre"><input type="text" name="search_firstname" size="6" value="'.$search_firstname.'"></td>'; } if (! empty($arrayfields['u.gender']['checked'])) { - print '<td class="liste_titre">'; - $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); - print $form->selectarray('search_gender', $arraygender, $search_gender, 1); - print '</td>'; + print '<td class="liste_titre">'; + $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); + print $form->selectarray('search_gender', $arraygender, $search_gender, 1); + print '</td>'; } if (! empty($arrayfields['u.employee']['checked'])) { - print '<td class="liste_titre">'; - print $form->selectyesno('search_employee', $search_employee, 1, false, 1); - print '</td>'; + print '<td class="liste_titre">'; + print $form->selectyesno('search_employee', $search_employee, 1, false, 1); + print '</td>'; } if (! empty($arrayfields['u.accountancy_code']['checked'])) { - print '<td class="liste_titre"><input type="text" name="search_accountancy_code" size="4" value="'.$search_accountancy_code.'"></td>'; + print '<td class="liste_titre"><input type="text" name="search_accountancy_code" size="4" value="'.$search_accountancy_code.'"></td>'; } if (! empty($arrayfields['u.email']['checked'])) { - print '<td class="liste_titre"><input type="text" name="search_email" size="6" value="'.$search_email.'"></td>'; + print '<td class="liste_titre"><input type="text" name="search_email" size="6" value="'.$search_email.'"></td>'; } if (! empty($arrayfields['u.fk_soc']['checked'])) { - print '<td class="liste_titre"><input type="text" name="search_thirdparty" size="6" value="'.$search_thirdparty.'"></td>'; + print '<td class="liste_titre"><input type="text" name="search_thirdparty" size="6" value="'.$search_thirdparty.'"></td>'; } if (! empty($arrayfields['u.entity']['checked'])) { - print '<td class="liste_titre"></td>'; + print '<td class="liste_titre"></td>'; } // Supervisor if (! empty($arrayfields['u.fk_user']['checked'])) { - print '<td class="liste_titre">'; - print $form->select_dolusers($search_supervisor, 'search_supervisor', 1, array(), 0, '', 0, 0, 0, 0, '', 0, '', 'maxwidth200'); - print '</td>'; + print '<td class="liste_titre">'; + print $form->select_dolusers($search_supervisor, 'search_supervisor', 1, array(), 0, '', 0, 0, 0, 0, '', 0, '', 'maxwidth200'); + print '</td>'; } if (! empty($arrayfields['u.datelastlogin']['checked'])) { - print '<td class="liste_titre"></td>'; + print '<td class="liste_titre"></td>'; } if (! empty($arrayfields['u.datepreviouslogin']['checked'])) { - print '<td class="liste_titre"></td>'; + print '<td class="liste_titre"></td>'; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) @@ -380,12 +380,12 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { if (! empty($arrayfields["ef.".$key]['checked'])) { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print '<td class="liste_titre'.($align?' '.$align:'').'">'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print '<td class="liste_titre'.($align?' '.$align:'').'">'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) { - $crit=$val; + $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); $searchclass=''; if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; @@ -402,22 +402,22 @@ $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // N print $hookmanager->resPrint; if (! empty($arrayfields['u.datec']['checked'])) { - // Date creation - print '<td class="liste_titre">'; - print '</td>'; + // Date creation + print '<td class="liste_titre">'; + print '</td>'; } if (! empty($arrayfields['u.tms']['checked'])) { - // Date modification - print '<td class="liste_titre">'; - print '</td>'; + // Date modification + print '<td class="liste_titre">'; + print '</td>'; } if (! empty($arrayfields['u.statut']['checked'])) { - // Status - print '<td class="liste_titre" align="center">'; - print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut); - print '</td>'; + // Status + print '<td class="liste_titre" align="center">'; + print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut); + print '</td>'; } // Action column print '<td class="liste_titre" align="right">'; @@ -444,16 +444,16 @@ if (! empty($arrayfields['u.datepreviouslogin']['checked'])) print_liste_field_t // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); $sortonfield = "ef.".$key; if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -471,151 +471,151 @@ $i = 0; $totalarray=array(); while ($i < min($num,$limit)) { - $obj = $db->fetch_object($result); + $obj = $db->fetch_object($result); $userstatic->id=$obj->rowid; $userstatic->ref=$obj->label; $userstatic->login=$obj->login; $userstatic->statut=$obj->statut; - $userstatic->email=$obj->email; - $userstatic->gender=$obj->gender; - $userstatic->societe_id=$obj->fk_soc; - $userstatic->firstname=$obj->firstname; + $userstatic->email=$obj->email; + $userstatic->gender=$obj->gender; + $userstatic->societe_id=$obj->fk_soc; + $userstatic->firstname=$obj->firstname; $userstatic->lastname=$obj->lastname; $userstatic->employee=$obj->employee; $userstatic->photo=$obj->photo; $li=$userstatic->getNomUrl(-1,'',0,0,24,1,'login'); - print "<tr>"; - if (! empty($arrayfields['u.login']['checked'])) + print "<tr>"; + if (! empty($arrayfields['u.login']['checked'])) { - print '<td>'; + print '<td>'; print $li; - if (! empty($conf->multicompany->enabled) && $obj->admin && ! $obj->entity) - { - print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); - } - else if ($obj->admin) - { - print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! empty($conf->multicompany->enabled) && $obj->admin && ! $obj->entity) + { + print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); + } + else if ($obj->admin) + { + print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['u.lastname']['checked'])) + if (! empty($arrayfields['u.lastname']['checked'])) { - print '<td>'.$obj->lastname.'</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td>'.$obj->lastname.'</td>'; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['u.firstname']['checked'])) + if (! empty($arrayfields['u.firstname']['checked'])) { print '<td>'.$obj->firstname.'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['u.gender']['checked'])) + if (! empty($arrayfields['u.gender']['checked'])) { print '<td>'; if ($obj->gender) print $langs->trans("Gender".$obj->gender); print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['u.employee']['checked'])) + if (! empty($arrayfields['u.employee']['checked'])) { print '<td>'.yn($obj->employee).'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['u.accountancy_code']['checked'])) { print '<td>'.$obj->accountancy_code.'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['u.email']['checked'])) + if (! empty($arrayfields['u.email']['checked'])) { print '<td>'.$obj->email.'</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['u.fk_soc']['checked'])) { print "<td>"; - if ($obj->fk_soc) - { - $companystatic->id=$obj->fk_soc; - $companystatic->name=$obj->name; - $companystatic->canvas=$obj->canvas; - print $companystatic->getNomUrl(1); - } - else if ($obj->ldap_sid) - { - print $langs->trans("DomainUser"); - } - else - { - print $langs->trans("InternalUser"); - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + if ($obj->fk_soc) + { + $companystatic->id=$obj->fk_soc; + $companystatic->name=$obj->name; + $companystatic->canvas=$obj->canvas; + print $companystatic->getNomUrl(1); + } + else if ($obj->ldap_sid) + { + print $langs->trans("DomainUser"); + } + else + { + print $langs->trans("InternalUser"); + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; } - // Multicompany enabled + // Multicompany enabled if (! empty($conf->multicompany->enabled) && is_object($mc) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - if (! empty($arrayfields['u.entity']['checked'])) + { + if (! empty($arrayfields['u.entity']['checked'])) { - print '<td>'; - if (! $obj->entity) - { - print $langs->trans("AllEntities"); - } - else - { - $mc->getInfo($obj->entity); - print $mc->label; - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td>'; + if (! $obj->entity) + { + print $langs->trans("AllEntities"); + } + else + { + $mc->getInfo($obj->entity); + print $mc->label; + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; } - } - // Supervisor - if (! empty($arrayfields['u.fk_user']['checked'])) + } + // Supervisor + if (! empty($arrayfields['u.fk_user']['checked'])) { // Resp - print '<td class="nowrap">'; - if ($obj->login2) - { - $user2->id=$obj->id2; - $user2->login=$obj->login2; - $user2->lastname=$obj->lastname2; - $user2->firstname=$obj->firstname2; - $user2->gender=$obj->gender2; - $user2->photo=$obj->photo2; - $user2->admin=$obj->admin2; - $user2->email=$obj->email2; - $user2->socid=$obj->fk_soc2; - print $user2->getNomUrl(-1,'',0,0,24,0,''); - if (! empty($conf->multicompany->enabled) && $obj->admin2 && ! $obj->entity2) - { - print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); - } - else if ($obj->admin2) - { - print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); - } - } - print '</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="nowrap">'; + if ($obj->login2) + { + $user2->id=$obj->id2; + $user2->login=$obj->login2; + $user2->lastname=$obj->lastname2; + $user2->firstname=$obj->firstname2; + $user2->gender=$obj->gender2; + $user2->photo=$obj->photo2; + $user2->admin=$obj->admin2; + $user2->email=$obj->email2; + $user2->socid=$obj->fk_soc2; + print $user2->getNomUrl(-1,'',0,0,24,0,''); + if (! empty($conf->multicompany->enabled) && $obj->admin2 && ! $obj->entity2) + { + print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); + } + else if ($obj->admin2) + { + print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); + } + } + print '</td>'; + if (! $i) $totalarray['nbfield']++; } - // Date last login - if (! empty($arrayfields['u.datelastlogin']['checked'])) + // Date last login + if (! empty($arrayfields['u.datelastlogin']['checked'])) { - print '<td class="nowrap" align="center">'.dol_print_date($db->jdate($obj->datelastlogin),"dayhour").'</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="nowrap" align="center">'.dol_print_date($db->jdate($obj->datelastlogin),"dayhour").'</td>'; + if (! $i) $totalarray['nbfield']++; } - // Date previous login - if (! empty($arrayfields['u.datepreviouslogin']['checked'])) + // Date previous login + if (! empty($arrayfields['u.datepreviouslogin']['checked'])) { - print '<td class="nowrap" align="center">'.dol_print_date($db->jdate($obj->datepreviouslogin),"dayhour").'</td>'; - if (! $i) $totalarray['nbfield']++; + print '<td class="nowrap" align="center">'.dol_print_date($db->jdate($obj->datepreviouslogin),"dayhour").'</td>'; + if (! $i) $totalarray['nbfield']++; } // Extra fields @@ -632,44 +632,44 @@ while ($i < min($num,$limit)) $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print '</td>'; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } } } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + // 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; + print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['u.datec']['checked'])) - { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['u.tms']['checked'])) - { - print '<td align="center">'; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print '</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['u.statut']['checked'])) - { + if (! empty($arrayfields['u.datec']['checked'])) + { + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['u.tms']['checked'])) + { + print '<td align="center">'; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print '</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['u.statut']['checked'])) + { $userstatic->statut=$obj->statut; - print '<td align="center">'.$userstatic->getLibStatut(3).'</td>'; - if (! $i) $totalarray['nbfield']++; - } - // Action column - print '<td></td>'; - if (! $i) $totalarray['nbfield']++; + print '<td align="center">'.$userstatic->getLibStatut(3).'</td>'; + if (! $i) $totalarray['nbfield']++; + } + // Action column + print '<td></td>'; + if (! $i) $totalarray['nbfield']++; - print "</tr>\n"; + print "</tr>\n"; - $i++; + $i++; } $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql);