'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
print '
';
print '';
@@ -120,8 +141,7 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire)
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON ptva.fk_typepaiement = pct.id";
$sql .= " WHERE ptva.fk_tva = tva.rowid";
$sql .= " AND tva.entity = ".$conf->entity;
- if ($year > 0)
- {
+ if ($year > 0) {
$sql .= " AND (";
// Si period renseignee on l'utilise comme critere de date, sinon on prend date echeance,
// ceci afin d'etre compatible avec les cas ou la periode n'etait pas obligatoire
@@ -133,22 +153,22 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire)
|| preg_match('/^tva\./', $sortfield)
|| preg_match('/^ptva\./', $sortfield)
|| preg_match('/^pct\./', $sortfield)
- || preg_match('/^bank\./', $sortfield)) $sql .= $db->order($sortfield, $sortorder);
+ || preg_match('/^bank\./', $sortfield)) {
+ $sql .= $db->order($sortfield, $sortorder);
+ }
//$sql.= $db->plimit($limit+1,$offset);
//print $sql;
dol_syslog("compta/tva/payments.php: select payment", LOG_DEBUG);
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $db->num_rows($resql);
$i = 0;
$total = 0;
$totalnb = 0;
$totalpaye = 0;
- while ($i < min($num, $limit))
- {
+ while ($i < min($num, $limit)) {
$obj = $db->fetch_object($resql);
$payment_vat_static->id = $obj->pid;
@@ -159,11 +179,13 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire)
print ''.$payment_vat_static->getNomUrl(1)." \n";
// Date payment
print ''.dol_print_date($db->jdate($obj->datep), 'day').' ';
- // Type payment
- print '';
- if ($obj->payment_code) print $langs->trans("PaymentTypeShort".$obj->payment_code).' ';
- print $obj->num_payment.' ';
- // Account
+ // Type payment
+ print '';
+ if ($obj->payment_code) {
+ print $langs->trans("PaymentTypeShort".$obj->payment_code).' ';
+ }
+ print $obj->num_payment.' ';
+ // Account
print '';
$account = new Account($db);
$account->fetch($obj->fk_account);
@@ -185,7 +207,9 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire)
print ' '.price($obj->total).' ';
// Paid
print '';
- if ($obj->totalpaye) print price($obj->totalpaye);
+ if ($obj->totalpaye) {
+ print price($obj->totalpaye);
+ }
print ' ';
print ' ';
@@ -194,16 +218,15 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire)
$totalpaye = $totalpaye + $obj->totalpaye;
$i++;
}
- print ''.$langs->trans("Total").' ';
- print ' '; // A total here has no sense
- //print ' ';
- print ' ';
+ print ''.$langs->trans("Total").' ';
+ print ' '; // A total here has no sense
+ //print ' ';
print ' ';
print ' ';
- print ''.price($totalpaye)." ";
+ print ' ';
+ print ''.price($totalpaye)." ";
print " ";
- }
- else {
+ } else {
dol_print_error($db);
}
print '
';
diff --git a/htdocs/compta/tva/quadri_detail.php b/htdocs/compta/tva/quadri_detail.php
index ba12b08b3b0..04f90ba02f9 100644
--- a/htdocs/compta/tva/quadri_detail.php
+++ b/htdocs/compta/tva/quadri_detail.php
@@ -46,12 +46,13 @@ $langs->loadLangs(array("other", "compta", "banks", "bills", "companies", "produ
$now = dol_now();
$current_date = dol_getdate($now);
-if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) $conf->global->SOCIETE_FISCAL_MONTH_START = 1;
+if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) {
+ $conf->global->SOCIETE_FISCAL_MONTH_START = 1;
+}
// Date range
$year = GETPOST("year", "int");
-if (empty($year))
-{
+if (empty($year)) {
$year_current = $current_date['year'];
$year_start = $year_current;
} else {
@@ -61,12 +62,12 @@ if (empty($year))
$date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear"));
$date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear"));
// Set default period if not defined
-if (empty($date_start) || empty($date_end)) // We define date_start and date_end
-{
+if (empty($date_start) || empty($date_end)) { // We define date_start and date_end
$q = GETPOST("q", "int");
- if (empty($q))
- {
- if (GETPOST("month", "int")) { $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); } else {
+ if (empty($q)) {
+ if (GETPOST("month", "int")) {
+ $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false);
+ } else {
if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { // quaterly vat, we take last past complete quarter
$date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -3 - (($current_date['mon'] - $conf->global->SOCIETE_FISCAL_MONTH_START) % 3), 'm');
$date_end = dol_time_plus_duree($date_start, 3, 'm') - 1;
@@ -88,25 +89,41 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end
}
}
} else {
- if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); }
- if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); }
- if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); }
- if ($q == 4) { $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); }
+ if ($q == 1) {
+ $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false);
+ }
+ if ($q == 2) {
+ $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false);
+ }
+ if ($q == 3) {
+ $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false);
+ }
+ if ($q == 4) {
+ $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false);
+ }
}
}
$min = price2num(GETPOST("min", "alpha"));
-if (empty($min)) $min = 0;
+if (empty($min)) {
+ $min = 0;
+}
// Define modetax (0 or 1)
// 0=normal, 1=option vat for services is on debit, 2=option on payments for products
$modetax = $conf->global->TAX_MODE;
-if (GETPOSTISSET("modetax")) $modetax = GETPOST("modetax", 'int');
-if (empty($modetax)) $modetax = 0;
+if (GETPOSTISSET("modetax")) {
+ $modetax = GETPOST("modetax", 'int');
+}
+if (empty($modetax)) {
+ $modetax = 0;
+}
// Security check
$socid = GETPOST('socid', 'int');
-if ($user->socid) $socid = $user->socid;
+if ($user->socid) {
+ $socid = $user->socid;
+}
$result = restrictedArea($user, 'tax', '', '', 'charges');
@@ -127,9 +144,10 @@ $paymentexpensereport_static = new PaymentExpenseReport($db);
$morequerystring = '';
$listofparams = array('date_startmonth', 'date_startyear', 'date_startday', 'date_endmonth', 'date_endyear', 'date_endday');
-foreach ($listofparams as $param)
-{
- if (GETPOST($param) != '') $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param);
+foreach ($listofparams as $param) {
+ if (GETPOST($param) != '') {
+ $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param);
+ }
}
$title = $langs->trans("VATReport")." ".dol_print_date($date_start)." -> ".dol_print_date($date_end);
@@ -149,9 +167,15 @@ $fsearch .= '
';
// Show report header
$name = $langs->trans("VATReportByRates");
$calcmode = '';
-if ($modetax == 0) $calcmode = $langs->trans('OptionVATDefault');
-if ($modetax == 1) $calcmode = $langs->trans('OptionVATDebitOption');
-if ($modetax == 2) $calcmode = $langs->trans('OptionPaymentForProductAndServices');
+if ($modetax == 0) {
+ $calcmode = $langs->trans('OptionVATDefault');
+}
+if ($modetax == 1) {
+ $calcmode = $langs->trans('OptionVATDebitOption');
+}
+if ($modetax == 2) {
+ $calcmode = $langs->trans('OptionPaymentForProductAndServices');
+}
$calcmode .= '
('.$langs->trans("TaxModuleSetupToModifyRules", DOL_URL_ROOT.'/admin/taxes.php').') ';
// Set period
$period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0);
@@ -173,14 +197,24 @@ if ($nextquarter < 4) {
$description .= $fsearch;
$builddate = dol_now();
-if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description .= $langs->trans("RulesVATDueProducts");
-if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description .= $langs->trans("RulesVATInProducts");
-if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description .= '
'.$langs->trans("RulesVATDueServices");
-if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description .= '
'.$langs->trans("RulesVATInServices");
+if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') {
+ $description .= $langs->trans("RulesVATDueProducts");
+}
+if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') {
+ $description .= $langs->trans("RulesVATInProducts");
+}
+if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') {
+ $description .= '
'.$langs->trans("RulesVATDueServices");
+}
+if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') {
+ $description .= '
'.$langs->trans("RulesVATInServices");
+}
if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
$description .= '
'.$langs->trans("DepositsAreNotIncluded");
}
-if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description .= '
'.$langs->trans("ThisIsAnEstimatedValue");
+if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) {
+ $description .= '
'.$langs->trans("ThisIsAnEstimatedValue");
+}
// Customers invoices
$elementcust = $langs->trans("CustomersInvoices");
@@ -225,8 +259,7 @@ $columns = 5;
$x_coll = tax_by_rate('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'sell');
$x_paye = tax_by_rate('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'buy');
-if (!is_array($x_coll) || !is_array($x_paye))
-{
+if (!is_array($x_coll) || !is_array($x_paye)) {
$langs->load("errors");
if ($x_coll == -1) {
print '
'.$langs->trans("ErrorNoAccountancyModuleLoaded").' ';
@@ -238,15 +271,14 @@ if (!is_array($x_coll) || !is_array($x_paye))
} else {
$x_both = array();
//now, from these two arrays, get another array with one rate per line
- foreach (array_keys($x_coll) as $my_coll_rate)
- {
+ foreach (array_keys($x_coll) as $my_coll_rate) {
$x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht'];
$x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat'];
$x_both[$my_coll_rate]['paye']['totalht'] = 0;
$x_both[$my_coll_rate]['paye']['vat'] = 0;
$x_both[$my_coll_rate]['coll']['links'] = '';
$x_both[$my_coll_rate]['coll']['detail'] = array();
- foreach ($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) {
+ foreach ($x_coll[$my_coll_rate]['facid'] as $id => $dummy) {
$invoice_customer->id = $x_coll[$my_coll_rate]['facid'][$id];
$invoice_customer->ref = $x_coll[$my_coll_rate]['facnum'][$id];
$invoice_customer->type = $x_coll[$my_coll_rate]['type'][$id];
@@ -284,11 +316,9 @@ if (!is_array($x_coll) || !is_array($x_paye))
$x_both[$my_paye_rate]['paye']['links'] = '';
$x_both[$my_paye_rate]['paye']['detail'] = array();
- foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy)
- {
+ foreach ($x_paye[$my_paye_rate]['facid'] as $id => $dummy) {
// ExpenseReport
- if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment')
- {
+ if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') {
$expensereport->id = $x_paye[$my_paye_rate]['facid'][$id];
$expensereport->ref = $x_paye[$my_paye_rate]['facnum'][$id];
$expensereport->type = $x_paye[$my_paye_rate]['type'][$id];
@@ -349,7 +379,9 @@ if (!is_array($x_coll) || !is_array($x_paye))
$x_paye_ht = 0;
$span = $columns;
- if ($modetax != 1) $span += 2;
+ if ($modetax != 1) {
+ $span += 2;
+ }
//print '
'..') ';
@@ -357,12 +389,14 @@ if (!is_array($x_coll) || !is_array($x_paye))
print '
';
print ''.$elementcust.' ';
print ''.$langs->trans("DateInvoice").' ';
- if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''.$langs->trans("DatePayment").' ';
- else print ' ';
+ if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') {
+ print ''.$langs->trans("DatePayment").' ';
+ } else {
+ print ' ';
+ }
print ''.$namecust.' ';
print ''.$productcust.' ';
- if ($modetax != 1)
- {
+ if ($modetax != 1) {
print ''.$amountcust.' ';
print ''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").') ';
}
@@ -385,8 +419,7 @@ if (!is_array($x_coll) || !is_array($x_paye))
$subtot_coll_total_ht = 0;
$subtot_coll_vat = 0;
- if (is_array($x_both[$rate]['coll']['detail']))
- {
+ if (is_array($x_both[$rate]['coll']['detail'])) {
// VAT Rate
print " ";
print ''.$langs->trans("Rate").': '.vatrate($rate).'% ';
@@ -415,16 +448,18 @@ if (!is_array($x_coll) || !is_array($x_paye))
print ''.dol_print_date($fields['datef'], 'day').' ';
// Payment date
- if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''.dol_print_date($fields['datep'], 'day').' ';
- else print ' ';
+ if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') {
+ print ''.dol_print_date($fields['datep'], 'day').' ';
+ } else {
+ print ' ';
+ }
// Company name
print ''.$fields['company_link'].' ';
// Description
print '';
- if ($fields['pid'])
- {
+ if ($fields['pid']) {
$product_static->id = $fields['pid'];
$product_static->ref = $fields['pref'];
$product_static->type = $fields['dtype']; // We force with the type of line to have type how line is registered
@@ -455,12 +490,10 @@ if (!is_array($x_coll) || !is_array($x_paye))
print ' ';
// Total HT
- if ($modetax != 1)
- {
+ if ($modetax != 1) {
print '';
print price($fields['totalht']);
- if (price2num($fields['ftotal_ttc']))
- {
+ if (price2num($fields['ftotal_ttc'])) {
//print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - ";
$ratiolineinvoice = ($fields['dtotal_ttc'] / $fields['ftotal_ttc']);
//print ' ('.round($ratiolineinvoice*100,2).'%)';
@@ -470,18 +503,15 @@ if (!is_array($x_coll) || !is_array($x_paye))
// Payment
$ratiopaymentinvoice = 1;
- if ($modetax != 1)
- {
+ if ($modetax != 1) {
print ' ';
//print $fields['totalht']."-".$fields['payment_amount']."-".$fields['ftotal_ttc'];
- if ($fields['payment_amount'] && $fields['ftotal_ttc'])
- {
+ if ($fields['payment_amount'] && $fields['ftotal_ttc']) {
$payment_static->id = $fields['payment_id'];
print $payment_static->getNomUrl(2);
}
if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice')
- || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice'))
- {
+ || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) {
print $langs->trans("NA");
} else {
if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) {
@@ -527,8 +557,7 @@ if (!is_array($x_coll) || !is_array($x_paye))
print ' ';
}
- if (count($x_coll) == 0) // Show a total line if nothing shown
- {
+ if (count($x_coll) == 0) { // Show a total line if nothing shown
print '
';
print ' ';
print ''.$langs->trans("Total").': ';
@@ -548,8 +577,11 @@ if (!is_array($x_coll) || !is_array($x_paye))
print ' ';
print ''.$elementsup.' ';
print ''.$langs->trans("DateInvoice").' ';
- if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''.$langs->trans("DatePayment").' ';
- else print ' ';
+ if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') {
+ print ''.$langs->trans("DatePayment").' ';
+ } else {
+ print ' ';
+ }
print ''.$namesup.' ';
print ''.$productsup.' ';
if ($modetax != 1) {
@@ -560,18 +592,16 @@ if (!is_array($x_coll) || !is_array($x_paye))
print ''.$vatsup.' ';
print ' '."\n";
- foreach (array_keys($x_paye) as $rate)
- {
+ foreach (array_keys($x_paye) as $rate) {
$subtot_paye_total_ht = 0;
$subtot_paye_vat = 0;
- if (is_array($x_both[$rate]['paye']['detail']))
- {
+ if (is_array($x_both[$rate]['paye']['detail'])) {
print "
";
print ''.$langs->trans("Rate").': '.vatrate($rate).'% ';
print ' '."\n";
- foreach ($x_both[$rate]['paye']['detail'] as $index=>$fields) {
+ foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) {
// Define type
// We MUST use dtype (type in line). We can use something else, only if dtype is really unknown.
$type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']);
@@ -594,16 +624,18 @@ if (!is_array($x_coll) || !is_array($x_paye))
print '
'.dol_print_date($fields['datef'], 'day').' ';
// Payment date
- if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print '
'.dol_print_date($fields['datep'], 'day').' ';
- else print '
';
+ if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') {
+ print '
'.dol_print_date($fields['datep'], 'day').' ';
+ } else {
+ print '
';
+ }
// Company name
print '
'.$fields['company_link'].' ';
// Description
print '
';
- if ($fields['pid'])
- {
+ if ($fields['pid']) {
$product_static->id = $fields['pid'];
$product_static->ref = $fields['pref'];
$product_static->type = $fields['dtype']; // We force with the type of line to have type how line is registered
@@ -634,12 +666,10 @@ if (!is_array($x_coll) || !is_array($x_paye))
print ' ';
// Total HT
- if ($modetax != 1)
- {
+ if ($modetax != 1) {
print '
';
print price($fields['totalht']);
- if (price2num($fields['ftotal_ttc']))
- {
+ if (price2num($fields['ftotal_ttc'])) {
//print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - ";
$ratiolineinvoice = ($fields['dtotal_ttc'] / $fields['ftotal_ttc']);
//print ' ('.round($ratiolineinvoice*100,2).'%)';
@@ -649,18 +679,15 @@ if (!is_array($x_coll) || !is_array($x_paye))
// Payment
$ratiopaymentinvoice = 1;
- if ($modetax != 1)
- {
+ if ($modetax != 1) {
print ' ';
- if ($fields['payment_amount'] && $fields['ftotal_ttc'])
- {
+ if ($fields['payment_amount'] && $fields['ftotal_ttc']) {
$paymentfourn_static->id = $fields['payment_id'];
print $paymentfourn_static->getNomUrl(2);
}
if (($type == 0 && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')
- || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice'))
- {
+ || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) {
print $langs->trans("NA");
} else {
if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) {
diff --git a/htdocs/contact/agenda.php b/htdocs/contact/agenda.php
index 2aeb2e4e2a1..ca496540a47 100644
--- a/htdocs/contact/agenda.php
+++ b/htdocs/contact/agenda.php
@@ -65,36 +65,44 @@ $extrafields->fetch_name_optionals_label($object->table_element);
$object->getCanvas($id);
$objcanvas = null;
$canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas"));
-if (!empty($canvas))
-{
+if (!empty($canvas)) {
require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
$objcanvas = new Canvas($db, $action);
$objcanvas->getCanvas('contact', 'contactcard', $canvas);
}
-if (GETPOST('actioncode', 'array'))
-{
+if (GETPOST('actioncode', 'array')) {
$actioncode = GETPOST('actioncode', 'array', 3);
- if (!count($actioncode)) $actioncode = '0';
+ if (!count($actioncode)) {
+ $actioncode = '0';
+ }
} else {
$actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
}
$search_agenda_label = GETPOST('search_agenda_label');
// Security check
-if ($user->socid) $socid = $user->socid;
+if ($user->socid) {
+ $socid = $user->socid;
+}
$result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', 0); // If we create a contact with no company (shared contacts), no check on write permission
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+ $page = 0;
+} // If $page is not defined, or '' or -1
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
-if (!$sortfield) $sortfield = 'a.datep, a.id';
-if (!$sortorder) $sortorder = 'DESC';
+if (!$sortfield) {
+ $sortfield = 'a.datep, a.id';
+}
+if (!$sortorder) {
+ $sortorder = 'DESC';
+}
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('contactagenda', 'globalcard'));
@@ -106,20 +114,19 @@ $hookmanager->initHooks(array('contactagenda', 'globalcard'));
$parameters = array('id'=>$id, 'objcanvas'=>$objcanvas);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+ setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
-if (empty($reshook))
-{
+if (empty($reshook)) {
// Cancel
- if (GETPOST('cancel', 'alpha') && !empty($backtopage))
- {
+ if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
header("Location: ".$backtopage);
exit;
}
// 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
- {
+ 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
$actioncode = '';
$search_agenda_label = '';
}
@@ -133,29 +140,30 @@ if (empty($reshook))
$form = new Form($db);
$title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
-if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname;
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) {
+ $title = $object->lastname;
+}
$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
llxHeader('', $title, $help_url);
-if ($socid > 0)
-{
+if ($socid > 0) {
$objsoc = new Societe($db);
$objsoc->fetch($socid);
}
-if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
-{
+if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
// -----------------------------------------
// When used with CANVAS
// -----------------------------------------
- if (empty($object->error) && $id)
- {
- $object = new Contact($db);
- $result = $object->fetch($id);
- if ($result <= 0) dol_print_error('', $object->error);
- }
- $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates
+ if (empty($object->error) && $id) {
+ $object = new Contact($db);
+ $result = $object->fetch($id);
+ if ($result <= 0) {
+ dol_print_error('', $object->error);
+ }
+ }
+ $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates
$objcanvas->display_canvas($action); // Show template
} else {
// -----------------------------------------
@@ -163,26 +171,27 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
// -----------------------------------------
// Confirm deleting contact
- if ($user->rights->societe->contact->supprimer)
- {
- if ($action == 'delete')
- {
+ if ($user->rights->societe->contact->supprimer) {
+ if ($action == 'delete') {
print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage ? '&backtopage='.$backtopage : ''), $langs->trans("DeleteContact"), $langs->trans("ConfirmDeleteContact"), "confirm_delete", '', 0, 1);
}
}
/*
- * Onglets
- */
+ * Onglets
+ */
$head = array();
- if ($id > 0)
- {
+ if ($id > 0) {
// Si edition contact deja existant
$object = new Contact($db);
$res = $object->fetch($id, $user);
- if ($res < 0) { dol_print_error($db, $object->error); exit; }
+ if ($res < 0) {
+ dol_print_error($db, $object->error); exit;
+ }
$res = $object->fetch_optionals();
- if ($res < 0) { dol_print_error($db, $object->error); exit; }
+ if ($res < 0) {
+ dol_print_error($db, $object->error); exit;
+ }
// Show tabs
$head = contact_prepare_head($object);
@@ -190,13 +199,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
}
- if (!empty($id) && $action != 'edit' && $action != 'create')
- {
+ if (!empty($id) && $action != 'edit' && $action != 'create') {
$objsoc = new Societe($db);
/*
- * Fiche en mode visualisation
- */
+ * Fiche en mode visualisation
+ */
dol_htmloutput_errors($error, $errors);
@@ -205,14 +213,16 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$linkback = ''.$langs->trans("BackToList").' ';
$morehtmlref = '';
- if (empty($conf->global->SOCIETE_DISABLE_CONTACTS))
- {
+ if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) {
$objsoc = new Societe($db);
$objsoc->fetch($object->socid);
// Thirdparty
$morehtmlref .= $langs->trans('ThirdParty').' : ';
- if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1);
- else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany");
+ if ($objsoc->id > 0) {
+ $morehtmlref .= $objsoc->getNomUrl(1);
+ } else {
+ $morehtmlref .= $langs->trans("ContactNotLinkedToCompany");
+ }
}
$morehtmlref .= '
';
@@ -238,29 +248,31 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$out = '';
$permok = $user->rights->agenda->myactions->create;
- if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok)
- {
- if (is_object($objthirdparty) && get_class($objthirdparty) == 'Societe') $out .= '&originid='.$objthirdparty->id.($objthirdparty->id > 0 ? '&socid='.$objthirdparty->id : '');
+ if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) {
+ if (is_object($objthirdparty) && get_class($objthirdparty) == 'Societe') {
+ $out .= '&originid='.$objthirdparty->id.($objthirdparty->id > 0 ? '&socid='.$objthirdparty->id : '');
+ }
$out .= (!empty($objcon->id) ? '&contactid='.$objcon->id : '').'&origin=contact&originid='.$object->id.'&percentage=-1&backtopage='.urlencode($_SERVER['PHP_SELF'].($objcon->id > 0 ? '?id='.$objcon->id : ''));
$out .= '&datep='.urlencode(dol_print_date(dol_now(), 'dayhourlog'));
}
$newcardbutton = '';
- if (!empty($conf->agenda->enabled))
- {
- if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create))
- {
+ if (!empty($conf->agenda->enabled)) {
+ if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) {
$newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out);
}
}
- if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read)))
- {
- print ' ';
+ if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
+ print ' ';
$param = '&id='.$id;
- 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;
+ }
print load_fiche_titre($langs->trans("ActionsOnContact"), $newcardbutton, '');
//print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $morehtmlcenter, 0, -1, '', '', '', '', 0, 1, 1);
diff --git a/htdocs/contact/canvas/actions_contactcard_common.class.php b/htdocs/contact/canvas/actions_contactcard_common.class.php
index f6f6fa0b45e..a32263cd65e 100644
--- a/htdocs/contact/canvas/actions_contactcard_common.class.php
+++ b/htdocs/contact/canvas/actions_contactcard_common.class.php
@@ -64,14 +64,16 @@ abstract class ActionsContactCardCommon
{
/*$ret = $this->getInstanceDao();
- if (is_object($this->object) && method_exists($this->object,'fetch'))
- {
- if (! empty($id)) $this->object->fetch($id);
- }
- else
- {*/
+ if (is_object($this->object) && method_exists($this->object,'fetch'))
+ {
+ if (! empty($id)) $this->object->fetch($id);
+ }
+ else
+ {*/
$object = new Contact($this->db);
- if (!empty($id)) $object->fetch($id);
+ if (!empty($id)) {
+ $object->fetch($id);
+ }
$this->object = $object;
//}
}
@@ -90,20 +92,19 @@ abstract class ActionsContactCardCommon
global $conf, $langs, $user, $canvas;
global $form, $formcompany, $objsoc;
- if ($action == 'add' || $action == 'update') $this->assign_post();
+ if ($action == 'add' || $action == 'update') {
+ $this->assign_post();
+ }
- foreach ($this->object as $key => $value)
- {
+ foreach ($this->object as $key => $value) {
$this->tpl[$key] = $value;
}
$this->tpl['error'] = $this->error;
$this->tpl['errors'] = $this->errors;
- if ($action == 'create' || $action == 'edit')
- {
- if ($conf->use_javascript_ajax)
- {
+ if ($action == 'create' || $action == 'edit') {
+ if ($conf->use_javascript_ajax) {
$this->tpl['ajax_selectcountry'] = "\n".''."\n";
}
- if (is_object($objsoc) && $objsoc->id > 0)
- {
+ if (is_object($objsoc) && $objsoc->id > 0) {
$this->tpl['company'] = $objsoc->getNomUrl(1);
$this->tpl['company_id'] = $objsoc->id;
} else {
@@ -127,14 +127,25 @@ abstract class ActionsContactCardCommon
$this->tpl['select_civility'] = $formcompany->select_civility($this->object->civility_id);
// Predefined with third party
- if ((isset($objsoc->typent_code) && $objsoc->typent_code == 'TE_PRIVATE') || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS))
- {
- if (dol_strlen(trim($this->object->address)) == 0) $this->tpl['address'] = $objsoc->address;
- if (dol_strlen(trim($this->object->zip)) == 0) $this->object->zip = $objsoc->zip;
- if (dol_strlen(trim($this->object->town)) == 0) $this->object->town = $objsoc->town;
- if (dol_strlen(trim($this->object->phone_pro)) == 0) $this->object->phone_pro = $objsoc->phone;
- if (dol_strlen(trim($this->object->fax)) == 0) $this->object->fax = $objsoc->fax;
- if (dol_strlen(trim($this->object->email)) == 0) $this->object->email = $objsoc->email;
+ if ((isset($objsoc->typent_code) && $objsoc->typent_code == 'TE_PRIVATE') || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) {
+ if (dol_strlen(trim($this->object->address)) == 0) {
+ $this->tpl['address'] = $objsoc->address;
+ }
+ if (dol_strlen(trim($this->object->zip)) == 0) {
+ $this->object->zip = $objsoc->zip;
+ }
+ if (dol_strlen(trim($this->object->town)) == 0) {
+ $this->object->town = $objsoc->town;
+ }
+ if (dol_strlen(trim($this->object->phone_pro)) == 0) {
+ $this->object->phone_pro = $objsoc->phone;
+ }
+ if (dol_strlen(trim($this->object->fax)) == 0) {
+ $this->object->fax = $objsoc->fax;
+ }
+ if (dol_strlen(trim($this->object->email)) == 0) {
+ $this->object->email = $objsoc->email;
+ }
}
// Zip
@@ -143,28 +154,33 @@ abstract class ActionsContactCardCommon
// Town
$this->tpl['select_town'] = $formcompany->select_ziptown($this->object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id'));
- if (dol_strlen(trim($this->object->country_id)) == 0) $this->object->country_id = $objsoc->country_id;
+ if (dol_strlen(trim($this->object->country_id)) == 0) {
+ $this->object->country_id = $objsoc->country_id;
+ }
// Country
$this->tpl['select_country'] = $form->select_country($this->object->country_id, 'country_id');
$countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')';
- if ($user->admin) $this->tpl['info_admin'] = info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
+ if ($user->admin) {
+ $this->tpl['info_admin'] = info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
+ }
// State
- if ($this->object->country_id) $this->tpl['select_state'] = $formcompany->select_state($this->object->state_id, $this->object->country_code);
- else $this->tpl['select_state'] = $countrynotdefined;
+ if ($this->object->country_id) {
+ $this->tpl['select_state'] = $formcompany->select_state($this->object->state_id, $this->object->country_code);
+ } else {
+ $this->tpl['select_state'] = $countrynotdefined;
+ }
// Public or private
$selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate"));
$this->tpl['select_visibility'] = $form->selectarray('priv', $selectarray, $this->object->priv, 0);
}
- if ($action == 'view' || $action == 'edit' || $action == 'delete')
- {
+ if ($action == 'view' || $action == 'edit' || $action == 'delete') {
// Emailing
- if (!empty($conf->mailing->enabled))
- {
+ if (!empty($conf->mailing->enabled)) {
$langs->load("mails");
$this->tpl['nb_emailing'] = $this->object->getNbOfEMailings();
}
@@ -175,46 +191,41 @@ abstract class ActionsContactCardCommon
$this->object->load_ref_elements();
- if (!empty($conf->commande->enabled))
- {
+ if (!empty($conf->commande->enabled)) {
$this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForOrders");
$this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_commande ? $this->object->ref_commande : $langs->trans("NoContactForAnyOrder");
$i++;
}
- if (!empty($conf->propal->enabled))
- {
+ if (!empty($conf->propal->enabled)) {
$this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForProposals");
$this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_propal ? $this->object->ref_propal : $langs->trans("NoContactForAnyProposal");
$i++;
}
- if (!empty($conf->contrat->enabled))
- {
+ if (!empty($conf->contrat->enabled)) {
$this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForContracts");
$this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_contrat ? $this->object->ref_contrat : $langs->trans("NoContactForAnyContract");
$i++;
}
- if (!empty($conf->facture->enabled))
- {
+ if (!empty($conf->facture->enabled)) {
$this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForInvoices");
$this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_facturation ? $this->object->ref_facturation : $langs->trans("NoContactForAnyInvoice");
$i++;
}
// Dolibarr user
- if ($this->object->user_id)
- {
+ if ($this->object->user_id) {
$dolibarr_user = new User($this->db);
$result = $dolibarr_user->fetch($this->object->user_id);
$this->tpl['dolibarr_user'] = $dolibarr_user->getLoginUrl(1);
- } else $this->tpl['dolibarr_user'] = $langs->trans("NoDolibarrAccess");
+ } else {
+ $this->tpl['dolibarr_user'] = $langs->trans("NoDolibarrAccess");
+ }
}
- if ($action == 'view' || $action == 'delete')
- {
+ if ($action == 'view' || $action == 'delete') {
$this->tpl['showrefnav'] = $form->showrefnav($this->object, 'id');
- if ($this->object->socid > 0)
- {
+ if ($this->object->socid > 0) {
$objsoc = new Societe($this->db);
$objsoc->fetch($this->object->socid);
@@ -243,14 +254,13 @@ abstract class ActionsContactCardCommon
$this->tpl['note'] = nl2br($this->object->note);
}
- if ($action == 'create_user')
- {
+ if ($action == 'create_user') {
// Full firstname and lastname separated with a dot : firstname.lastname
include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$login = dol_buildlogin($this->object->lastname, $this->object->firstname);
- $generated_password = getRandomPassword(false);
+ $generated_password = getRandomPassword(false);
$password = $generated_password;
// Create a form array
@@ -297,12 +307,10 @@ abstract class ActionsContactCardCommon
$this->object->canvas = $_POST["canvas"];
// We set country_id, and country_code label of the chosen country
- if ($this->object->country_id)
- {
+ if ($this->object->country_id) {
$sql = "SELECT code, label FROM ".MAIN_DB_PREFIX."c_country WHERE rowid = ".$this->object->country_id;
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $this->db->fetch_object($resql);
} else {
dol_print_error($this->db);
diff --git a/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php
index 98a66e499b9..bd5cf24e195 100644
--- a/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php
+++ b/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php
@@ -16,8 +16,7 @@
*/
// Protection to avoid direct call of template
-if (empty($conf) || !is_object($conf))
-{
+if (empty($conf) || !is_object($conf)) {
print "Error, template page can't be called as URL";
exit;
}
diff --git a/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php
index 2c82a868ed4..41fbdb5def9 100644
--- a/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php
+++ b/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php
@@ -16,8 +16,7 @@
*/
// Protection to avoid direct call of template
-if (empty($conf) || !is_object($conf))
-{
+if (empty($conf) || !is_object($conf)) {
print "Error, template page can't be called as URL";
exit;
}
diff --git a/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php
index 43fd48e3ef0..c624eca4026 100644
--- a/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php
+++ b/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php
@@ -16,8 +16,7 @@
*/
// Protection to avoid direct call of template
-if (empty($conf) || !is_object($conf))
-{
+if (empty($conf) || !is_object($conf)) {
print "Error, template page can't be called as URL";
exit;
}
@@ -30,8 +29,12 @@ echo $this->control->tpl['showhead'];
dol_htmloutput_errors($this->control->tpl['error'], $this->control->tpl['errors']);
-if (!empty($this->control->tpl['action_create_user'])) echo $this->control->tpl['action_create_user'];
-if (!empty($this->control->tpl['action_delete'])) echo $this->control->tpl['action_delete']; ?>
+if (!empty($this->control->tpl['action_create_user'])) {
+ echo $this->control->tpl['action_create_user'];
+}
+if (!empty($this->control->tpl['action_delete'])) {
+ echo $this->control->tpl['action_delete'];
+} ?>
diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php
index 3866405bee8..0def459d444 100644
--- a/htdocs/contact/card.php
+++ b/htdocs/contact/card.php
@@ -71,24 +71,26 @@ $socialnetworks = getArrayOfSocialNetworks();
$object->getCanvas($id);
$objcanvas = null;
$canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas"));
-if (!empty($canvas))
-{
+if (!empty($canvas)) {
require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
$objcanvas = new Canvas($db, $action);
$objcanvas->getCanvas('contact', 'contactcard', $canvas);
}
// Security check
-if ($user->socid) $socid = $user->socid;
+if ($user->socid) {
+ $socid = $user->socid;
+}
$result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', 0); // If we create a contact with no company (shared contacts), no check on write permission
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('contactcard', 'globalcard'));
-if ($id > 0) $object->fetch($id);
+if ($id > 0) {
+ $object->fetch($id);
+}
-if (!($object->id > 0) && $action == 'view')
-{
+if (!($object->id > 0) && $action == 'view') {
$langs->load("errors");
print($langs->trans('ErrorRecordNotFound'));
exit;
@@ -100,36 +102,32 @@ if (!($object->id > 0) && $action == 'view')
$parameters = array('id'=>$id, 'objcanvas'=>$objcanvas);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+ setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
-if (empty($reshook))
-{
+if (empty($reshook)) {
// Cancel
- if (GETPOST('cancel', 'alpha') && !empty($backtopage))
- {
+ if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
header("Location: ".$backtopage);
exit;
}
// Creation utilisateur depuis contact
- if ($action == 'confirm_create_user' && $confirm == 'yes' && $user->rights->user->user->creer)
- {
+ if ($action == 'confirm_create_user' && $confirm == 'yes' && $user->rights->user->user->creer) {
// Recuperation contact actuel
$result = $object->fetch($id);
- if ($result > 0)
- {
+ if ($result > 0) {
$db->begin();
// Creation user
$nuser = new User($db);
$result = $nuser->create_from_contact($object, GETPOST("login")); // Do not use GETPOST(alpha)
- if ($result > 0)
- {
+ if ($result > 0) {
$result2 = $nuser->setPassword($user, GETPOST("password"), 0, 0, 1); // Do not use GETPOST(alpha)
- if ($result2)
- {
+ if ($result2) {
$db->commit();
} else {
$error = $nuser->error; $errors = $nuser->errors;
@@ -146,11 +144,9 @@ if (empty($reshook))
// Confirmation desactivation
- if ($action == 'disable')
- {
+ if ($action == 'disable') {
$object->fetch($id);
- if ($object->setstatus(0) < 0)
- {
+ if ($object->setstatus(0) < 0) {
setEventMessages($object->error, $object->errors, 'errors');
} else {
header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id);
@@ -159,11 +155,9 @@ if (empty($reshook))
}
// Confirmation activation
- if ($action == 'enable')
- {
+ if ($action == 'enable') {
$object->fetch($id);
- if ($object->setstatus(1) < 0)
- {
+ if ($object->setstatus(1) < 0) {
setEventMessages($object->error, $object->errors, 'errors');
} else {
header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id);
@@ -172,11 +166,12 @@ if (empty($reshook))
}
// Add contact
- if ($action == 'add' && $user->rights->societe->contact->creer)
- {
+ if ($action == 'add' && $user->rights->societe->contact->creer) {
$db->begin();
- if ($canvas) $object->canvas = $canvas;
+ if ($canvas) {
+ $object->canvas = $canvas;
+ }
$object->entity = (GETPOSTISSET('entity') ?GETPOST('entity', 'int') : $conf->entity);
$object->socid = GETPOST("socid", 'int');
@@ -221,8 +216,7 @@ if (empty($reshook))
// Fill array 'array_options' with data from add form
$ret = $extrafields->setOptionalsFromPost(null, $object);
- if ($ret < 0)
- {
+ if ($ret < 0) {
$error++;
$action = 'create';
}
@@ -233,8 +227,7 @@ if (empty($reshook))
$action = 'create';
}
- if (!empty($object->email) && !isValidEMail($object->email))
- {
+ if (!empty($object->email) && !isValidEMail($object->email)) {
$langs->load("errors");
$error++;
$errors[] = $langs->trans("ErrorBadEMail", GETPOST('email', 'alpha'));
@@ -279,11 +272,13 @@ if (empty($reshook))
}
}
- if (empty($error) && $id > 0)
- {
+ if (empty($error) && $id > 0) {
$db->commit();
- if (!empty($backtopage)) $url = $backtopage;
- else $url = 'card.php?id='.$id;
+ if (!empty($backtopage)) {
+ $url = $backtopage;
+ } else {
+ $url = 'card.php?id='.$id;
+ }
header("Location: ".$url);
exit;
} else {
@@ -291,8 +286,7 @@ if (empty($reshook))
}
}
- if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->contact->supprimer)
- {
+ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->contact->supprimer) {
$result = $object->fetch($id);
$object->oldcopy = clone $object;
@@ -313,10 +307,8 @@ if (empty($reshook))
}
}
- if ($action == 'update' && empty($cancel) && $user->rights->societe->contact->creer)
- {
- if (!GETPOST("lastname", 'alpha'))
- {
+ if ($action == 'update' && empty($cancel) && $user->rights->societe->contact->creer) {
+ if (!GETPOST("lastname", 'alpha')) {
$error++; $errors = array($langs->trans("ErrorFieldRequired", $langs->transnoentities("Name").' / '.$langs->transnoentities("Label")));
$action = 'edit';
}
@@ -327,16 +319,14 @@ if (empty($reshook))
$action = 'edit';
}
- if (!empty(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL)) && !isValidEMail(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL)))
- {
+ if (!empty(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL)) && !isValidEMail(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL))) {
$langs->load("errors");
$error++;
$errors[] = $langs->trans("ErrorBadEMail", GETPOST('email', 'alpha'));
$action = 'edit';
}
- if (!$error)
- {
+ if (!$error) {
$contactid = GETPOST("contactid", 'int');
$object->fetch($contactid);
$object->fetchRoles($contactid);
@@ -344,27 +334,22 @@ if (empty($reshook))
// Photo save
$dir = $conf->societe->multidir_output[$object->entity]."/contact/".$object->id."/photos";
$file_OK = is_uploaded_file($_FILES['photo']['tmp_name']);
- if (GETPOST('deletephoto') && $object->photo)
- {
+ if (GETPOST('deletephoto') && $object->photo) {
$fileimg = $dir.'/'.$object->photo;
$dirthumbs = $dir.'/thumbs';
dol_delete_file($fileimg);
dol_delete_dir_recursive($dirthumbs);
$object->photo = '';
}
- if ($file_OK)
- {
- if (image_format_supported($_FILES['photo']['name']) > 0)
- {
+ if ($file_OK) {
+ if (image_format_supported($_FILES['photo']['name']) > 0) {
dol_mkdir($dir);
- if (@is_dir($dir))
- {
+ if (@is_dir($dir)) {
$newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']);
$result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1);
- if (!$result > 0)
- {
+ if (!$result > 0) {
$errors[] = "ErrorFailedToSaveFile";
} else {
$object->photo = dol_sanitizeFileName($_FILES['photo']['name']);
@@ -377,8 +362,7 @@ if (empty($reshook))
$errors[] = "ErrorBadImageFormat";
}
} else {
- switch ($_FILES['photo']['error'])
- {
+ switch ($_FILES['photo']['error']) {
case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
$errors[] = "ErrorFileSizeTooLarge";
@@ -433,10 +417,11 @@ if (empty($reshook))
// Fill array 'array_options' with data from add form
$ret = $extrafields->setOptionalsFromPost(null, $object);
- if ($ret < 0) $error++;
+ if ($ret < 0) {
+ $error++;
+ }
- if (!$error)
- {
+ if (!$error) {
$result = $object->update($contactid, $user);
if ($result > 0) {
@@ -445,8 +430,7 @@ if (empty($reshook))
$object->setCategories($categories);
// Update mass emailing flag into table mailing_unsubscribe
- if (GETPOSTISSET('no_email') && $object->email)
- {
+ if (GETPOSTISSET('no_email') && $object->email) {
$no_email = GETPOST('no_email', 'int');
$result=$object->setNoEmail($no_email);
if ($result<0) {
@@ -465,31 +449,31 @@ if (empty($reshook))
}
}
- if (!$error && empty($errors))
- {
- if (!empty($backtopage))
- {
- header("Location: ".$backtopage);
- exit;
- }
+ if (!$error && empty($errors)) {
+ if (!empty($backtopage)) {
+ header("Location: ".$backtopage);
+ exit;
+ }
}
}
- if ($action == 'setprospectcontactlevel' && $user->rights->societe->contact->creer)
- {
+ if ($action == 'setprospectcontactlevel' && $user->rights->societe->contact->creer) {
$object->fetch($id);
$object->fk_prospectlevel = GETPOST('prospect_contact_level_id', 'alpha');
$result = $object->update($object->id, $user);
- if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
+ if ($result < 0) {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
}
// set communication status
- if ($action == 'setstcomm')
- {
+ if ($action == 'setstcomm') {
$object->fetch($id);
$object->stcomm_id = dol_getIdFromCode($db, GETPOST('stcomm', 'alpha'), 'c_stcommcontact');
$result = $object->update($object->id, $user);
- if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
+ if ($result < 0) {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
}
// Actions to send emails
@@ -506,7 +490,9 @@ if (empty($reshook))
$title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
-if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname;
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) {
+ $title = $object->lastname;
+}
$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
llxHeader('', $title, $help_url);
@@ -515,24 +501,23 @@ $formcompany = new FormCompany($db);
$countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')';
-if ($socid > 0)
-{
+if ($socid > 0) {
$objsoc = new Societe($db);
$objsoc->fetch($socid);
}
-if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
-{
+if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
// -----------------------------------------
// When used with CANVAS
// -----------------------------------------
- if (empty($object->error) && $id)
- {
- $object = new Contact($db);
- $result = $object->fetch($id);
- if ($result <= 0) dol_print_error('', $object->error);
- }
- $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates
+ if (empty($object->error) && $id) {
+ $object = new Contact($db);
+ $result = $object->fetch($id);
+ if ($result <= 0) {
+ dol_print_error('', $object->error);
+ }
+ }
+ $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates
$objcanvas->display_canvas($action); // Show template
} else {
// -----------------------------------------
@@ -540,20 +525,17 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
// -----------------------------------------
// Confirm deleting contact
- if ($user->rights->societe->contact->supprimer)
- {
- if ($action == 'delete')
- {
+ if ($user->rights->societe->contact->supprimer) {
+ if ($action == 'delete') {
print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage ? '&backtopage='.$backtopage : ''), $langs->trans("DeleteContact"), $langs->trans("ConfirmDeleteContact"), "confirm_delete", '', 0, 1);
}
}
/*
- * Onglets
- */
+ * Onglets
+ */
$head = array();
- if ($id > 0)
- {
+ if ($id > 0) {
// Si edition contact deja existant
$object = new Contact($db);
$res = $object->fetch($id, $user);
@@ -569,21 +551,18 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
}
- if ($user->rights->societe->contact->creer)
- {
- if ($action == 'create')
- {
+ if ($user->rights->societe->contact->creer) {
+ if ($action == 'create') {
/*
- * Fiche en mode creation
- */
+ * Fiche en mode creation
+ */
$object->canvas = $canvas;
$object->state_id = GETPOST("state_id");
// We set country_id, country_code and label for the selected country
$object->country_id = $_POST["country_id"] ?GETPOST("country_id") : (empty($objsoc->country_id) ? $mysoc->country_id : $objsoc->country_id);
- if ($object->country_id)
- {
+ if ($object->country_id) {
$tmparray = getCountry($object->country_id, 'all');
$object->country_code = $tmparray['code'];
$object->country = $tmparray['label'];
@@ -596,8 +575,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
// Show errors
dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors);
- if ($conf->use_javascript_ajax)
- {
+ if ($conf->use_javascript_ajax) {
print "\n".''."\n";
}
- if (!GETPOSTISSET("no_email") && !empty($object->email))
- {
+ if (!GETPOSTISSET("no_email") && !empty($object->email)) {
$result=$object->getNoEmail();
if ($result<0) {
setEventMessages($object->error, $object->errors, 'errors');
@@ -829,8 +820,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$parameters = array('socid' => $socid, 'objsoc' => $objsoc, 'colspan' => ' colspan="3"', 'cols' => 3);
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
- if (empty($reshook))
- {
+ if (empty($reshook)) {
print $object->showOptionals($extrafields, 'edit', $parameters);
}
@@ -846,8 +836,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
// Date To Birth
print ''.$langs->trans("DateOfBirth").' ';
$form = new Form($db);
- if ($object->birthday)
- {
+ if ($object->birthday) {
print $form->selectDate($object->birthday, 'birthday', 0, 0, 0, "perso", 1, 0);
} else {
print $form->selectDate('', 'birthday', 0, 0, 1, "perso", 1, 0);
@@ -855,8 +844,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
print ' ';
print ''.$langs->trans("Alert").' : ';
- if ($object->birthday_alert)
- {
+ if ($object->birthday_alert) {
print ' ';
} else {
print ' ';
@@ -870,8 +858,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
print '';
print '
';
- if (!empty($backtopage))
- {
+ if (!empty($backtopage)) {
print ' ';
print '
';
} else {
@@ -883,12 +870,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
print "";
} elseif ($action == 'edit' && !empty($id)) {
/*
- * Fiche en mode edition
- */
+ * Fiche en mode edition
+ */
// We set country_id, and country_code label of the chosen country
- if (GETPOSTISSET("country_id") || $object->country_id)
- {
+ if (GETPOSTISSET("country_id") || $object->country_id) {
$tmparray = getCountry($object->country_id, 'all');
$object->country_code = $tmparray['code'];
$object->country = $tmparray['label'];
@@ -900,8 +886,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
// Show errors
dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors);
- if ($conf->use_javascript_ajax)
- {
+ if ($conf->use_javascript_ajax) {
print "\n".''."\n";
}
- if (!GETPOSTISSET("no_email") && !empty($object->email))
- {
+ if (!GETPOSTISSET("no_email") && !empty($object->email)) {
$result=$object->getNoEmail();
if ($result<0) {
setEventMessages($object->error, $object->errors, 'errors');
@@ -1145,36 +1128,31 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$parameters = array('colspan' => ' colspan="3"', 'cols'=> '3');
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
- if (empty($reshook))
- {
+ if (empty($reshook)) {
print $object->showOptionals($extrafields, 'edit', $parameters);
}
$object->load_ref_elements();
- if (!empty($conf->commande->enabled))
- {
+ if (!empty($conf->commande->enabled)) {
print '
'.$langs->trans("ContactForOrders").' ';
print $object->ref_commande ? $object->ref_commande : $langs->trans("NoContactForAnyOrder");
print ' ';
}
- if (!empty($conf->propal->enabled))
- {
+ if (!empty($conf->propal->enabled)) {
print '
'.$langs->trans("ContactForProposals").' ';
print $object->ref_propal ? $object->ref_propal : $langs->trans("NoContactForAnyProposal");
print ' ';
}
- if (!empty($conf->contrat->enabled))
- {
+ if (!empty($conf->contrat->enabled)) {
print '
'.$langs->trans("ContactForContracts").' ';
print $object->ref_contrat ? $object->ref_contrat : $langs->trans("NoContactForAnyContract");
print ' ';
}
- if (!empty($conf->facture->enabled))
- {
+ if (!empty($conf->facture->enabled)) {
print '
'.$langs->trans("ContactForInvoices").' ';
print $object->ref_facturation ? $object->ref_facturation : $langs->trans("NoContactForAnyInvoice");
print ' ';
@@ -1182,12 +1160,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
// Login Dolibarr
print '
'.$langs->trans("DolibarrLogin").' ';
- if ($object->user_id)
- {
+ if ($object->user_id) {
$dolibarr_user = new User($db);
$result = $dolibarr_user->fetch($object->user_id);
print $dolibarr_user->getLoginUrl(1);
- } else print $langs->trans("NoDolibarrAccess");
+ } else {
+ print $langs->trans("NoDolibarrAccess");
+ }
print ' ';
// Photo
@@ -1199,7 +1178,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
print "
\n";
}
print '
';
@@ -1226,8 +1207,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$action = 'presend';
}
- if (!empty($id) && $action != 'edit' && $action != 'create')
- {
+ if (!empty($id) && $action != 'edit' && $action != 'create') {
$objsoc = new Societe($db);
// View mode
@@ -1237,15 +1217,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
print dol_get_fiche_head($head, 'card', $title, -1, 'contact');
- if ($action == 'create_user')
- {
+ if ($action == 'create_user') {
// Full firstname and lastname separated with a dot : firstname.lastname
include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
$login = dol_buildlogin($object->lastname, $object->firstname);
$generated_password = '';
- if (!$ldap_sid) // TODO ldap_sid ?
- {
+ if (!$ldap_sid) { // TODO ldap_sid ?
require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$generated_password = getRandomPassword(false);
}
@@ -1258,10 +1236,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
//array('label' => $form->textwithpicto($langs->trans("Type"),$langs->trans("InternalExternalDesc")), 'type' => 'select', 'name' => 'intern', 'default' => 1, 'values' => array(0=>$langs->trans('Internal'),1=>$langs->trans('External')))
);
$text = $langs->trans("ConfirmCreateContact").'
';
- if (!empty($conf->societe->enabled))
- {
- if ($object->socid > 0) $text .= $langs->trans("UserWillBeExternalUser");
- else $text .= $langs->trans("UserWillBeInternalUser");
+ if (!empty($conf->societe->enabled)) {
+ if ($object->socid > 0) {
+ $text .= $langs->trans("UserWillBeExternalUser");
+ } else {
+ $text .= $langs->trans("UserWillBeInternalUser");
+ }
}
print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CreateDolibarrLogin"), $text, "confirm_create_user", $formquestion, 'yes');
}
@@ -1269,13 +1249,15 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$linkback = '
'.$langs->trans("BackToList").' ';
$morehtmlref = '
';
- if (empty($conf->global->SOCIETE_DISABLE_CONTACTS))
- {
+ if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) {
$objsoc->fetch($object->socid);
// Thirdparty
$morehtmlref .= $langs->trans('ThirdParty').' : ';
- if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1, 'contact');
- else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany");
+ if ($objsoc->id > 0) {
+ $morehtmlref .= $objsoc->getNomUrl(1, 'contact');
+ } else {
+ $morehtmlref .= $langs->trans("ContactNotLinkedToCompany");
+ }
}
$morehtmlref .= '
';
@@ -1297,16 +1279,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
print '
'.$langs->trans("PostOrFunction").' '.$object->poste.' ';
// Email
- if (!empty($conf->mailing->enabled))
- {
+ if (!empty($conf->mailing->enabled)) {
$langs->load("mails");
print '
'.$langs->trans("NbOfEMailingsSend").' ';
print ''.$object->getNbOfEMailings().' ';
}
// Unsubscribe opt-out
- if (!empty($conf->mailing->enabled))
- {
+ if (!empty($conf->mailing->enabled)) {
$result=$object->getNoEmail();
if ($result<0) {
setEventMessages($object->error, $object->errors, 'errors');
@@ -1324,8 +1304,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$object->fetch_thirdparty();
if (!empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) {
- if ($object->thirdparty->client == 2 || $object->thirdparty->client == 3)
- {
+ if ($object->thirdparty->client == 2 || $object->thirdparty->client == 3) {
print '
';
print '
';
@@ -1336,7 +1315,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
print '
';
print '
';
if ($action == 'editlevel') {
@@ -1354,8 +1335,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
print '';
foreach ($object->cacheprospectstatus as $key => $val) {
$titlealt = 'default';
- if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label'];
- if ($object->stcomm_id != $val['id']) print '
id.'&stcomm='.$val['code'].'&action=setstcomm&token='.newToken().'">'.img_action($titlealt, $val['code'], $val['picto']).' ';
+ if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) {
+ $titlealt = $val['label'];
+ }
+ if ($object->stcomm_id != $val['id']) {
+ print '
id.'&stcomm='.$val['code'].'&action=setstcomm&token='.newToken().'">'.img_action($titlealt, $val['code'], $val['picto']).' ';
+ }
}
print '
';
@@ -1391,45 +1376,48 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$object->load_ref_elements();
- if (!empty($conf->propal->enabled))
- {
+ if (!empty($conf->propal->enabled)) {
print ''.$langs->trans("ContactForProposals").' ';
print $object->ref_propal ? $object->ref_propal : $langs->trans("NoContactForAnyProposal");
print ' ';
}
- if (!empty($conf->commande->enabled) || !empty($conf->expedition->enabled))
- {
+ if (!empty($conf->commande->enabled) || !empty($conf->expedition->enabled)) {
print '';
- if (!empty($conf->expedition->enabled)) { print $langs->trans("ContactForOrdersOrShipments"); } else print $langs->trans("ContactForOrders");
+ if (!empty($conf->expedition->enabled)) {
+ print $langs->trans("ContactForOrdersOrShipments");
+ } else {
+ print $langs->trans("ContactForOrders");
+ }
print ' ';
$none = $langs->trans("NoContactForAnyOrder");
- if (!empty($conf->expedition->enabled)) { $none = $langs->trans("NoContactForAnyOrderOrShipments"); }
+ if (!empty($conf->expedition->enabled)) {
+ $none = $langs->trans("NoContactForAnyOrderOrShipments");
+ }
print $object->ref_commande ? $object->ref_commande : $none;
print ' ';
}
- if (!empty($conf->contrat->enabled))
- {
+ if (!empty($conf->contrat->enabled)) {
print ''.$langs->trans("ContactForContracts").' ';
print $object->ref_contrat ? $object->ref_contrat : $langs->trans("NoContactForAnyContract");
print ' ';
}
- if (!empty($conf->facture->enabled))
- {
+ if (!empty($conf->facture->enabled)) {
print ''.$langs->trans("ContactForInvoices").' ';
print $object->ref_facturation ? $object->ref_facturation : $langs->trans("NoContactForAnyInvoice");
print ' ';
}
print ''.$langs->trans("DolibarrLogin").' ';
- if ($object->user_id)
- {
+ if ($object->user_id) {
$dolibarr_user = new User($db);
$result = $dolibarr_user->fetch($object->user_id);
print $dolibarr_user->getLoginUrl(1);
- } else print $langs->trans("NoDolibarrAccess");
+ } else {
+ print $langs->trans("NoDolibarrAccess");
+ }
print ' ';
print '';
@@ -1452,11 +1440,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
- if (empty($reshook) && $action != 'presend')
- {
+ if (empty($reshook) && $action != 'presend') {
if (empty($user->socid)) {
- if (!empty($object->email))
- {
+ if (!empty($object->email)) {
$langs->load("mails");
print '';
} else {
@@ -1465,30 +1451,25 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
}
}
- if ($user->rights->societe->contact->creer)
- {
+ if ($user->rights->societe->contact->creer) {
print ''.$langs->trans('Modify').' ';
}
- if (!$object->user_id && $user->rights->user->user->creer)
- {
+ if (!$object->user_id && $user->rights->user->user->creer) {
print ''.$langs->trans("CreateDolibarrLogin").' ';
}
// Activer
- if ($object->statut == 0 && $user->rights->societe->contact->creer)
- {
+ if ($object->statut == 0 && $user->rights->societe->contact->creer) {
print ''.$langs->trans("Reactivate").' ';
}
// Desactiver
- if ($object->statut == 1 && $user->rights->societe->contact->creer)
- {
+ if ($object->statut == 1 && $user->rights->societe->contact->creer) {
print ''.$langs->trans("DisableUser").' ';
}
// Delete
- if ($user->rights->societe->contact->supprimer)
- {
+ if ($user->rights->societe->contact->supprimer) {
print ''.$langs->trans('Delete').' ';
}
}
@@ -1500,8 +1481,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$action = 'presend';
}
- if ($action != 'presend')
- {
+ if ($action != 'presend') {
print '';
print '
';
diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php
index 1d2cb3355a5..0c7f3ac73aa 100644
--- a/htdocs/contact/class/contact.class.php
+++ b/htdocs/contact/class/contact.class.php
@@ -473,40 +473,35 @@ class Contact extends CommonObject
dol_syslog(get_class($this)."::create", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."socpeople");
- if (!$error)
- {
+ if (!$error) {
$result = $this->update($this->id, $user, 1, 'add'); // This include updateRoles(), ...
- if ($result < 0)
- {
+ if ($result < 0) {
$error++;
$this->error = $this->db->lasterror();
}
}
- if (!$error)
- {
+ if (!$error) {
$result = $this->update_perso($this->id, $user, 1); // TODO Remove function update_perso, should be same than update
- if ($result < 0)
- {
+ if ($result < 0) {
$error++;
$this->error = $this->db->lasterror();
}
}
- if (!$error)
- {
+ if (!$error) {
// Call trigger
$result = $this->call_trigger('CONTACT_CREATE', $user);
- if ($result < 0) { $error++; }
+ if ($result < 0) {
+ $error++;
+ }
// End call triggers
}
- if (!$error)
- {
+ if (!$error) {
$this->db->commit();
return $this->id;
} else {
@@ -558,13 +553,20 @@ class Contact extends CommonObject
$this->town = (empty($this->town) ? '' : trim($this->town));
$this->setUpperOrLowerCase();
$this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
- if (empty($this->statut)) $this->statut = 0;
- if (empty($this->civility_code) && !is_numeric($this->civility_id)) $this->civility_code = $this->civility_id; // For backward compatibility
+ if (empty($this->statut)) {
+ $this->statut = 0;
+ }
+ if (empty($this->civility_code) && !is_numeric($this->civility_id)) {
+ $this->civility_code = $this->civility_id; // For backward compatibility
+ }
$this->db->begin();
$sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET ";
- if ($this->socid > 0) $sql .= " fk_soc='".$this->db->escape($this->socid)."',";
- elseif ($this->socid == -1) $sql .= " fk_soc=null,";
+ if ($this->socid > 0) {
+ $sql .= " fk_soc='".$this->db->escape($this->socid)."',";
+ } elseif ($this->socid == -1) {
+ $sql .= " fk_soc=null,";
+ }
$sql .= " civility='".$this->db->escape($this->civility_code)."'";
$sql .= ", lastname='".$this->db->escape($this->lastname)."'";
$sql .= ", firstname='".$this->db->escape($this->firstname)."'";
@@ -586,8 +588,7 @@ class Contact extends CommonObject
$sql .= ", phone_mobile = ".(isset($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
$sql .= ", priv = '".$this->db->escape($this->priv)."'";
$sql .= ", fk_prospectcontactlevel = '".$this->db->escape($this->fk_prospectlevel)."'";
- if (isset($this->stcomm_id))
- {
+ if (isset($this->stcomm_id)) {
$sql .= ", fk_stcommcontact = ".($this->stcomm_id > 0 || $this->stcomm_id == -1 ? $this->stcomm_id : "0");
}
$sql .= ", statut = ".$this->db->escape($this->statut);
@@ -598,8 +599,7 @@ class Contact extends CommonObject
dol_syslog(get_class($this)."::update", LOG_DEBUG);
$result = $this->db->query($sql);
- if ($result)
- {
+ if ($result) {
unset($this->country_code);
unset($this->country);
unset($this->state_code);
@@ -608,25 +608,21 @@ class Contact extends CommonObject
$action = 'update';
// Actions on extra fields
- if (!$error)
- {
+ if (!$error) {
$result = $this->insertExtraFields();
- if ($result < 0)
- {
+ if ($result < 0) {
$error++;
}
}
if (!$error) {
$result = $this->updateRoles();
- if ($result < 0)
- {
+ if ($result < 0) {
$error++;
}
}
- if (!$error && $this->user_id > 0)
- {
+ if (!$error && $this->user_id > 0) {
// If contact is linked to a user
$tmpobj = new User($this->db);
$tmpobj->fetch($this->user_id);
@@ -685,14 +681,18 @@ class Contact extends CommonObject
// }
if ($usermustbemodified) {
$result = $tmpobj->update($user, 0, 1, 1, 1);
- if ($result < 0) { $error++; }
+ if ($result < 0) {
+ $error++;
+ }
}
}
if (!$error && !$notrigger) {
// Call trigger
$result = $this->call_trigger('CONTACT_MODIFY', $user);
- if ($result < 0) { $error++; }
+ if ($result < 0) {
+ $error++;
+ }
// End call triggers
}
@@ -759,34 +759,69 @@ class Contact extends CommonObject
$this->fullname = $this->getFullName($langs);
// Fields
- if ($this->fullname && !empty($conf->global->LDAP_CONTACT_FIELD_FULLNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FULLNAME] = $this->fullname;
- if ($this->lastname && !empty($conf->global->LDAP_CONTACT_FIELD_NAME)) $info[$conf->global->LDAP_CONTACT_FIELD_NAME] = $this->lastname;
- if ($this->firstname && !empty($conf->global->LDAP_CONTACT_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FIRSTNAME] = $this->firstname;
+ if ($this->fullname && !empty($conf->global->LDAP_CONTACT_FIELD_FULLNAME)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_FULLNAME] = $this->fullname;
+ }
+ if ($this->lastname && !empty($conf->global->LDAP_CONTACT_FIELD_NAME)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_NAME] = $this->lastname;
+ }
+ if ($this->firstname && !empty($conf->global->LDAP_CONTACT_FIELD_FIRSTNAME)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_FIRSTNAME] = $this->firstname;
+ }
- if ($this->poste) $info["title"] = $this->poste;
+ if ($this->poste) {
+ $info["title"] = $this->poste;
+ }
if ($this->socid > 0) {
$soc = new Societe($this->db);
$soc->fetch($this->socid);
$info[$conf->global->LDAP_CONTACT_FIELD_COMPANY] = $soc->name;
- if ($soc->client == 1) $info["businessCategory"] = "Customers";
- if ($soc->client == 2) $info["businessCategory"] = "Prospects";
- if ($soc->fournisseur == 1) $info["businessCategory"] = "Suppliers";
+ if ($soc->client == 1) {
+ $info["businessCategory"] = "Customers";
+ }
+ if ($soc->client == 2) {
+ $info["businessCategory"] = "Prospects";
+ }
+ if ($soc->fournisseur == 1) {
+ $info["businessCategory"] = "Suppliers";
+ }
+ }
+ if ($this->address && !empty($conf->global->LDAP_CONTACT_FIELD_ADDRESS)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_ADDRESS] = $this->address;
+ }
+ if ($this->zip && !empty($conf->global->LDAP_CONTACT_FIELD_ZIP)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_ZIP] = $this->zip;
+ }
+ if ($this->town && !empty($conf->global->LDAP_CONTACT_FIELD_TOWN)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_TOWN] = $this->town;
+ }
+ if ($this->country_code && !empty($conf->global->LDAP_CONTACT_FIELD_COUNTRY)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_COUNTRY] = $this->country_code;
+ }
+ if ($this->phone_pro && !empty($conf->global->LDAP_CONTACT_FIELD_PHONE)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_PHONE] = $this->phone_pro;
+ }
+ if ($this->phone_perso && !empty($conf->global->LDAP_CONTACT_FIELD_HOMEPHONE)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_HOMEPHONE] = $this->phone_perso;
+ }
+ if ($this->phone_mobile && !empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile;
+ }
+ if ($this->fax && !empty($conf->global->LDAP_CONTACT_FIELD_FAX)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax;
+ }
+ if ($this->skype && !empty($conf->global->LDAP_CONTACT_FIELD_SKYPE)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = $this->skype;
+ }
+ if ($this->note_private && !empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2);
+ }
+ if ($this->email && !empty($conf->global->LDAP_CONTACT_FIELD_MAIL)) {
+ $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email;
}
- if ($this->address && !empty($conf->global->LDAP_CONTACT_FIELD_ADDRESS)) $info[$conf->global->LDAP_CONTACT_FIELD_ADDRESS] = $this->address;
- if ($this->zip && !empty($conf->global->LDAP_CONTACT_FIELD_ZIP)) $info[$conf->global->LDAP_CONTACT_FIELD_ZIP] = $this->zip;
- if ($this->town && !empty($conf->global->LDAP_CONTACT_FIELD_TOWN)) $info[$conf->global->LDAP_CONTACT_FIELD_TOWN] = $this->town;
- if ($this->country_code && !empty($conf->global->LDAP_CONTACT_FIELD_COUNTRY)) $info[$conf->global->LDAP_CONTACT_FIELD_COUNTRY] = $this->country_code;
- if ($this->phone_pro && !empty($conf->global->LDAP_CONTACT_FIELD_PHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_PHONE] = $this->phone_pro;
- if ($this->phone_perso && !empty($conf->global->LDAP_CONTACT_FIELD_HOMEPHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_HOMEPHONE] = $this->phone_perso;
- if ($this->phone_mobile && !empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile;
- if ($this->fax && !empty($conf->global->LDAP_CONTACT_FIELD_FAX)) $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax;
- if ($this->skype && !empty($conf->global->LDAP_CONTACT_FIELD_SKYPE)) $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = $this->skype;
- if ($this->note_private && !empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2);
- if ($this->email && !empty($conf->global->LDAP_CONTACT_FIELD_MAIL)) $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email;
- if ($conf->global->LDAP_SERVER_TYPE == 'egroupware')
- {
+ if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') {
$info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
$info['uidnumber'] = $this->id;
@@ -805,8 +840,12 @@ class Contact extends CommonObject
$info["phpgwContactOwner"] = $this->egroupware_id;
- if ($this->email) $info["rfc822Mailbox"] = $this->email;
- if ($this->phone_mobile) $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
+ if ($this->email) {
+ $info["rfc822Mailbox"] = $this->email;
+ }
+ if ($this->phone_mobile) {
+ $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
+ }
}
return $info;
@@ -834,13 +873,14 @@ class Contact extends CommonObject
$sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET";
$sql .= " birthday=".($this->birthday ? "'".$this->db->idate($this->birthday)."'" : "null");
$sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
- if ($user) $sql .= ", fk_user_modif=".$user->id;
+ if ($user) {
+ $sql .= ", fk_user_modif=".$user->id;
+ }
$sql .= " WHERE rowid=".$this->db->escape($id);
dol_syslog(get_class($this)."::update_perso this->birthday=".$this->birthday." -", LOG_DEBUG);
$resql = $this->db->query($sql);
- if (!$resql)
- {
+ if (!$resql) {
$error++;
$this->error = $this->db->lasterror();
}
@@ -875,7 +915,9 @@ class Contact extends CommonObject
if (!$error && !$notrigger) {
// Call trigger
$result = $this->call_trigger('CONTACT_MODIFY', $user);
- if ($result < 0) { $error++; }
+ if ($result < 0) {
+ $error++;
+ }
// End call triggers
}
@@ -906,8 +948,7 @@ class Contact extends CommonObject
dol_syslog(get_class($this)."::fetch id=".$id." ref_ext=".$ref_ext." email=".$email, LOG_DEBUG);
- if (empty($id) && empty($ref_ext) && empty($email))
- {
+ if (empty($id) && empty($ref_ext) && empty($email)) {
$this->error = 'BadParameter';
return -1;
}
@@ -936,8 +977,9 @@ class Contact extends CommonObject
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON c.rowid = u.fk_socpeople";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcommcontact as st ON c.fk_stcommcontact = st.id';
- if ($id) $sql .= " WHERE c.rowid = ".((int) $id);
- else {
+ if ($id) {
+ $sql .= " WHERE c.rowid = ".((int) $id);
+ } else {
$sql .= " WHERE c.entity IN (".getEntity($this->element).")";
if ($ref_ext) {
$sql .= " AND c.ref_ext = '".$this->db->escape($ref_ext)."'";
@@ -948,17 +990,14 @@ class Contact extends CommonObject
}
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $this->db->num_rows($resql);
- if ($num > 1)
- {
+ if ($num > 1) {
$this->error = 'Fetch found several records. Rename one of contact to avoid duplicate.';
dol_syslog($this->error, LOG_ERR);
return 2;
- } elseif ($num) // $num = 1
- {
+ } elseif ($num) { // $num = 1
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
@@ -1030,10 +1069,8 @@ class Contact extends CommonObject
$sql .= " WHERE u.fk_socpeople = ".$this->id;
$resql = $this->db->query($sql);
- if ($resql)
- {
- if ($this->db->num_rows($resql))
- {
+ if ($resql) {
+ if ($this->db->num_rows($resql)) {
$uobj = $this->db->fetch_object($resql);
$this->user_id = $uobj->rowid;
@@ -1049,17 +1086,14 @@ class Contact extends CommonObject
$this->fetch_optionals();
// Load also alerts of this user
- if ($user)
- {
+ if ($user) {
$sql = "SELECT fk_user";
$sql .= " FROM ".MAIN_DB_PREFIX."user_alert";
$sql .= " WHERE fk_user = ".$user->id." AND fk_contact = ".$this->db->escape($id);
$resql = $this->db->query($sql);
- if ($resql)
- {
- if ($this->db->num_rows($resql))
- {
+ if ($resql) {
+ if ($this->db->num_rows($resql)) {
$obj = $this->db->fetch_object($resql);
$this->birthday_alert = 1;
@@ -1102,11 +1136,9 @@ class Contact extends CommonObject
{
unset($this->gender);
- if (in_array($this->civility_id, array('MR')) || in_array($this->civility_code, array('MR')))
- {
+ if (in_array($this->civility_id, array('MR')) || in_array($this->civility_code, array('MR'))) {
$this->gender = 'man';
- } elseif (in_array($this->civility_id, array('MME', 'MLE')) || in_array($this->civility_code, array('MME', 'MLE')))
- {
+ } elseif (in_array($this->civility_id, array('MME', 'MLE')) || in_array($this->civility_code, array('MME', 'MLE'))) {
$this->gender = 'woman';
}
}
@@ -1135,16 +1167,18 @@ class Contact extends CommonObject
dol_syslog(get_class($this)."::load_ref_elements", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
- while ($obj = $this->db->fetch_object($resql))
- {
- if ($obj->nb)
- {
- if ($obj->element == 'facture') $this->ref_facturation = $obj->nb;
- elseif ($obj->element == 'contrat') $this->ref_contrat = $obj->nb;
- elseif ($obj->element == 'commande') $this->ref_commande = $obj->nb;
- elseif ($obj->element == 'propal') $this->ref_propal = $obj->nb;
+ if ($resql) {
+ while ($obj = $this->db->fetch_object($resql)) {
+ if ($obj->nb) {
+ if ($obj->element == 'facture') {
+ $this->ref_facturation = $obj->nb;
+ } elseif ($obj->element == 'contrat') {
+ $this->ref_contrat = $obj->nb;
+ } elseif ($obj->element == 'commande') {
+ $this->ref_commande = $obj->nb;
+ } elseif ($obj->element == 'propal') {
+ $this->ref_propal = $obj->nb;
+ }
}
}
$this->db->free($resql);
@@ -1169,8 +1203,7 @@ class Contact extends CommonObject
$this->db->begin();
- if (!$error)
- {
+ if (!$error) {
// Get all rowid of element_contact linked to a type that is link to llx_socpeople
$sql = "SELECT ec.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."element_contact ec,";
@@ -1180,21 +1213,18 @@ class Contact extends CommonObject
$sql .= " AND tc.source='external'";
dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $this->db->num_rows($resql);
$i = 0;
- while ($i < $num && !$error)
- {
+ while ($i < $num && !$error) {
$obj = $this->db->fetch_object($resql);
$sqldel = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
$sqldel .= " WHERE rowid = ".$obj->rowid;
dol_syslog(__METHOD__, LOG_DEBUG);
$result = $this->db->query($sqldel);
- if (!$result)
- {
+ if (!$result) {
$error++;
$this->error = $this->db->error().' sql='.$sqldel;
}
@@ -1207,56 +1237,48 @@ class Contact extends CommonObject
}
}
- if (!$error)
- {
+ if (!$error) {
// Remove Roles
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".$this->id;
dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql);
- if (!$resql)
- {
+ if (!$resql) {
$error++;
$this->error .= $this->db->lasterror();
$errorflag = -1;
}
}
- if (!$error)
- {
+ if (!$error) {
// Remove Roles
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".$this->id;
dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql);
- if (!$resql)
- {
+ if (!$resql) {
$error++;
$this->error .= $this->db->lasterror();
$errorflag = -1;
}
}
- if (!$error)
- {
+ if (!$error) {
// Remove category
$sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople = ".$this->id;
dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql);
- if (!$resql)
- {
+ if (!$resql) {
$error++;
$this->error .= $this->db->lasterror();
$errorflag = -1;
}
}
- if (!$error)
- {
+ if (!$error) {
$sql = "DELETE FROM ".MAIN_DB_PREFIX."socpeople";
$sql .= " WHERE rowid=".$this->id;
dol_syslog(__METHOD__, LOG_DEBUG);
$result = $this->db->query($sql);
- if (!$result)
- {
+ if (!$result) {
$error++;
$this->error = $this->db->error().' sql='.$sql;
}
@@ -1266,19 +1288,21 @@ class Contact extends CommonObject
if (!$error) {
// For avoid conflicts if trigger used
$result = $this->deleteExtraFields();
- if ($result < 0) $error++;
+ if ($result < 0) {
+ $error++;
+ }
}
- if (!$error && !$notrigger)
- {
+ if (!$error && !$notrigger) {
// Call trigger
$result = $this->call_trigger('CONTACT_DELETE', $user);
- if ($result < 0) { $error++; }
+ if ($result < 0) {
+ $error++;
+ }
// End call triggers
}
- if (!$error)
- {
+ if (!$error) {
$this->db->commit();
return 1;
} else {
@@ -1303,10 +1327,8 @@ class Contact extends CommonObject
$sql .= " WHERE c.rowid = ".$this->db->escape($id);
$resql = $this->db->query($sql);
- if ($resql)
- {
- if ($this->db->num_rows($resql))
- {
+ if ($resql) {
+ if ($this->db->num_rows($resql)) {
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
@@ -1346,8 +1368,7 @@ class Contact extends CommonObject
$sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $this->db->fetch_object($resql);
$nb = $obj->nb;
@@ -1377,8 +1398,7 @@ class Contact extends CommonObject
$result = ''; $label = '';
- if (!empty($this->photo) && class_exists('Form'))
- {
+ if (!empty($this->photo) && class_exists('Form')) {
$label .= '
';
$label .= Form::showphoto('contact', $this, 0, 40, 0, '', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
$label .= '
';
@@ -1388,67 +1408,83 @@ class Contact extends CommonObject
$label .= ' '.$this->getLibStatut(4);
$label .= '
'.$langs->trans("Name").': '.$this->getFullName($langs);
//if ($this->civility_id) $label.= '
' . $langs->trans("Civility") . ': '.$this->civility_id; // TODO Translate cibilty_id code
- if (!empty($this->poste)) $label .= '
'.$langs->trans("Poste").': '.$this->poste;
+ if (!empty($this->poste)) {
+ $label .= '
'.$langs->trans("Poste").': '.$this->poste;
+ }
$label .= '
'.$langs->trans("EMail").': '.$this->email;
$phonelist = array();
$country_code = empty($this->country_code) ? '': $this->country_code;
- if ($this->phone_pro) $phonelist[] = dol_print_phone($this->phone_pro, $country_code, $this->id, 0, '', ' ', 'phone');
- if ($this->phone_mobile) $phonelist[] = dol_print_phone($this->phone_mobile, $country_code, $this->id, 0, '', ' ', 'mobile');
- if ($this->phone_perso) $phonelist[] = dol_print_phone($this->phone_perso, $country_code, $this->id, 0, '', ' ', 'phone');
+ if ($this->phone_pro) {
+ $phonelist[] = dol_print_phone($this->phone_pro, $country_code, $this->id, 0, '', ' ', 'phone');
+ }
+ if ($this->phone_mobile) {
+ $phonelist[] = dol_print_phone($this->phone_mobile, $country_code, $this->id, 0, '', ' ', 'mobile');
+ }
+ if ($this->phone_perso) {
+ $phonelist[] = dol_print_phone($this->phone_perso, $country_code, $this->id, 0, '', ' ', 'phone');
+ }
$label .= '
'.$langs->trans("Phone").': '.implode(' ', $phonelist);
$label .= '
'.$langs->trans("Address").': '.dol_format_address($this, 1, ' ', $langs);
$url = DOL_URL_ROOT.'/contact/card.php?id='.$this->id;
- if ($option !== 'nolink')
- {
+ 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';
+ 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';
+ }
}
$url .= $moreparam;
$linkclose = "";
if (empty($notooltip)) {
- if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
- {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
$label = $langs->trans("ShowContact");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
}
- $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
- $linkclose .= ' class="classfortooltip"';
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip"';
- /*
- $hookmanager->initHooks(array('contactdao'));
- $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;
- */
+ /*
+ $hookmanager->initHooks(array('contactdao'));
+ $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 = '
';
$linkend = ' ';
- if ($option == 'xxx')
- {
+ if ($option == 'xxx') {
$linkstart = '
';
$linkend = ' ';
}
$result .= $linkstart;
- if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
- if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->getFullName($langs), $maxlen) : $this->getFullName($langs));
+ if ($withpicto) {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ if ($withpicto != 2) {
+ $result .= ($maxlen ?dol_trunc($this->getFullName($langs), $maxlen) : $this->getFullName($langs));
+ }
$result .= $linkend;
global $action;
$hookmanager->initHooks(array('contactdao'));
$parameters = array('id'=>$this->id, 'getnomurl'=>$result);
$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
- if ($reshook > 0) $result = $hookmanager->resPrint;
- else $result .= $hookmanager->resPrint;
+ if ($reshook > 0) {
+ $result = $hookmanager->resPrint;
+ } else {
+ $result .= $hookmanager->resPrint;
+ }
return $result;
}
@@ -1463,7 +1499,9 @@ class Contact extends CommonObject
global $langs;
$code = ($this->civility_code ? $this->civility_code : (!empty($this->civility_id) ? $this->civility : (!empty($this->civilite) ? $this->civilite : '')));
- if (empty($code)) return '';
+ if (empty($code)) {
+ return '';
+ }
$langs->load("dict");
return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code);
@@ -1507,7 +1545,9 @@ class Contact extends CommonObject
);
$statusType = 'status4';
- if ($status == 0 || $status == 5) $statusType = 'status5';
+ if ($status == 0 || $status == 5) {
+ $statusType = 'status5';
+ }
$label = $langs->trans($labelStatus[$status]);
$labelshort = $langs->trans($labelStatusShort[$status]);
@@ -1527,8 +1567,11 @@ class Contact extends CommonObject
{
// phpcs:enable
global $langs;
- if ($status == '1') return $langs->trans('ContactPrivate');
- else return $langs->trans('ContactPublic');
+ if ($status == '1') {
+ return $langs->trans('ContactPrivate');
+ } else {
+ return $langs->trans('ContactPublic');
+ }
}
@@ -1547,7 +1590,9 @@ class Contact extends CommonObject
$resql = $this->db->query($sql);
if ($resql) {
$obj = $this->db->fetch_object($resql);
- if ($obj) $socid = $obj->rowid;
+ if ($obj) {
+ $socid = $obj->rowid;
+ }
}
// Initialise parameters
@@ -1592,8 +1637,11 @@ class Contact extends CommonObject
$error = 0;
// Check parameters
- if ($this->statut == $status) return 0;
- else $this->statut = $status;
+ if ($this->statut == $status) {
+ return 0;
+ } else {
+ $this->statut = $status;
+ }
$this->db->begin();
@@ -1604,16 +1652,16 @@ class Contact extends CommonObject
$result = $this->db->query($sql);
dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
- if ($result)
- {
+ if ($result) {
// Call trigger
$result = $this->call_trigger('CONTACT_ENABLEDISABLE', $user);
- if ($result < 0) { $error++; }
+ if ($result < 0) {
+ $error++;
+ }
// End call triggers
}
- if ($error)
- {
+ if ($error) {
$this->db->rollback();
return -$error;
} else {
@@ -1725,12 +1773,10 @@ class Contact extends CommonObject
dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $this->db->num_rows($resql);
$i = 0;
- while ($i < $num)
- {
+ while ($i < $num) {
$obj = $this->db->fetch_object($resql);
$tab[] = array('fk_socpeople'=>$obj->id, 'type_contact'=>$obj->fk_c_type_contact);
@@ -1758,11 +1804,13 @@ class Contact extends CommonObject
$error = 0;
- if (!isset($this->roles)) return; // Avoid to loose roles when property not set
+ if (!isset($this->roles)) {
+ return; // Avoid to loose roles when property not set
+ }
$this->db->begin();
- $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople=".$this->id." AND entity IN (".getEntity("societe_contact").")";
+ $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople=".((int) $this->id)." AND entity IN (".getEntity("societe_contact").")";
$result = $this->db->query($sql);
if (!$result) {
@@ -1800,8 +1848,7 @@ class Contact extends CommonObject
$sql .= ")";
$result = $this->db->query($sql);
- if (!$result)
- {
+ if (!$result) {
$this->errors[] = $this->db->lasterror().' sql='.$sql;
$error++;
}
@@ -1830,12 +1877,13 @@ class Contact extends CommonObject
global $langs;
$sql = "SELECT id, code, libelle as label, picto FROM ".MAIN_DB_PREFIX."c_stcommcontact";
- if ($active >= 0) $sql .= " WHERE active = ".$active;
+ if ($active >= 0) {
+ $sql .= " WHERE active = ".$active;
+ }
$resql = $this->db->query($sql);
$num = $this->db->num_rows($resql);
$i = 0;
- while ($i < $num)
- {
+ while ($i < $num) {
$obj = $this->db->fetch_object($resql);
$this->cacheprospectstatus[$obj->id] = array('id' => $obj->id, 'code' => $obj->code, 'label' => ($langs->trans("ST_".strtoupper($obj->code)) == "ST_".strtoupper($obj->code)) ? $obj->label : $langs->trans("ST_".strtoupper($obj->code)), 'picto' => $obj->picto);
$i++;
@@ -1865,8 +1913,7 @@ class Contact extends CommonObject
$lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
// If lib not found in language file, we get label from cache/databse
- if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel))
- {
+ if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
$lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
}
return $lib;
@@ -1915,36 +1962,48 @@ class Contact extends CommonObject
global $langs;
$langs->load('customers');
- if ($mode == 2)
- {
- if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
- elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
- elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
- elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
- elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
- else {
+ if ($mode == 2) {
+ if ($statut == '-1' || $statut == 'ST_NO') {
+ return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
+ } elseif ($statut == '0' || $statut == 'ST_NEVER') {
+ return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
+ } elseif ($statut == '1' || $statut == 'ST_TODO') {
+ return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
+ } elseif ($statut == '2' || $statut == 'ST_PEND') {
+ return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
+ } elseif ($statut == '3' || $statut == 'ST_DONE') {
+ return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
+ } else {
return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
}
}
- if ($mode == 3)
- {
- if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto);
- elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto);
- elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto);
- elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto);
- elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto);
- else {
+ if ($mode == 3) {
+ if ($statut == '-1' || $statut == 'ST_NO') {
+ return img_action($langs->trans("StatusProspect-1"), -1, $picto);
+ } elseif ($statut == '0' || $statut == 'ST_NEVER') {
+ return img_action($langs->trans("StatusProspect0"), 0, $picto);
+ } elseif ($statut == '1' || $statut == 'ST_TODO') {
+ return img_action($langs->trans("StatusProspect1"), 1, $picto);
+ } elseif ($statut == '2' || $statut == 'ST_PEND') {
+ return img_action($langs->trans("StatusProspect2"), 2, $picto);
+ } elseif ($statut == '3' || $statut == 'ST_DONE') {
+ return img_action($langs->trans("StatusProspect3"), 3, $picto);
+ } else {
return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto);
}
}
- if ($mode == 4)
- {
- if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
- elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
- elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
- elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
- elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
- else {
+ if ($mode == 4) {
+ if ($statut == '-1' || $statut == 'ST_NO') {
+ return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
+ } elseif ($statut == '0' || $statut == 'ST_NEVER') {
+ return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
+ } elseif ($statut == '1' || $statut == 'ST_TODO') {
+ return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
+ } elseif ($statut == '2' || $statut == 'ST_PEND') {
+ return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
+ } elseif ($statut == '3' || $statut == 'ST_DONE') {
+ return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
+ } else {
return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
}
}
@@ -1964,24 +2023,19 @@ class Contact extends CommonObject
$error = 0;
// Update mass emailing flag into table mailing_unsubscribe
- if ($this->email)
- {
+ if ($this->email) {
$this->db->begin();
- if ($no_email)
- {
+ if ($no_email) {
$sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$this->db->escape($this->email)."'";
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $this->db->fetch_object($resql);
$noemail = $obj->nb;
- if (empty($noemail))
- {
+ if (empty($noemail)) {
$sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$this->db->escape($this->email)."', ".$this->db->escape(getEntity('mailing', 0)).", '".$this->db->idate(dol_now())."')";
$resql = $this->db->query($sql);
- if (!$resql)
- {
+ if (!$resql) {
$error++;
$this->error = $this->db->lasterror();
$this->errors[] = $this->error;
@@ -1995,8 +2049,7 @@ class Contact extends CommonObject
} else {
$sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity = ".$this->db->escape(getEntity('mailing', 0));
$resql = $this->db->query($sql);
- if (!$resql)
- {
+ if (!$resql) {
$error++;
$this->error = $this->db->lasterror();
$this->errors[] = $this->error;
@@ -2024,8 +2077,7 @@ class Contact extends CommonObject
*/
public function getNoEmail()
{
- if ($this->email)
- {
+ if ($this->email) {
$sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
$resql = $this->db->query($sql);
if ($resql) {
diff --git a/htdocs/contact/consumption.php b/htdocs/contact/consumption.php
index da00374cc2a..1e0f5b06094 100644
--- a/htdocs/contact/consumption.php
+++ b/htdocs/contact/consumption.php
@@ -37,8 +37,12 @@ $id = GETPOST('id', 'int');
$result = restrictedArea($user, 'contact', $id, 'socpeople&societe');
$object = new Contact($db);
-if ($id > 0) $object->fetch($id);
-if (empty($object->thirdparty)) $object->fetch_thirdparty();
+if ($id > 0) {
+ $object->fetch($id);
+}
+if (empty($object->thirdparty)) {
+ $object->fetch_thirdparty();
+}
$socid = $object->thirdparty->id;
// Sort & Order fields
@@ -46,12 +50,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+ $page = 0;
+} // If $page is not defined, or '' or -1
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
-if (!$sortorder) $sortorder = 'DESC';
-if (!$sortfield) $sortfield = 'dateprint';
+if (!$sortorder) {
+ $sortorder = 'DESC';
+}
+if (!$sortfield) {
+ $sortfield = 'dateprint';
+}
// Search fields
$sref = GETPOST("sref");
@@ -60,8 +70,7 @@ $month = GETPOST('month', 'int');
$year = GETPOST('year', 'int');
// Clean up on purge search criteria ?
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers
$sref = '';
$sprod_fulldescr = '';
$year = '';
@@ -84,7 +93,9 @@ $hookmanager->initHooks(array('consumptioncontact'));
$parameters = array('id'=>$id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+ setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
/*
@@ -99,8 +110,7 @@ $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("C
$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
llxHeader('', $title, $help_url);
-if (empty($id))
-{
+if (empty($id)) {
dol_print_error($db);
exit;
}
@@ -111,13 +121,15 @@ print dol_get_fiche_head($head, 'consumption', $langs->trans("ContactsAddresses"
$linkback = '
'.$langs->trans("BackToList").' ';
$morehtmlref = '
';
-if (empty($conf->global->SOCIETE_DISABLE_CONTACTS))
-{
+if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) {
$objsoc->fetch($socid);
// Thirdparty
$morehtmlref .= $langs->trans('ThirdParty').' : ';
- if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1, 'contact');
- else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany");
+ if ($objsoc->id > 0) {
+ $morehtmlref .= $objsoc->getNomUrl(1, 'contact');
+ } else {
+ $morehtmlref .= $langs->trans("ContactNotLinkedToCompany");
+ }
}
$morehtmlref .= '
';
@@ -133,22 +145,34 @@ print '
'.$langs->trans("UserTitle").' ';
print $object->getCivilityLabel();
print ' ';
-if ($object->thirdparty->client)
-{
+if ($object->thirdparty->client) {
$thirdTypeArray['customer'] = $langs->trans("customer");
- if ($conf->propal->enabled && $user->rights->propal->lire) $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals');
- if ($conf->commande->enabled && $user->rights->commande->lire) $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders');
- if ($conf->facture->enabled && $user->rights->facture->lire) $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices');
- if ($conf->contrat->enabled && $user->rights->contrat->lire) $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts');
+ if ($conf->propal->enabled && $user->rights->propal->lire) {
+ $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals');
+ }
+ if ($conf->commande->enabled && $user->rights->commande->lire) {
+ $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders');
+ }
+ if ($conf->facture->enabled && $user->rights->facture->lire) {
+ $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices');
+ }
+ if ($conf->contrat->enabled && $user->rights->contrat->lire) {
+ $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts');
+ }
}
-if ($conf->ficheinter->enabled && $user->rights->ficheinter->lire) $elementTypeArray['fichinter'] = $langs->transnoentitiesnoconv('Interventions');
+if ($conf->ficheinter->enabled && $user->rights->ficheinter->lire) {
+ $elementTypeArray['fichinter'] = $langs->transnoentitiesnoconv('Interventions');
+}
-if ($object->thirdparty->fournisseur)
-{
+if ($object->thirdparty->fournisseur) {
$thirdTypeArray['supplier'] = $langs->trans("supplier");
- if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) $elementTypeArray['supplier_invoice'] = $langs->transnoentitiesnoconv('SuppliersInvoices');
- if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) $elementTypeArray['supplier_order'] = $langs->transnoentitiesnoconv('SuppliersOrders');
+ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) {
+ $elementTypeArray['supplier_invoice'] = $langs->transnoentitiesnoconv('SuppliersInvoices');
+ }
+ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) {
+ $elementTypeArray['supplier_order'] = $langs->transnoentitiesnoconv('SuppliersOrders');
+ }
// There no contact type for supplier proposals
// if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $user->rights->supplier_proposal->lire) $elementTypeArray['supplier_proposal']=$langs->transnoentitiesnoconv('SupplierProposals');
@@ -166,8 +190,7 @@ print '
';
- if ($withdolfichehead) print dol_get_fiche_end();
+ if ($withdolfichehead) {
+ print dol_get_fiche_end();
+ }
print '';
print '
';
@@ -761,7 +761,9 @@ class FormTicket
// 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);
+ 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]);
@@ -782,23 +784,25 @@ class FormTicket
$formmail = new FormMail($this->db);
$addfileaction = 'addfile';
- if (!is_object($form)) $form = new Form($this->db);
+ if (!is_object($form)) {
+ $form = new Form($this->db);
+ }
// Load translation files required by the page
$langs->loadLangs(array('other', 'mails'));
// Clear temp files. Must be done at beginning, before call of triggers
- if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1'))
- {
+ if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) {
$this->clear_attached_files();
}
// Define output language
$outputlangs = $langs;
$newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $this->param['langsmodels'];
- if (!empty($newlang))
- {
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
+ $newlang = $this->param['langsmodels'];
+ }
+ if (!empty($newlang)) {
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
$outputlangs->load('other');
@@ -806,11 +810,9 @@ class FormTicket
// Get message template for $this->param["models"] into c_email_templates
$arraydefaultmessage = -1;
- if ($this->param['models'] != 'none')
- {
+ if ($this->param['models'] != 'none') {
$model_id = 0;
- if (array_key_exists('models_id', $this->param))
- {
+ if (array_key_exists('models_id', $this->param)) {
$model_id = $this->param["models_id"];
}
@@ -823,20 +825,23 @@ class FormTicket
$listofmimes = array();
$keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
- if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1'))
- {
- if (!empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit']))
- {
- foreach ($this->param['fileinit'] as $file)
- {
+ if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) {
+ if (!empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit'])) {
+ foreach ($this->param['fileinit'] as $file) {
$this->add_attached_files($file, basename($file), dol_mimetype($file));
}
}
}
- 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 (!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]);
+ }
// Define output language
$outputlangs = $langs;
@@ -902,8 +907,7 @@ class FormTicket
print '
';
// External users can't send message email
- if ($user->rights->ticket->write && !$user->socid)
- {
+ if ($user->rights->ticket->write && !$user->socid) {
print '';
$checkbox_selected = (GETPOST('send_email') == "1" ? ' checked' : '');
print ' ';
diff --git a/htdocs/core/class/html.formwebsite.class.php b/htdocs/core/class/html.formwebsite.class.php
index 8cbb7967415..9f1afab13f7 100644
--- a/htdocs/core/class/html.formwebsite.class.php
+++ b/htdocs/core/class/html.formwebsite.class.php
@@ -68,21 +68,17 @@ class FormWebsite
$sql .= " WHERE 1 = 1";
$sql .= " ORDER BY rowid";
$result = $this->db->query($sql);
- if ($result)
- {
+ if ($result) {
$out .= '';
- if ($useempty)
- {
+ if ($useempty) {
$out .= ' ';
}
$num = $this->db->num_rows($result);
$i = 0;
- while ($i < $num)
- {
+ while ($i < $num) {
$obj = $this->db->fetch_object($result);
- if ($selected == $obj->rowid)
- {
+ if ($selected == $obj->rowid) {
$out .= '';
} else {
$out .= ' ';
@@ -123,23 +119,18 @@ class FormWebsite
dol_syslog(get_class($this)."::selectTypeOfContainer", LOG_DEBUG);
$result = $this->db->query($sql);
- if ($result)
- {
+ if ($result) {
$num = $this->db->num_rows($result);
$i = 0;
- if ($num)
- {
+ if ($num) {
print '';
- if ($useempty == 1 || ($useempty == 2 && $num > 1))
- {
+ if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
print ' ';
}
- while ($i < $num)
- {
+ while ($i < $num) {
$obj = $this->db->fetch_object($result);
- if ($selected == $obj->rowid || $selected == $obj->code)
- {
+ if ($selected == $obj->rowid || $selected == $obj->code) {
print '';
} else {
print ' ';
@@ -149,7 +140,9 @@ class FormWebsite
$i++;
}
print " ";
- if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
+ if ($user->admin) {
+ print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
+ }
if ($addjscombo) {
print ajax_combobox('select'.$htmlname);
@@ -183,14 +176,14 @@ class FormWebsite
$arrayofsamples = array();
$arrayofsamples['empty'] = 'EmptyPage'; // Always this one first
- foreach ($listofsamples as $sample)
- {
+ foreach ($listofsamples as $sample) {
$reg = array();
- if (preg_match('/^page-sample-(.*)\.html$/', $sample['name'], $reg))
- {
+ if (preg_match('/^page-sample-(.*)\.html$/', $sample['name'], $reg)) {
$key = $reg[1];
$labelkey = ucfirst($key);
- if ($key == 'empty') $labelkey = 'EmptyPage';
+ if ($key == 'empty') {
+ $labelkey = 'EmptyPage';
+ }
$arrayofsamples[$key] = $labelkey;
}
}
@@ -198,15 +191,12 @@ class FormWebsite
$out = '';
$out .= '';
- if ($useempty == 1 || $useempty == 2)
- {
+ if ($useempty == 1 || $useempty == 2) {
$out .= ' ';
}
- foreach ($arrayofsamples as $key => $val)
- {
- if ($selected == $key)
- {
+ foreach ($arrayofsamples as $key => $val) {
+ if ($selected == $key) {
$out .= '';
} else {
$out .= ' ';
@@ -244,31 +234,34 @@ class FormWebsite
$atleastonepage = (is_array($website->lines) && count($website->lines) > 0);
$out = '';
- if ($atleastonepage && $action != 'editsource')
- {
+ if ($atleastonepage && $action != 'editsource') {
$out .= '';
} else {
$out .= '';
}
- if ($showempty || !$atleastonepage) $out .= ' ';
+ if ($showempty || !$atleastonepage) {
+ $out .= ' ';
+ }
- if ($atleastonepage)
- {
- if (empty($pageid) && $action != 'createcontainer') // Page id is not defined, we try to take one
- {
+ if ($atleastonepage) {
+ if (empty($pageid) && $action != 'createcontainer') { // Page id is not defined, we try to take one
$firstpageid = 0; $homepageid = 0;
- foreach ($website->lines as $key => $valpage)
- {
- if (empty($firstpageid)) $firstpageid = $valpage->id;
- if ($website->fk_default_home && $key == $website->fk_default_home) $homepageid = $valpage->id;
+ foreach ($website->lines as $key => $valpage) {
+ if (empty($firstpageid)) {
+ $firstpageid = $valpage->id;
+ }
+ if ($website->fk_default_home && $key == $website->fk_default_home) {
+ $homepageid = $valpage->id;
+ }
}
$pageid = $homepageid ? $homepageid : $firstpageid; // We choose home page and if not defined yet, we take first page
}
- foreach ($website->lines as $key => $valpage)
- {
- if (is_array($excludeids) && count($excludeids) && in_array($valpage->id, $excludeids)) continue;
+ foreach ($website->lines as $key => $valpage) {
+ if (is_array($excludeids) && count($excludeids) && in_array($valpage->id, $excludeids)) {
+ continue;
+ }
$valueforoption = '['.$valpage->type_container.' '.sprintf("%03d", $valpage->id).'] ';
$valueforoption .= $valpage->pageurl.' - '.$valpage->title;
@@ -283,7 +276,9 @@ class FormWebsite
}
$out .= ' 0 && $pageid == $key) $out .= ' selected'; // To preselect a value
+ if ($pageid > 0 && $pageid == $key) {
+ $out .= ' selected'; // To preselect a value
+ }
$out .= ' data-html="'.dol_escape_htmltag($valueforoption).'"';
$out .= '>';
$out .= $valueforoption;
@@ -294,8 +289,7 @@ class FormWebsite
}
$out .= ' ';
- if ($atleastonepage && $action != 'editsource')
- {
+ if ($atleastonepage && $action != 'editsource') {
$out .= ajax_combobox($htmlname);
} else {
$out .= ' ';
diff --git a/htdocs/core/class/infobox.class.php b/htdocs/core/class/infobox.class.php
index cedcebbd7cf..de44d238726 100644
--- a/htdocs/core/class/infobox.class.php
+++ b/htdocs/core/class/infobox.class.php
@@ -153,11 +153,13 @@ class InfoBox
$box->sourcefile = $relsourcefile;
$box->class = $boxname;
- if ($mode == 'activated' && !is_object($user)) // List of activated box was not yet personalized into database
- {
+ if ($mode == 'activated' && !is_object($user)) { // List of activated box was not yet personalized into database
if (is_numeric($box->box_order)) {
- if ($box->box_order % 2 == 1) $box->box_order = 'A'.$box->box_order;
- elseif ($box->box_order % 2 == 0) $box->box_order = 'B'.$box->box_order;
+ if ($box->box_order % 2 == 1) {
+ $box->box_order = 'A'.$box->box_order;
+ } elseif ($box->box_order % 2 == 0) {
+ $box->box_order = 'B'.$box->box_order;
+ }
}
}
// box_def properties
@@ -173,11 +175,12 @@ class InfoBox
$tmpenabled = 0; // $tmpenabled is used for the '|' test (OR)
foreach ($arrayelem as $module) {
$tmpmodule = preg_replace('/@[^@]+/', '', $module);
- if (!empty($conf->$tmpmodule->enabled)) $tmpenabled = 1;
+ if (!empty($conf->$tmpmodule->enabled)) {
+ $tmpenabled = 1;
+ }
//print $boxname.'-'.$module.'-module enabled='.(empty($conf->$tmpmodule->enabled)?0:1).' ';
}
- if (empty($tmpenabled)) // We found at least one module required that is disabled
- {
+ if (empty($tmpenabled)) { // We found at least one module required that is disabled
$enabled = 0;
break;
}
@@ -186,8 +189,11 @@ class InfoBox
//print '=>'.$boxname.'-enabled='.$enabled.' ';
//print 'xx module='.$module.' enabled='.$enabled;
- if ($enabled && ($includehidden || empty($box->hidden))) $boxes[] = $box;
- else unset($box);
+ if ($enabled && ($includehidden || empty($box->hidden))) {
+ $boxes[] = $box;
+ } else {
+ unset($box);
+ }
} else {
dol_syslog("Failed to load box '".$boxname."' into file '".$relsourcefile."'", LOG_WARNING);
}
@@ -222,7 +228,9 @@ class InfoBox
dol_syslog(get_class()."::saveboxorder zone=".$zone." userid=".$userid);
- if (!$userid || $userid == 0) return 0;
+ if (!$userid || $userid == 0) {
+ return 0;
+ }
$user = new User($db);
$user->id = $userid;
@@ -247,11 +255,9 @@ class InfoBox
dol_syslog(get_class()."::saveboxorder", LOG_DEBUG);
$result = $db->query($sql);
- if ($result)
- {
+ if ($result) {
$colonnes = explode('-', $boxorder);
- foreach ($colonnes as $collist)
- {
+ foreach ($colonnes as $collist) {
$part = explode(':', $collist);
$colonne = $part[0];
$list = $part[1];
@@ -259,10 +265,8 @@ class InfoBox
$i = 0;
$listarray = explode(',', $list);
- foreach ($listarray as $id)
- {
- if (is_numeric($id))
- {
+ foreach ($listarray as $id) {
+ if (is_numeric($id)) {
//dol_syslog("aaaaa".count($listarray));
$i++;
$ii = sprintf('%02d', $i);
@@ -290,8 +294,7 @@ class InfoBox
$error++;
}
- if ($error)
- {
+ if ($error) {
$db->rollback();
return -2;
} else {
diff --git a/htdocs/core/class/interfaces.class.php b/htdocs/core/class/interfaces.class.php
index 534d6b5803e..f442038c51d 100644
--- a/htdocs/core/class/interfaces.class.php
+++ b/htdocs/core/class/interfaces.class.php
@@ -69,19 +69,16 @@ class Interfaces
{
// phpcs:enable
// Check parameters
- if (!is_object($object) || !is_object($conf)) // Error
- {
+ if (!is_object($object) || !is_object($conf)) { // Error
$this->error = 'function run_triggers called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf);
dol_syslog(get_class($this).'::run_triggers '.$this->error, LOG_ERR);
$this->errors[] = $this->error;
return -1;
}
- if (!is_object($langs)) // Warning
- {
+ if (!is_object($langs)) { // Warning
dol_syslog(get_class($this).'::run_triggers was called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf), LOG_WARNING);
}
- if (!is_object($user)) // Warning
- {
+ if (!is_object($user)) { // Warning
dol_syslog(get_class($this).'::run_triggers was called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf), LOG_WARNING);
$user = new User($this->db);
}
@@ -96,24 +93,22 @@ class Interfaces
$dirtriggers = array_merge(array('/core/triggers'), $conf->modules_parts['triggers']);
- foreach ($dirtriggers as $reldir)
- {
+ foreach ($dirtriggers as $reldir) {
$dir = dol_buildpath($reldir, 0);
$newdir = dol_osencode($dir);
//print "xx".$dir;exit;
// Check if directory exists (we do not use dol_is_dir to avoir loading files.lib.php at each call)
- if (!is_dir($newdir)) continue;
+ if (!is_dir($newdir)) {
+ continue;
+ }
$handle = opendir($newdir);
- if (is_resource($handle))
- {
+ if (is_resource($handle)) {
$fullpathfiles = array();
- while (($file = readdir($handle)) !== false)
- {
+ while (($file = readdir($handle)) !== false) {
$reg = array();
- if (is_readable($newdir."/".$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php$/i', $file, $reg))
- {
+ if (is_readable($newdir."/".$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php$/i', $file, $reg)) {
$part1 = $reg[1];
$part2 = $reg[2];
$part3 = $reg[3];
@@ -121,26 +116,27 @@ class Interfaces
$nbfile++;
// Check if trigger file is disabled by name
- if (preg_match('/NORUN$/i', $file)) continue;
+ if (preg_match('/NORUN$/i', $file)) {
+ continue;
+ }
// Check if trigger file is for a particular module
$qualified = true;
- if (strtolower($reg[2]) != 'all')
- {
+ if (strtolower($reg[2]) != 'all') {
$module = preg_replace('/^mod/i', '', $reg[2]);
$constparam = 'MAIN_MODULE_'.strtoupper($module);
- if (empty($conf->global->$constparam)) $qualified = false;
+ if (empty($conf->global->$constparam)) {
+ $qualified = false;
+ }
}
- if (!$qualified)
- {
+ if (!$qualified) {
//dol_syslog(get_class($this)."::run_triggers action=".$action." Triggers for file '".$file."' need module to be enabled", LOG_DEBUG);
continue;
}
$modName = "Interface".ucfirst($reg[3]);
//print "file=$file - modName=$modName\n";
- if (in_array($modName, $modules)) // $modules = list of modName already loaded
- {
+ if (in_array($modName, $modules)) { // $modules = list of modName already loaded
$langs->load("errors");
dol_syslog(get_class($this)."::run_triggers action=".$action." ".$langs->trans("ErrorDuplicateTrigger", $newdir."/".$file, $fullpathfiles[$modName]), LOG_WARNING);
continue;
@@ -150,8 +146,7 @@ class Interfaces
//print 'Todo for '.$modName." : ".$newdir.'/'.$file."\n";
include_once $newdir.'/'.$file;
//print 'Done for '.$modName."\n";
- } catch (Exception $e)
- {
+ } catch (Exception $e) {
dol_syslog('ko for '.$modName." ".$e->getMessage()."\n", LOG_ERR);
}
@@ -171,14 +166,14 @@ class Interfaces
asort($orders);
// Loop on each trigger
- foreach ($orders as $key => $value)
- {
+ foreach ($orders as $key => $value) {
$modName = $modules[$key];
- if (empty($modName)) continue;
+ if (empty($modName)) {
+ continue;
+ }
$objMod = new $modName($this->db);
- if ($objMod)
- {
+ if ($objMod) {
$dblevelbefore = $this->db->transaction_opened;
$result = 0;
@@ -202,25 +197,25 @@ class Interfaces
$result = -1;
}
- if ($result > 0)
- {
+ if ($result > 0) {
// Action OK
$nbtotal++;
$nbok++;
}
- if ($result == 0)
- {
+ if ($result == 0) {
// Aucune action faite
$nbtotal++;
}
- if ($result < 0)
- {
+ if ($result < 0) {
// Action KO
//dol_syslog("Error in trigger ".$action." - result = ".$result." - Nb of error string returned = ".count($objMod->errors), LOG_ERR);
$nbtotal++;
$nbko++;
- if (!empty($objMod->errors)) $this->errors = array_merge($this->errors, $objMod->errors);
- elseif (!empty($objMod->error)) $this->errors[] = $objMod->error;
+ if (!empty($objMod->errors)) {
+ $this->errors = array_merge($this->errors, $objMod->errors);
+ } elseif (!empty($objMod->error)) {
+ $this->errors[] = $objMod->error;
+ }
//dol_syslog("Error in trigger ".$action." - Nb of error string returned = ".count($this->errors), LOG_ERR);
}
} else {
@@ -228,8 +223,7 @@ class Interfaces
}
}
- if ($nbko)
- {
+ if ($nbko) {
dol_syslog(get_class($this)."::run_triggers action=".$action." Files found: ".$nbfile.", Files launched: ".$nbtotal.", Done: ".$nbok.", Failed: ".$nbko." - Nb of error string returned in this->errors = ".count($this->errors), LOG_ERR);
return -$nbko;
} else {
@@ -258,28 +252,27 @@ class Interfaces
$i = 0;
$dirtriggers = array_merge(array('/core/triggers/'), $conf->modules_parts['triggers']);
- if (is_array($forcedirtriggers))
- {
+ if (is_array($forcedirtriggers)) {
$dirtriggers = $forcedirtriggers;
}
- foreach ($dirtriggers as $reldir)
- {
+ foreach ($dirtriggers as $reldir) {
$dir = dol_buildpath($reldir, 0);
$newdir = dol_osencode($dir);
// Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php at each call)
- if (!is_dir($newdir)) continue;
+ if (!is_dir($newdir)) {
+ continue;
+ }
$handle = opendir($newdir);
- if (is_resource($handle))
- {
- while (($file = readdir($handle)) !== false)
- {
+ if (is_resource($handle)) {
+ while (($file = readdir($handle)) !== false) {
$reg = array();
- if (is_readable($newdir.'/'.$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/', $file, $reg))
- {
- if (preg_match('/\.back$/', $file)) continue;
+ if (is_readable($newdir.'/'.$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/', $file, $reg)) {
+ if (preg_match('/\.back$/', $file)) {
+ continue;
+ }
$part1 = $reg[1];
$part2 = $reg[2];
@@ -287,8 +280,7 @@ class Interfaces
$modName = 'Interface'.ucfirst($reg[3]);
//print "file=$file"; print "modName=$modName"; exit;
- if (in_array($modName, $modules))
- {
+ if (in_array($modName, $modules)) {
$langs->load("errors");
print ''.$langs->trans("Error").' : '.$langs->trans("ErrorDuplicateTrigger", $modName, "/htdocs/core/triggers/").'
';
} else {
@@ -315,13 +307,13 @@ class Interfaces
$j = 0;
// Loop on each trigger
- foreach ($orders as $key => $value)
- {
+ foreach ($orders as $key => $value) {
$modName = $modules[$key];
- if (empty($modName)) continue;
+ if (empty($modName)) {
+ continue;
+ }
- if (!class_exists($modName))
- {
+ if (!class_exists($modName)) {
print 'Error: A trigger file was found but its class "'.$modName.'" was not found.'." \n";
continue;
}
@@ -331,22 +323,25 @@ class Interfaces
try {
$objMod = new $modName($db);
- if (is_subclass_of($objMod, 'DolibarrTriggers'))
- {
+ if (is_subclass_of($objMod, 'DolibarrTriggers')) {
// Define disabledbyname and disabledbymodule
$disabledbyname = 0;
$disabledbymodule = 1;
$module = '';
// Check if trigger file is disabled by name
- if (preg_match('/NORUN$/i', $files[$key])) $disabledbyname = 1;
+ if (preg_match('/NORUN$/i', $files[$key])) {
+ $disabledbyname = 1;
+ }
// Check if trigger file is for a particular module
- if (preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/i', $files[$key], $reg))
- {
+ if (preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/i', $files[$key], $reg)) {
$module = preg_replace('/^mod/i', '', $reg[2]);
$constparam = 'MAIN_MODULE_'.strtoupper($module);
- if (strtolower($module) == 'all') $disabledbymodule = 0;
- elseif (empty($conf->global->$constparam)) $disabledbymodule = 2;
+ if (strtolower($module) == 'all') {
+ $disabledbymodule = 0;
+ } elseif (empty($conf->global->$constparam)) {
+ $disabledbymodule = 2;
+ }
$triggers[$j]['module'] = strtolower($module);
}
@@ -358,19 +353,28 @@ class Interfaces
$triggers[$j]['iscoreorexternal'] = $iscoreorexternal[$key];
$triggers[$j]['version'] = $objMod->getVersion();
$triggers[$j]['status'] = img_picto($langs->trans("Active"), 'tick');
- if ($disabledbyname > 0 || $disabledbymodule > 1) $triggers[$j]['status'] = '';
+ if ($disabledbyname > 0 || $disabledbymodule > 1) {
+ $triggers[$j]['status'] = '';
+ }
$text = ''.$langs->trans("Description").': ';
$text .= $objMod->getDesc().' ';
$text .= ''.$langs->trans("Status").': ';
- if ($disabledbyname == 1)
- {
+ if ($disabledbyname == 1) {
$text .= $langs->trans("TriggerDisabledByName").' ';
- if ($disabledbymodule == 2) $text .= $langs->trans("TriggerDisabledAsModuleDisabled", $module).' ';
+ if ($disabledbymodule == 2) {
+ $text .= $langs->trans("TriggerDisabledAsModuleDisabled", $module).' ';
+ }
} else {
- if ($disabledbymodule == 0) $text .= $langs->trans("TriggerAlwaysActive").' ';
- if ($disabledbymodule == 1) $text .= $langs->trans("TriggerActiveAsModuleActive", $module).' ';
- if ($disabledbymodule == 2) $text .= $langs->trans("TriggerDisabledAsModuleDisabled", $module).' ';
+ if ($disabledbymodule == 0) {
+ $text .= $langs->trans("TriggerAlwaysActive").' ';
+ }
+ if ($disabledbymodule == 1) {
+ $text .= $langs->trans("TriggerActiveAsModuleActive", $module).' ';
+ }
+ if ($disabledbymodule == 2) {
+ $text .= $langs->trans("TriggerDisabledAsModuleDisabled", $module).' ';
+ }
}
} else {
print 'Error: Trigger '.$modName.' does not extends DolibarrTriggers ';
diff --git a/htdocs/core/class/ldap.class.php b/htdocs/core/class/ldap.class.php
index 1bd25e123a3..9963a178d1b 100644
--- a/htdocs/core/class/ldap.class.php
+++ b/htdocs/core/class/ldap.class.php
@@ -122,8 +122,12 @@ class Ldap
global $conf;
// Server
- if (!empty($conf->global->LDAP_SERVER_HOST)) $this->server[] = $conf->global->LDAP_SERVER_HOST;
- if (!empty($conf->global->LDAP_SERVER_HOST_SLAVE)) $this->server[] = $conf->global->LDAP_SERVER_HOST_SLAVE;
+ if (!empty($conf->global->LDAP_SERVER_HOST)) {
+ $this->server[] = $conf->global->LDAP_SERVER_HOST;
+ }
+ if (!empty($conf->global->LDAP_SERVER_HOST_SLAVE)) {
+ $this->server[] = $conf->global->LDAP_SERVER_HOST_SLAVE;
+ }
$this->serverPort = $conf->global->LDAP_SERVER_PORT;
$this->ldapProtocolVersion = $conf->global->LDAP_SERVER_PROTOCOLVERSION;
$this->dn = $conf->global->LDAP_SERVER_DN;
@@ -170,39 +174,38 @@ class Ldap
$this->bind = 0;
// Check parameters
- if (count($this->server) == 0 || empty($this->server[0]))
- {
+ if (count($this->server) == 0 || empty($this->server[0])) {
$this->error = 'LDAP setup (file conf.php) is not complete';
dol_syslog(get_class($this)."::connect_bind ".$this->error, LOG_WARNING);
return -1;
}
- if (!function_exists("ldap_connect"))
- {
+ if (!function_exists("ldap_connect")) {
$this->error = 'LDAPFunctionsNotAvailableOnPHP';
dol_syslog(get_class($this)."::connect_bind ".$this->error, LOG_WARNING);
$return = -1;
}
- if (empty($this->error))
- {
+ if (empty($this->error)) {
// Loop on each ldap server
- foreach ($this->server as $host)
- {
- if ($connected) break;
- if (empty($host)) continue;
+ foreach ($this->server as $host) {
+ if ($connected) {
+ break;
+ }
+ if (empty($host)) {
+ continue;
+ }
if ($this->serverPing($host, $this->serverPort) === true) {
$this->connection = ldap_connect($host, $this->serverPort);
- } else continue;
+ } else {
+ continue;
+ }
- if (is_resource($this->connection))
- {
+ if (is_resource($this->connection)) {
// Begin TLS if requested by the configuration
- if (!empty($conf->global->LDAP_SERVER_USE_TLS))
- {
- if (!ldap_start_tls($this->connection))
- {
+ if (!empty($conf->global->LDAP_SERVER_USE_TLS)) {
+ if (!ldap_start_tls($this->connection)) {
dol_syslog(get_class($this)."::connect_bind failed to start tls", LOG_WARNING);
$connected = 0;
$this->close();
@@ -214,13 +217,11 @@ class Ldap
ldap_set_option($this->connection, LDAP_OPT_SIZELIMIT, 0); // no limit here. should return true.
- if ($this->serverType == "activedirectory")
- {
+ if ($this->serverType == "activedirectory") {
$result = $this->setReferrals();
dol_syslog(get_class($this)."::connect_bind try bindauth for activedirectory on ".$host." user=".$this->searchUser." password=".preg_replace('/./', '*', $this->searchPassword), LOG_DEBUG);
$this->result = $this->bindauth($this->searchUser, $this->searchPassword);
- if ($this->result)
- {
+ if ($this->result) {
$this->bind = $this->result;
$connected = 2;
break;
@@ -229,12 +230,10 @@ class Ldap
}
} else {
// Try in auth mode
- if ($this->searchUser && $this->searchPassword)
- {
+ if ($this->searchUser && $this->searchPassword) {
dol_syslog(get_class($this)."::connect_bind try bindauth on ".$host." user=".$this->searchUser." password=".preg_replace('/./', '*', $this->searchPassword), LOG_DEBUG);
$this->result = $this->bindauth($this->searchUser, $this->searchPassword);
- if ($this->result)
- {
+ if ($this->result) {
$this->bind = $this->result;
$connected = 2;
break;
@@ -243,12 +242,10 @@ class Ldap
}
}
// Try in anonymous
- if (!$this->bind)
- {
+ if (!$this->bind) {
dol_syslog(get_class($this)."::connect_bind try bind on ".$host, LOG_DEBUG);
$result = $this->bind();
- if ($result)
- {
+ if ($result) {
$this->bind = $this->result;
$connected = 1;
break;
@@ -259,12 +256,13 @@ class Ldap
}
}
- if (!$connected) $this->close();
+ if (!$connected) {
+ $this->close();
+ }
}
}
- if ($connected)
- {
+ if ($connected) {
$return = $connected;
dol_syslog(get_class($this)."::connect_bind return=".$return, LOG_DEBUG);
} else {
@@ -285,8 +283,7 @@ class Ldap
*/
public function close()
{
- if ($this->connection && !@ldap_close($this->connection))
- {
+ if ($this->connection && !@ldap_close($this->connection)) {
return false;
} else {
return true;
@@ -301,8 +298,7 @@ class Ldap
*/
public function bind()
{
- if (!$this->result = @ldap_bind($this->connection))
- {
+ if (!$this->result = @ldap_bind($this->connection)) {
$this->ldapErrorCode = ldap_errno($this->connection);
$this->ldapErrorText = ldap_error($this->connection);
$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
@@ -324,8 +320,7 @@ class Ldap
*/
public function bindauth($bindDn, $pass)
{
- if (!$this->result = @ldap_bind($this->connection, $bindDn, $pass))
- {
+ if (!$this->result = @ldap_bind($this->connection, $bindDn, $pass)) {
$this->ldapErrorCode = ldap_errno($this->connection);
$this->ldapErrorText = ldap_error($this->connection);
$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
@@ -342,8 +337,7 @@ class Ldap
*/
public function unbind()
{
- if (!$this->result = @ldap_unbind($this->connection))
- {
+ if (!$this->result = @ldap_unbind($this->connection)) {
return false;
} else {
return true;
@@ -402,22 +396,21 @@ class Ldap
dol_syslog(get_class($this)."::add dn=".$dn." info=".join(',', $info));
// Check parameters
- if (!$this->connection)
- {
+ if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
- if (!$this->bind)
- {
+ if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
// Encode to LDAP page code
$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
- foreach ($info as $key => $val)
- {
- if (!is_array($val)) $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
+ foreach ($info as $key => $val) {
+ if (!is_array($val)) {
+ $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
+ }
}
$this->dump($dn, $info);
@@ -425,8 +418,7 @@ class Ldap
//print_r($info);
$result = @ldap_add($this->connection, $dn, $info);
- if ($result)
- {
+ if ($result) {
dol_syslog(get_class($this)."::add successfull", LOG_DEBUG);
return 1;
} else {
@@ -452,22 +444,21 @@ class Ldap
dol_syslog(get_class($this)."::modify dn=".$dn." info=".join(',', $info));
// Check parameters
- if (!$this->connection)
- {
+ if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
- if (!$this->bind)
- {
+ if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
// Encode to LDAP page code
$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
- foreach ($info as $key => $val)
- {
- if (!is_array($val)) $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
+ foreach ($info as $key => $val) {
+ if (!is_array($val)) {
+ $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
+ }
}
$this->dump($dn, $info);
@@ -480,8 +471,7 @@ class Ldap
}
$result = @ldap_modify($this->connection, $dn, $info);
- if ($result)
- {
+ if ($result) {
dol_syslog(get_class($this)."::modify successfull", LOG_DEBUG);
return 1;
} else {
@@ -507,13 +497,11 @@ class Ldap
dol_syslog(get_class($this)."::modify dn=".$dn." newrdn=".$newrdn." newparent=".$newparent." deleteoldrdn=".($deleteoldrdn ? 1 : 0));
// Check parameters
- if (!$this->connection)
- {
+ if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
- if (!$this->bind)
- {
+ if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
@@ -526,8 +514,7 @@ class Ldap
//print_r($info);
$result = @ldap_rename($this->connection, $dn, $newrdn, $newparent, $deleteoldrdn);
- if ($result)
- {
+ if ($result) {
dol_syslog(get_class($this)."::rename successfull", LOG_DEBUG);
return 1;
} else {
@@ -554,36 +541,33 @@ class Ldap
dol_syslog(get_class($this)."::update dn=".$dn." olddn=".$olddn);
// Check parameters
- if (!$this->connection)
- {
+ if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
- if (!$this->bind)
- {
+ if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
- if (!$olddn || $olddn != $dn)
- {
- if (!empty($olddn) && !empty($newrdn) && !empty($newparent) && $this->ldapProtocolVersion === '3')
- {
+ if (!$olddn || $olddn != $dn) {
+ if (!empty($olddn) && !empty($newrdn) && !empty($newparent) && $this->ldapProtocolVersion === '3') {
// This function currently only works with LDAPv3
$result = $this->rename($olddn, $newrdn, $newparent, $user, true);
$result = $this->modify($dn, $info, $user); // We force "modify" for avoid some fields not modify
} else {
// If change we make is rename the key of LDAP record, we create new one and if ok, we delete old one.
$result = $this->add($dn, $info, $user);
- if ($result > 0 && $olddn && $olddn != $dn) $result = $this->delete($olddn); // If add fails, we do not try to delete old one
+ if ($result > 0 && $olddn && $olddn != $dn) {
+ $result = $this->delete($olddn); // If add fails, we do not try to delete old one
+ }
}
} else {
//$result = $this->delete($olddn);
$result = $this->add($dn, $info, $user); // If record has been deleted from LDAP, we recreate it. We ignore error if it already exists.
$result = $this->modify($dn, $info, $user); // We use add/modify instead of delete/add when olddn is received
}
- if ($result <= 0)
- {
+ if ($result <= 0) {
$this->error = ldap_error($this->connection).' (Code '.ldap_errno($this->connection).") ".$this->error;
dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
//print_r($info);
@@ -607,13 +591,11 @@ class Ldap
dol_syslog(get_class($this)."::delete Delete LDAP entry dn=".$dn);
// Check parameters
- if (!$this->connection)
- {
+ if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
- if (!$this->bind)
- {
+ if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
@@ -623,7 +605,9 @@ class Ldap
$result = @ldap_delete($this->connection, $dn);
- if ($result) return 1;
+ if ($result) {
+ return 1;
+ }
return -1;
}
@@ -641,8 +625,7 @@ class Ldap
$content = '';
// Create file content
- if (preg_match('/^ldap/', $this->server[0]))
- {
+ if (preg_match('/^ldap/', $this->server[0])) {
$target = "-H ".join(',', $this->server);
} else {
$target = "-h ".join(',', $this->server)." -p ".$this->serverPort;
@@ -650,16 +633,15 @@ class Ldap
$content .= "# ldapadd $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
$content .= "# ldapmodify $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
$content .= "# ldapdelete $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
- if (in_array('localhost', $this->server)) $content .= "# If commands fails to connect, try without -h and -p\n";
+ if (in_array('localhost', $this->server)) {
+ $content .= "# If commands fails to connect, try without -h and -p\n";
+ }
$content .= "dn: ".$dn."\n";
- foreach ($info as $key => $value)
- {
- if (!is_array($value))
- {
+ foreach ($info as $key => $value) {
+ if (!is_array($value)) {
$content .= "$key: $value\n";
} else {
- foreach ($value as $valuevalue)
- {
+ foreach ($value as $valuevalue) {
$content .= "$key: $valuevalue\n";
}
}
@@ -686,12 +668,12 @@ class Ldap
$outputfile = $conf->ldap->dir_temp.'/ldapinput.in';
$fp = fopen($outputfile, "w");
- if ($fp)
- {
+ if ($fp) {
fputs($fp, $content);
fclose($fp);
- if (!empty($conf->global->MAIN_UMASK))
- @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
+ if (!empty($conf->global->MAIN_UMASK)) {
+ @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
+ }
return 1;
} else {
return -1;
@@ -717,8 +699,9 @@ class Ldap
$host = $regs[1];
}
$op = @fsockopen($host, $port, $errno, $errstr, $timeout);
- if (!$op) return false; //DC is N/A
- else {
+ if (!$op) {
+ return false; //DC is N/A
+ } else {
fclose($op); //explicitly close open socket connection
return true; //DC is up & running, we can safely connect with ldap_connect
}
@@ -741,22 +724,21 @@ class Ldap
dol_syslog(get_class($this)."::addAttribute dn=".$dn." info=".join(',', $info));
// Check parameters
- if (!$this->connection)
- {
+ if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
- if (!$this->bind)
- {
+ if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
// Encode to LDAP page code
$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
- foreach ($info as $key => $val)
- {
- if (!is_array($val)) $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
+ foreach ($info as $key => $val) {
+ if (!is_array($val)) {
+ $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
+ }
}
$this->dump($dn, $info);
@@ -764,8 +746,7 @@ class Ldap
//print_r($info);
$result = @ldap_mod_add($this->connection, $dn, $info);
- if ($result)
- {
+ if ($result) {
dol_syslog(get_class($this)."::add_attribute successfull", LOG_DEBUG);
return 1;
} else {
@@ -789,22 +770,21 @@ class Ldap
dol_syslog(get_class($this)."::updateAttribute dn=".$dn." info=".join(',', $info));
// Check parameters
- if (!$this->connection)
- {
+ if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
- if (!$this->bind)
- {
+ if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
// Encode to LDAP page code
$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
- foreach ($info as $key => $val)
- {
- if (!is_array($val)) $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
+ foreach ($info as $key => $val) {
+ if (!is_array($val)) {
+ $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
+ }
}
$this->dump($dn, $info);
@@ -812,8 +792,7 @@ class Ldap
//print_r($info);
$result = @ldap_mod_replace($this->connection, $dn, $info);
- if ($result)
- {
+ if ($result) {
dol_syslog(get_class($this)."::updateAttribute successfull", LOG_DEBUG);
return 1;
} else {
@@ -837,22 +816,21 @@ class Ldap
dol_syslog(get_class($this)."::deleteAttribute dn=".$dn." info=".join(',', $info));
// Check parameters
- if (!$this->connection)
- {
+ if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
- if (!$this->bind)
- {
+ if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
// Encode to LDAP page code
$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
- foreach ($info as $key => $val)
- {
- if (!is_array($val)) $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
+ foreach ($info as $key => $val) {
+ if (!is_array($val)) {
+ $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
+ }
}
$this->dump($dn, $info);
@@ -860,8 +838,7 @@ class Ldap
//print_r($info);
$result = @ldap_mod_del($this->connection, $dn, $info);
- if ($result)
- {
+ if ($result) {
dol_syslog(get_class($this)."::deleteAttribute successfull", LOG_DEBUG);
return 1;
} else {
@@ -881,13 +858,11 @@ class Ldap
public function getAttribute($dn, $filter)
{
// Check parameters
- if (!$this->connection)
- {
+ if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
- if (!$this->bind)
- {
+ if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
@@ -897,16 +872,14 @@ class Ldap
// Only one entry should ever be returned
$entry = ldap_first_entry($this->connection, $search);
- if (!$entry)
- {
+ if (!$entry) {
$this->ldapErrorCode = -1;
$this->ldapErrorText = "Couldn't find entry";
return 0; // Couldn't find entry...
}
// Get values
- if (!($values = ldap_get_attributes($this->connection, $entry)))
- {
+ if (!($values = ldap_get_attributes($this->connection, $entry))) {
$this->ldapErrorCode = ldap_errno($this->connection);
$this->ldapErrorText = ldap_error($this->connection);
return 0; // No matching attributes
@@ -937,16 +910,14 @@ class Ldap
// Only one entry should ever be returned (no user will have the same uid)
$entry = ldap_first_entry($this->connection, $this->result);
- if (!$entry)
- {
+ if (!$entry) {
$this->ldapErrorCode = -1;
$this->ldapErrorText = "Couldn't find user";
return false; // Couldn't find the user...
}
// Get values
- if (!$values = @ldap_get_values($this->connection, $entry, $attribute))
- {
+ if (!$values = @ldap_get_values($this->connection, $entry, $attribute)) {
$this->ldapErrorCode = ldap_errno($this->connection);
$this->ldapErrorText = ldap_error($this->connection);
return false; // No matching attributes
@@ -975,15 +946,13 @@ class Ldap
dol_syslog(get_class($this)."::getRecords search=".$search." userDn=".$userDn." useridentifier=".$useridentifier." attributeArray=array(".join(',', $attributeArray).") activefilter=".$activefilter);
// if the directory is AD, then bind first with the search user first
- if ($this->serverType == "activedirectory")
- {
+ if ($this->serverType == "activedirectory") {
$this->bindauth($this->searchUser, $this->searchPassword);
dol_syslog(get_class($this)."::bindauth serverType=activedirectory searchUser=".$this->searchUser);
}
// Define filter
- if (!empty($activefilter))
- {
+ if (!empty($activefilter)) {
if (((string) $activefilter == '1' || (string) $activefilter == 'user') && $this->filter) {
$filter = '('.$this->filter.')';
} elseif (((string) $activefilter == 'member') && $this->filter) {
@@ -996,8 +965,7 @@ class Ldap
$filter = '('.$useridentifier.'='.$search.')';
}
- if (is_array($attributeArray))
- {
+ if (is_array($attributeArray)) {
// Return list with required fields
$attributeArray = array_values($attributeArray); // This is to force to have index reordered from 0 (not make ldap_search fails)
dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter." attributeArray=(".join(',', $attributeArray).")");
@@ -1008,8 +976,7 @@ class Ldap
dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter);
$this->result = @ldap_search($this->connection, $userDn, $filter);
}
- if (!$this->result)
- {
+ if (!$this->result) {
$this->error = 'LDAP search failed: '.ldap_errno($this->connection)." ".ldap_error($this->connection);
return -1;
}
@@ -1020,24 +987,20 @@ class Ldap
// a ldap_search en majuscule !!!
//print_r($info);
- for ($i = 0; $i < $info["count"]; $i++)
- {
+ for ($i = 0; $i < $info["count"]; $i++) {
$recordid = $this->convToOutputCharset($info[$i][$useridentifier][0], $this->ldapcharset);
- if ($recordid)
- {
+ if ($recordid) {
//print "Found record with key $useridentifier=".$recordid." \n";
$fulllist[$recordid][$useridentifier] = $recordid;
// Add to the array for each attribute in my list
$num = count($attributeArray);
- for ($j = 0; $j < $num; $j++)
- {
+ for ($j = 0; $j < $num; $j++) {
$keyattributelower = strtolower($attributeArray[$j]);
//print " Param ".$attributeArray[$j]."=".$info[$i][$keyattributelower][0]." \n";
//permet de recuperer le SID avec Active Directory
- if ($this->serverType == "activedirectory" && $keyattributelower == "objectsid")
- {
+ if ($this->serverType == "activedirectory" && $keyattributelower == "objectsid") {
$objectsid = $this->getObjectSid($recordid);
$fulllist[$recordid][$attributeArray[$j]] = $objectsid;
} else {
@@ -1089,28 +1052,24 @@ class Ldap
$justthese = array("objectsid");
// if the directory is AD, then bind first with the search user first
- if ($this->serverType == "activedirectory")
- {
+ if ($this->serverType == "activedirectory") {
$this->bindauth($this->searchUser, $this->searchPassword);
}
$i = 0;
$searchDN = $this->people;
- while ($i <= 2)
- {
+ while ($i <= 2) {
$ldapSearchResult = @ldap_search($this->connection, $searchDN, $criteria, $justthese);
- if (!$ldapSearchResult)
- {
+ if (!$ldapSearchResult) {
$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
return -1;
}
$entry = ldap_first_entry($this->connection, $ldapSearchResult);
- if (!$entry)
- {
+ if (!$entry) {
// Si pas de resultat on cherche dans le domaine
$searchDN = $this->domain;
$i++;
@@ -1120,8 +1079,7 @@ class Ldap
}
}
- if ($entry)
- {
+ if ($entry) {
$ldapBinary = ldap_get_values_len($this->connection, $entry, "objectsid");
$SIDText = $this->binSIDtoText($ldapBinary[0]);
return $SIDText;
@@ -1145,8 +1103,7 @@ class Ldap
$subcount = hexdec(substr($hex_sid, 2, 2)); // Get count of sub-auth entries
$auth = hexdec(substr($hex_sid, 4, 12)); // SECURITY_NT_AUTHORITY
$result = "$rev-$auth";
- for ($x = 0; $x < $subcount; $x++)
- {
+ for ($x = 0; $x < $subcount; $x++) {
$result .= "-".hexdec($this->littleEndian(substr($hex_sid, 16 + ($x * 8), 8))); // get all SECURITY_NT_AUTHORITY
}
return $result;
@@ -1179,8 +1136,7 @@ class Ldap
$this->result = @ldap_search($this->connection, $checkDn, $filter);
$result = @ldap_get_entries($this->connection, $this->result);
- if (!$result)
- {
+ if (!$result) {
$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
return -1;
} else {
@@ -1211,15 +1167,16 @@ class Ldap
$result = '';
$i = 0;
- while ($i <= 2)
- {
+ while ($i <= 2) {
dol_syslog(get_class($this)."::fetch search with searchDN=".$searchDN." filter=".$filter);
$this->result = @ldap_search($this->connection, $searchDN, $filter);
- if ($this->result)
- {
+ if ($this->result) {
$result = @ldap_get_entries($this->connection, $this->result);
- if ($result['count'] > 0) dol_syslog('Ldap::fetch search found '.$result['count'].' records');
- else dol_syslog('Ldap::fetch search returns but found no records');
+ if ($result['count'] > 0) {
+ dol_syslog('Ldap::fetch search found '.$result['count'].' records');
+ } else {
+ dol_syslog('Ldap::fetch search returns but found no records');
+ }
//var_dump($result);exit;
} else {
$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
@@ -1227,8 +1184,7 @@ class Ldap
return -1;
}
- if (!$result)
- {
+ if (!$result) {
// Si pas de resultat on cherche dans le domaine
$searchDN = $this->domain;
$i++;
@@ -1237,8 +1193,7 @@ class Ldap
}
}
- if (!$result)
- {
+ if (!$result) {
$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
return -1;
} else {
@@ -1252,13 +1207,14 @@ class Ldap
$this->mobile = $this->convToOutputCharset($result[0][$this->attr_mobile][0], $this->ldapcharset);
$this->uacf = $this->parseUACF($this->convToOutputCharset($result[0]["useraccountcontrol"][0], $this->ldapcharset));
- if (isset($result[0]["pwdlastset"][0])) // If expiration on password exists
- {
+ if (isset($result[0]["pwdlastset"][0])) { // If expiration on password exists
$this->pwdlastset = ($result[0]["pwdlastset"][0] != 0) ? $this->convert_time($this->convToOutputCharset($result[0]["pwdlastset"][0], $this->ldapcharset)) : 0;
} else {
$this->pwdlastset = -1;
}
- if (!$this->name && !$this->login) $this->pwdlastset = -1;
+ if (!$this->name && !$this->login) {
+ $this->pwdlastset = -1;
+ }
$this->badpwdtime = $this->convert_time($this->convToOutputCharset($result[0]["badpasswordtime"][0], $this->ldapcharset));
// FQDN domain
@@ -1364,7 +1320,9 @@ class Ldap
break;
}
}
- if (empty($retval)) $retval = "UNKNOWN_TYPE_".$samtype;
+ if (empty($retval)) {
+ $retval = "UNKNOWN_TYPE_".$samtype;
+ }
return($retval);
}
@@ -1397,8 +1355,12 @@ class Ldap
private function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
{
global $conf;
- if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') $str = utf8_encode($str);
- if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') $str = utf8_decode($str);
+ if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') {
+ $str = utf8_encode($str);
+ }
+ if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') {
+ $str = utf8_decode($str);
+ }
return $str;
}
@@ -1412,8 +1374,12 @@ class Ldap
public function convFromOutputCharset($str, $pagecodeto = 'UTF-8')
{
global $conf;
- if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') $str = utf8_decode($str);
- if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') $str = utf8_encode($str);
+ if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') {
+ $str = utf8_decode($str);
+ }
+ if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') {
+ $str = utf8_encode($str);
+ }
return $str;
}
@@ -1428,16 +1394,16 @@ class Ldap
{
global $conf;
- if (empty($keygroup)) $keygroup = 'LDAP_KEY_GROUPS';
+ if (empty($keygroup)) {
+ $keygroup = 'LDAP_KEY_GROUPS';
+ }
$search = '('.$conf->global->$keygroup.'=*)';
$result = $this->search($this->groups, $search);
- if ($result)
- {
+ if ($result) {
$c = $result['count'];
$gids = array();
- for ($i = 0; $i < $c; $i++)
- {
+ for ($i = 0; $i < $c; $i++) {
$gids[] = $result[$i]['gidnumber'][0];
}
rsort($gids);
diff --git a/htdocs/core/class/lessc.class.php b/htdocs/core/class/lessc.class.php
index b85cfc3f399..73007db9363 100644
--- a/htdocs/core/class/lessc.class.php
+++ b/htdocs/core/class/lessc.class.php
@@ -35,7 +35,8 @@
* The `lessc_formatter` takes a CSS tree, and dumps it to a formatted string,
* handling things like indentation.
*/
-class Lessc {
+class Lessc
+{
public static $VERSION = "v0.5.0";
public static $TRUE = array("keyword", "true");
@@ -64,7 +65,8 @@ class Lessc {
protected static $nextImportId = 0; // uniquely identify imports
// attempts to find the path of an import url, returns null for css files
- protected function findImport($url) {
+ protected function findImport($url)
+ {
foreach ((array) $this->importDir as $dir) {
$full = $dir.(substr($dir, -1) != '/' ? '/' : '').$url;
if ($this->fileExists($file = $full.'.less') || $this->fileExists($file = $full)) {
@@ -81,35 +83,48 @@ class Lessc {
* @param string $name Filename
* @return boolean
*/
- protected function fileExists($name) {
+ protected function fileExists($name)
+ {
return is_file($name);
}
- public static function compressList($items, $delim) {
- if (!isset($items[1]) && isset($items[0])) return $items[0];
- else return array('list', $delim, $items);
+ public static function compressList($items, $delim)
+ {
+ if (!isset($items[1]) && isset($items[0])) {
+ return $items[0];
+ } else {
+ return array('list', $delim, $items);
+ }
}
- public static function preg_quote($what) {
+ public static function preg_quote($what)
+ {
return preg_quote($what, '/');
}
- protected function tryImport($importPath, $parentBlock, $out) {
+ protected function tryImport($importPath, $parentBlock, $out)
+ {
if ($importPath[0] == "function" && $importPath[1] == "url") {
$importPath = $this->flattenList($importPath[2]);
}
$str = $this->coerceString($importPath);
- if ($str === null) return false;
+ if ($str === null) {
+ return false;
+ }
$url = $this->compileValue($this->lib_e($str));
// don't import if it ends in css
- if (substr_compare($url, '.css', -4, 4) === 0) return false;
+ if (substr_compare($url, '.css', -4, 4) === 0) {
+ return false;
+ }
$realPath = $this->findImport($url);
- if ($realPath === null) return false;
+ if ($realPath === null) {
+ return false;
+ }
if ($this->importDisabled) {
return array(false, "/* import disabled */");
@@ -137,7 +152,8 @@ class Lessc {
if (isset($parentBlock->children[$childName])) {
$parentBlock->children[$childName] = array_merge(
$parentBlock->children[$childName],
- $child);
+ $child
+ );
} else {
$parentBlock->children[$childName] = $child;
}
@@ -152,7 +168,8 @@ class Lessc {
return array(true, $bottom, $parser, $dir);
}
- protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir) {
+ protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir)
+ {
$oldSourceParser = $this->sourceParser;
$oldImport = $this->importDir;
@@ -190,7 +207,8 @@ class Lessc {
* See lessc::compileProp()
*
*/
- protected function compileBlock($block) {
+ protected function compileBlock($block)
+ {
switch ($block->type) {
case "root":
$this->compileRoot($block);
@@ -214,7 +232,8 @@ class Lessc {
}
}
- protected function compileCSSBlock($block) {
+ protected function compileCSSBlock($block)
+ {
$env = $this->pushEnv();
$selectors = $this->compileSelectors($block->tags);
@@ -228,7 +247,8 @@ class Lessc {
$this->popEnv();
}
- protected function compileMedia($media) {
+ protected function compileMedia($media)
+ {
$env = $this->pushEnv($media);
$parentScope = $this->mediaParent($this->scope);
@@ -253,7 +273,8 @@ class Lessc {
$this->popEnv();
}
- protected function mediaParent($scope) {
+ protected function mediaParent($scope)
+ {
while (!empty($scope->parent)) {
if (!empty($scope->type) && $scope->type != "media") {
break;
@@ -264,7 +285,8 @@ class Lessc {
return $scope;
}
- protected function compileNestedBlock($block, $selectors) {
+ protected function compileNestedBlock($block, $selectors)
+ {
$this->pushEnv($block);
$this->scope = $this->makeOutputBlock($block->type, $selectors);
$this->scope->parent->children[] = $this->scope;
@@ -275,14 +297,16 @@ class Lessc {
$this->popEnv();
}
- protected function compileRoot($root) {
+ protected function compileRoot($root)
+ {
$this->pushEnv();
$this->scope = $this->makeOutputBlock($root->type);
$this->compileProps($root, $this->scope);
$this->popEnv();
}
- protected function compileProps($block, $out) {
+ protected function compileProps($block, $out)
+ {
foreach ($this->sortProps($block->props) as $prop) {
$this->compileProp($prop, $block, $out);
}
@@ -294,7 +318,8 @@ class Lessc {
* duplicate rule is detected, the comments immediately preceding each
* occurence are consolidated.
*/
- protected function deduplicate($lines) {
+ protected function deduplicate($lines)
+ {
$unique = array();
$comments = array();
@@ -312,7 +337,8 @@ class Lessc {
return array_merge($unique, $comments);
}
- protected function sortProps($props, $split = false) {
+ protected function sortProps($props, $split = false)
+ {
$vars = array();
$imports = array();
$other = array();
@@ -356,7 +382,8 @@ class Lessc {
}
}
- protected function compileMediaQuery($queries) {
+ protected function compileMediaQuery($queries)
+ {
$compiledQueries = array();
foreach ($queries as $query) {
$parts = array();
@@ -392,34 +419,36 @@ class Lessc {
return $out;
}
- protected function multiplyMedia($env, $childQueries = null) {
+ protected function multiplyMedia($env, $childQueries = null)
+ {
if (is_null($env) ||
!empty($env->block->type) && $env->block->type != "media"
) {
return $childQueries;
- }
+ }
// plain old block, skip
- if (empty($env->block->type)) {
- return $this->multiplyMedia($env->parent, $childQueries);
- }
+ if (empty($env->block->type)) {
+ return $this->multiplyMedia($env->parent, $childQueries);
+ }
$out = array();
$queries = $env->block->queries;
- if (is_null($childQueries)) {
- $out = $queries;
- } else {
- foreach ($queries as $parent) {
- foreach ($childQueries as $child) {
- $out[] = array_merge($parent, $child);
- }
+ if (is_null($childQueries)) {
+ $out = $queries;
+ } else {
+ foreach ($queries as $parent) {
+ foreach ($childQueries as $child) {
+ $out[] = array_merge($parent, $child);
}
}
+ }
return $this->multiplyMedia($env->parent, $out);
}
- protected function expandParentSelectors(&$tag, $replace) {
+ protected function expandParentSelectors(&$tag, $replace)
+ {
$parts = explode("$&$", $tag);
$count = 0;
foreach ($parts as &$part) {
@@ -430,7 +459,8 @@ class Lessc {
return $count;
}
- protected function findClosestSelectors() {
+ protected function findClosestSelectors()
+ {
$env = $this->env;
$selectors = null;
while ($env !== null) {
@@ -446,7 +476,8 @@ class Lessc {
// multiply $selectors against the nearest selectors in env
- protected function multiplySelectors($selectors) {
+ protected function multiplySelectors($selectors)
+ {
// find parent selectors
$parentSelectors = $this->findClosestSelectors();
@@ -477,7 +508,8 @@ class Lessc {
}
// reduces selector expressions
- protected function compileSelectors($selectors) {
+ protected function compileSelectors($selectors)
+ {
$out = array();
foreach ($selectors as $s) {
@@ -492,11 +524,13 @@ class Lessc {
return $out;
}
- protected function eq($left, $right) {
+ protected function eq($left, $right)
+ {
return $left == $right;
}
- protected function patternMatch($block, $orderedArgs, $keywordArgs) {
+ protected function patternMatch($block, $orderedArgs, $keywordArgs)
+ {
// match the guards if it has them
// any one of the groups must have all its guards pass for a match
if (!empty($block->guards)) {
@@ -513,7 +547,9 @@ class Lessc {
}
$passed = $this->reduce($guard) == self::$TRUE;
- if ($negate) $passed = !$passed;
+ if ($negate) {
+ $passed = !$passed;
+ }
$this->popEnv();
@@ -525,7 +561,9 @@ class Lessc {
}
}
- if ($groupPassed) break;
+ if ($groupPassed) {
+ break;
+ }
}
if (!$groupPassed) {
@@ -579,7 +617,8 @@ class Lessc {
}
}
- protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip = array()) {
+ protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip = array())
+ {
$matches = null;
foreach ($blocks as $block) {
// skip seen blocks that don't have arguments
@@ -596,9 +635,14 @@ class Lessc {
}
// attempt to find blocks matched by path and args
- protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen = array()) {
- if ($searchIn == null) return null;
- if (isset($seen[$searchIn->id])) return null;
+ protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen = array())
+ {
+ if ($searchIn == null) {
+ return null;
+ }
+ if (isset($seen[$searchIn->id])) {
+ return null;
+ }
$seen[$searchIn->id] = true;
$name = $path[0];
@@ -615,8 +659,13 @@ class Lessc {
} else {
$matches = array();
foreach ($blocks as $subBlock) {
- $subMatches = $this->findBlocks($subBlock,
- array_slice($path, 1), $orderedArgs, $keywordArgs, $seen);
+ $subMatches = $this->findBlocks(
+ $subBlock,
+ array_slice($path, 1),
+ $orderedArgs,
+ $keywordArgs,
+ $seen
+ );
if (!is_null($subMatches)) {
foreach ($subMatches as $sm) {
@@ -628,13 +677,16 @@ class Lessc {
return count($matches) > 0 ? $matches : null;
}
}
- if ($searchIn->parent === $searchIn) return null;
+ if ($searchIn->parent === $searchIn) {
+ return null;
+ }
return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen);
}
// sets all argument names in $args to either the default value
// or the one passed in through $values
- protected function zipSetArgs($args, $orderedValues, $keywordValues) {
+ protected function zipSetArgs($args, $orderedValues, $keywordValues)
+ {
$assignedValues = array();
$i = 0;
@@ -676,7 +728,8 @@ class Lessc {
}
// compile a prop and update $lines or $blocks appropriately
- protected function compileProp($prop, $block, $out) {
+ protected function compileProp($prop, $block, $out)
+ {
// set error position context
$this->sourceLoc = isset($prop[-1]) ? $prop[-1] : -1;
@@ -686,8 +739,10 @@ class Lessc {
if ($name[0] == $this->vPrefix) {
$this->set($name, $value);
} else {
- $out->lines[] = $this->formatter->property($name,
- $this->compileValue($this->reduce($value)));
+ $out->lines[] = $this->formatter->property(
+ $name,
+ $this->compileValue($this->reduce($value))
+ );
}
break;
case 'block':
@@ -744,7 +799,9 @@ class Lessc {
}
$oldParent = $mixin->parent;
- if ($mixin != $block) $mixin->parent = $block;
+ if ($mixin != $block) {
+ $mixin->parent = $block;
+ }
foreach ($this->sortProps($mixin->props) as $subProp) {
if ($suffix !== null &&
@@ -756,15 +813,19 @@ class Lessc {
'list', ' ',
array($subProp[2], array('keyword', $suffix))
);
- }
+ }
$this->compileProp($subProp, $mixin, $out);
}
$mixin->parent = $oldParent;
- if ($haveArgs) $this->popEnv();
- if ($haveScope) $this->popEnv();
+ if ($haveArgs) {
+ $this->popEnv();
+ }
+ if ($haveScope) {
+ $this->popEnv();
+ }
}
break;
@@ -822,7 +883,8 @@ class Lessc {
* The input is expected to be reduced. This function will not work on
* things like expressions and variables.
*/
- public function compileValue($value) {
+ public function compileValue($value)
+ {
switch ($value[0]) {
case 'list':
// [1] - delimiter
@@ -886,52 +948,63 @@ class Lessc {
}
}
- protected function lib_pow($args) {
+ protected function lib_pow($args)
+ {
list($base, $exp) = $this->assertArgs($args, 2, "pow");
return pow($this->assertNumber($base), $this->assertNumber($exp));
}
- protected function lib_pi() {
+ protected function lib_pi()
+ {
return pi();
}
- protected function lib_mod($args) {
+ protected function lib_mod($args)
+ {
list($a, $b) = $this->assertArgs($args, 2, "mod");
return $this->assertNumber($a) % $this->assertNumber($b);
}
- protected function lib_tan($num) {
+ protected function lib_tan($num)
+ {
return tan($this->assertNumber($num));
}
- protected function lib_sin($num) {
+ protected function lib_sin($num)
+ {
return sin($this->assertNumber($num));
}
- protected function lib_cos($num) {
+ protected function lib_cos($num)
+ {
return cos($this->assertNumber($num));
}
- protected function lib_atan($num) {
+ protected function lib_atan($num)
+ {
$num = atan($this->assertNumber($num));
return array("number", $num, "rad");
}
- protected function lib_asin($num) {
+ protected function lib_asin($num)
+ {
$num = asin($this->assertNumber($num));
return array("number", $num, "rad");
}
- protected function lib_acos($num) {
+ protected function lib_acos($num)
+ {
$num = acos($this->assertNumber($num));
return array("number", $num, "rad");
}
- protected function lib_sqrt($num) {
+ protected function lib_sqrt($num)
+ {
return sqrt($this->assertNumber($num));
}
- protected function lib_extract($value) {
+ protected function lib_extract($value)
+ {
list($list, $idx) = $this->assertArgs($value, 2, "extract");
$idx = $this->assertNumber($idx);
// 1 indexed
@@ -940,53 +1013,64 @@ class Lessc {
}
}
- protected function lib_isnumber($value) {
+ protected function lib_isnumber($value)
+ {
return $this->toBool($value[0] == "number");
}
- protected function lib_isstring($value) {
+ protected function lib_isstring($value)
+ {
return $this->toBool($value[0] == "string");
}
- protected function lib_iscolor($value) {
+ protected function lib_iscolor($value)
+ {
return $this->toBool($this->coerceColor($value));
}
- protected function lib_iskeyword($value) {
+ protected function lib_iskeyword($value)
+ {
return $this->toBool($value[0] == "keyword");
}
- protected function lib_ispixel($value) {
+ protected function lib_ispixel($value)
+ {
return $this->toBool($value[0] == "number" && $value[2] == "px");
}
- protected function lib_ispercentage($value) {
+ protected function lib_ispercentage($value)
+ {
return $this->toBool($value[0] == "number" && $value[2] == "%");
}
- protected function lib_isem($value) {
+ protected function lib_isem($value)
+ {
return $this->toBool($value[0] == "number" && $value[2] == "em");
}
- protected function lib_isrem($value) {
+ protected function lib_isrem($value)
+ {
return $this->toBool($value[0] == "number" && $value[2] == "rem");
}
- protected function lib_rgbahex($color) {
+ protected function lib_rgbahex($color)
+ {
$color = $this->coerceColor($color);
if (is_null($color)) {
$this->throwError("color expected for rgbahex");
}
- return sprintf("#%02x%02x%02x%02x",
+ return sprintf(
+ "#%02x%02x%02x%02x",
isset($color[4]) ? $color[4] * 255 : 255,
$color[1],
$color[2],
$color[3]
- );
+ );
}
- protected function lib_argb($color) {
+ protected function lib_argb($color)
+ {
return $this->lib_rgbahex($color);
}
@@ -996,7 +1080,8 @@ class Lessc {
* @param array $value either an argument list (two strings) or a single string
* @return string formatted url(), either as a link or base64-encoded
*/
- protected function lib_data_uri($value) {
+ protected function lib_data_uri($value)
+ {
$mime = ($value[0] === 'list') ? $value[2][0][2] : null;
$url = ($value[0] === 'list') ? $value[2][1][2][0] : $value[2][0];
@@ -1015,8 +1100,9 @@ class Lessc {
}
}
- if (!is_null($mime)) // fallback if the mime type is still unknown
+ if (!is_null($mime)) { // fallback if the mime type is still unknown
$url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath)));
+ }
}
}
@@ -1024,7 +1110,8 @@ class Lessc {
}
// utility func to unquote a string
- protected function lib_e($arg) {
+ protected function lib_e($arg)
+ {
switch ($arg[0]) {
case "list":
$items = $arg[2];
@@ -1043,8 +1130,11 @@ class Lessc {
}
}
- protected function lib__sprintf($args) {
- if ($args[0] != "list") return $args;
+ protected function lib__sprintf($args)
+ {
+ if ($args[0] != "list") {
+ return $args;
+ }
$values = $args[2];
$string = array_shift($values);
$template = $this->compileValue($this->lib_e($string));
@@ -1063,8 +1153,12 @@ class Lessc {
$i++;
$rep = $this->compileValue($this->lib_e($val));
- $template = preg_replace('/'.self::preg_quote($match).'/',
- $rep, $template, 1);
+ $template = preg_replace(
+ '/'.self::preg_quote($match).'/',
+ $rep,
+ $template,
+ 1
+ );
}
}
@@ -1072,17 +1166,20 @@ class Lessc {
return array("string", $d, array($template));
}
- protected function lib_floor($arg) {
+ protected function lib_floor($arg)
+ {
$value = $this->assertNumber($arg);
return array("number", floor($value), $arg[2]);
}
- protected function lib_ceil($arg) {
+ protected function lib_ceil($arg)
+ {
$value = $this->assertNumber($arg);
return array("number", ceil($value), $arg[2]);
}
- protected function lib_round($arg) {
+ protected function lib_round($arg)
+ {
if ($arg[0] != "list") {
$value = $this->assertNumber($arg);
return array("number", round($value), $arg[2]);
@@ -1093,7 +1190,8 @@ class Lessc {
}
}
- protected function lib_unit($arg) {
+ protected function lib_unit($arg)
+ {
if ($arg[0] == "list") {
list($number, $newUnit) = $arg[2];
return array("number", $this->assertNumber($number),
@@ -1107,7 +1205,8 @@ class Lessc {
* Helper function to get arguments for color manipulation functions.
* takes a list that contains a color like thing and a percentage
*/
- public function colorArgs($args) {
+ public function colorArgs($args)
+ {
if ($args[0] != 'list' || count($args[2]) < 2) {
return array(array('color', 0, 0, 0), 0);
}
@@ -1118,7 +1217,8 @@ class Lessc {
return array($color, $delta);
}
- protected function lib_darken($args) {
+ protected function lib_darken($args)
+ {
list($color, $delta) = $this->colorArgs($args);
$hsl = $this->toHSL($color);
@@ -1126,7 +1226,8 @@ class Lessc {
return $this->toRGB($hsl);
}
- protected function lib_lighten($args) {
+ protected function lib_lighten($args)
+ {
list($color, $delta) = $this->colorArgs($args);
$hsl = $this->toHSL($color);
@@ -1134,7 +1235,8 @@ class Lessc {
return $this->toRGB($hsl);
}
- protected function lib_saturate($args) {
+ protected function lib_saturate($args)
+ {
list($color, $delta) = $this->colorArgs($args);
$hsl = $this->toHSL($color);
@@ -1142,7 +1244,8 @@ class Lessc {
return $this->toRGB($hsl);
}
- protected function lib_desaturate($args) {
+ protected function lib_desaturate($args)
+ {
list($color, $delta) = $this->colorArgs($args);
$hsl = $this->toHSL($color);
@@ -1150,7 +1253,8 @@ class Lessc {
return $this->toRGB($hsl);
}
- protected function lib_spin($args) {
+ protected function lib_spin($args)
+ {
list($color, $delta) = $this->colorArgs($args);
$hsl = $this->toHSL($color);
@@ -1163,49 +1267,57 @@ class Lessc {
return $this->toRGB($hsl);
}
- protected function lib_fadeout($args) {
+ protected function lib_fadeout($args)
+ {
list($color, $delta) = $this->colorArgs($args);
$color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta / 100);
return $color;
}
- protected function lib_fadein($args) {
+ protected function lib_fadein($args)
+ {
list($color, $delta) = $this->colorArgs($args);
$color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta / 100);
return $color;
}
- protected function lib_hue($color) {
+ protected function lib_hue($color)
+ {
$hsl = $this->toHSL($this->assertColor($color));
return round($hsl[1]);
}
- protected function lib_saturation($color) {
+ protected function lib_saturation($color)
+ {
$hsl = $this->toHSL($this->assertColor($color));
return round($hsl[2]);
}
- protected function lib_lightness($color) {
+ protected function lib_lightness($color)
+ {
$hsl = $this->toHSL($this->assertColor($color));
return round($hsl[3]);
}
// get the alpha of a color
// defaults to 1 for non-colors or colors without an alpha
- protected function lib_alpha($value) {
+ protected function lib_alpha($value)
+ {
if (!is_null($color = $this->coerceColor($value))) {
return isset($color[4]) ? $color[4] : 1;
}
}
// set the alpha of the color
- protected function lib_fade($args) {
+ protected function lib_fade($args)
+ {
list($color, $alpha) = $this->colorArgs($args);
$color[4] = $this->clamp($alpha / 100.0);
return $color;
}
- protected function lib_percentage($arg) {
+ protected function lib_percentage($arg)
+ {
$num = $this->assertNumber($arg);
return array("number", $num * 100, "%");
}
@@ -1221,7 +1333,8 @@ class Lessc {
*
* @return array Color
*/
- protected function lib_tint($args) {
+ protected function lib_tint($args)
+ {
$white = ['color', 255, 255, 255];
if ($args[0] == 'color') {
return $this->lib_mix(['list', ',', [$white, $args]]);
@@ -1243,7 +1356,8 @@ class Lessc {
*
* @return array Color
*/
- protected function lib_shade($args) {
+ protected function lib_shade($args)
+ {
$black = ['color', 0, 0, 0];
if ($args[0] == 'color') {
return $this->lib_mix(['list', ',', [$black, $args]]);
@@ -1257,9 +1371,11 @@ class Lessc {
// mixes two colors by weight
// mix(@color1, @color2, [@weight: 50%]);
// http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
- protected function lib_mix($args) {
- if ($args[0] != "list" || count($args[2]) < 2)
+ protected function lib_mix($args)
+ {
+ if ($args[0] != "list" || count($args[2]) < 2) {
$this->throwError("mix expects (color1, color2, weight)");
+ }
list($first, $second) = $args[2];
$first = $this->assertColor($first);
@@ -1268,11 +1384,11 @@ class Lessc {
$first_a = $this->lib_alpha($first);
$second_a = $this->lib_alpha($second);
- if (isset($args[2][2])) {
- $weight = $args[2][2][1] / 100.0;
- } else {
- $weight = 0.5;
- }
+ if (isset($args[2][2])) {
+ $weight = $args[2][2][1] / 100.0;
+ } else {
+ $weight = 0.5;
+ }
$w = $weight * 2 - 1;
$a = $first_a - $second_a;
@@ -1293,7 +1409,8 @@ class Lessc {
return $this->fixColor($new);
}
- protected function lib_contrast($args) {
+ protected function lib_contrast($args)
+ {
$darkColor = array('color', 0, 0, 0);
$lightColor = array('color', 255, 255, 255);
$threshold = 0.43;
@@ -1303,8 +1420,7 @@ class Lessc {
$darkColor = (isset($args[2][1])) ? $this->assertColor($args[2][1]) : $darkColor;
$lightColor = (isset($args[2][2])) ? $this->assertColor($args[2][2]) : $lightColor;
$threshold = (isset($args[2][3])) ? $this->assertNumber($args[2][3]) : $threshold;
- }
- else {
+ } else {
$inputColor = $this->assertColor($args);
}
@@ -1326,7 +1442,8 @@ class Lessc {
return $darkColor;
}
- private function toLuma($color) {
+ private function toLuma($color)
+ {
list(, $r, $g, $b) = $this->coerceColor($color);
$r = $r / 255;
@@ -1340,27 +1457,37 @@ class Lessc {
return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
}
- protected function lib_luma($color) {
+ protected function lib_luma($color)
+ {
return array("number", round($this->toLuma($color) * 100, 8), "%");
}
- public function assertColor($value, $error = "expected color value") {
+ public function assertColor($value, $error = "expected color value")
+ {
$color = $this->coerceColor($value);
- if (is_null($color)) $this->throwError($error);
+ if (is_null($color)) {
+ $this->throwError($error);
+ }
return $color;
}
- public function assertNumber($value, $error = "expecting number") {
- if ($value[0] == "number") return $value[1];
+ public function assertNumber($value, $error = "expecting number")
+ {
+ if ($value[0] == "number") {
+ return $value[1];
+ }
$this->throwError($error);
}
- public function assertArgs($value, $expectedArgs, $name = "") {
+ public function assertArgs($value, $expectedArgs, $name = "")
+ {
if ($expectedArgs == 1) {
return $value;
} else {
- if ($value[0] !== "list" || $value[1] != ",") $this->throwError("expecting list");
+ if ($value[0] !== "list" || $value[1] != ",") {
+ $this->throwError("expecting list");
+ }
$values = $value[2];
$numValues = count($values);
if ($expectedArgs != $numValues) {
@@ -1375,7 +1502,8 @@ class Lessc {
}
}
- protected function toHSL($color) {
+ protected function toHSL($color)
+ {
if ($color[0] === 'hsl') {
return $color;
}
@@ -1403,7 +1531,6 @@ class Lessc {
} elseif ($b == $max) {
$H = 4.0 + ($r - $g) / ($max - $min);
}
-
}
$out = array('hsl',
@@ -1419,7 +1546,8 @@ class Lessc {
return $out;
}
- protected function toRGB_helper($comp, $temp1, $temp2) {
+ protected function toRGB_helper($comp, $temp1, $temp2)
+ {
if ($comp < 0) {
$comp += 1.0;
} elseif ($comp > 1) {
@@ -1443,7 +1571,8 @@ class Lessc {
* Converts a hsl array into a color value in rgb.
* Expects H to be in range of 0 to 360, S and L in 0 to 100
*/
- protected function toRGB($color) {
+ protected function toRGB($color)
+ {
if ($color[0] === 'color') {
return $color;
}
@@ -1474,7 +1603,8 @@ class Lessc {
return $out;
}
- protected function clamp($v, $max = 1, $min = 0) {
+ protected function clamp($v, $max = 1, $min = 0)
+ {
return min($max, max($min, $v));
}
@@ -1482,7 +1612,8 @@ class Lessc {
* Convert the rgb, rgba, hsl color literals of function type
* as returned by the parser into values of color type.
*/
- protected function funcToColor($func) {
+ protected function funcToColor($func)
+ {
$fname = $func[1];
if ($func[2][0] != 'list') {
// need a list of arguments
@@ -1513,7 +1644,6 @@ class Lessc {
$hsl[] = 0;
}
return $this->toRGB($hsl);
-
} elseif ($fname == 'rgb' || $fname == 'rgba') {
$components = array();
$i = 1;
@@ -1531,7 +1661,9 @@ class Lessc {
} else {
$components[] = floatval($c[1]);
}
- } else break;
+ } else {
+ break;
+ }
$i++;
}
@@ -1545,7 +1677,8 @@ class Lessc {
return false;
}
- protected function reduce($value, $forExpression = false) {
+ protected function reduce($value, $forExpression = false)
+ {
switch ($value[0]) {
case "interpolate":
$reduced = $this->reduce($value[1]);
@@ -1556,7 +1689,9 @@ class Lessc {
$res = $this->coerceColor($res);
}
- if (empty($value[2])) $res = $this->lib_e($res);
+ if (empty($value[2])) {
+ $res = $this->lib_e($res);
+ }
return $res;
case "variable":
@@ -1588,7 +1723,9 @@ class Lessc {
if (is_array($part)) {
$strip = $part[0] == "variable";
$part = $this->reduce($part);
- if ($strip) $part = $this->lib_e($part);
+ if ($strip) {
+ $part = $this->lib_e($part);
+ }
}
}
return $value;
@@ -1597,32 +1734,37 @@ class Lessc {
return $this->lib_e($this->reduce($inner));
case "function":
$color = $this->funcToColor($value);
- if ($color) return $color;
+ if ($color) {
+ return $color;
+ }
list(, $name, $args) = $value;
- if ($name == "%") $name = "_sprintf";
+ if ($name == "%") {
+ $name = "_sprintf";
+ }
$f = isset($this->libFunctions[$name]) ?
$this->libFunctions[$name] : array($this, 'lib_'.str_replace('-', '_', $name));
if (is_callable($f)) {
- if ($args[0] == 'list')
+ if ($args[0] == 'list') {
$args = self::compressList($args[2], $args[1]);
+ }
$ret = call_user_func($f, $this->reduce($args, true), $this);
- if (is_null($ret)) {
- return array("string", "", array(
- $name, "(", $args, ")"
- ));
- }
+ if (is_null($ret)) {
+ return array("string", "", array(
+ $name, "(", $args, ")"
+ ));
+ }
// convert to a typed value if the result is a php primitive
- if (is_numeric($ret)) {
- $ret = array('number', $ret, "");
- } elseif (!is_array($ret)) {
- $ret = array('keyword', $ret);
- }
+ if (is_numeric($ret)) {
+ $ret = array('number', $ret, "");
+ } elseif (!is_array($ret)) {
+ $ret = array('keyword', $ret);
+ }
return $ret;
}
@@ -1663,9 +1805,11 @@ class Lessc {
// coerce a value for use in color operation
- protected function coerceColor($value) {
+ protected function coerceColor($value)
+ {
switch ($value[0]) {
- case 'color': return $value;
+ case 'color':
+ return $value;
case 'raw_color':
$c = array("color", 0, 0, 0);
$colorStr = substr($value[1], 1);
@@ -1695,7 +1839,8 @@ class Lessc {
}
// make something string like into a string
- protected function coerceString($value) {
+ protected function coerceString($value)
+ {
switch ($value[0]) {
case "string":
return $value;
@@ -1706,19 +1851,22 @@ class Lessc {
}
// turn list of length 1 into value type
- protected function flattenList($value) {
+ protected function flattenList($value)
+ {
if ($value[0] == "list" && count($value[2]) == 1) {
return $this->flattenList($value[2][0]);
}
return $value;
}
- public function toBool($a) {
+ public function toBool($a)
+ {
return $a ? self::$TRUE : self::$FALSE;
}
// evaluate an expression
- protected function evaluate($exp) {
+ protected function evaluate($exp)
+ {
list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
$left = $this->reduce($left, true);
@@ -1752,7 +1900,9 @@ class Lessc {
$fname = "op_${ltype}_${rtype}";
if (is_callable(array($this, $fname))) {
$out = $this->$fname($op, $left, $right);
- if (!is_null($out)) return $out;
+ if (!is_null($out)) {
+ return $out;
+ }
}
// make the expression look it did before being parsed
@@ -1767,7 +1917,8 @@ class Lessc {
return array("string", "", array($left, $paddedOp, $right));
}
- protected function stringConcatenate($left, $right) {
+ protected function stringConcatenate($left, $right)
+ {
if ($strLeft = $this->coerceString($left)) {
if ($right[0] == "string") {
$right[1] = "";
@@ -1784,29 +1935,42 @@ class Lessc {
// make sure a color's components don't go out of bounds
- protected function fixColor($c) {
+ protected function fixColor($c)
+ {
foreach (range(1, 3) as $i) {
- if ($c[$i] < 0) $c[$i] = 0;
- if ($c[$i] > 255) $c[$i] = 255;
+ if ($c[$i] < 0) {
+ $c[$i] = 0;
+ }
+ if ($c[$i] > 255) {
+ $c[$i] = 255;
+ }
}
return $c;
}
- protected function op_number_color($op, $lft, $rgt) {
+ protected function op_number_color($op, $lft, $rgt)
+ {
if ($op == '+' || $op == '*') {
return $this->op_color_number($op, $rgt, $lft);
}
}
- protected function op_color_number($op, $lft, $rgt) {
- if ($rgt[0] == '%') $rgt[1] /= 100;
+ protected function op_color_number($op, $lft, $rgt)
+ {
+ if ($rgt[0] == '%') {
+ $rgt[1] /= 100;
+ }
- return $this->op_color_color($op, $lft,
- array_fill(1, count($lft) - 1, $rgt[1]));
+ return $this->op_color_color(
+ $op,
+ $lft,
+ array_fill(1, count($lft) - 1, $rgt[1])
+ );
}
- protected function op_color_color($op, $left, $right) {
+ protected function op_color_color($op, $left, $right)
+ {
$out = array('color');
$max = count($left) > count($right) ? count($left) : count($right);
foreach (range(1, $max - 1) as $i) {
@@ -1838,7 +2002,8 @@ class Lessc {
return $this->fixColor($out);
}
- public function lib_red($color) {
+ public function lib_red($color)
+ {
$color = $this->coerceColor($color);
if (is_null($color)) {
$this->throwError('color expected for red()');
@@ -1847,7 +2012,8 @@ class Lessc {
return $color[1];
}
- public function lib_green($color) {
+ public function lib_green($color)
+ {
$color = $this->coerceColor($color);
if (is_null($color)) {
$this->throwError('color expected for green()');
@@ -1856,7 +2022,8 @@ class Lessc {
return $color[2];
}
- public function lib_blue($color) {
+ public function lib_blue($color)
+ {
$color = $this->coerceColor($color);
if (is_null($color)) {
$this->throwError('color expected for blue()');
@@ -1867,7 +2034,8 @@ class Lessc {
// operator on two numbers
- protected function op_number_number($op, $left, $right) {
+ protected function op_number_number($op, $left, $right)
+ {
$unit = empty($left[2]) ? $right[2] : $left[2];
$value = 0;
@@ -1885,7 +2053,9 @@ class Lessc {
$value = $left[1] % $right[1];
break;
case '/':
- if ($right[1] == 0) $this->throwError('parse error: divide by zero');
+ if ($right[1] == 0) {
+ $this->throwError('parse error: divide by zero');
+ }
$value = $left[1] / $right[1];
break;
case '<':
@@ -1906,7 +2076,8 @@ class Lessc {
/* environment functions */
- protected function makeOutputBlock($type, $selectors = null) {
+ protected function makeOutputBlock($type, $selectors = null)
+ {
$b = new stdclass;
$b->lines = array();
$b->children = array();
@@ -1917,7 +2088,8 @@ class Lessc {
}
// the state of execution
- protected function pushEnv($block = null) {
+ protected function pushEnv($block = null)
+ {
$e = new stdclass;
$e->parent = $this->env;
$e->store = array();
@@ -1928,20 +2100,23 @@ class Lessc {
}
// pop something off the stack
- protected function popEnv() {
+ protected function popEnv()
+ {
$old = $this->env;
$this->env = $this->env->parent;
return $old;
}
// set something in the current env
- protected function set($name, $value) {
+ protected function set($name, $value)
+ {
$this->env->store[$name] = $value;
}
// get the highest occurrence entry for a name
- protected function get($name) {
+ protected function get($name)
+ {
$current = $this->env;
$isArguments = $name == $this->vPrefix.'arguments';
@@ -1962,7 +2137,8 @@ class Lessc {
}
// inject array of unparsed strings into environment as variables
- protected function injectVariables($args) {
+ protected function injectVariables($args)
+ {
$this->pushEnv();
$parser = new lessc_parser($this, __METHOD__);
foreach ($args as $name => $strValue) {
@@ -1983,14 +2159,16 @@ class Lessc {
* Initialize any static state, can initialize parser for a file
* $opts isn't used yet
*/
- public function __construct($fname = null) {
+ public function __construct($fname = null)
+ {
if ($fname !== null) {
// used for deprecated parse method
$this->_parseFile = $fname;
}
}
- public function compile($string, $name = null) {
+ public function compile($string, $name = null)
+ {
$locale = setlocale(LC_NUMERIC, 0);
setlocale(LC_NUMERIC, "C");
@@ -2016,7 +2194,8 @@ class Lessc {
return $out;
}
- public function compileFile($fname, $outFname = null) {
+ public function compileFile($fname, $outFname = null)
+ {
if (!is_readable($fname)) {
throw new Exception('load error: failed to find '.$fname);
}
@@ -2042,7 +2221,8 @@ class Lessc {
}
// compile only if changed input has changed or output doesn't exist
- public function checkedCompile($in, $out) {
+ public function checkedCompile($in, $out)
+ {
if (!is_file($out) || filemtime($in) > filemtime($out)) {
$this->compileFile($in, $out);
return true;
@@ -2070,7 +2250,8 @@ class Lessc {
* @param bool $force Force rebuild?
* @return array lessphp cache structure
*/
- public function cachedCompile($in, $force = false) {
+ public function cachedCompile($in, $force = false)
+ {
// assume no root
$root = null;
@@ -2111,12 +2292,12 @@ class Lessc {
// we were given initially.
return $in;
}
-
}
// parse and compile buffer
// This is deprecated
- public function parse($str = null, $initialVariables = null) {
+ public function parse($str = null, $initialVariables = null)
+ {
if (is_array($str)) {
$initialVariables = $str;
$str = null;
@@ -2141,69 +2322,83 @@ class Lessc {
return $out;
}
- protected function makeParser($name) {
+ protected function makeParser($name)
+ {
$parser = new lessc_parser($this, $name);
$parser->writeComments = $this->preserveComments;
return $parser;
}
- public function setFormatter($name) {
+ public function setFormatter($name)
+ {
$this->formatterName = $name;
}
- protected function newFormatter() {
+ protected function newFormatter()
+ {
$className = "lessc_formatter_lessjs";
if (!empty($this->formatterName)) {
- if (!is_string($this->formatterName))
+ if (!is_string($this->formatterName)) {
return $this->formatterName;
+ }
$className = "lessc_formatter_$this->formatterName";
}
return new $className;
}
- public function setPreserveComments($preserve) {
+ public function setPreserveComments($preserve)
+ {
$this->preserveComments = $preserve;
}
- public function registerFunction($name, $func) {
+ public function registerFunction($name, $func)
+ {
$this->libFunctions[$name] = $func;
}
- public function unregisterFunction($name) {
+ public function unregisterFunction($name)
+ {
unset($this->libFunctions[$name]);
}
- public function setVariables($variables) {
+ public function setVariables($variables)
+ {
$this->registeredVars = array_merge($this->registeredVars, $variables);
}
- public function unsetVariable($name) {
+ public function unsetVariable($name)
+ {
unset($this->registeredVars[$name]);
}
- public function setImportDir($dirs) {
+ public function setImportDir($dirs)
+ {
$this->importDir = (array) $dirs;
}
- public function addImportDir($dir) {
+ public function addImportDir($dir)
+ {
$this->importDir = (array) $this->importDir;
$this->importDir[] = $dir;
}
- public function allParsedFiles() {
+ public function allParsedFiles()
+ {
return $this->allParsedFiles;
}
- public function addParsedFile($file) {
+ public function addParsedFile($file)
+ {
$this->allParsedFiles[realpath($file)] = filemtime($file);
}
/**
* Uses the current value of $this->count to show line and line number
*/
- public function throwError($msg = null) {
+ public function throwError($msg = null)
+ {
if ($this->sourceLoc >= 0) {
$this->sourceParser->throwError($msg, $this->sourceLoc);
}
@@ -2212,14 +2407,16 @@ class Lessc {
// compile file $in to file $out if $in is newer than $out
// returns true when it compiles, false otherwise
- public static function ccompile($in, $out, $less = null) {
+ public static function ccompile($in, $out, $less = null)
+ {
if ($less === null) {
$less = new self;
}
return $less->checkedCompile($in, $out);
}
- public static function cexecute($in, $force = false, $less = null) {
+ public static function cexecute($in, $force = false, $less = null)
+ {
if ($less === null) {
$less = new self;
}
@@ -2380,7 +2577,8 @@ class Lessc {
// responsible for taking a string of LESS code and converting it into a
// syntax tree
-class lessc_parser {
+class lessc_parser
+{
protected static $nextBlockId = 0; // used to uniquely identify blocks
protected static $precedence = array(
@@ -2428,7 +2626,8 @@ class lessc_parser {
// caches preg escaped literals
protected static $literalCache = array();
- public function __construct($lessc, $sourceName = null) {
+ public function __construct($lessc, $sourceName = null)
+ {
$this->eatWhiteDefault = true;
// reference to less needed for vPrefix, mPrefix, and parentSelector
$this->lessc = $lessc;
@@ -2439,8 +2638,10 @@ class lessc_parser {
if (!self::$operatorString) {
self::$operatorString =
- '('.implode('|', array_map(array('lessc', 'preg_quote'),
- array_keys(self::$precedence))).')';
+ '('.implode('|', array_map(
+ array('lessc', 'preg_quote'),
+ array_keys(self::$precedence)
+ )).')';
$commentSingle = lessc::preg_quote(self::$commentSingle);
$commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
@@ -2458,7 +2659,8 @@ class lessc_parser {
* @throws exception
* @return NULL|stdclass
*/
- public function parse($buffer) {
+ public function parse($buffer)
+ {
$this->count = 0;
$this->line = 1;
@@ -2478,19 +2680,17 @@ class lessc_parser {
// parse the entire file
while (false !== $this->parseChunk());
- if ($this->count != strlen($this->buffer))
- {
- $this->throwError('parse error count '.$this->count.' != len buffer '.strlen($this->buffer));
- }
+ if ($this->count != strlen($this->buffer)) {
+ $this->throwError('parse error count '.$this->count.' != len buffer '.strlen($this->buffer));
+ }
// TODO report where the block was opened
- if (!property_exists($this->env, 'parent') || !is_null($this->env->parent))
- {
- throw new exception('parse error: unclosed block');
- }
+ if (!property_exists($this->env, 'parent') || !is_null($this->env->parent)) {
+ throw new exception('parse error: unclosed block');
+ }
return $this->env;
- }
+ }
/**
* Parse a single chunk off the head of the buffer and append it to the
@@ -2528,1257 +2728,1397 @@ class lessc_parser {
* position into $s. Then if a chain fails, use $this->seek($s) to
* go back where we started.
*/
- protected function parseChunk() {
- if (empty($this->buffer)) return false;
- $s = $this->seek();
-
- if ($this->whitespace()) {
- return true;
- }
-
- // setting a property
- if ($this->keyword($key) && $this->assign() &&
- $this->propertyValue($value, $key) && $this->end()
- ) {
- $this->append(array('assign', $key, $value), $s);
- return true;
- } else {
- $this->seek($s);
- }
-
-
- // look for special css blocks
- if ($this->literal('@', false)) {
- $this->count--;
-
- // media
- if ($this->literal('@media')) {
- if (($this->mediaQueryList($mediaQueries) || true)
- && $this->literal('{')
- ) {
- $media = $this->pushSpecialBlock("media");
- $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
- return true;
- } else {
- $this->seek($s);
- return false;
- }
- }
-
- if ($this->literal("@", false) && $this->keyword($dirName)) {
- if ($this->isDirective($dirName, $this->blockDirectives)) {
- if (($this->openString("{", $dirValue, null, array(";")) || true) &&
- $this->literal("{")
- ) {
- $dir = $this->pushSpecialBlock("directive");
- $dir->name = $dirName;
- if (isset($dirValue)) $dir->value = $dirValue;
- return true;
- }
- } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
- if ($this->propertyValue($dirValue) && $this->end()) {
- $this->append(array("directive", $dirName, $dirValue));
- return true;
- }
- }
- }
-
- $this->seek($s);
- }
-
- // setting a variable
- if ($this->variable($var) && $this->assign() &&
- $this->propertyValue($value) && $this->end()
- ) {
- $this->append(array('assign', $var, $value), $s);
- return true;
- } else {
- $this->seek($s);
- }
-
- if ($this->import($importValue)) {
- $this->append($importValue, $s);
- return true;
- }
-
- // opening parametric mixin
- if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
- ($this->guards($guards) || true) &&
- $this->literal('{')
- ) {
- $block = $this->pushBlock($this->fixTags(array($tag)));
- $block->args = $args;
- $block->isVararg = $isVararg;
- if (!empty($guards)) $block->guards = $guards;
- return true;
- } else {
- $this->seek($s);
- }
-
- // opening a simple block
- if ($this->tags($tags) && $this->literal('{', false)) {
- $tags = $this->fixTags($tags);
- $this->pushBlock($tags);
- return true;
- } else {
- $this->seek($s);
- }
-
- // closing a block
- if ($this->literal('}', false)) {
- try {
- $block = $this->pop();
- } catch (exception $e) {
- $this->seek($s);
- $this->throwError($e->getMessage());
- }
-
- $hidden = false;
- if (is_null($block->type)) {
- $hidden = true;
- if (!isset($block->args)) {
- foreach ($block->tags as $tag) {
- if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix) {
- $hidden = false;
- break;
- }
- }
- }
-
- foreach ($block->tags as $tag) {
- if (is_string($tag)) {
- $this->env->children[$tag][] = $block;
- }
- }
- }
-
- if (!$hidden) {
- $this->append(array('block', $block), $s);
- }
-
- // this is done here so comments aren't bundled into he block that
- // was just closed
- $this->whitespace();
- return true;
- }
-
- // mixin
- if ($this->mixinTags($tags) &&
- ($this->argumentDef($argv, $isVararg) || true) &&
- ($this->keyword($suffix) || true) && $this->end()
- ) {
- $tags = $this->fixTags($tags);
- $this->append(array('mixin', $tags, $argv, $suffix), $s);
- return true;
- } else {
- $this->seek($s);
- }
-
- // spare ;
- if ($this->literal(';')) return true;
-
- return false; // got nothing, throw error
+ protected function parseChunk()
+ {
+ if (empty($this->buffer)) {
+ return false;
}
+ $s = $this->seek();
- protected function isDirective($dirname, $directives) {
- // TODO: cache pattern in parser
- $pattern = implode("|",
- array_map(array("lessc", "preg_quote"), $directives));
- $pattern = '/^(-[a-z-]+-)?('.$pattern.')$/i';
-
- return preg_match($pattern, $dirname);
- }
-
- protected function fixTags($tags) {
- // move @ tags out of variable namespace
- foreach ($tags as &$tag) {
- if ($tag[0] == $this->lessc->vPrefix)
- $tag[0] = $this->lessc->mPrefix;
- }
- return $tags;
- }
-
- // a list of expressions
- protected function expressionList(&$exps) {
- $values = array();
-
- while ($this->expression($exp)) {
- $values[] = $exp;
- }
-
- if (count($values) == 0) return false;
-
- $exps = lessc::compressList($values, ' ');
+ if ($this->whitespace()) {
return true;
}
+ // setting a property
+ if ($this->keyword($key) && $this->assign() &&
+ $this->propertyValue($value, $key) && $this->end()
+ ) {
+ $this->append(array('assign', $key, $value), $s);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+
+ // look for special css blocks
+ if ($this->literal('@', false)) {
+ $this->count--;
+
+ // media
+ if ($this->literal('@media')) {
+ if (($this->mediaQueryList($mediaQueries) || true)
+ && $this->literal('{')
+ ) {
+ $media = $this->pushSpecialBlock("media");
+ $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
+ return true;
+ } else {
+ $this->seek($s);
+ return false;
+ }
+ }
+
+ if ($this->literal("@", false) && $this->keyword($dirName)) {
+ if ($this->isDirective($dirName, $this->blockDirectives)) {
+ if (($this->openString("{", $dirValue, null, array(";")) || true) &&
+ $this->literal("{")
+ ) {
+ $dir = $this->pushSpecialBlock("directive");
+ $dir->name = $dirName;
+ if (isset($dirValue)) {
+ $dir->value = $dirValue;
+ }
+ return true;
+ }
+ } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
+ if ($this->propertyValue($dirValue) && $this->end()) {
+ $this->append(array("directive", $dirName, $dirValue));
+ return true;
+ }
+ }
+ }
+
+ $this->seek($s);
+ }
+
+ // setting a variable
+ if ($this->variable($var) && $this->assign() &&
+ $this->propertyValue($value) && $this->end()
+ ) {
+ $this->append(array('assign', $var, $value), $s);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ if ($this->import($importValue)) {
+ $this->append($importValue, $s);
+ return true;
+ }
+
+ // opening parametric mixin
+ if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
+ ($this->guards($guards) || true) &&
+ $this->literal('{')
+ ) {
+ $block = $this->pushBlock($this->fixTags(array($tag)));
+ $block->args = $args;
+ $block->isVararg = $isVararg;
+ if (!empty($guards)) {
+ $block->guards = $guards;
+ }
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ // opening a simple block
+ if ($this->tags($tags) && $this->literal('{', false)) {
+ $tags = $this->fixTags($tags);
+ $this->pushBlock($tags);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ // closing a block
+ if ($this->literal('}', false)) {
+ try {
+ $block = $this->pop();
+ } catch (exception $e) {
+ $this->seek($s);
+ $this->throwError($e->getMessage());
+ }
+
+ $hidden = false;
+ if (is_null($block->type)) {
+ $hidden = true;
+ if (!isset($block->args)) {
+ foreach ($block->tags as $tag) {
+ if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix) {
+ $hidden = false;
+ break;
+ }
+ }
+ }
+
+ foreach ($block->tags as $tag) {
+ if (is_string($tag)) {
+ $this->env->children[$tag][] = $block;
+ }
+ }
+ }
+
+ if (!$hidden) {
+ $this->append(array('block', $block), $s);
+ }
+
+ // this is done here so comments aren't bundled into he block that
+ // was just closed
+ $this->whitespace();
+ return true;
+ }
+
+ // mixin
+ if ($this->mixinTags($tags) &&
+ ($this->argumentDef($argv, $isVararg) || true) &&
+ ($this->keyword($suffix) || true) && $this->end()
+ ) {
+ $tags = $this->fixTags($tags);
+ $this->append(array('mixin', $tags, $argv, $suffix), $s);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ // spare ;
+ if ($this->literal(';')) {
+ return true;
+ }
+
+ return false; // got nothing, throw error
+ }
+
+ protected function isDirective($dirname, $directives)
+ {
+ // TODO: cache pattern in parser
+ $pattern = implode(
+ "|",
+ array_map(array("lessc", "preg_quote"), $directives)
+ );
+ $pattern = '/^(-[a-z-]+-)?('.$pattern.')$/i';
+
+ return preg_match($pattern, $dirname);
+ }
+
+ protected function fixTags($tags)
+ {
+ // move @ tags out of variable namespace
+ foreach ($tags as &$tag) {
+ if ($tag[0] == $this->lessc->vPrefix) {
+ $tag[0] = $this->lessc->mPrefix;
+ }
+ }
+ return $tags;
+ }
+
+ // a list of expressions
+ protected function expressionList(&$exps)
+ {
+ $values = array();
+
+ while ($this->expression($exp)) {
+ $values[] = $exp;
+ }
+
+ if (count($values) == 0) {
+ return false;
+ }
+
+ $exps = lessc::compressList($values, ' ');
+ return true;
+ }
+
/**
* Attempt to consume an expression.
* @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
*/
- protected function expression(&$out) {
- if ($this->value($lhs)) {
- $out = $this->expHelper($lhs, 0);
+ protected function expression(&$out)
+ {
+ if ($this->value($lhs)) {
+ $out = $this->expHelper($lhs, 0);
- // look for / shorthand
- if (!empty($this->env->supressedDivision)) {
- unset($this->env->supressedDivision);
- $s = $this->seek();
- if ($this->literal("/") && $this->value($rhs)) {
- $out = array("list", "",
- array($out, array("keyword", "/"), $rhs));
- } else {
- $this->seek($s);
- }
+ // look for / shorthand
+ if (!empty($this->env->supressedDivision)) {
+ unset($this->env->supressedDivision);
+ $s = $this->seek();
+ if ($this->literal("/") && $this->value($rhs)) {
+ $out = array("list", "",
+ array($out, array("keyword", "/"), $rhs));
+ } else {
+ $this->seek($s);
}
-
- return true;
}
- return false;
+
+ return true;
}
+ return false;
+ }
/**
* recursively parse infix equation with $lhs at precedence $minP
*/
- protected function expHelper($lhs, $minP) {
- $this->inExp = true;
- $ss = $this->seek();
+ protected function expHelper($lhs, $minP)
+ {
+ $this->inExp = true;
+ $ss = $this->seek();
- while (true) {
- $whiteBefore = isset($this->buffer[$this->count - 1]) &&
- ctype_space($this->buffer[$this->count - 1]);
+ while (true) {
+ $whiteBefore = isset($this->buffer[$this->count - 1]) &&
+ ctype_space($this->buffer[$this->count - 1]);
- // If there is whitespace before the operator, then we require
- // whitespace after the operator for it to be an expression
- $needWhite = $whiteBefore && !$this->inParens;
+ // If there is whitespace before the operator, then we require
+ // whitespace after the operator for it to be an expression
+ $needWhite = $whiteBefore && !$this->inParens;
- if ($this->match(self::$operatorString.($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) {
- if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision)) {
- foreach (self::$supressDivisionProps as $pattern) {
- if (preg_match($pattern, $this->env->currentProperty)) {
- $this->env->supressedDivision = true;
- break 2;
- }
+ if ($this->match(self::$operatorString.($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) {
+ if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision)) {
+ foreach (self::$supressDivisionProps as $pattern) {
+ if (preg_match($pattern, $this->env->currentProperty)) {
+ $this->env->supressedDivision = true;
+ break 2;
}
}
-
-
- $whiteAfter = isset($this->buffer[$this->count - 1]) &&
- ctype_space($this->buffer[$this->count - 1]);
-
- if (!$this->value($rhs)) break;
-
- // peek for next operator to see what to do with rhs
- if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
- $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
- }
-
- $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
- $ss = $this->seek();
-
- continue;
}
- break;
- }
- $this->seek($ss);
+ $whiteAfter = isset($this->buffer[$this->count - 1]) &&
+ ctype_space($this->buffer[$this->count - 1]);
- return $lhs;
- }
-
- // consume a list of values for a property
- public function propertyValue(&$value, $keyName = null) {
- $values = array();
-
- if ($keyName !== null) $this->env->currentProperty = $keyName;
-
- $s = null;
- while ($this->expressionList($v)) {
- $values[] = $v;
- $s = $this->seek();
- if (!$this->literal(',')) break;
- }
-
- if ($s) $this->seek($s);
-
- if ($keyName !== null) unset($this->env->currentProperty);
-
- if (count($values) == 0) return false;
-
- $value = lessc::compressList($values, ', ');
- return true;
- }
-
- protected function parenValue(&$out) {
- $s = $this->seek();
-
- // speed shortcut
- if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") {
- return false;
- }
-
- $inParens = $this->inParens;
- if ($this->literal("(") &&
- ($this->inParens = true) && $this->expression($exp) &&
- $this->literal(")")
- ) {
- $out = $exp;
- $this->inParens = $inParens;
- return true;
- } else {
- $this->inParens = $inParens;
- $this->seek($s);
- }
-
- return false;
- }
-
- // a single value
- protected function value(&$value) {
- $s = $this->seek();
-
- // speed shortcut
- if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") {
- // negation
- if ($this->literal("-", false) &&
- (($this->variable($inner) && $inner = array("variable", $inner)) ||
- $this->unit($inner) ||
- $this->parenValue($inner))
- ) {
- $value = array("unary", "-", $inner);
- return true;
- } else {
- $this->seek($s);
- }
- }
-
- if ($this->parenValue($value)) return true;
- if ($this->unit($value)) return true;
- if ($this->color($value)) return true;
- if ($this->func($value)) return true;
- if ($this->string($value)) return true;
-
- if ($this->keyword($word)) {
- $value = array('keyword', $word);
- return true;
- }
-
- // try a variable
- if ($this->variable($var)) {
- $value = array('variable', $var);
- return true;
- }
-
- // unquote string (should this work on any type?
- if ($this->literal("~") && $this->string($str)) {
- $value = array("escape", $str);
- return true;
- } else {
- $this->seek($s);
- }
-
- // css hack: \0
- if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
- $value = array('keyword', '\\'.$m[1]);
- return true;
- } else {
- $this->seek($s);
- }
-
- return false;
- }
-
- // an import statement
- protected function import(&$out) {
- if (!$this->literal('@import')) return false;
-
- // @import "something.css" media;
- // @import url("something.css") media;
- // @import url(something.css) media;
-
- if ($this->propertyValue($value)) {
- $out = array("import", $value);
- return true;
- }
- }
-
- protected function mediaQueryList(&$out) {
- if ($this->genericList($list, "mediaQuery", ",", false)) {
- $out = $list[2];
- return true;
- }
- return false;
- }
-
- protected function mediaQuery(&$out) {
- $s = $this->seek();
-
- $expressions = null;
- $parts = array();
-
- if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType)) {
- $prop = array("mediaType");
- if (isset($only)) $prop[] = "only";
- if (isset($not)) $prop[] = "not";
- $prop[] = $mediaType;
- $parts[] = $prop;
- } else {
- $this->seek($s);
- }
-
-
- if (!empty($mediaType) && !$this->literal("and")) {
- // ~
- } else {
- $this->genericList($expressions, "mediaExpression", "and", false);
- if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
- }
-
- if (count($parts) == 0) {
- $this->seek($s);
- return false;
- }
-
- $out = $parts;
- return true;
- }
-
- protected function mediaExpression(&$out) {
- $s = $this->seek();
- $value = null;
- if ($this->literal("(") &&
- $this->keyword($feature) &&
- ($this->literal(":") && $this->expression($value) || true) &&
- $this->literal(")")
- ) {
- $out = array("mediaExp", $feature);
- if ($value) $out[] = $value;
- return true;
- } elseif ($this->variable($variable)) {
- $out = array('variable', $variable);
- return true;
- }
-
- $this->seek($s);
- return false;
- }
-
- // an unbounded string stopped by $end
- protected function openString($end, &$out, $nestingOpen = null, $rejectStrs = null) {
- $oldWhite = $this->eatWhiteDefault;
- $this->eatWhiteDefault = false;
-
- $stop = array("'", '"', "@{", $end);
- $stop = array_map(array("lessc", "preg_quote"), $stop);
- // $stop[] = self::$commentMulti;
-
- if (!is_null($rejectStrs)) {
- $stop = array_merge($stop, $rejectStrs);
- }
-
- $patt = '(.*?)('.implode("|", $stop).')';
-
- $nestingLevel = 0;
-
- $content = array();
- while ($this->match($patt, $m, false)) {
- if (!empty($m[1])) {
- $content[] = $m[1];
- if ($nestingOpen) {
- $nestingLevel += substr_count($m[1], $nestingOpen);
- }
- }
-
- $tok = $m[2];
-
- $this->count -= strlen($tok);
- if ($tok == $end) {
- if ($nestingLevel == 0) {
- break;
- } else {
- $nestingLevel--;
- }
- }
-
- if (($tok == "'" || $tok == '"') && $this->string($str)) {
- $content[] = $str;
- continue;
- }
-
- if ($tok == "@{" && $this->interpolation($inter)) {
- $content[] = $inter;
- continue;
- }
-
- if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
+ if (!$this->value($rhs)) {
break;
}
- $content[] = $tok;
- $this->count += strlen($tok);
+ // peek for next operator to see what to do with rhs
+ if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
+ $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
+ }
+
+ $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
+ $ss = $this->seek();
+
+ continue;
}
- $this->eatWhiteDefault = $oldWhite;
+ break;
+ }
- if (count($content) == 0) return false;
+ $this->seek($ss);
- // trim the end
- if (is_string(end($content))) {
- $content[count($content) - 1] = rtrim(end($content));
+ return $lhs;
+ }
+
+ // consume a list of values for a property
+ public function propertyValue(&$value, $keyName = null)
+ {
+ $values = array();
+
+ if ($keyName !== null) {
+ $this->env->currentProperty = $keyName;
+ }
+
+ $s = null;
+ while ($this->expressionList($v)) {
+ $values[] = $v;
+ $s = $this->seek();
+ if (!$this->literal(',')) {
+ break;
}
+ }
- $out = array("string", "", $content);
+ if ($s) {
+ $this->seek($s);
+ }
+
+ if ($keyName !== null) {
+ unset($this->env->currentProperty);
+ }
+
+ if (count($values) == 0) {
+ return false;
+ }
+
+ $value = lessc::compressList($values, ', ');
+ return true;
+ }
+
+ protected function parenValue(&$out)
+ {
+ $s = $this->seek();
+
+ // speed shortcut
+ if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") {
+ return false;
+ }
+
+ $inParens = $this->inParens;
+ if ($this->literal("(") &&
+ ($this->inParens = true) && $this->expression($exp) &&
+ $this->literal(")")
+ ) {
+ $out = $exp;
+ $this->inParens = $inParens;
+ return true;
+ } else {
+ $this->inParens = $inParens;
+ $this->seek($s);
+ }
+
+ return false;
+ }
+
+ // a single value
+ protected function value(&$value)
+ {
+ $s = $this->seek();
+
+ // speed shortcut
+ if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") {
+ // negation
+ if ($this->literal("-", false) &&
+ (($this->variable($inner) && $inner = array("variable", $inner)) ||
+ $this->unit($inner) ||
+ $this->parenValue($inner))
+ ) {
+ $value = array("unary", "-", $inner);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+ }
+
+ if ($this->parenValue($value)) {
+ return true;
+ }
+ if ($this->unit($value)) {
+ return true;
+ }
+ if ($this->color($value)) {
+ return true;
+ }
+ if ($this->func($value)) {
+ return true;
+ }
+ if ($this->string($value)) {
return true;
}
- protected function string(&$out) {
- $s = $this->seek();
- if ($this->literal('"', false)) {
- $delim = '"';
- } elseif ($this->literal("'", false)) {
- $delim = "'";
- } else {
- return false;
- }
-
- $content = array();
-
- // look for either ending delim , escape, or string interpolation
- $patt = '([^\n]*?)(@\{|\\\\|'.
- lessc::preg_quote($delim).')';
-
- $oldWhite = $this->eatWhiteDefault;
- $this->eatWhiteDefault = false;
-
- while ($this->match($patt, $m, false)) {
- $content[] = $m[1];
- if ($m[2] == "@{") {
- $this->count -= strlen($m[2]);
- if ($this->interpolation($inter)) {
- $content[] = $inter;
- } else {
- $this->count += strlen($m[2]);
- $content[] = "@{"; // ignore it
- }
- } elseif ($m[2] == '\\') {
- $content[] = $m[2];
- if ($this->literal($delim, false)) {
- $content[] = $delim;
- }
- } else {
- $this->count -= strlen($delim);
- break; // delim
- }
- }
-
- $this->eatWhiteDefault = $oldWhite;
-
- if ($this->literal($delim)) {
- $out = array("string", $delim, $content);
- return true;
- }
-
- $this->seek($s);
- return false;
+ if ($this->keyword($word)) {
+ $value = array('keyword', $word);
+ return true;
}
- protected function interpolation(&$out) {
- $oldWhite = $this->eatWhiteDefault;
- $this->eatWhiteDefault = true;
-
- $s = $this->seek();
- if ($this->literal("@{") &&
- $this->openString("}", $interp, null, array("'", '"', ";")) &&
- $this->literal("}", false)
- ) {
- $out = array("interpolate", $interp);
- $this->eatWhiteDefault = $oldWhite;
- if ($this->eatWhiteDefault) $this->whitespace();
- return true;
- }
-
- $this->eatWhiteDefault = $oldWhite;
- $this->seek($s);
- return false;
+ // try a variable
+ if ($this->variable($var)) {
+ $value = array('variable', $var);
+ return true;
}
- protected function unit(&$unit) {
- // speed shortcut
- if (isset($this->buffer[$this->count])) {
- $char = $this->buffer[$this->count];
- if (!ctype_digit($char) && $char != ".") return false;
- }
+ // unquote string (should this work on any type?
+ if ($this->literal("~") && $this->string($str)) {
+ $value = array("escape", $str);
+ return true;
+ } else {
+ $this->seek($s);
+ }
- if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
- $unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
- return true;
- }
+ // css hack: \0
+ if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
+ $value = array('keyword', '\\'.$m[1]);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ return false;
+ }
+
+ // an import statement
+ protected function import(&$out)
+ {
+ if (!$this->literal('@import')) {
return false;
}
+ // @import "something.css" media;
+ // @import url("something.css") media;
+ // @import url(something.css) media;
+
+ if ($this->propertyValue($value)) {
+ $out = array("import", $value);
+ return true;
+ }
+ }
+
+ protected function mediaQueryList(&$out)
+ {
+ if ($this->genericList($list, "mediaQuery", ",", false)) {
+ $out = $list[2];
+ return true;
+ }
+ return false;
+ }
+
+ protected function mediaQuery(&$out)
+ {
+ $s = $this->seek();
+
+ $expressions = null;
+ $parts = array();
+
+ if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType)) {
+ $prop = array("mediaType");
+ if (isset($only)) {
+ $prop[] = "only";
+ }
+ if (isset($not)) {
+ $prop[] = "not";
+ }
+ $prop[] = $mediaType;
+ $parts[] = $prop;
+ } else {
+ $this->seek($s);
+ }
+
+
+ if (!empty($mediaType) && !$this->literal("and")) {
+ // ~
+ } else {
+ $this->genericList($expressions, "mediaExpression", "and", false);
+ if (is_array($expressions)) {
+ $parts = array_merge($parts, $expressions[2]);
+ }
+ }
+
+ if (count($parts) == 0) {
+ $this->seek($s);
+ return false;
+ }
+
+ $out = $parts;
+ return true;
+ }
+
+ protected function mediaExpression(&$out)
+ {
+ $s = $this->seek();
+ $value = null;
+ if ($this->literal("(") &&
+ $this->keyword($feature) &&
+ ($this->literal(":") && $this->expression($value) || true) &&
+ $this->literal(")")
+ ) {
+ $out = array("mediaExp", $feature);
+ if ($value) {
+ $out[] = $value;
+ }
+ return true;
+ } elseif ($this->variable($variable)) {
+ $out = array('variable', $variable);
+ return true;
+ }
+
+ $this->seek($s);
+ return false;
+ }
+
+ // an unbounded string stopped by $end
+ protected function openString($end, &$out, $nestingOpen = null, $rejectStrs = null)
+ {
+ $oldWhite = $this->eatWhiteDefault;
+ $this->eatWhiteDefault = false;
+
+ $stop = array("'", '"', "@{", $end);
+ $stop = array_map(array("lessc", "preg_quote"), $stop);
+ // $stop[] = self::$commentMulti;
+
+ if (!is_null($rejectStrs)) {
+ $stop = array_merge($stop, $rejectStrs);
+ }
+
+ $patt = '(.*?)('.implode("|", $stop).')';
+
+ $nestingLevel = 0;
+
+ $content = array();
+ while ($this->match($patt, $m, false)) {
+ if (!empty($m[1])) {
+ $content[] = $m[1];
+ if ($nestingOpen) {
+ $nestingLevel += substr_count($m[1], $nestingOpen);
+ }
+ }
+
+ $tok = $m[2];
+
+ $this->count -= strlen($tok);
+ if ($tok == $end) {
+ if ($nestingLevel == 0) {
+ break;
+ } else {
+ $nestingLevel--;
+ }
+ }
+
+ if (($tok == "'" || $tok == '"') && $this->string($str)) {
+ $content[] = $str;
+ continue;
+ }
+
+ if ($tok == "@{" && $this->interpolation($inter)) {
+ $content[] = $inter;
+ continue;
+ }
+
+ if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
+ break;
+ }
+
+ $content[] = $tok;
+ $this->count += strlen($tok);
+ }
+
+ $this->eatWhiteDefault = $oldWhite;
+
+ if (count($content) == 0) {
+ return false;
+ }
+
+ // trim the end
+ if (is_string(end($content))) {
+ $content[count($content) - 1] = rtrim(end($content));
+ }
+
+ $out = array("string", "", $content);
+ return true;
+ }
+
+ protected function string(&$out)
+ {
+ $s = $this->seek();
+ if ($this->literal('"', false)) {
+ $delim = '"';
+ } elseif ($this->literal("'", false)) {
+ $delim = "'";
+ } else {
+ return false;
+ }
+
+ $content = array();
+
+ // look for either ending delim , escape, or string interpolation
+ $patt = '([^\n]*?)(@\{|\\\\|'.
+ lessc::preg_quote($delim).')';
+
+ $oldWhite = $this->eatWhiteDefault;
+ $this->eatWhiteDefault = false;
+
+ while ($this->match($patt, $m, false)) {
+ $content[] = $m[1];
+ if ($m[2] == "@{") {
+ $this->count -= strlen($m[2]);
+ if ($this->interpolation($inter)) {
+ $content[] = $inter;
+ } else {
+ $this->count += strlen($m[2]);
+ $content[] = "@{"; // ignore it
+ }
+ } elseif ($m[2] == '\\') {
+ $content[] = $m[2];
+ if ($this->literal($delim, false)) {
+ $content[] = $delim;
+ }
+ } else {
+ $this->count -= strlen($delim);
+ break; // delim
+ }
+ }
+
+ $this->eatWhiteDefault = $oldWhite;
+
+ if ($this->literal($delim)) {
+ $out = array("string", $delim, $content);
+ return true;
+ }
+
+ $this->seek($s);
+ return false;
+ }
+
+ protected function interpolation(&$out)
+ {
+ $oldWhite = $this->eatWhiteDefault;
+ $this->eatWhiteDefault = true;
+
+ $s = $this->seek();
+ if ($this->literal("@{") &&
+ $this->openString("}", $interp, null, array("'", '"', ";")) &&
+ $this->literal("}", false)
+ ) {
+ $out = array("interpolate", $interp);
+ $this->eatWhiteDefault = $oldWhite;
+ if ($this->eatWhiteDefault) {
+ $this->whitespace();
+ }
+ return true;
+ }
+
+ $this->eatWhiteDefault = $oldWhite;
+ $this->seek($s);
+ return false;
+ }
+
+ protected function unit(&$unit)
+ {
+ // speed shortcut
+ if (isset($this->buffer[$this->count])) {
+ $char = $this->buffer[$this->count];
+ if (!ctype_digit($char) && $char != ".") {
+ return false;
+ }
+ }
+
+ if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
+ $unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
+ return true;
+ }
+ return false;
+ }
+
// a # color
- protected function color(&$out) {
- if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
- if (strlen($m[1]) > 7) {
- $out = array("string", "", array($m[1]));
- } else {
- $out = array("raw_color", $m[1]);
- }
- return true;
+ protected function color(&$out)
+ {
+ if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
+ if (strlen($m[1]) > 7) {
+ $out = array("string", "", array($m[1]));
+ } else {
+ $out = array("raw_color", $m[1]);
}
-
- return false;
+ return true;
}
+ return false;
+ }
+
// consume an argument definition list surrounded by ()
// each argument is a variable name with optional value
// or at the end a ... or a variable named followed by ...
// arguments are separated by , unless a ; is in the list, then ; is the
// delimiter.
- protected function argumentDef(&$args, &$isVararg) {
- $s = $this->seek();
- if (!$this->literal('(')) {
- return false;
+ protected function argumentDef(&$args, &$isVararg)
+ {
+ $s = $this->seek();
+ if (!$this->literal('(')) {
+ return false;
+ }
+
+ $values = array();
+ $delim = ",";
+ $method = "expressionList";
+
+ $isVararg = false;
+ while (true) {
+ if ($this->literal("...")) {
+ $isVararg = true;
+ break;
}
- $values = array();
- $delim = ",";
- $method = "expressionList";
+ if ($this->$method($value)) {
+ if ($value[0] == "variable") {
+ $arg = array("arg", $value[1]);
+ $ss = $this->seek();
- $isVararg = false;
- while (true) {
- if ($this->literal("...")) {
- $isVararg = true;
- break;
- }
-
- if ($this->$method($value)) {
- if ($value[0] == "variable") {
- $arg = array("arg", $value[1]);
- $ss = $this->seek();
-
- if ($this->assign() && $this->$method($rhs)) {
- $arg[] = $rhs;
- } else {
- $this->seek($ss);
- if ($this->literal("...")) {
- $arg[0] = "rest";
- $isVararg = true;
- }
- }
-
- $values[] = $arg;
- if ($isVararg) {
- break;
- }
- continue;
+ if ($this->assign() && $this->$method($rhs)) {
+ $arg[] = $rhs;
} else {
- $values[] = array("lit", $value);
+ $this->seek($ss);
+ if ($this->literal("...")) {
+ $arg[0] = "rest";
+ $isVararg = true;
+ }
}
- }
-
- if (!$this->literal($delim)) {
- if ($delim == "," && $this->literal(";")) {
- // found new delim, convert existing args
- $delim = ";";
- $method = "propertyValue";
-
- // transform arg list
- if (isset($values[1])) { // 2 items
- $newList = array();
- foreach ($values as $i => $arg) {
- switch ($arg[0]) {
- case "arg":
- if ($i) {
- $this->throwError("Cannot mix ; and , as delimiter types");
- }
- $newList[] = $arg[2];
- break;
- case "lit":
- $newList[] = $arg[1];
- break;
- case "rest":
- $this->throwError("Unexpected rest before semicolon");
- }
- }
-
- $newList = array("list", ", ", $newList);
-
- switch ($values[0][0]) {
- case "arg":
- $newArg = array("arg", $values[0][1], $newList);
- break;
- case "lit":
- $newArg = array("lit", $newList);
- break;
- }
-
- } elseif ($values) { // 1 item
- $newArg = $values[0];
- }
-
- if ($newArg) {
- $values = array($newArg);
- }
- } else {
+ $values[] = $arg;
+ if ($isVararg) {
break;
}
+ continue;
+ } else {
+ $values[] = array("lit", $value);
}
}
- if (!$this->literal(')')) {
- $this->seek($s);
- return false;
- }
- $args = $values;
+ if (!$this->literal($delim)) {
+ if ($delim == "," && $this->literal(";")) {
+ // found new delim, convert existing args
+ $delim = ";";
+ $method = "propertyValue";
- return true;
- }
-
- // consume a list of tags
- // this accepts a hanging delimiter
- protected function tags(&$tags, $simple = false, $delim = ',') {
- $tags = array();
- while ($this->tag($tt, $simple)) {
- $tags[] = $tt;
- if (!$this->literal($delim)) break;
- }
- if (count($tags) == 0) return false;
-
- return true;
- }
-
- // list of tags of specifying mixin path
- // optionally separated by > (lazy, accepts extra >)
- protected function mixinTags(&$tags) {
- $tags = array();
- while ($this->tag($tt, true)) {
- $tags[] = $tt;
- $this->literal(">");
- }
-
- if (!$tags) {
- return false;
- }
-
- return true;
- }
-
- // a bracketed value (contained within in a tag definition)
- protected function tagBracket(&$parts, &$hasExpression) {
- // speed shortcut
- if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") {
- return false;
- }
-
- $s = $this->seek();
-
- $hasInterpolation = false;
-
- if ($this->literal("[", false)) {
- $attrParts = array("[");
- // keyword, string, operator
- while (true) {
- if ($this->literal("]", false)) {
- $this->count--;
- break; // get out early
- }
-
- if ($this->match('\s+', $m)) {
- $attrParts[] = " ";
- continue;
- }
- if ($this->string($str)) {
- // escape parent selector, (yuck)
- foreach ($str[2] as &$chunk) {
- $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk);
+ // transform arg list
+ if (isset($values[1])) { // 2 items
+ $newList = array();
+ foreach ($values as $i => $arg) {
+ switch ($arg[0]) {
+ case "arg":
+ if ($i) {
+ $this->throwError("Cannot mix ; and , as delimiter types");
+ }
+ $newList[] = $arg[2];
+ break;
+ case "lit":
+ $newList[] = $arg[1];
+ break;
+ case "rest":
+ $this->throwError("Unexpected rest before semicolon");
+ }
}
- $attrParts[] = $str;
- $hasInterpolation = true;
- continue;
+ $newList = array("list", ", ", $newList);
+
+ switch ($values[0][0]) {
+ case "arg":
+ $newArg = array("arg", $values[0][1], $newList);
+ break;
+ case "lit":
+ $newArg = array("lit", $newList);
+ break;
+ }
+ } elseif ($values) { // 1 item
+ $newArg = $values[0];
}
- if ($this->keyword($word)) {
- $attrParts[] = $word;
- continue;
+ if ($newArg) {
+ $values = array($newArg);
}
-
- if ($this->interpolation($inter)) {
- $attrParts[] = $inter;
- $hasInterpolation = true;
- continue;
- }
-
- // operator, handles attr namespace too
- if ($this->match('[|-~\$\*\^=]+', $m)) {
- $attrParts[] = $m[0];
- continue;
- }
-
+ } else {
break;
}
-
- if ($this->literal("]", false)) {
- $attrParts[] = "]";
- foreach ($attrParts as $part) {
- $parts[] = $part;
- }
- $hasExpression = $hasExpression || $hasInterpolation;
- return true;
- }
- $this->seek($s);
}
+ }
+ if (!$this->literal(')')) {
$this->seek($s);
return false;
}
- // a space separated list of selectors
- protected function tag(&$tag, $simple = false) {
- if ($simple) {
- $chars = '^@,:;{}\][>\(\) "\'';
- } else {
- $chars = '^@,;{}["\'';
+ $args = $values;
+
+ return true;
+ }
+
+ // consume a list of tags
+ // this accepts a hanging delimiter
+ protected function tags(&$tags, $simple = false, $delim = ',')
+ {
+ $tags = array();
+ while ($this->tag($tt, $simple)) {
+ $tags[] = $tt;
+ if (!$this->literal($delim)) {
+ break;
}
- $s = $this->seek();
+ }
+ if (count($tags) == 0) {
+ return false;
+ }
- $hasExpression = false;
- $parts = array();
- while ($this->tagBracket($parts, $hasExpression));
+ return true;
+ }
- $oldWhite = $this->eatWhiteDefault;
- $this->eatWhiteDefault = false;
+ // list of tags of specifying mixin path
+ // optionally separated by > (lazy, accepts extra >)
+ protected function mixinTags(&$tags)
+ {
+ $tags = array();
+ while ($this->tag($tt, true)) {
+ $tags[] = $tt;
+ $this->literal(">");
+ }
+ if (!$tags) {
+ return false;
+ }
+
+ return true;
+ }
+
+ // a bracketed value (contained within in a tag definition)
+ protected function tagBracket(&$parts, &$hasExpression)
+ {
+ // speed shortcut
+ if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") {
+ return false;
+ }
+
+ $s = $this->seek();
+
+ $hasInterpolation = false;
+
+ if ($this->literal("[", false)) {
+ $attrParts = array("[");
+ // keyword, string, operator
while (true) {
- if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
- $parts[] = $m[1];
- if ($simple) break;
+ if ($this->literal("]", false)) {
+ $this->count--;
+ break; // get out early
+ }
- while ($this->tagBracket($parts, $hasExpression));
+ if ($this->match('\s+', $m)) {
+ $attrParts[] = " ";
+ continue;
+ }
+ if ($this->string($str)) {
+ // escape parent selector, (yuck)
+ foreach ($str[2] as &$chunk) {
+ $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk);
+ }
+
+ $attrParts[] = $str;
+ $hasInterpolation = true;
continue;
}
- if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
- if ($this->interpolation($interp)) {
- $hasExpression = true;
- $interp[2] = true; // don't unescape
- $parts[] = $interp;
- continue;
- }
-
- if ($this->literal("@")) {
- $parts[] = "@";
- continue;
- }
+ if ($this->keyword($word)) {
+ $attrParts[] = $word;
+ continue;
}
- if ($this->unit($unit)) { // for keyframes
- $parts[] = $unit[1];
- $parts[] = $unit[2];
+ if ($this->interpolation($inter)) {
+ $attrParts[] = $inter;
+ $hasInterpolation = true;
+ continue;
+ }
+
+ // operator, handles attr namespace too
+ if ($this->match('[|-~\$\*\^=]+', $m)) {
+ $attrParts[] = $m[0];
continue;
}
break;
}
- $this->eatWhiteDefault = $oldWhite;
- if (!$parts) {
- $this->seek($s);
- return false;
+ if ($this->literal("]", false)) {
+ $attrParts[] = "]";
+ foreach ($attrParts as $part) {
+ $parts[] = $part;
+ }
+ $hasExpression = $hasExpression || $hasInterpolation;
+ return true;
}
-
- if ($hasExpression) {
- $tag = array("exp", array("string", "", $parts));
- } else {
- $tag = trim(implode($parts));
- }
-
- $this->whitespace();
- return true;
+ $this->seek($s);
}
- // a css function
- protected function func(&$func) {
- $s = $this->seek();
+ $this->seek($s);
+ return false;
+ }
- if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
- $fname = $m[1];
+ // a space separated list of selectors
+ protected function tag(&$tag, $simple = false)
+ {
+ if ($simple) {
+ $chars = '^@,:;{}\][>\(\) "\'';
+ } else {
+ $chars = '^@,;{}["\'';
+ }
+ $s = $this->seek();
- $sPreArgs = $this->seek();
+ $hasExpression = false;
+ $parts = array();
+ while ($this->tagBracket($parts, $hasExpression));
- $args = array();
- while (true) {
- $ss = $this->seek();
- // this ugly nonsense is for ie filter properties
- if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
- $args[] = array("string", "", array($name, "=", $value));
- } else {
- $this->seek($ss);
- if ($this->expressionList($value)) {
- $args[] = $value;
- }
- }
+ $oldWhite = $this->eatWhiteDefault;
+ $this->eatWhiteDefault = false;
- if (!$this->literal(',')) break;
+ while (true) {
+ if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
+ $parts[] = $m[1];
+ if ($simple) {
+ break;
}
- $args = array('list', ',', $args);
- if ($this->literal(')')) {
- $func = array('function', $fname, $args);
- return true;
- } elseif ($fname == 'url') {
- // couldn't parse and in url? treat as string
- $this->seek($sPreArgs);
- if ($this->openString(")", $string) && $this->literal(")")) {
- $func = array('function', $fname, $string);
- return true;
- }
+ while ($this->tagBracket($parts, $hasExpression));
+ continue;
+ }
+
+ if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
+ if ($this->interpolation($interp)) {
+ $hasExpression = true;
+ $interp[2] = true; // don't unescape
+ $parts[] = $interp;
+ continue;
+ }
+
+ if ($this->literal("@")) {
+ $parts[] = "@";
+ continue;
}
}
+ if ($this->unit($unit)) { // for keyframes
+ $parts[] = $unit[1];
+ $parts[] = $unit[2];
+ continue;
+ }
+
+ break;
+ }
+
+ $this->eatWhiteDefault = $oldWhite;
+ if (!$parts) {
$this->seek($s);
return false;
}
- // consume a less variable
- protected function variable(&$name) {
- $s = $this->seek();
- if ($this->literal($this->lessc->vPrefix, false) &&
- ($this->variable($sub) || $this->keyword($name))
- ) {
- if (!empty($sub)) {
- $name = array('variable', $sub);
- } else {
- $name = $this->lessc->vPrefix.$name;
+ if ($hasExpression) {
+ $tag = array("exp", array("string", "", $parts));
+ } else {
+ $tag = trim(implode($parts));
+ }
+
+ $this->whitespace();
+ return true;
+ }
+
+ // a css function
+ protected function func(&$func)
+ {
+ $s = $this->seek();
+
+ if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
+ $fname = $m[1];
+
+ $sPreArgs = $this->seek();
+
+ $args = array();
+ while (true) {
+ $ss = $this->seek();
+ // this ugly nonsense is for ie filter properties
+ if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
+ $args[] = array("string", "", array($name, "=", $value));
+ } else {
+ $this->seek($ss);
+ if ($this->expressionList($value)) {
+ $args[] = $value;
}
- return true;
}
- $name = null;
- $this->seek($s);
- return false;
+ if (!$this->literal(',')) {
+ break;
+ }
+ }
+ $args = array('list', ',', $args);
+
+ if ($this->literal(')')) {
+ $func = array('function', $fname, $args);
+ return true;
+ } elseif ($fname == 'url') {
+ // couldn't parse and in url? treat as string
+ $this->seek($sPreArgs);
+ if ($this->openString(")", $string) && $this->literal(")")) {
+ $func = array('function', $fname, $string);
+ return true;
+ }
+ }
}
+ $this->seek($s);
+ return false;
+ }
+
+ // consume a less variable
+ protected function variable(&$name)
+ {
+ $s = $this->seek();
+ if ($this->literal($this->lessc->vPrefix, false) &&
+ ($this->variable($sub) || $this->keyword($name))
+ ) {
+ if (!empty($sub)) {
+ $name = array('variable', $sub);
+ } else {
+ $name = $this->lessc->vPrefix.$name;
+ }
+ return true;
+ }
+
+ $name = null;
+ $this->seek($s);
+ return false;
+ }
+
/**
* Consume an assignment operator
* Can optionally take a name that will be set to the current property name
*/
- protected function assign($name = null) {
- if ($name) $this->currentProperty = $name;
- return $this->literal(':') || $this->literal('=');
+ protected function assign($name = null)
+ {
+ if ($name) {
+ $this->currentProperty = $name;
}
+ return $this->literal(':') || $this->literal('=');
+ }
// consume a keyword
- protected function keyword(&$word) {
- if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
- $word = $m[1];
- return true;
- }
- return false;
+ protected function keyword(&$word)
+ {
+ if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
+ $word = $m[1];
+ return true;
}
+ return false;
+ }
// consume an end of statement delimiter
- protected function end() {
- if ($this->literal(';', false)) {
- return true;
- } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] == '}') {
- // if there is end of file or a closing block next then we don't need a ;
- return true;
- }
- return false;
- }
-
- protected function guards(&$guards) {
- $s = $this->seek();
-
- if (!$this->literal("when")) {
- $this->seek($s);
- return false;
- }
-
- $guards = array();
-
- while ($this->guardGroup($g)) {
- $guards[] = $g;
- if (!$this->literal(",")) break;
- }
-
- if (count($guards) == 0) {
- $guards = null;
- $this->seek($s);
- return false;
- }
-
+ protected function end()
+ {
+ if ($this->literal(';', false)) {
+ return true;
+ } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] == '}') {
+ // if there is end of file or a closing block next then we don't need a ;
return true;
}
+ return false;
+ }
- // a bunch of guards that are and'd together
- // TODO rename to guardGroup
- protected function guardGroup(&$guardGroup) {
- $s = $this->seek();
- $guardGroup = array();
- while ($this->guard($guard)) {
- $guardGroup[] = $guard;
- if (!$this->literal("and")) break;
- }
-
- if (count($guardGroup) == 0) {
- $guardGroup = null;
- $this->seek($s);
- return false;
- }
-
- return true;
- }
-
- protected function guard(&$guard) {
- $s = $this->seek();
- $negate = $this->literal("not");
-
- if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
- $guard = $exp;
- if ($negate) $guard = array("negate", $guard);
- return true;
- }
+ protected function guards(&$guards)
+ {
+ $s = $this->seek();
+ if (!$this->literal("when")) {
$this->seek($s);
return false;
}
- /* raw parsing functions */
+ $guards = array();
- protected function literal($what, $eatWhitespace = null) {
- if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
-
- // shortcut on single letter
- if (!isset($what[1]) && isset($this->buffer[$this->count])) {
- if ($this->buffer[$this->count] == $what) {
- if (!$eatWhitespace) {
- $this->count++;
- return true;
- }
- // goes below...
- } else {
- return false;
- }
+ while ($this->guardGroup($g)) {
+ $guards[] = $g;
+ if (!$this->literal(",")) {
+ break;
}
-
- if (!isset(self::$literalCache[$what])) {
- self::$literalCache[$what] = lessc::preg_quote($what);
- }
-
- return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
}
- protected function genericList(&$out, $parseItem, $delim = "", $flatten = true) {
- $s = $this->seek();
- $items = array();
- while ($this->$parseItem($value)) {
- $items[] = $value;
- if ($delim) {
- if (!$this->literal($delim)) break;
- }
- }
+ if (count($guards) == 0) {
+ $guards = null;
+ $this->seek($s);
+ return false;
+ }
- if (count($items) == 0) {
- $this->seek($s);
- return false;
- }
+ return true;
+ }
- if ($flatten && count($items) == 1) {
- $out = $items[0];
- } else {
- $out = array("list", $delim, $items);
+ // a bunch of guards that are and'd together
+ // TODO rename to guardGroup
+ protected function guardGroup(&$guardGroup)
+ {
+ $s = $this->seek();
+ $guardGroup = array();
+ while ($this->guard($guard)) {
+ $guardGroup[] = $guard;
+ if (!$this->literal("and")) {
+ break;
}
+ }
+ if (count($guardGroup) == 0) {
+ $guardGroup = null;
+ $this->seek($s);
+ return false;
+ }
+
+ return true;
+ }
+
+ protected function guard(&$guard)
+ {
+ $s = $this->seek();
+ $negate = $this->literal("not");
+
+ if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
+ $guard = $exp;
+ if ($negate) {
+ $guard = array("negate", $guard);
+ }
return true;
}
+ $this->seek($s);
+ return false;
+ }
+
+ /* raw parsing functions */
+
+ protected function literal($what, $eatWhitespace = null)
+ {
+ if ($eatWhitespace === null) {
+ $eatWhitespace = $this->eatWhiteDefault;
+ }
+
+ // shortcut on single letter
+ if (!isset($what[1]) && isset($this->buffer[$this->count])) {
+ if ($this->buffer[$this->count] == $what) {
+ if (!$eatWhitespace) {
+ $this->count++;
+ return true;
+ }
+ // goes below...
+ } else {
+ return false;
+ }
+ }
+
+ if (!isset(self::$literalCache[$what])) {
+ self::$literalCache[$what] = lessc::preg_quote($what);
+ }
+
+ return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
+ }
+
+ protected function genericList(&$out, $parseItem, $delim = "", $flatten = true)
+ {
+ $s = $this->seek();
+ $items = array();
+ while ($this->$parseItem($value)) {
+ $items[] = $value;
+ if ($delim) {
+ if (!$this->literal($delim)) {
+ break;
+ }
+ }
+ }
+
+ if (count($items) == 0) {
+ $this->seek($s);
+ return false;
+ }
+
+ if ($flatten && count($items) == 1) {
+ $out = $items[0];
+ } else {
+ $out = array("list", $delim, $items);
+ }
+
+ return true;
+ }
+
// advance counter to next occurrence of $what
// $until - don't include $what in advance
// $allowNewline, if string, will be used as valid char set
- protected function to($what, &$out, $until = false, $allowNewline = false) {
- if (is_string($allowNewline)) {
- $validChars = $allowNewline;
- } else {
- $validChars = $allowNewline ? "." : "[^\n]";
- }
- if (!$this->match('('.$validChars.'*?)'.lessc::preg_quote($what), $m, !$until)) return false;
- if ($until) $this->count -= strlen($what); // give back $what
- $out = $m[1];
- return true;
+ protected function to($what, &$out, $until = false, $allowNewline = false)
+ {
+ if (is_string($allowNewline)) {
+ $validChars = $allowNewline;
+ } else {
+ $validChars = $allowNewline ? "." : "[^\n]";
}
-
- // try to match something on head of buffer
- protected function match($regex, &$out, $eatWhitespace = null) {
- if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
-
- $r = '/'.$regex.($eatWhitespace && !$this->writeComments ? '\s*' : '').'/Ais';
- if (preg_match($r, $this->buffer, $out, null, $this->count)) {
- $this->count += strlen($out[0]);
- if ($eatWhitespace && $this->writeComments) $this->whitespace();
- return true;
- }
+ if (!$this->match('('.$validChars.'*?)'.lessc::preg_quote($what), $m, !$until)) {
return false;
}
+ if ($until) {
+ $this->count -= strlen($what); // give back $what
+ }
+ $out = $m[1];
+ return true;
+ }
- // match some whitespace
- protected function whitespace() {
- if ($this->writeComments) {
- $gotWhite = false;
- while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) {
- if (isset($m[1]) && empty($this->seenComments[$this->count])) {
- $this->append(array("comment", $m[1]));
- $this->seenComments[$this->count] = true;
- }
- $this->count += strlen($m[0]);
- $gotWhite = true;
- }
- return $gotWhite;
- } else {
- $this->match("", $m);
- return strlen($m[0]) > 0;
+ // try to match something on head of buffer
+ protected function match($regex, &$out, $eatWhitespace = null)
+ {
+ if ($eatWhitespace === null) {
+ $eatWhitespace = $this->eatWhiteDefault;
+ }
+
+ $r = '/'.$regex.($eatWhitespace && !$this->writeComments ? '\s*' : '').'/Ais';
+ if (preg_match($r, $this->buffer, $out, null, $this->count)) {
+ $this->count += strlen($out[0]);
+ if ($eatWhitespace && $this->writeComments) {
+ $this->whitespace();
}
- }
-
- // match something without consuming it
- protected function peek($regex, &$out = null, $from = null) {
- if (is_null($from)) $from = $this->count;
- $r = '/'.$regex.'/Ais';
- $result = preg_match($r, $this->buffer, $out, null, $from);
-
- return $result;
- }
-
- // seek to a spot in the buffer or return where we are on no argument
- protected function seek($where = null) {
- if ($where === null) return $this->count;
- else $this->count = $where;
return true;
}
+ return false;
+ }
+
+ // match some whitespace
+ protected function whitespace()
+ {
+ if ($this->writeComments) {
+ $gotWhite = false;
+ while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) {
+ if (isset($m[1]) && empty($this->seenComments[$this->count])) {
+ $this->append(array("comment", $m[1]));
+ $this->seenComments[$this->count] = true;
+ }
+ $this->count += strlen($m[0]);
+ $gotWhite = true;
+ }
+ return $gotWhite;
+ } else {
+ $this->match("", $m);
+ return strlen($m[0]) > 0;
+ }
+ }
+
+ // match something without consuming it
+ protected function peek($regex, &$out = null, $from = null)
+ {
+ if (is_null($from)) {
+ $from = $this->count;
+ }
+ $r = '/'.$regex.'/Ais';
+ $result = preg_match($r, $this->buffer, $out, null, $from);
+
+ return $result;
+ }
+
+ // seek to a spot in the buffer or return where we are on no argument
+ protected function seek($where = null)
+ {
+ if ($where === null) {
+ return $this->count;
+ } else {
+ $this->count = $where;
+ }
+ return true;
+ }
/* misc functions */
- public function throwError($msg = "parse error", $count = null) {
- $count = is_null($count) ? $this->count : $count;
+ public function throwError($msg = "parse error", $count = null)
+ {
+ $count = is_null($count) ? $this->count : $count;
- $line = $this->line +
- substr_count(substr($this->buffer, 0, $count), "\n");
+ $line = $this->line +
+ substr_count(substr($this->buffer, 0, $count), "\n");
- if (!empty($this->sourceName)) {
- $loc = "$this->sourceName on line $line";
- } else {
- $loc = "line: $line";
- }
-
- // TODO this depends on $this->count
- if ($this->peek("(.*?)(\n|$)", $m, $count)) {
- throw new exception("$msg: failed at `$m[1]` $loc");
- } else {
- throw new exception("$msg: $loc");
- }
+ if (!empty($this->sourceName)) {
+ $loc = "$this->sourceName on line $line";
+ } else {
+ $loc = "line: $line";
}
- protected function pushBlock($selectors = null, $type = null) {
- $b = new stdclass;
- $b->parent = $this->env;
-
- $b->type = $type;
- $b->id = self::$nextBlockId++;
-
- $b->isVararg = false; // TODO: kill me from here
- $b->tags = $selectors;
-
- $b->props = array();
- $b->children = array();
-
- $this->env = $b;
- return $b;
+ // TODO this depends on $this->count
+ if ($this->peek("(.*?)(\n|$)", $m, $count)) {
+ throw new exception("$msg: failed at `$m[1]` $loc");
+ } else {
+ throw new exception("$msg: $loc");
}
+ }
+
+ protected function pushBlock($selectors = null, $type = null)
+ {
+ $b = new stdclass;
+ $b->parent = $this->env;
+
+ $b->type = $type;
+ $b->id = self::$nextBlockId++;
+
+ $b->isVararg = false; // TODO: kill me from here
+ $b->tags = $selectors;
+
+ $b->props = array();
+ $b->children = array();
+
+ $this->env = $b;
+ return $b;
+ }
// push a block that doesn't multiply tags
- protected function pushSpecialBlock($type) {
- return $this->pushBlock(null, $type);
- }
+ protected function pushSpecialBlock($type)
+ {
+ return $this->pushBlock(null, $type);
+ }
// append a property to the current block
- protected function append($prop, $pos = null) {
- if ($pos !== null) $prop[-1] = $pos;
- $this->env->props[] = $prop;
+ protected function append($prop, $pos = null)
+ {
+ if ($pos !== null) {
+ $prop[-1] = $pos;
}
+ $this->env->props[] = $prop;
+ }
// pop something off the stack
- protected function pop() {
- $old = $this->env;
- $this->env = $this->env->parent;
- return $old;
- }
+ protected function pop()
+ {
+ $old = $this->env;
+ $this->env = $this->env->parent;
+ return $old;
+ }
// remove comments from $text
// todo: make it work for all functions, not just url
- protected function removeComments($text) {
- $look = array(
- 'url(', '//', '/*', '"', "'"
- );
+ protected function removeComments($text)
+ {
+ $look = array(
+ 'url(', '//', '/*', '"', "'"
+ );
- $out = '';
- $min = null;
- while (true) {
- // find the next item
- foreach ($look as $token) {
- $pos = strpos($text, $token);
- if ($pos !== false) {
- if (!isset($min) || $pos < $min[1]) $min = array($token, $pos);
+ $out = '';
+ $min = null;
+ while (true) {
+ // find the next item
+ foreach ($look as $token) {
+ $pos = strpos($text, $token);
+ if ($pos !== false) {
+ if (!isset($min) || $pos < $min[1]) {
+ $min = array($token, $pos);
}
}
-
- if (is_null($min)) break;
-
- $count = $min[1];
- $skip = 0;
- $newlines = 0;
- switch ($min[0]) {
- case 'url(':
- if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
- $count += strlen($m[0]) - strlen($min[0]);
- break;
- case '"':
- case "'":
- if (preg_match('/'.$min[0].'.*?(?indentLevel = 0;
}
- public function indentStr($n = 0) {
+ public function indentStr($n = 0)
+ {
return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
}
- public function property($name, $value) {
+ public function property($name, $value)
+ {
return $name.$this->assignSeparator.$value.";";
}
- protected function isEmpty($block) {
+ protected function isEmpty($block)
+ {
if (empty($block->lines)) {
foreach ($block->children as $child) {
- if (!$this->isEmpty($child)) return false;
+ if (!$this->isEmpty($child)) {
+ return false;
+ }
}
return true;
@@ -3818,8 +4164,11 @@ class lessc_formatter_classic {
return false;
}
- public function block($block) {
- if ($this->isEmpty($block)) return;
+ public function block($block)
+ {
+ if ($this->isEmpty($block)) {
+ return;
+ }
$inner = $pre = $this->indentStr();
@@ -3844,7 +4193,6 @@ class lessc_formatter_classic {
echo $this->open.$this->break;
$inner = $this->indentStr();
}
-
}
if (!empty($block->lines)) {
@@ -3860,7 +4208,9 @@ class lessc_formatter_classic {
}
if (!empty($block->selectors)) {
- if (!$isSingle && empty($block->children)) echo $this->break;
+ if (!$isSingle && empty($block->children)) {
+ echo $this->break;
+ }
if ($isSingle) {
echo $this->closeSingle.$this->break;
@@ -3876,7 +4226,8 @@ class lessc_formatter_classic {
/**
* Class for compressed result
*/
-class lessc_formatter_compressed extends lessc_formatter_classic {
+class lessc_formatter_compressed extends lessc_formatter_classic
+{
public $disableSingle = true;
public $open = "{";
public $selectorSeparator = ",";
@@ -3884,7 +4235,8 @@ class lessc_formatter_compressed extends lessc_formatter_classic {
public $break = "";
public $compressColors = true;
- public function indentStr($n = 0) {
+ public function indentStr($n = 0)
+ {
return "";
}
}
@@ -3892,7 +4244,8 @@ class lessc_formatter_compressed extends lessc_formatter_classic {
/**
* Class for lessjs
*/
-class lessc_formatter_lessjs extends lessc_formatter_classic {
+class lessc_formatter_lessjs extends lessc_formatter_classic
+{
public $disableSingle = true;
public $breakSelectors = true;
public $assignSeparator = ": ";
diff --git a/htdocs/core/class/link.class.php b/htdocs/core/class/link.class.php
index 2c08d2709ca..0f59859bd64 100644
--- a/htdocs/core/class/link.class.php
+++ b/htdocs/core/class/link.class.php
@@ -112,14 +112,15 @@ class Link extends CommonObject
if ($this->id > 0) {
// Call trigger
$result = $this->call_trigger('LINK_CREATE', $user);
- if ($result < 0) $error++;
+ if ($result < 0) {
+ $error++;
+ }
// End call triggers
} else {
$error++;
}
- if (!$error)
- {
+ if (!$error) {
dol_syslog(get_class($this)."::Create success id=".$this->id);
$this->db->commit();
return $this->id;
@@ -129,8 +130,7 @@ class Link extends CommonObject
return -3;
}
} else {
- if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
- {
+ if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
$this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name);
$result = -1;
} else {
@@ -160,15 +160,16 @@ class Link extends CommonObject
dol_syslog(get_class($this)."::Update id = ".$this->id." call_trigger = ".$call_trigger);
// Check parameters
- if (empty($this->url))
- {
+ if (empty($this->url)) {
$this->error = $langs->trans("NoURL");
return -1;
}
// Clean parameters
$this->url = clean_url($this->url, 1);
- if (empty($this->label)) $this->label = basename($this->url);
+ if (empty($this->label)) {
+ $this->label = basename($this->url);
+ }
$this->label = trim($this->label);
@@ -185,18 +186,17 @@ class Link extends CommonObject
dol_syslog(get_class($this)."::update sql = ".$sql);
$resql = $this->db->query($sql);
- if ($resql)
- {
- if ($call_trigger)
- {
+ if ($resql) {
+ if ($call_trigger) {
// Call trigger
$result = $this->call_trigger('LINK_MODIFY', $user);
- if ($result < 0) $error++;
+ if ($result < 0) {
+ $error++;
+ }
// End call triggers
}
- if (!$error)
- {
+ if (!$error) {
dol_syslog(get_class($this)."::Update success");
$this->db->commit();
return 1;
@@ -206,8 +206,7 @@ class Link extends CommonObject
return -1;
}
} else {
- if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
- {
+ if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
// Doublon
$this->error = $langs->trans("ErrorDuplicateField");
$result = -1;
@@ -236,7 +235,9 @@ class Link extends CommonObject
$sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM ".MAIN_DB_PREFIX."links";
$sql .= " WHERE objecttype = '".$this->db->escape($objecttype)."' AND objectid = ".$objectid;
- if ($conf->entity != 0) $sql .= " AND entity = ".$conf->entity;
+ if ($conf->entity != 0) {
+ $sql .= " AND entity = ".$conf->entity;
+ }
if ($sortfield) {
if (empty($sortorder)) {
$sortorder = "ASC";
@@ -246,14 +247,11 @@ class Link extends CommonObject
dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $this->db->num_rows($resql);
dol_syslog(get_class($this)."::fetchAll ".$num."records", LOG_DEBUG);
- if ($num > 0)
- {
- while ($obj = $this->db->fetch_object($resql))
- {
+ if ($num > 0) {
+ while ($obj = $this->db->fetch_object($resql)) {
$link = new Link($this->db);
$link->id = $obj->rowid;
$link->entity = $obj->entity;
@@ -287,13 +285,16 @@ class Link extends CommonObject
$sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."links";
$sql .= " WHERE objecttype = '".$db->escape($objecttype)."' AND objectid = ".$objectid;
- if ($conf->entity != 0) $sql .= " AND entity = ".$conf->entity;
+ if ($conf->entity != 0) {
+ $sql .= " AND entity = ".$conf->entity;
+ }
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $db->fetch_object($resql);
- if ($obj) return $obj->nb;
+ if ($obj) {
+ return $obj->nb;
+ }
}
return -1;
}
@@ -314,14 +315,14 @@ class Link extends CommonObject
$sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM ".MAIN_DB_PREFIX."links";
$sql .= " WHERE rowid = ".$rowid;
- if ($conf->entity != 0) $sql .= " AND entity = ".$conf->entity;
+ if ($conf->entity != 0) {
+ $sql .= " AND entity = ".$conf->entity;
+ }
dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
- if ($this->db->num_rows($resql) > 0)
- {
+ if ($resql) {
+ if ($this->db->num_rows($resql) > 0) {
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
@@ -356,8 +357,7 @@ class Link extends CommonObject
// Call trigger
$result = $this->call_trigger('LINK_DELETE', $user);
- if ($result < 0)
- {
+ if ($result < 0) {
$this->db->rollback();
return -1;
}
@@ -368,8 +368,7 @@ class Link extends CommonObject
$sql .= " WHERE rowid = ".$this->id;
dol_syslog(get_class($this)."::delete", LOG_DEBUG);
- if (!$this->db->query($sql))
- {
+ if (!$this->db->query($sql)) {
$error++;
$this->error = $this->db->lasterror();
}
diff --git a/htdocs/core/class/menu.class.php b/htdocs/core/class/menu.class.php
index 52bd1ebddad..e88ec701320 100644
--- a/htdocs/core/class/menu.class.php
+++ b/htdocs/core/class/menu.class.php
@@ -118,10 +118,11 @@ class Menu
public function getNbOfVisibleMenuEntries()
{
$nb = 0;
- foreach ($this->liste as $val)
- {
+ foreach ($this->liste as $val) {
//if (dol_eval($val['enabled'], 1)) $nb++;
- if (!empty($val['enabled'])) $nb++; // $val['enabled'] is already evaluated to 0 or 1, no need for dol_eval()
+ if (!empty($val['enabled'])) {
+ $nb++; // $val['enabled'] is already evaluated to 0 or 1, no need for dol_eval()
+ }
}
return $nb;
}
diff --git a/htdocs/core/class/menubase.class.php b/htdocs/core/class/menubase.class.php
index a31c5245ce0..a9fb8b01c16 100644
--- a/htdocs/core/class/menubase.class.php
+++ b/htdocs/core/class/menubase.class.php
@@ -178,7 +178,9 @@ class Menubase
global $conf, $langs;
// Clean parameters
- if (!isset($this->enabled)) $this->enabled = '1';
+ if (!isset($this->enabled)) {
+ $this->enabled = '1';
+ }
$this->menu_handler = trim($this->menu_handler);
$this->module = trim($this->module);
$this->type = trim($this->type);
@@ -195,17 +197,22 @@ class Menubase
$this->perms = trim($this->perms);
$this->enabled = trim($this->enabled);
$this->user = (int) $this->user;
- if (empty($this->position)) $this->position = 0;
- if (!$this->level) $this->level = 0;
+ if (empty($this->position)) {
+ $this->position = 0;
+ }
+ if (!$this->level) {
+ $this->level = 0;
+ }
// Check parameters
- if (empty($this->menu_handler)) return -1;
+ if (empty($this->menu_handler)) {
+ return -1;
+ }
// For PGSQL, we must first found the max rowid and use it as rowid in insert because postgresql
// may use an already used value because its internal cursor does not increase when we do
// an insert with a forced id.
- if (in_array($this->db->type, array('pgsql')))
- {
+ if (in_array($this->db->type, array('pgsql'))) {
$sql = "SELECT MAX(rowid) as maxrowid FROM ".MAIN_DB_PREFIX."menu";
$resqlrowid = $this->db->query($sql);
if ($resqlrowid) {
@@ -213,13 +220,19 @@ class Menubase
$maxrowid = $obj->maxrowid;
// Max rowid can be empty if there is no record yet
- if (empty($maxrowid)) $maxrowid = 1;
+ if (empty($maxrowid)) {
+ $maxrowid = 1;
+ }
$sql = "SELECT setval('".MAIN_DB_PREFIX."menu_rowid_seq', ".($maxrowid).")";
//print $sql; exit;
$resqlrowidset = $this->db->query($sql);
- if (!$resqlrowidset) dol_print_error($this->db);
- } else dol_print_error($this->db);
+ if (!$resqlrowidset) {
+ dol_print_error($this->db);
+ }
+ } else {
+ dol_print_error($this->db);
+ }
}
// Check that entry does not exists yet on key menu_handler-fk_menu-position-url-entity, to avoid errors with postgresql
@@ -232,12 +245,10 @@ class Menubase
$sql .= " AND entity = ".$conf->entity;
$result = $this->db->query($sql);
- if ($result)
- {
+ if ($result) {
$row = $this->db->fetch_row($result);
- if ($row[0] == 0) // If not found
- {
+ if ($row[0] == 0) { // If not found
// Insert request
$sql = "INSERT INTO ".MAIN_DB_PREFIX."menu(";
$sql .= "menu_handler,";
@@ -281,8 +292,7 @@ class Menubase
dol_syslog(get_class($this)."::create", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."menu");
dol_syslog(get_class($this)."::create record added has rowid=".$this->id, LOG_DEBUG);
@@ -358,8 +368,7 @@ class Menubase
dol_syslog(get_class($this)."::update", LOG_DEBUG);
$resql = $this->db->query($sql);
- if (!$resql)
- {
+ if (!$resql) {
$this->error = "Error ".$this->db->lasterror();
return -1;
}
@@ -405,10 +414,8 @@ class Menubase
dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
- if ($this->db->num_rows($resql))
- {
+ if ($resql) {
+ if ($this->db->num_rows($resql)) {
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
@@ -458,8 +465,7 @@ class Menubase
dol_syslog(get_class($this)."::delete", LOG_DEBUG);
$resql = $this->db->query($sql);
- if (!$resql)
- {
+ if (!$resql) {
$this->error = "Error ".$this->db->lasterror();
return -1;
}
@@ -517,7 +523,9 @@ class Menubase
$newTabMenu = array();
foreach ($tabMenu as $val) {
- if ($val['type'] == 'top') $newTabMenu[] = $val;
+ if ($val['type'] == 'top') {
+ $newTabMenu[] = $val;
+ }
}
return $newTabMenu;
@@ -545,11 +553,9 @@ class Menubase
// Detect what is top mainmenu id
$menutopid = '';
- foreach ($tabMenu as $key => $val)
- {
+ foreach ($tabMenu as $key => $val) {
// Define menutopid of mainmenu
- if (empty($menutopid) && $val['type'] == 'top' && $val['mainmenu'] == $mainmenu)
- {
+ if (empty($menutopid) && $val['type'] == 'top' && $val['mainmenu'] == $mainmenu) {
$menutopid = $val['rowid'];
break;
}
@@ -562,10 +568,8 @@ class Menubase
$this->recur($tabMenu, $menutopid, 1);
// Now complete $this->newmenu->list when fk_menu value is -1 (left menu added by modules with no top menu)
- foreach ($tabMenu as $key => $val)
- {
- if ($val['fk_menu'] == -1 && $val['fk_mainmenu'] == $mainmenu) // We found a menu entry not linked to parent with good mainmenu
- {
+ foreach ($tabMenu as $key => $val) {
+ if ($val['fk_menu'] == -1 && $val['fk_mainmenu'] == $mainmenu) { // We found a menu entry not linked to parent with good mainmenu
//print 'Try to add menu (current is mainmenu='.$mainmenu.' leftmenu='.$leftmenu.') for '.join(',',$val).' fk_mainmenu='.$val['fk_mainmenu'].' fk_leftmenu='.$val['fk_leftmenu'].' ';
//var_dump($this->newmenu->liste);exit;
@@ -575,14 +579,13 @@ class Menubase
} else {
// Search first menu with this couple (mainmenu,leftmenu)=(fk_mainmenu,fk_leftmenu)
$searchlastsub = 0; $lastid = 0; $nextid = 0; $found = 0;
- foreach ($this->newmenu->liste as $keyparent => $valparent)
- {
+ foreach ($this->newmenu->liste as $keyparent => $valparent) {
//var_dump($valparent);
- if ($searchlastsub) // If we started to search for last submenu
- {
- if ($valparent['level'] >= $searchlastsub) $lastid = $keyparent;
- if ($valparent['level'] < $searchlastsub)
- {
+ if ($searchlastsub) { // If we started to search for last submenu
+ if ($valparent['level'] >= $searchlastsub) {
+ $lastid = $keyparent;
+ }
+ if ($valparent['level'] < $searchlastsub) {
$nextid = $keyparent;
break;
}
@@ -632,52 +635,53 @@ class Menubase
$sql .= " FROM ".MAIN_DB_PREFIX."menu as m";
$sql .= " WHERE m.entity IN (0,".$conf->entity.")";
$sql .= " AND m.menu_handler IN ('".$this->db->escape($menu_handler)."','all')";
- if ($type_user == 0) $sql .= " AND m.usertype IN (0,2)";
- if ($type_user == 1) $sql .= " AND m.usertype IN (1,2)";
+ if ($type_user == 0) {
+ $sql .= " AND m.usertype IN (0,2)";
+ }
+ if ($type_user == 1) {
+ $sql .= " AND m.usertype IN (1,2)";
+ }
$sql .= " ORDER BY m.position, m.rowid";
//print $sql;
//dol_syslog(get_class($this)."::menuLoad mymainmenu=".$mymainmenu." myleftmenu=".$myleftmenu." type_user=".$type_user." menu_handler=".$menu_handler." tabMenu size=".count($tabMenu)."", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$numa = $this->db->num_rows($resql);
$a = 0;
$b = 0;
- while ($a < $numa)
- {
+ while ($a < $numa) {
//$objm = $this->db->fetch_object($resql);
$menu = $this->db->fetch_array($resql);
// Define $right
$perms = true;
- if (isset($menu['perms']))
- {
+ if (isset($menu['perms'])) {
$tmpcond = $menu['perms'];
- if ($leftmenu == 'all') $tmpcond = preg_replace('/\$leftmenu\s*==\s*["\'a-zA-Z_]+/', '1==1', $tmpcond); // Force part of condition to true
+ if ($leftmenu == 'all') {
+ $tmpcond = preg_replace('/\$leftmenu\s*==\s*["\'a-zA-Z_]+/', '1==1', $tmpcond); // Force part of condition to true
+ }
$perms = verifCond($tmpcond);
//print "verifCond rowid=".$menu['rowid']." ".$tmpcond.":".$perms." \n";
}
// Define $enabled
$enabled = true;
- if (isset($menu['enabled']))
- {
+ if (isset($menu['enabled'])) {
$tmpcond = $menu['enabled'];
- if ($leftmenu == 'all') $tmpcond = preg_replace('/\$leftmenu\s*==\s*["\'a-zA-Z_]+/', '1==1', $tmpcond); // Force part of condition to true
+ if ($leftmenu == 'all') {
+ $tmpcond = preg_replace('/\$leftmenu\s*==\s*["\'a-zA-Z_]+/', '1==1', $tmpcond); // Force part of condition to true
+ }
$enabled = verifCond($tmpcond);
}
// Define $title
- if ($enabled)
- {
+ if ($enabled) {
$title = $langs->trans($menu['titre']); // If $menu['titre'] start with $, a dol_eval is done.
//var_dump($title.'-'.$menu['titre']);
- if ($title == $menu['titre']) // Translation not found
- {
- if (!empty($menu['langs'])) // If there is a dedicated translation file
- {
+ if ($title == $menu['titre']) { // Translation not found
+ if (!empty($menu['langs'])) { // If there is a dedicated translation file
//print 'Load file '.$menu['langs'].' ';
$langs->load($menu['langs']);
}
@@ -685,12 +689,10 @@ class Menubase
$substitarray = array('__LOGIN__' => $user->login, '__USER_ID__' => $user->id, '__USER_SUPERVISOR_ID__' => $user->fk_user);
$menu['titre'] = make_substitutions($menu['titre'], $substitarray);
- if (preg_match("/\//", $menu['titre'])) // To manage translation when title is string1/string2
- {
+ if (preg_match("/\//", $menu['titre'])) { // To manage translation when title is string1/string2
$tab_titre = explode("/", $menu['titre']);
$title = $langs->trans($tab_titre[0])."/".$langs->trans($tab_titre[1]);
- } elseif (preg_match('/\|\|/', $menu['titre']))
- {
+ } elseif (preg_match('/\|\|/', $menu['titre'])) {
// To manage different translation (Title||AltTitle@ConditionForAltTitle)
$tab_title = explode("||", $menu['titre']);
$alt_title = explode("@", $tab_title[1]);
@@ -758,8 +760,7 @@ class Menubase
{
// Loop on tab array
$num = count($tab);
- for ($x = 0; $x < $num; $x++)
- {
+ for ($x = 0; $x < $num; $x++) {
//si un element a pour pere : $pere
if ((($tab[$x]['fk_menu'] >= 0 && $tab[$x]['fk_menu'] == $pere)) && $tab[$x]['enabled']) {
$this->newmenu->add($tab[$x]['url'], $tab[$x]['titre'], ($level - 1), $tab[$x]['perms'], $tab[$x]['target'], $tab[$x]['mainmenu'], $tab[$x]['leftmenu'], 0, '', '', '', $tab[$x]['prefix']);
diff --git a/htdocs/core/class/notify.class.php b/htdocs/core/class/notify.class.php
index 86380651658..add5ccda7b3 100644
--- a/htdocs/core/class/notify.class.php
+++ b/htdocs/core/class/notify.class.php
@@ -82,7 +82,7 @@ class Notify
'EXPENSE_REPORT_APPROVE',
'HOLIDAY_VALIDATE',
'HOLIDAY_APPROVE',
- 'ACTION_CREATE'
+ 'ACTION_CREATE'
);
@@ -531,18 +531,18 @@ class Notify
$object_type = 'holiday';
$mesg = $outputlangs->transnoentitiesnoconv("EMailTextHolidayValidated", $link);
break;
- case 'HOLIDAY_APPROVE':
- $link = ''.$newref.' ';
- $dir_output = $conf->holiday->dir_output;
- $object_type = 'holiday';
- $mesg = $outputlangs->transnoentitiesnoconv("EMailTextHolidayApproved", $link);
- break;
- case 'ACTION_CREATE':
- $link = ''.$newref.' ';
- $dir_output = $conf->agenda->dir_output;
- $object_type = 'action';
- $mesg = $outputlangs->transnoentitiesnoconv("EMailTextActionAdded", $link);
- break;
+ case 'HOLIDAY_APPROVE':
+ $link = ''.$newref.' ';
+ $dir_output = $conf->holiday->dir_output;
+ $object_type = 'holiday';
+ $mesg = $outputlangs->transnoentitiesnoconv("EMailTextHolidayApproved", $link);
+ break;
+ case 'ACTION_CREATE':
+ $link = ''.$newref.' ';
+ $dir_output = $conf->agenda->dir_output;
+ $object_type = 'action';
+ $mesg = $outputlangs->transnoentitiesnoconv("EMailTextActionAdded", $link);
+ break;
}
$ref = dol_sanitizeFileName($newref);
$pdf_path = $dir_output."/".$ref."/".$ref.".pdf";
@@ -756,12 +756,12 @@ class Notify
$object_type = 'holiday';
$mesg = $langs->transnoentitiesnoconv("EMailTextHolidayApproved", $link);
break;
- case 'ACTION_CREATE':
- $link = ''.$newref.' ';
- $dir_output = $conf->agenda->dir_output;
- $object_type = 'action';
- $mesg = $langs->transnoentitiesnoconv("EMailTextActionAdded", $link);
- break;
+ case 'ACTION_CREATE':
+ $link = ''.$newref.' ';
+ $dir_output = $conf->agenda->dir_output;
+ $object_type = 'action';
+ $mesg = $langs->transnoentitiesnoconv("EMailTextActionAdded", $link);
+ break;
}
$ref = dol_sanitizeFileName($newref);
$pdf_path = $dir_output."/".$ref."/".$ref.".pdf";
diff --git a/htdocs/core/class/openid.class.php b/htdocs/core/class/openid.class.php
index b2a265c47d5..5156e7b767a 100644
--- a/htdocs/core/class/openid.class.php
+++ b/htdocs/core/class/openid.class.php
@@ -39,8 +39,7 @@ class SimpleOpenID
*/
public function __construct()
{
- if (!function_exists('curl_exec'))
- {
+ if (!function_exists('curl_exec')) {
die('Error: Class SimpleOpenID requires curl extension to work');
}
}
@@ -147,18 +146,18 @@ class SimpleOpenID
$a = 'http://'.$a;
}
/*
- $u = parse_url(trim($a));
- if (!isset($u['path'])){
- $u['path'] = '/';
- }else if(substr($u['path'],-1,1) == '/'){
- $u['path'] = substr($u['path'], 0, strlen($u['path'])-1);
- }
- if (isset($u['query'])){ // If there is a query string, then use identity as is
- $identity = $a;
- }else{
- $identity = $u['scheme'] . '://' . $u['host'] . $u['path'];
- }
- */
+ $u = parse_url(trim($a));
+ if (!isset($u['path'])){
+ $u['path'] = '/';
+ }else if(substr($u['path'],-1,1) == '/'){
+ $u['path'] = substr($u['path'], 0, strlen($u['path'])-1);
+ }
+ if (isset($u['query'])){ // If there is a query string, then use identity as is
+ $identity = $a;
+ }else{
+ $identity = $u['scheme'] . '://' . $u['host'] . $u['path'];
+ }
+ */
$this->openid_url_identity = $a;
}
@@ -215,8 +214,7 @@ class SimpleOpenID
public function IsError()
{
// phpcs:enable
- if (count($this->error) > 0)
- {
+ if (count($this->error) > 0) {
return true;
} else {
return false;
@@ -253,8 +251,9 @@ class SimpleOpenID
public function OpenID_Standarize($openid_identity = null)
{
// phpcs:enable
- if ($openid_identity === null)
- $openid_identity = $this->openid_url_identity;
+ if ($openid_identity === null) {
+ $openid_identity = $this->openid_url_identity;
+ }
$u = parse_url(strtolower(trim($openid_identity)));
@@ -337,7 +336,9 @@ class SimpleOpenID
{
// phpcs:enable
// Remember, SSL MUST BE SUPPORTED
- if (is_array($params)) $params = $this->array2url($params);
+ if (is_array($params)) {
+ $params = $this->array2url($params);
+ }
$curl = curl_init($url.($method == "GET" && $params != "" ? "?".$params : ""));
@curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
@@ -345,7 +346,9 @@ class SimpleOpenID
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPGET, ($method == "GET"));
curl_setopt($curl, CURLOPT_POST, ($method == "POST"));
- if ($method == "POST") curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
+ if ($method == "POST") {
+ curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
+ }
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
@@ -398,7 +401,9 @@ class SimpleOpenID
global $conf;
include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
- if (empty($url)) $url = $conf->global->MAIN_AUTHENTICATION_OPENID_URL;
+ if (empty($url)) {
+ $url = $conf->global->MAIN_AUTHENTICATION_OPENID_URL;
+ }
$response = getURLContent($url);
@@ -451,8 +456,7 @@ class SimpleOpenID
{
// phpcs:enable
$redirect_to = $this->GetRedirectURL();
- if (headers_sent())
- { // Use JavaScript to redirect if content has been previously sent (not recommended, but safe)
+ if (headers_sent()) { // Use JavaScript to redirect if content has been previously sent (not recommended, but safe)
echo '';
@@ -478,8 +482,7 @@ class SimpleOpenID
// Send only required parameters to confirm validity
$arr_signed = explode(",", str_replace('sreg.', 'sreg_', $_GET['openid_signed']));
$num = count($arr_signed);
- for ($i = 0; $i < $num; $i++)
- {
+ for ($i = 0; $i < $num; $i++) {
$s = str_replace('sreg_', 'sreg.', $arr_signed[$i]);
$c = $_GET['openid_'.$arr_signed[$i]];
// if ($c != ""){
@@ -489,14 +492,12 @@ class SimpleOpenID
$params['openid.mode'] = "check_authentication";
$openid_server = $this->GetOpenIDServer();
- if ($openid_server == false)
- {
+ if ($openid_server == false) {
return false;
}
$response = $this->CURL_Request($openid_server, 'POST', $params);
$data = $this->splitResponse($response);
- if ($data['is_valid'] == "true")
- {
+ if ($data['is_valid'] == "true") {
return true;
} else {
return false;
@@ -517,35 +518,35 @@ class SimpleOpenID
global $conf;
include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
- if (empty($url)) $url = $conf->global->MAIN_AUTHENTICATION_OPENID_URL;
+ if (empty($url)) {
+ $url = $conf->global->MAIN_AUTHENTICATION_OPENID_URL;
+ }
dol_syslog(get_class($this).'::sendDiscoveryRequestToGetXRDS get XRDS');
$addheaders = array('Accept: application/xrds+xml');
$response = getURLContent($url, 'GET', '', 1, $addheaders);
/* response should like this:
-
-
-
-
- http://specs.openid.net/auth/2.0/server
- http://openid.net/srv/ax/1.0
- ...
- https://www.google.com/accounts/o8/ud
-
-
-
- */
+
+
+
+
+ http://specs.openid.net/auth/2.0/server
+ http://openid.net/srv/ax/1.0
+ ...
+ https://www.google.com/accounts/o8/ud
+
+
+
+ */
$content = $response['content'];
$server = '';
- if (preg_match('/'.preg_quote('', '/').'(.*)'.preg_quote(' ', '/').'/is', $content, $reg))
- {
+ if (preg_match('/'.preg_quote('', '/').'(.*)'.preg_quote(' ', '/').'/is', $content, $reg)) {
$server = $reg[1];
}
- if (empty($server))
- {
+ if (empty($server)) {
$this->ErrorStore('OPENID_NOSERVERSFOUND');
return false;
} else {
diff --git a/htdocs/core/class/rssparser.class.php b/htdocs/core/class/rssparser.class.php
index 578e180edff..aae4acd7bc0 100644
--- a/htdocs/core/class/rssparser.class.php
+++ b/htdocs/core/class/rssparser.class.php
@@ -194,8 +194,7 @@ class RssParser
$str = ''; // This will contain content of feed
// Check parameters
- if (!dol_is_url($urlRSS))
- {
+ if (!dol_is_url($urlRSS)) {
$this->error = "ErrorBadUrl";
return -1;
}
@@ -209,11 +208,9 @@ class RssParser
// Search into cache
$foundintocache = 0;
- if ($cachedelay > 0 && $cachedir)
- {
+ if ($cachedelay > 0 && $cachedir) {
$filedate = dol_filemtime($newpathofdestfile);
- if ($filedate >= ($nowgmt - $cachedelay))
- {
+ if ($filedate >= ($nowgmt - $cachedelay)) {
//dol_syslog("RssParser::parser cache file ".$newpathofdestfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we use it.");
$foundintocache = 1;
@@ -224,8 +221,7 @@ class RssParser
}
// Load file into $str
- if ($foundintocache) // Cache file found and is not too old
- {
+ if ($foundintocache) { // Cache file found and is not too old
$str = file_get_contents($newpathofdestfile);
} else {
try {
@@ -234,8 +230,12 @@ class RssParser
ini_set("default_socket_timeout", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
$opts = array('http'=>array('method'=>"GET"));
- if (!empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) $opts['http']['timeout'] = $conf->global->MAIN_USE_CONNECT_TIMEOUT;
- if (!empty($conf->global->MAIN_PROXY_USE)) $opts['http']['proxy'] = 'tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
+ if (!empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) {
+ $opts['http']['timeout'] = $conf->global->MAIN_USE_CONNECT_TIMEOUT;
+ }
+ if (!empty($conf->global->MAIN_PROXY_USE)) {
+ $opts['http']['proxy'] = 'tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
+ }
//var_dump($opts);exit;
$context = stream_context_create($opts);
@@ -245,11 +245,9 @@ class RssParser
}
}
- if ($str !== false)
- {
+ if ($str !== false) {
// Convert $str into xml
- if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
- {
+ if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
//print 'xx'.LIBXML_NOCDATA;
libxml_use_internal_errors(false);
$rss = simplexml_load_string($str, "SimpleXMLElement", LIBXML_NOCDATA);
@@ -276,19 +274,20 @@ class RssParser
}
// If $rss loaded
- if ($rss)
- {
+ if ($rss) {
// Save file into cache
- if (empty($foundintocache) && $cachedir)
- {
+ if (empty($foundintocache) && $cachedir) {
dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is saved onto disk.");
- if (!dol_is_dir($cachedir)) dol_mkdir($cachedir);
+ if (!dol_is_dir($cachedir)) {
+ dol_mkdir($cachedir);
+ }
$fp = fopen($newpathofdestfile, 'w');
- if ($fp)
- {
+ if ($fp) {
fwrite($fp, $str);
fclose($fp);
- if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
+ if (!empty($conf->global->MAIN_UMASK)) {
+ $newmask = $conf->global->MAIN_UMASK;
+ }
@chmod($newpathofdestfile, octdec($newmask));
$this->_lastfetchdate = $nowgmt;
@@ -299,10 +298,11 @@ class RssParser
unset($str); // Free memory
- if (empty($rss->_format)) // If format not detected automatically
- {
+ if (empty($rss->_format)) { // If format not detected automatically
$rss->_format = 'rss';
- if (empty($rss->channel)) $rss->_format = 'atom';
+ if (empty($rss->channel)) {
+ $rss->_format = 'atom';
+ }
}
$items = array();
@@ -311,46 +311,98 @@ class RssParser
if ($rss->_format == 'rss') {
//var_dump($rss);
if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
- if (!empty($rss->channel->language)) $this->_language = (string) $rss->channel->language;
- if (!empty($rss->channel->generator)) $this->_generator = (string) $rss->channel->generator;
- if (!empty($rss->channel->copyright)) $this->_copyright = (string) $rss->channel->copyright;
- if (!empty($rss->channel->lastbuilddate)) $this->_lastbuilddate = (string) $rss->channel->lastbuilddate;
- if (!empty($rss->channel->image->url[0])) $this->_imageurl = (string) $rss->channel->image->url[0];
- if (!empty($rss->channel->link)) $this->_link = (string) $rss->channel->link;
- if (!empty($rss->channel->title)) $this->_title = (string) $rss->channel->title;
- if (!empty($rss->channel->description)) $this->_description = (string) $rss->channel->description;
+ if (!empty($rss->channel->language)) {
+ $this->_language = (string) $rss->channel->language;
+ }
+ if (!empty($rss->channel->generator)) {
+ $this->_generator = (string) $rss->channel->generator;
+ }
+ if (!empty($rss->channel->copyright)) {
+ $this->_copyright = (string) $rss->channel->copyright;
+ }
+ if (!empty($rss->channel->lastbuilddate)) {
+ $this->_lastbuilddate = (string) $rss->channel->lastbuilddate;
+ }
+ if (!empty($rss->channel->image->url[0])) {
+ $this->_imageurl = (string) $rss->channel->image->url[0];
+ }
+ if (!empty($rss->channel->link)) {
+ $this->_link = (string) $rss->channel->link;
+ }
+ if (!empty($rss->channel->title)) {
+ $this->_title = (string) $rss->channel->title;
+ }
+ if (!empty($rss->channel->description)) {
+ $this->_description = (string) $rss->channel->description;
+ }
} else {
//var_dump($rss->channel);
- if (!empty($rss->channel['language'])) $this->_language = (string) $rss->channel['language'];
- if (!empty($rss->channel['generator'])) $this->_generator = (string) $rss->channel['generator'];
- if (!empty($rss->channel['copyright'])) $this->_copyright = (string) $rss->channel['copyright'];
- if (!empty($rss->channel['lastbuilddate'])) $this->_lastbuilddate = (string) $rss->channel['lastbuilddate'];
- if (!empty($rss->image['url'])) $this->_imageurl = (string) $rss->image['url'];
- if (!empty($rss->channel['link'])) $this->_link = (string) $rss->channel['link'];
- if (!empty($rss->channel['title'])) $this->_title = (string) $rss->channel['title'];
- if (!empty($rss->channel['description'])) $this->_description = (string) $rss->channel['description'];
+ if (!empty($rss->channel['language'])) {
+ $this->_language = (string) $rss->channel['language'];
+ }
+ if (!empty($rss->channel['generator'])) {
+ $this->_generator = (string) $rss->channel['generator'];
+ }
+ if (!empty($rss->channel['copyright'])) {
+ $this->_copyright = (string) $rss->channel['copyright'];
+ }
+ if (!empty($rss->channel['lastbuilddate'])) {
+ $this->_lastbuilddate = (string) $rss->channel['lastbuilddate'];
+ }
+ if (!empty($rss->image['url'])) {
+ $this->_imageurl = (string) $rss->image['url'];
+ }
+ if (!empty($rss->channel['link'])) {
+ $this->_link = (string) $rss->channel['link'];
+ }
+ if (!empty($rss->channel['title'])) {
+ $this->_title = (string) $rss->channel['title'];
+ }
+ if (!empty($rss->channel['description'])) {
+ $this->_description = (string) $rss->channel['description'];
+ }
}
- if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) $items = $rss->channel->item; // With simplexml
- else $items = $rss->items; // With xmlparse
+ if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
+ $items = $rss->channel->item; // With simplexml
+ } else {
+ $items = $rss->items; // With xmlparse
+ }
//var_dump($items);exit;
} elseif ($rss->_format == 'atom') {
//var_dump($rss);
- if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
- {
- if (!empty($rss->generator)) $this->_generator = (string) $rss->generator;
- if (!empty($rss->lastbuilddate)) $this->_lastbuilddate = (string) $rss->modified;
- if (!empty($rss->link->href)) $this->_link = (string) $rss->link->href;
- if (!empty($rss->title)) $this->_title = (string) $rss->title;
- if (!empty($rss->description)) $this->_description = (string) $rss->description;
+ if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
+ if (!empty($rss->generator)) {
+ $this->_generator = (string) $rss->generator;
+ }
+ if (!empty($rss->lastbuilddate)) {
+ $this->_lastbuilddate = (string) $rss->modified;
+ }
+ if (!empty($rss->link->href)) {
+ $this->_link = (string) $rss->link->href;
+ }
+ if (!empty($rss->title)) {
+ $this->_title = (string) $rss->title;
+ }
+ if (!empty($rss->description)) {
+ $this->_description = (string) $rss->description;
+ }
} else {
//if (!empty($rss->channel['rss_language'])) $this->_language = (string) $rss->channel['rss_language'];
- if (!empty($rss->channel['generator'])) $this->_generator = (string) $rss->channel['generator'];
+ if (!empty($rss->channel['generator'])) {
+ $this->_generator = (string) $rss->channel['generator'];
+ }
//if (!empty($rss->channel['rss_copyright'])) $this->_copyright = (string) $rss->channel['rss_copyright'];
- if (!empty($rss->channel['modified'])) $this->_lastbuilddate = (string) $rss->channel['modified'];
+ if (!empty($rss->channel['modified'])) {
+ $this->_lastbuilddate = (string) $rss->channel['modified'];
+ }
//if (!empty($rss->image['rss_url'])) $this->_imageurl = (string) $rss->image['rss_url'];
- if (!empty($rss->channel['link'])) $this->_link = (string) $rss->channel['link'];
- if (!empty($rss->channel['title'])) $this->_title = (string) $rss->channel['title'];
+ if (!empty($rss->channel['link'])) {
+ $this->_link = (string) $rss->channel['link'];
+ }
+ if (!empty($rss->channel['title'])) {
+ $this->_title = (string) $rss->channel['title'];
+ }
//if (!empty($rss->channel['rss_description'])) $this->_description = (string) $rss->channel['rss_description'];
if (!empty($rss->channel)) {
@@ -360,7 +412,9 @@ class RssParser
if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
$tmprss = xml2php($rss); $items = $tmprss['entry'];
} // With simplexml
- else $items = $rss->items; // With xmlparse
+ else {
+ $items = $rss->items; // With xmlparse
+ }
//var_dump($items);exit;
}
@@ -436,7 +490,9 @@ class RssParser
$i++;
- if ($i > $maxNb) break; // We get all records we want
+ if ($i > $maxNb) {
+ break; // We get all records we want
+ }
}
}
@@ -466,18 +522,15 @@ class RssParser
// check for a namespace, and split if found
$ns = false;
- if (strpos($element, ':'))
- {
+ if (strpos($element, ':')) {
list($ns, $el) = explode(':', $element, 2);
}
- if ($ns and $ns != 'rdf')
- {
+ if ($ns and $ns != 'rdf') {
$this->current_namespace = $ns;
}
// if feed type isn't set, then this is first element of feed identify feed from root element
- if (empty($this->_format))
- {
+ if (empty($this->_format)) {
if ($el == 'rdf') {
$this->_format = 'rss';
$this->feed_version = '1.0';
@@ -492,11 +545,9 @@ class RssParser
return;
}
- if ($el == 'channel')
- {
+ if ($el == 'channel') {
$this->inchannel = true;
- } elseif ($el == 'item' or $el == 'entry')
- {
+ } elseif ($el == 'item' or $el == 'entry') {
$this->initem = true;
if (isset($attrs['rdf:about'])) {
$this->current_item['about'] = $attrs['rdf:about'];
@@ -505,23 +556,18 @@ class RssParser
// if we're in the default namespace of an RSS feed,
// record textinput or image fields
- elseif (
- $this->_format == 'rss' and
+ elseif ($this->_format == 'rss' and
$this->current_namespace == '' and
- $el == 'textinput' )
- {
+ $el == 'textinput') {
$this->intextinput = true;
- } elseif (
- $this->_format == 'rss' and
+ } elseif ($this->_format == 'rss' and
$this->current_namespace == '' and
- $el == 'image' )
- {
+ $el == 'image') {
$this->inimage = true;
}
// handle atom content constructs
- elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS))
- {
+ elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS)) {
// avoid clashing w/ RSS mod_content
if ($el == 'content') {
$el = 'atom_content';
@@ -531,8 +577,7 @@ class RssParser
}
// if inside an Atom content construct (e.g. content or summary) field treat tags as text
- elseif ($this->_format == 'atom' and $this->incontent)
- {
+ elseif ($this->_format == 'atom' and $this->incontent) {
// if tags are inlined, then flatten
$attrs_str = join(' ', array_map('map_attrs', array_keys($attrs), array_values($attrs)));
@@ -545,13 +590,10 @@ class RssParser
// Magpie treats link elements of type rel='alternate'
// as being equivalent to RSS's simple link element.
//
- elseif ($this->_format == 'atom' and $el == 'link')
- {
- if (isset($attrs['rel']) && $attrs['rel'] == 'alternate')
- {
+ elseif ($this->_format == 'atom' and $el == 'link') {
+ if (isset($attrs['rel']) && $attrs['rel'] == 'alternate') {
$link_el = 'link';
- } elseif (!isset($attrs['rel']))
- {
+ } elseif (!isset($attrs['rel'])) {
$link_el = 'link';
} else {
$link_el = 'link_'.$attrs['rel'];
@@ -577,8 +619,7 @@ class RssParser
public function feed_cdata($p, $text)
{
// phpcs:enable
- if ($this->_format == 'atom' and $this->incontent)
- {
+ if ($this->_format == 'atom' and $this->incontent) {
$this->append_content($text);
} else {
$current_el = join('_', array_reverse($this->stack));
@@ -599,28 +640,22 @@ class RssParser
// phpcs:enable
$el = strtolower($el);
- if ($el == 'item' or $el == 'entry')
- {
+ if ($el == 'item' or $el == 'entry') {
$this->items[] = $this->current_item;
$this->current_item = array();
$this->initem = false;
- } elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput')
- {
+ } elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput') {
$this->intextinput = false;
- } elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image')
- {
+ } elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image') {
$this->inimage = false;
- } elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS))
- {
+ } elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS)) {
$this->incontent = false;
- } elseif ($el == 'channel' or $el == 'feed')
- {
+ } elseif ($el == 'channel' or $el == 'feed') {
$this->inchannel = false;
} elseif ($this->_format == 'atom' and $this->incontent) {
// balance tags properly
// note: i don't think this is actually neccessary
- if ($this->stack[0] == $el)
- {
+ if ($this->stack[0] == $el) {
$this->append_content("$el>");
} else {
$this->append_content("<$el />");
@@ -679,8 +714,7 @@ class RssParser
if (!$el) {
return;
}
- if ($this->current_namespace)
- {
+ if ($this->current_namespace) {
if ($this->initem) {
$this->concat($this->current_item[$this->current_namespace][$el], $text);
} elseif ($this->inchannel) {
@@ -714,11 +748,9 @@ class RssParser
{
$result = "";
- if (isset($item['summary']))
- {
+ if (isset($item['summary'])) {
$result = $item['summary'];
- } elseif (isset($item['atom_content']))
- {
+ } elseif (isset($item['atom_content'])) {
$result = $item['atom_content'];
}
@@ -728,8 +760,7 @@ class RssParser
$result = str_replace("\n", "", $result);
- if (strlen($result) > $maxlength)
- {
+ if (strlen($result) > $maxlength) {
$result = substr($result, 0, $maxlength);
$result .= "...";
}
@@ -745,28 +776,23 @@ class RssParser
*/
private function getAtomImageUrl(array $feed)
{
- if (isset($feed['icon']))
- {
+ if (isset($feed['icon'])) {
return $feed['logo'];
}
- if (isset($feed['icon']))
- {
+ if (isset($feed['icon'])) {
return $feed['logo'];
}
- if (isset($feed['webfeeds:logo']))
- {
+ if (isset($feed['webfeeds:logo'])) {
return $feed['webfeeds:logo'];
}
- if (isset($feed['webfeeds:icon']))
- {
+ if (isset($feed['webfeeds:icon'])) {
return $feed['webfeeds:icon'];
}
- if (isset($feed['webfeeds:wordmark']))
- {
+ if (isset($feed['webfeeds:wordmark'])) {
return $feed['webfeeds:wordmark'];
}
@@ -786,27 +812,23 @@ function xml2php($xml)
$fils = 0;
$tab = false;
$array = array();
- foreach ($xml->children() as $key => $value)
- {
+ foreach ($xml->children() as $key => $value) {
$child = xml2php($value);
//To deal with the attributes
- foreach ($value->attributes() as $ak=>$av)
- {
+ foreach ($value->attributes() as $ak => $av) {
$child[$ak] = (string) $av;
}
//Let see if the new child is not in the array
- if ($tab === false && in_array($key, array_keys($array)))
- {
+ if ($tab === false && in_array($key, array_keys($array))) {
//If this element is already in the array we will create an indexed array
$tmp = $array[$key];
$array[$key] = null;
$array[$key][] = $tmp;
$array[$key][] = $child;
$tab = true;
- } elseif ($tab === true)
- {
+ } elseif ($tab === true) {
//Add an element in an existing array
$array[$key][] = $child;
} else {
@@ -818,8 +840,7 @@ function xml2php($xml)
}
- if ($fils == 0)
- {
+ if ($fils == 0) {
return (string) $xml;
}
diff --git a/htdocs/core/class/smtps.class.php b/htdocs/core/class/smtps.class.php
index 8254cc56ed2..3618cfc2413 100644
--- a/htdocs/core/class/smtps.class.php
+++ b/htdocs/core/class/smtps.class.php
@@ -315,8 +315,9 @@ class SMTPs
*/
public function setErrorsTo($_strErrorsTo)
{
- if ($_strErrorsTo)
- $this->_errorsTo = $this->_strip_email($_strErrorsTo);
+ if ($_strErrorsTo) {
+ $this->_errorsTo = $this->_strip_email($_strErrorsTo);
+ }
}
/**
@@ -329,9 +330,11 @@ class SMTPs
{
$_retValue = '';
- if ($_part === true)
- $_retValue = $this->_errorsTo;
- else $_retValue = $this->_errorsTo[$_part];
+ if ($_part === true) {
+ $_retValue = $this->_errorsTo;
+ } else {
+ $_retValue = $this->_errorsTo[$_part];
+ }
return $_retValue;
}
@@ -383,8 +386,7 @@ class SMTPs
// @CHANGE LDR
include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
- if ((!is_ip($host)) && ((gethostbyname($host)) == $host))
- {
+ if ((!is_ip($host)) && ((gethostbyname($host)) == $host)) {
$this->_setErr(99, $host.' is either offline or is an invalid host name.');
$_retVal = false;
} else {
@@ -403,30 +405,34 @@ class SMTPs
} else {
$this->socket = @fsockopen(
preg_replace('@tls://@i', '', $this->getHost()), // Host to 'hit', IP or domain
- $this->getPort(), // which Port number to use
- $this->errno, // actual system level error
- $this->errstr, // and any text that goes with the error
- $this->_smtpTimeout // timeout for reading/writing data over the socket
+ $this->getPort(), // which Port number to use
+ $this->errno, // actual system level error
+ $this->errstr, // and any text that goes with the error
+ $this->_smtpTimeout // timeout for reading/writing data over the socket
);
}
//See if we can connect to the SMTP server
- if (is_resource($this->socket))
- {
+ if (is_resource($this->socket)) {
// Fix from PHP SMTP class by 'Chris Ryan'
// Sometimes the SMTP server takes a little longer to respond
// so we will give it a longer timeout for the first read
// Windows still does not have support for this timeout function
- if (function_exists('stream_set_timeout')) stream_set_timeout($this->socket, $this->_smtpTimeout, 0);
+ if (function_exists('stream_set_timeout')) {
+ stream_set_timeout($this->socket, $this->_smtpTimeout, 0);
+ }
// Check response from Server
- if ($_retVal = $this->server_parse($this->socket, "220"))
- $_retVal = $this->socket;
+ if ($_retVal = $this->server_parse($this->socket, "220")) {
+ $_retVal = $this->socket;
+ }
}
// This connection attempt failed.
else {
// @CHANGE LDR
- if (empty($this->errstr)) $this->errstr = 'Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort();
+ if (empty($this->errstr)) {
+ $this->errstr = 'Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort();
+ }
$this->_setErr($this->errno, $this->errstr);
$_retVal = false;
}
@@ -456,12 +462,13 @@ class SMTPs
$host = preg_replace('@ssl://@i', '', $host); // Remove prefix
$host = preg_replace('@tls://@i', '', $host); // Remove prefix
- if ($usetls && !empty($conf->global->MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO)) $host = 'tls://'.$host;
+ if ($usetls && !empty($conf->global->MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO)) {
+ $host = 'tls://'.$host;
+ }
$hosth = $host;
- if (!empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
- {
+ if (!empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO)) {
// If the from to is 'aaa ', we will keep 'ccc.com'
$hosth = $this->getFrom('addr');
$hosth = preg_replace('/^.*', '', $hosth);
@@ -469,31 +476,28 @@ class SMTPs
$hosth = preg_replace('/.*@/', '', $hosth);
}
- if ($_retVal = $this->socket_send_str('EHLO '.$hosth, '250'))
- {
- if ($usetls)
- {
+ if ($_retVal = $this->socket_send_str('EHLO '.$hosth, '250')) {
+ if ($usetls) {
/*
- The following dialog illustrates how a client and server can start a TLS STARTTLS session
- S:
- C:
- S: 220 mail.imc.org SMTP service ready
- C: EHLO mail.ietf.org
- S: 250-mail.imc.org offers a warm hug of welcome
- S: 250 STARTTLS
- C: STARTTLS
- S: 220 Go ahead
- C:
- C & S:
- C & S:
- // Second pass EHLO
- C: EHLO client-domain.com
- S: 250-server-domain.com
- S: 250 AUTH LOGIN
- C: socket_send_str('STARTTLS', 220))
- {
+ The following dialog illustrates how a client and server can start a TLS STARTTLS session
+ S:
+ C:
+ S: 220 mail.imc.org SMTP service ready
+ C: EHLO mail.ietf.org
+ S: 250-mail.imc.org offers a warm hug of welcome
+ S: 250 STARTTLS
+ C: STARTTLS
+ S: 220 Go ahead
+ C:
+ C & S:
+ C & S:
+ // Second pass EHLO
+ C: EHLO client-domain.com
+ S: 250-server-domain.com
+ S: 250 AUTH LOGIN
+ C: socket_send_str('STARTTLS', 220)) {
$this->_setErr(131, 'STARTTLS connection is not supported.');
return $_retVal;
}
@@ -511,22 +515,22 @@ class SMTPs
$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
}
- if (!stream_socket_enable_crypto($this->socket, true, $crypto_method))
- {
+ if (!stream_socket_enable_crypto($this->socket, true, $crypto_method)) {
$this->_setErr(132, 'STARTTLS connection failed.');
return $_retVal;
}
// Most server servers expect a 2nd pass of EHLO after TLS is established to get another time
// the answer with list of supported AUTH methods. They may differs between non STARTTLS and with STARTTLS.
- if (!$_retVal = $this->socket_send_str('EHLO '.$hosth, '250'))
- {
+ if (!$_retVal = $this->socket_send_str('EHLO '.$hosth, '250')) {
$this->_setErr(126, '"'.$hosth.'" does not support authenticated connections.');
return $_retVal;
}
}
// Default authentication method is LOGIN
- if (empty($conf->global->MAIL_SMTP_AUTH_TYPE)) $conf->global->MAIL_SMTP_AUTH_TYPE = 'LOGIN';
+ if (empty($conf->global->MAIL_SMTP_AUTH_TYPE)) {
+ $conf->global->MAIL_SMTP_AUTH_TYPE = 'LOGIN';
+ }
// Send Authentication to Server
// Check for errors along the way
@@ -571,11 +575,9 @@ class SMTPs
$_retVal = false;
// Connect to Server
- if ($this->socket = $this->_server_connect())
- {
+ if ($this->socket = $this->_server_connect()) {
// If a User ID *and* a password is given, assume Authentication is desired
- if (!empty($this->_smtpsID) && !empty($this->_smtpsPW))
- {
+ if (!empty($this->_smtpsID) && !empty($this->_smtpsPW)) {
// Send the RFC2554 specified EHLO.
$_retVal = $this->_server_authenticate();
}
@@ -590,12 +592,13 @@ class SMTPs
$host = preg_replace('@ssl://@i', '', $host); // Remove prefix
$host = preg_replace('@tls://@i', '', $host); // Remove prefix
- if ($usetls && !empty($conf->global->MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO)) $host = 'tls://'.$host;
+ if ($usetls && !empty($conf->global->MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO)) {
+ $host = 'tls://'.$host;
+ }
$hosth = $host;
- if (!empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
- {
+ if (!empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO)) {
// If the from to is 'aaa ', we will keep 'ccc.com'
$hosth = $this->getFrom('addr');
$hosth = preg_replace('/^.*', '', $hosth);
@@ -607,8 +610,7 @@ class SMTPs
}
// Well, did we get to the server?
- if ($_retVal)
- {
+ if ($_retVal) {
// From this point onward most server response codes should be 250
// Specify who the mail is from....
// This has to be the raw email address, strip the "name" off
@@ -621,22 +623,21 @@ class SMTPs
// 'RCPT TO:' must be given a single address, so this has to loop
// through the list of addresses, regardless of TO, CC or BCC
// and send it out "single file"
- foreach ($this->get_RCPT_list() as $_address)
- {
+ foreach ($this->get_RCPT_list() as $_address) {
/* Note:
- * BCC email addresses must be listed in the RCPT TO command list,
- * but the BCC header should not be printed under the DATA command.
- * http://stackoverflow.com/questions/2750211/sending-bcc-emails-using-a-smtp-server
- */
+ * BCC email addresses must be listed in the RCPT TO command list,
+ * but the BCC header should not be printed under the DATA command.
+ * http://stackoverflow.com/questions/2750211/sending-bcc-emails-using-a-smtp-server
+ */
/*
- * TODO
- * After each 'RCPT TO:' is sent, we need to make sure it was kosher,
- * if not, the whole message will fail
- * If any email address fails, we will need to RESET the connection,
- * mark the last address as "bad" and start the address loop over again.
- * If any address fails, the entire message fails.
- */
+ * TODO
+ * After each 'RCPT TO:' is sent, we need to make sure it was kosher,
+ * if not, the whole message will fail
+ * If any email address fails, we will need to RESET the connection,
+ * mark the last address as "bad" and start the address loop over again.
+ * If any address fails, the entire message fails.
+ */
$this->socket_send_str('RCPT TO: <'.$_address.'>', '250');
}
@@ -697,12 +698,10 @@ class SMTPs
$_retVal = true;
// if we have a path...
- if (!empty($_strConfigPath))
- {
+ if (!empty($_strConfigPath)) {
// If the path is not valid, this will NOT generate an error,
// it will simply return false.
- if (!@include $_strConfigPath)
- {
+ if (!@include $_strConfigPath) {
$this->_setErr(110, '"'.$_strConfigPath.'" is not a valid path.');
$_retVal = false;
}
@@ -712,14 +711,17 @@ class SMTPs
else {
// Set these properties ONLY if they are set in the php.ini file.
// Otherwise the default values will be used.
- if ($_host = ini_get('SMTPs'))
- $this->setHost($_host);
+ if ($_host = ini_get('SMTPs')) {
+ $this->setHost($_host);
+ }
- if ($_port = ini_get('smtp_port'))
- $this->setPort($_port);
+ if ($_port = ini_get('smtp_port')) {
+ $this->setPort($_port);
+ }
- if ($_from = ini_get('sendmail_from'))
- $this->setFrom($_from);
+ if ($_from = ini_get('sendmail_from')) {
+ $this->setFrom($_from);
+ }
}
// Send back what we have
@@ -780,8 +782,9 @@ class SMTPs
*/
public function setHost($_strHost)
{
- if ($_strHost)
- $this->_smtpsHost = $_strHost;
+ if ($_strHost) {
+ $this->_smtpsHost = $_strHost;
+ }
}
/**
@@ -806,8 +809,9 @@ class SMTPs
public function setPort($_intPort)
{
if ((is_numeric($_intPort)) &&
- (($_intPort >= 1) && ($_intPort <= 65536)))
- $this->_smtpsPort = $_intPort;
+ (($_intPort >= 1) && ($_intPort <= 65536))) {
+ $this->_smtpsPort = $_intPort;
+ }
}
/**
@@ -872,8 +876,9 @@ class SMTPs
*/
public function setCharSet($_strCharSet)
{
- if ($_strCharSet)
- $this->_smtpsCharSet = $_strCharSet;
+ if ($_strCharSet) {
+ $this->_smtpsCharSet = $_strCharSet;
+ }
}
/**
@@ -903,8 +908,9 @@ class SMTPs
*/
public function setTransEncode($_strTransEncode)
{
- if (array_search($_strTransEncode, $this->_smtpsTransEncodeTypes))
- $this->_smtpsTransEncode = $_strTransEncode;
+ if (array_search($_strTransEncode, $this->_smtpsTransEncodeTypes)) {
+ $this->_smtpsTransEncode = $_strTransEncode;
+ }
}
/**
@@ -935,8 +941,9 @@ class SMTPs
*/
public function setTransEncodeType($_strTransEncodeType)
{
- if (array_search($_strTransEncodeType, $this->_smtpsTransEncodeTypes))
- $this->_smtpsTransEncodeType = $_strTransEncodeType;
+ if (array_search($_strTransEncodeType, $this->_smtpsTransEncodeTypes)) {
+ $this->_smtpsTransEncodeType = $_strTransEncodeType;
+ }
}
/**
@@ -960,8 +967,9 @@ class SMTPs
*/
public function setFrom($_strFrom)
{
- if ($_strFrom)
- $this->_msgFrom = $this->_strip_email($_strFrom);
+ if ($_strFrom) {
+ $this->_msgFrom = $this->_strip_email($_strFrom);
+ }
}
/**
@@ -974,9 +982,11 @@ class SMTPs
{
$_retValue = '';
- if ($_part === true)
- $_retValue = $this->_msgFrom;
- else $_retValue = $this->_msgFrom[$_part];
+ if ($_part === true) {
+ $_retValue = $this->_msgFrom;
+ } else {
+ $_retValue = $this->_msgFrom[$_part];
+ }
return $_retValue;
}
@@ -989,8 +999,9 @@ class SMTPs
*/
public function setReplyTo($_strReplyTo)
{
- if ($_strReplyTo)
+ if ($_strReplyTo) {
$this->_msgReplyTo = $this->_strip_email($_strReplyTo);
+ }
}
/**
@@ -1003,9 +1014,11 @@ class SMTPs
{
$_retValue = '';
- if ($_part === true)
+ if ($_part === true) {
$_retValue = $this->_msgReplyTo;
- else $_retValue = $this->_msgReplyTo[$_part];
+ } else {
+ $_retValue = $this->_msgReplyTo[$_part];
+ }
return $_retValue;
}
@@ -1028,23 +1041,23 @@ class SMTPs
$aryHost = $this->_msgRecipients;
// Only run this if we have something
- if (!empty($_addrList))
- {
+ if (!empty($_addrList)) {
// $_addrList can be a STRING or an array
- if (is_string($_addrList))
- {
+ if (is_string($_addrList)) {
// This could be a COMMA delimited string
- if (strstr($_addrList, ','))
- // "explode "list" into an array
- $_addrList = explode(',', $_addrList);
+ if (strstr($_addrList, ',')) {
+ // "explode "list" into an array
+ $_addrList = explode(',', $_addrList);
+ }
// Stick it in an array
- else $_addrList = array($_addrList);
+ else {
+ $_addrList = array($_addrList);
+ }
}
// take the array of addresses and split them further
- foreach ($_addrList as $_strAddr)
- {
+ foreach ($_addrList as $_strAddr) {
// Strip off the end '>'
$_strAddr = str_replace('>', '', $_strAddr);
@@ -1053,8 +1066,7 @@ class SMTPs
$_tmpaddr = explode('<', $_strAddr);
// We have a "Real Name" and eMail address
- if (count($_tmpaddr) == 2)
- {
+ if (count($_tmpaddr) == 2) {
$_tmpHost = explode('@', $_tmpaddr[1]);
$_tmpaddr[0] = trim($_tmpaddr[0], ' ">');
$aryHost[$_tmpHost[1]][$_type][$_tmpHost[0]] = $_tmpaddr[0];
@@ -1109,14 +1121,16 @@ class SMTPs
$_tmpAry = explode('<', $_strAddr);
// Do we have a "Real name"
- if (count($_tmpAry) == 2)
- {
+ if (count($_tmpAry) == 2) {
// We may not really have a "Real Name"
- if ($_tmpAry[0])
- $_aryEmail['real'] = trim($_tmpAry[0], ' ">');
+ if ($_tmpAry[0]) {
+ $_aryEmail['real'] = trim($_tmpAry[0], ' ">');
+ }
$_aryEmail['addr'] = $_tmpAry[1];
- } else $_aryEmail['addr'] = $_tmpAry[0];
+ } else {
+ $_aryEmail['addr'] = $_tmpAry[0];
+ }
// Pull User Name and Host.tld apart
list($_aryEmail['user'], $_aryEmail['host']) = explode('@', $_aryEmail['addr']);
@@ -1144,12 +1158,9 @@ class SMTPs
$_RCPT_list = array();
// walk down Recipients array and pull just email addresses
- foreach ($this->_msgRecipients as $_host => $_list)
- {
- foreach ($_list as $_subList)
- {
- foreach ($_subList as $_name => $_addr)
- {
+ foreach ($this->_msgRecipients as $_host => $_list) {
+ foreach ($_list as $_subList) {
+ foreach ($_subList as $_name => $_addr) {
// build RCPT list
$_RCPT_list[] = $_name.'@'.$_host;
}
@@ -1170,21 +1181,15 @@ class SMTPs
{
// phpcs:enable
// We need to know which address segment to pull
- if ($_which)
- {
+ if ($_which) {
// Make sure we have addresses to process
- if ($this->_msgRecipients)
- {
+ if ($this->_msgRecipients) {
$_RCPT_list = array();
// walk down Recipients array and pull just email addresses
- foreach ($this->_msgRecipients as $_host => $_list)
- {
- if ($this->_msgRecipients[$_host][$_which])
- {
- foreach ($this->_msgRecipients[$_host][$_which] as $_addr => $_realName)
- {
- if ($_realName) // @CHANGE LDR
- {
+ foreach ($this->_msgRecipients as $_host => $_list) {
+ if ($this->_msgRecipients[$_host][$_which]) {
+ foreach ($this->_msgRecipients[$_host][$_which] as $_addr => $_realName) {
+ if ($_realName) { // @CHANGE LDR
$_realName = '"'.$_realName.'"';
$_RCPT_list[] = $_realName.' <'.$_addr.'@'.$_host.'>';
} else {
@@ -1213,8 +1218,9 @@ class SMTPs
*/
public function setTO($_addrTo)
{
- if ($_addrTo)
- $this->_buildAddrList('to', $_addrTo);
+ if ($_addrTo) {
+ $this->_buildAddrList('to', $_addrTo);
+ }
}
/**
@@ -1235,8 +1241,9 @@ class SMTPs
*/
public function setCC($_strCC)
{
- if ($_strCC)
- $this->_buildAddrList('cc', $_strCC);
+ if ($_strCC) {
+ $this->_buildAddrList('cc', $_strCC);
+ }
}
/**
@@ -1257,8 +1264,9 @@ class SMTPs
*/
public function setBCC($_strBCC)
{
- if ($_strBCC)
- $this->_buildAddrList('bcc', $_strBCC);
+ if ($_strBCC) {
+ $this->_buildAddrList('bcc', $_strBCC);
+ }
}
/**
@@ -1279,8 +1287,9 @@ class SMTPs
*/
public function setSubject($_strSubject = '')
{
- if ($_strSubject)
- $this->_msgSubject = $_strSubject;
+ if ($_strSubject) {
+ $this->_msgSubject = $_strSubject;
+ }
}
/**
@@ -1305,19 +1314,20 @@ class SMTPs
$_header = 'From: '.$this->getFrom('org')."\r\n"
. 'To: '.$this->getTO()."\r\n";
- if ($this->getCC())
- $_header .= 'Cc: '.$this->getCC()."\r\n";
+ if ($this->getCC()) {
+ $_header .= 'Cc: '.$this->getCC()."\r\n";
+ }
/* Note:
- * BCC email addresses must be listed in the RCPT TO command list,
- * but the BCC header should not be printed under the DATA command.
- * So it is included into the function sendMsg() but not here.
- * http://stackoverflow.com/questions/2750211/sending-bcc-emails-using-a-smtp-server
- */
+ * BCC email addresses must be listed in the RCPT TO command list,
+ * but the BCC header should not be printed under the DATA command.
+ * So it is included into the function sendMsg() but not here.
+ * http://stackoverflow.com/questions/2750211/sending-bcc-emails-using-a-smtp-server
+ */
/*
- if ( $this->getBCC() )
- $_header .= 'Bcc: ' . $this->getBCC() . "\r\n";
- */
+ if ( $this->getBCC() )
+ $_header .= 'Bcc: ' . $this->getBCC() . "\r\n";
+ */
$host = dol_getprefix('email');
@@ -1326,8 +1336,7 @@ class SMTPs
$_header .= 'Date: '.date("r")."\r\n";
$trackid = $this->getTrackId();
- if ($trackid)
- {
+ if ($trackid) {
// References is kept in response and Message-ID is returned into In-Reply-To:
$_header .= 'Message-ID: <'.time().'.SMTPs-dolibarr-'.$trackid.'@'.$host.">\r\n";
$_header .= 'References: <'.time().'.SMTPs-dolibarr-'.$trackid.'@'.$host.">\r\n";
@@ -1335,28 +1344,36 @@ class SMTPs
} else {
$_header .= 'Message-ID: <'.time().'.SMTPs@'.$host.">\r\n";
}
- if (!empty($_SERVER['REMOTE_ADDR'])) $_header .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR']."\r\n";
- if ($this->getMoreInHeader())
+ if (!empty($_SERVER['REMOTE_ADDR'])) {
+ $_header .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR']."\r\n";
+ }
+ if ($this->getMoreInHeader()) {
$_header .= $this->getMoreInHeader(); // Value must include the "\r\n";
+ }
//$_header .=
// 'Read-Receipt-To: ' . $this->getFrom( 'org' ) . "\r\n"
// 'Return-Receipt-To: ' . $this->getFrom( 'org' ) . "\r\n";
- if ($this->getSensitivity())
- $_header .= 'Sensitivity: '.$this->getSensitivity()."\r\n";
+ if ($this->getSensitivity()) {
+ $_header .= 'Sensitivity: '.$this->getSensitivity()."\r\n";
+ }
- if ($this->_msgPriority != 3)
- $_header .= $this->getPriority();
+ if ($this->_msgPriority != 3) {
+ $_header .= $this->getPriority();
+ }
// @CHANGE LDR
- if ($this->getDeliveryReceipt())
+ if ($this->getDeliveryReceipt()) {
$_header .= 'Disposition-Notification-To: '.$this->getFrom('addr')."\r\n";
- if ($this->getErrorsTo())
+ }
+ if ($this->getErrorsTo()) {
$_header .= 'Errors-To: '.$this->getErrorsTo('addr')."\r\n";
- if ($this->getReplyTo())
+ }
+ if ($this->getReplyTo()) {
$_header .= "Reply-To: ".$this->getReplyTo('addr')."\r\n";
+ }
$_header .= 'X-Mailer: Dolibarr version '.DOL_VERSION.' (using SMTPs Mailer)'."\r\n";
$_header .= 'X-Dolibarr-Option: '.($conf->global->MAIN_MAIL_USE_MULTI_PART ? 'MAIN_MAIL_USE_MULTI_PART' : 'No MAIN_MAIL_USE_MULTI_PART')."\r\n";
@@ -1377,16 +1394,17 @@ class SMTPs
{
//if ( $strContent )
//{
- if ($strType == 'html')
- $strMimeType = 'text/html';
- else $strMimeType = 'text/plain';
+ if ($strType == 'html') {
+ $strMimeType = 'text/html';
+ } else {
+ $strMimeType = 'text/plain';
+ }
// Make RFC821 Compliant, replace bare linefeeds
$strContent = preg_replace("/(?.*<\/style><\/head>/', '', $strContent);
$strContentAltText = preg_replace("/ ]*>/", " ", $strContentAltText);
@@ -1404,8 +1422,9 @@ class SMTPs
$this->_msgContent[$strType]['data'] = $strContent;
$this->_msgContent[$strType]['dataText'] = $strContentAltText;
- if ($this->getMD5flag())
- $this->_msgContent[$strType]['md5'] = dol_hash($strContent, 3);
+ if ($this->getMD5flag()) {
+ $this->_msgContent[$strType]['md5'] = dol_hash($strContent, 3);
+ }
//}
}
@@ -1428,12 +1447,12 @@ class SMTPs
$keyCount = count($_types);
// If we have ZERO, we have a problem
- if ($keyCount === 0)
- die("Sorry, no content");
+ if ($keyCount === 0) {
+ die("Sorry, no content");
+ }
// If we have ONE, we can use the simple format
- elseif ($keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
- {
+ elseif ($keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
$_msgData = $this->_msgContent;
$_msgData = $_msgData[$_types[0]];
@@ -1442,16 +1461,16 @@ class SMTPs
. 'Content-Disposition: inline'."\r\n"
. 'Content-Description: Message'."\r\n";
- if ($this->getMD5flag())
- $content .= 'Content-MD5: '.$_msgData['md5']."\r\n";
+ if ($this->getMD5flag()) {
+ $content .= 'Content-MD5: '.$_msgData['md5']."\r\n";
+ }
$content .= "\r\n"
. $_msgData['data']."\r\n";
}
// If we have more than ONE, we use the multi-part format
- elseif ($keyCount >= 1 || !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
- {
+ elseif ($keyCount >= 1 || !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
// Since this is an actual multi-part message
// We need to define a content message Boundary
// NOTE: This was 'multipart/alternative', but Windows based mail servers have issues with this.
@@ -1466,8 +1485,7 @@ class SMTPs
$content .= "--".$this->_getBoundary('mixed')."\r\n";
- if (key_exists('image', $this->_msgContent)) // If inline image found
- {
+ if (key_exists('image', $this->_msgContent)) { // If inline image found
$content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n";
$content .= "\r\n";
$content .= "--".$this->_getBoundary('alternative')."\r\n";
@@ -1478,31 +1496,27 @@ class SMTPs
// Loop through message content array
- foreach ($this->_msgContent as $type => $_content)
- {
- if ($type == 'attachment')
- {
+ foreach ($this->_msgContent as $type => $_content) {
+ if ($type == 'attachment') {
// loop through all attachments
- foreach ($_content as $_file => $_data)
- {
+ foreach ($_content as $_file => $_data) {
$content .= "--".$this->_getBoundary('mixed')."\r\n"
. 'Content-Disposition: attachment; filename="'.$_data['fileName'].'"'."\r\n"
. 'Content-Type: '.$_data['mimeType'].'; name="'.$_data['fileName'].'"'."\r\n"
. 'Content-Transfer-Encoding: base64'."\r\n"
. 'Content-Description: '.$_data['fileName']."\r\n";
- if ($this->getMD5flag())
- $content .= 'Content-MD5: '.$_data['md5']."\r\n";
+ if ($this->getMD5flag()) {
+ $content .= 'Content-MD5: '.$_data['md5']."\r\n";
+ }
$content .= "\r\n".$_data['data']."\r\n\r\n";
}
}
// @CHANGE LDR
- elseif ($type == 'image')
- {
+ elseif ($type == 'image') {
// loop through all images
- foreach ($_content as $_image => $_data)
- {
+ foreach ($_content as $_image => $_data) {
$content .= "--".$this->_getBoundary('related')."\r\n"; // always related for an inline image
$content .= 'Content-Type: '.$_data['mimeType'].'; name="'.$_data['imageName'].'"'."\r\n"
@@ -1510,8 +1524,9 @@ class SMTPs
. 'Content-Disposition: inline; filename="'.$_data['imageName'].'"'."\r\n"
. 'Content-ID: <'.$_data['cid'].'> '."\r\n";
- if ($this->getMD5flag())
- $content .= 'Content-MD5: '.$_data['md5']."\r\n";
+ if ($this->getMD5flag()) {
+ $content .= 'Content-MD5: '.$_data['md5']."\r\n";
+ }
$content .= "\r\n"
. $_data['data']."\r\n";
@@ -1522,8 +1537,7 @@ class SMTPs
$content .= "\r\n--".$this->_getBoundary('alternative')."--\r\n";
$content .= "\r\n";
} else {
- if (key_exists('image', $this->_msgContent))
- {
+ if (key_exists('image', $this->_msgContent)) {
$content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n";
$content .= "\r\n".($_content['dataText'] ? $_content['dataText'] : strip_tags($_content['data']))."\r\n"; // Add plain text message
$content .= "--".$this->_getBoundary('alternative')."\r\n";
@@ -1532,8 +1546,7 @@ class SMTPs
$content .= "--".$this->_getBoundary('related')."\r\n";
}
- if (!key_exists('image', $this->_msgContent) && $_content['dataText'] && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part
- {
+ if (!key_exists('image', $this->_msgContent) && $_content['dataText'] && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) { // Add plain text message part before html part
$content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n";
$content .= "\r\n";
$content .= "--".$this->_getBoundary('alternative')."\r\n";
@@ -1553,8 +1566,7 @@ class SMTPs
$content .= "\r\n".$_content['data']."\r\n";
- if (!key_exists('image', $this->_msgContent) && $_content['dataText'] && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part
- {
+ if (!key_exists('image', $this->_msgContent) && $_content['dataText'] && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) { // Add plain text message part after html part
$content .= "--".$this->_getBoundary('alternative')."--\r\n";
}
@@ -1579,16 +1591,16 @@ class SMTPs
*/
public function setAttachment($strContent, $strFileName = 'unknown', $strMimeType = 'unknown')
{
- if ($strContent)
- {
+ if ($strContent) {
$strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n")); // 76 max is defined into http://tools.ietf.org/html/rfc2047
$this->_msgContent['attachment'][$strFileName]['mimeType'] = $strMimeType;
$this->_msgContent['attachment'][$strFileName]['fileName'] = $strFileName;
$this->_msgContent['attachment'][$strFileName]['data'] = $strContent;
- if ($this->getMD5flag())
- $this->_msgContent['attachment'][$strFileName]['md5'] = dol_hash($strContent, 3);
+ if ($this->getMD5flag()) {
+ $this->_msgContent['attachment'][$strFileName]['md5'] = dol_hash($strContent, 3);
+ }
}
}
@@ -1607,15 +1619,15 @@ class SMTPs
*/
public function setImageInline($strContent, $strImageName = 'unknown', $strMimeType = 'unknown', $strImageCid = 'unknown')
{
- if ($strContent)
- {
+ if ($strContent) {
$this->_msgContent['image'][$strImageName]['mimeType'] = $strMimeType;
$this->_msgContent['image'][$strImageName]['imageName'] = $strImageName;
$this->_msgContent['image'][$strImageName]['cid'] = $strImageCid;
$this->_msgContent['image'][$strImageName]['data'] = $strContent;
- if ($this->getMD5flag())
- $this->_msgContent['image'][$strImageName]['md5'] = dol_hash($strContent, 3);
+ if ($this->getMD5flag()) {
+ $this->_msgContent['image'][$strImageName]['md5'] = dol_hash($strContent, 3);
+ }
}
}
// END @CHANGE LDR
@@ -1635,8 +1647,9 @@ class SMTPs
public function setSensitivity($_value = 0)
{
if ((is_numeric($_value)) &&
- (($_value >= 0) && ($_value <= 3)))
- $this->_msgSensitivity = $_value;
+ (($_value >= 0) && ($_value <= 3))) {
+ $this->_msgSensitivity = $_value;
+ }
}
/**
@@ -1670,8 +1683,9 @@ class SMTPs
public function setPriority($_value = 3)
{
if ((is_numeric($_value)) &&
- (($_value >= 0) && ($_value <= 5)))
- $this->_msgPriority = $_value;
+ (($_value >= 0) && ($_value <= 5))) {
+ $this->_msgPriority = $_value;
+ }
}
/**
@@ -1724,8 +1738,9 @@ class SMTPs
*/
public function setXheader($strXdata)
{
- if ($strXdata)
- $this->_msgXheader[] = $strXdata;
+ if ($strXdata) {
+ $this->_msgXheader[] = $strXdata;
+ }
}
/**
@@ -1758,9 +1773,13 @@ class SMTPs
*/
private function _getBoundary($type = 'mixed')
{
- if ($type == 'mixed') return $this->_smtpsBoundary;
- elseif ($type == 'related') return $this->_smtpsRelatedBoundary;
- elseif ($type == 'alternative') return $this->_smtpsAlternativeBoundary;
+ if ($type == 'mixed') {
+ return $this->_smtpsBoundary;
+ } elseif ($type == 'related') {
+ return $this->_smtpsRelatedBoundary;
+ } elseif ($type == 'alternative') {
+ return $this->_smtpsAlternativeBoundary;
+ }
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
@@ -1786,10 +1805,8 @@ class SMTPs
// avoid infinite loop
$limit = 0;
- while (substr($server_response, 3, 1) != ' ' && $limit < 100)
- {
- if (!($server_response = fgets($socket, 256)))
- {
+ while (substr($server_response, 3, 1) != ' ' && $limit < 100) {
+ if (!($server_response = fgets($socket, 256))) {
$this->_setErr(121, "Couldn't get mail server response codes");
$_retVal = false;
break;
@@ -1798,8 +1815,7 @@ class SMTPs
$limit++;
}
- if (!(substr($server_response, 0, 3) == $response))
- {
+ if (!(substr($server_response, 0, 3) == $response)) {
$this->_setErr(120, "Ran into problems sending Mail.\r\nResponse: $server_response");
$_retVal = false;
}
@@ -1819,12 +1835,17 @@ class SMTPs
public function socket_send_str($_strSend, $_returnCode = null, $CRLF = "\r\n")
{
// phpcs:enable
- if ($this->_debug) $this->log .= $_strSend; // @CHANGE LDR for log
+ if ($this->_debug) {
+ $this->log .= $_strSend; // @CHANGE LDR for log
+ }
fputs($this->socket, $_strSend.$CRLF);
- if ($this->_debug) $this->log .= ' ('.$_returnCode.')'.$CRLF;
+ if ($this->_debug) {
+ $this->log .= ' ('.$_returnCode.')'.$CRLF;
+ }
- if ($_returnCode)
- return $this->server_parse($this->socket, $_returnCode);
+ if ($_returnCode) {
+ return $this->server_parse($this->socket, $_returnCode);
+ }
}
// =============================================================
@@ -1854,10 +1875,8 @@ class SMTPs
{
$_errMsg = array();
- if (is_array($this->_smtpsErrors))
- {
- foreach ($this->_smtpsErrors as $_err => $_info)
- {
+ if (is_array($this->_smtpsErrors)) {
+ foreach ($this->_smtpsErrors as $_err => $_info) {
$_errMsg[] = 'Error ['.$_info['num'].']: '.$_info['msg'];
}
}
diff --git a/htdocs/core/class/stats.class.php b/htdocs/core/class/stats.class.php
index b1d569eae45..b2c9b069095 100644
--- a/htdocs/core/class/stats.class.php
+++ b/htdocs/core/class/stats.class.php
@@ -47,13 +47,14 @@ abstract class Stats
{
global $conf, $user, $langs;
- if ($startyear > $endyear) return -1;
+ if ($startyear > $endyear) {
+ return -1;
+ }
$datay = array();
// Search into cache
- if (!empty($cachedelay))
- {
+ if (!empty($cachedelay)) {
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
}
@@ -64,11 +65,9 @@ abstract class Stats
$nowgmt = dol_now();
$foundintocache = 0;
- if ($cachedelay > 0)
- {
+ if ($cachedelay > 0) {
$filedate = dol_filemtime($newpathofdestfile);
- if ($filedate >= ($nowgmt - $cachedelay))
- {
+ if ($filedate >= ($nowgmt - $cachedelay)) {
$foundintocache = 1;
$this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
@@ -77,28 +76,26 @@ abstract class Stats
}
}
// Load file into $data
- if ($foundintocache) // Cache file found and is not too old
- {
+ if ($foundintocache) { // Cache file found and is not too old
dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
$data = json_decode(file_get_contents($newpathofdestfile), true);
} else {
$year = $startyear;
$sm = $startmonth - 1;
- if ($sm != 0) $year = $year - 1;
- while ($year <= $endyear)
- {
+ if ($sm != 0) {
+ $year = $year - 1;
+ }
+ while ($year <= $endyear) {
$datay[$year] = $this->getNbByMonth($year, $format);
$year++;
}
$data = array();
- for ($i = 0; $i < 12; $i++)
- {
+ for ($i = 0; $i < 12; $i++) {
$data[$i][] = $datay[$endyear][($i + $sm) % 12][0];
$year = $startyear;
- while ($year <= $endyear)
- {
+ while ($year <= $endyear) {
$data[$i][] = $datay[$year - (1 - ((int) ($i + $sm) / 12)) + ($sm == 0 ? 1 : 0)][($i + $sm) % 12][1];
$year++;
}
@@ -106,14 +103,17 @@ abstract class Stats
}
// Save cache file
- if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
- {
+ if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
- if (!dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
+ if (!dol_is_dir($conf->user->dir_temp)) {
+ dol_mkdir($conf->user->dir_temp);
+ }
$fp = fopen($newpathofdestfile, 'w');
fwrite($fp, json_encode($data));
fclose($fp);
- if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
+ if (!empty($conf->global->MAIN_UMASK)) {
+ $newmask = $conf->global->MAIN_UMASK;
+ }
@chmod($newpathofdestfile, octdec($newmask));
$this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
@@ -140,13 +140,14 @@ abstract class Stats
{
global $conf, $user, $langs;
- if ($startyear > $endyear) return -1;
+ if ($startyear > $endyear) {
+ return -1;
+ }
$datay = array();
// Search into cache
- if (!empty($cachedelay))
- {
+ if (!empty($cachedelay)) {
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
}
@@ -157,11 +158,9 @@ abstract class Stats
$nowgmt = dol_now();
$foundintocache = 0;
- if ($cachedelay > 0)
- {
+ if ($cachedelay > 0) {
$filedate = dol_filemtime($newpathofdestfile);
- if ($filedate >= ($nowgmt - $cachedelay))
- {
+ if ($filedate >= ($nowgmt - $cachedelay)) {
$foundintocache = 1;
$this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
@@ -171,28 +170,26 @@ abstract class Stats
}
// Load file into $data
- if ($foundintocache) // Cache file found and is not too old
- {
+ if ($foundintocache) { // Cache file found and is not too old
dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
$data = json_decode(file_get_contents($newpathofdestfile), true);
} else {
$year = $startyear;
$sm = $startmonth - 1;
- if ($sm != 0) $year = $year - 1;
- while ($year <= $endyear)
- {
+ if ($sm != 0) {
+ $year = $year - 1;
+ }
+ while ($year <= $endyear) {
$datay[$year] = $this->getAmountByMonth($year, $format);
$year++;
}
$data = array();
// $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
- for ($i = 0; $i < 12; $i++)
- {
+ for ($i = 0; $i < 12; $i++) {
$data[$i][] = isset($datay[$endyear][($i + $sm) % 12]['label']) ? $datay[$endyear][($i + $sm) % 12]['label'] : $datay[$endyear][($i + $sm) % 12][0]; // set label
$year = $startyear;
- while ($year <= $endyear)
- {
+ while ($year <= $endyear) {
$data[$i][] = $datay[$year - (1 - ((int) ($i + $sm) / 12)) + ($sm == 0 ? 1 : 0)][($i + $sm) % 12][1]; // set yval for x=i
$year++;
}
@@ -200,18 +197,22 @@ abstract class Stats
}
// Save cache file
- if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
- {
+ if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
- if (!dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
+ if (!dol_is_dir($conf->user->dir_temp)) {
+ dol_mkdir($conf->user->dir_temp);
+ }
$fp = fopen($newpathofdestfile, 'w');
- if ($fp)
- {
+ if ($fp) {
fwrite($fp, json_encode($data));
fclose($fp);
- if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
+ if (!empty($conf->global->MAIN_UMASK)) {
+ $newmask = $conf->global->MAIN_UMASK;
+ }
@chmod($newpathofdestfile, octdec($newmask));
- } else dol_syslog("Failed to write cache file", LOG_ERR);
+ } else {
+ dol_syslog("Failed to write cache file", LOG_ERR);
+ }
$this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
}
@@ -227,25 +228,24 @@ abstract class Stats
*/
public function getAverageByMonthWithPrevYear($endyear, $startyear)
{
- if ($startyear > $endyear) return -1;
+ if ($startyear > $endyear) {
+ return -1;
+ }
$datay = array();
$year = $startyear;
- while ($year <= $endyear)
- {
+ while ($year <= $endyear) {
$datay[$year] = $this->getAverageByMonth($year);
$year++;
}
$data = array();
- for ($i = 0; $i < 12; $i++)
- {
+ for ($i = 0; $i < 12; $i++) {
$data[$i][] = $datay[$endyear][$i][0];
$year = $startyear;
- while ($year <= $endyear)
- {
+ while ($year <= $endyear) {
$data[$i][] = $datay[$year][$i][1];
$year++;
}
@@ -269,8 +269,7 @@ abstract class Stats
$data = array();
// Search into cache
- if (!empty($cachedelay))
- {
+ if (!empty($cachedelay)) {
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
}
@@ -281,11 +280,9 @@ abstract class Stats
$nowgmt = dol_now();
$foundintocache = 0;
- if ($cachedelay > 0)
- {
+ if ($cachedelay > 0) {
$filedate = dol_filemtime($newpathofdestfile);
- if ($filedate >= ($nowgmt - $cachedelay))
- {
+ if ($filedate >= ($nowgmt - $cachedelay)) {
$foundintocache = 1;
$this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
@@ -295,8 +292,7 @@ abstract class Stats
}
// Load file into $data
- if ($foundintocache) // Cache file found and is not too old
- {
+ if ($foundintocache) { // Cache file found and is not too old
dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
$data = json_decode(file_get_contents($newpathofdestfile), true);
} else {
@@ -305,16 +301,18 @@ abstract class Stats
}
// Save cache file
- if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
- {
+ if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
- if (!dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
+ if (!dol_is_dir($conf->user->dir_temp)) {
+ dol_mkdir($conf->user->dir_temp);
+ }
$fp = fopen($newpathofdestfile, 'w');
- if ($fp)
- {
+ if ($fp) {
fwrite($fp, json_encode($data));
fclose($fp);
- if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
+ if (!empty($conf->global->MAIN_UMASK)) {
+ $newmask = $conf->global->MAIN_UMASK;
+ }
@chmod($newpathofdestfile, octdec($newmask));
}
$this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
@@ -341,12 +339,10 @@ abstract class Stats
dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $this->db->num_rows($resql);
$i = 0;
- while ($i < $num)
- {
+ while ($i < $num) {
$row = $this->db->fetch_row($resql);
$result[$i] = $row;
$i++;
@@ -372,25 +368,30 @@ abstract class Stats
dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $this->db->num_rows($resql);
$i = 0;
- while ($i < $num)
- {
+ while ($i < $num) {
$row = $this->db->fetch_object($resql);
$result[$i]['year'] = $row->year;
$result[$i]['nb'] = $row->nb;
- if ($i > 0 && $row->nb > 0) $result[$i - 1]['nb_diff'] = ($result[$i - 1]['nb'] - $row->nb) / $row->nb * 100;
+ if ($i > 0 && $row->nb > 0) {
+ $result[$i - 1]['nb_diff'] = ($result[$i - 1]['nb'] - $row->nb) / $row->nb * 100;
+ }
$result[$i]['total'] = $row->total;
- if ($i > 0 && $row->total > 0) $result[$i - 1]['total_diff'] = ($result[$i - 1]['total'] - $row->total) / $row->total * 100;
+ if ($i > 0 && $row->total > 0) {
+ $result[$i - 1]['total_diff'] = ($result[$i - 1]['total'] - $row->total) / $row->total * 100;
+ }
$result[$i]['avg'] = $row->avg;
- if ($i > 0 && $row->avg > 0) $result[$i - 1]['avg_diff'] = ($result[$i - 1]['avg'] - $row->avg) / $row->avg * 100;
+ if ($i > 0 && $row->avg > 0) {
+ $result[$i - 1]['avg_diff'] = ($result[$i - 1]['avg'] - $row->avg) / $row->avg * 100;
+ }
// For some $sql only
- if (isset($row->weighted))
- {
+ if (isset($row->weighted)) {
$result[$i]['weighted'] = $row->weighted;
- if ($i > 0 && $row->weighted > 0) $result[$i - 1]['avg_weighted'] = ($result[$i - 1]['weighted'] - $row->weighted) / $row->weighted * 100;
+ if ($i > 0 && $row->weighted > 0) {
+ $result[$i - 1]['avg_weighted'] = ($result[$i - 1]['weighted'] - $row->weighted) / $row->weighted * 100;
+ }
}
$i++;
}
@@ -421,12 +422,10 @@ abstract class Stats
dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $this->db->num_rows($resql);
$i = 0; $j = 0;
- while ($i < $num)
- {
+ while ($i < $num) {
$row = $this->db->fetch_row($resql);
$j = $row[0] * 1;
$result[$j] = $row[1];
@@ -437,19 +436,21 @@ abstract class Stats
dol_print_error($this->db);
}
- for ($i = 1; $i < 13; $i++)
- {
+ for ($i = 1; $i < 13; $i++) {
$res[$i] = (isset($result[$i]) ? $result[$i] : 0);
}
$data = array();
- for ($i = 1; $i < 13; $i++)
- {
+ for ($i = 1; $i < 13; $i++) {
$month = 'unknown';
- if ($format == 0) $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
- elseif ($format == 1) $month = $i;
- elseif ($format == 2) $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
+ if ($format == 0) {
+ $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
+ } elseif ($format == 1) {
+ $month = $i;
+ } elseif ($format == 2) {
+ $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
+ }
//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
//$month=dol_substr($month,0,3);
$data[$i - 1] = array($month, $res[$i]);
@@ -479,33 +480,35 @@ abstract class Stats
dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $this->db->num_rows($resql);
$i = 0;
- while ($i < $num)
- {
- $row = $this->db->fetch_row($resql);
- $j = $row[0] * 1;
- $result[$j] = $row[1];
- $i++;
- }
- $this->db->free($resql);
- } else dol_print_error($this->db);
+ while ($i < $num) {
+ $row = $this->db->fetch_row($resql);
+ $j = $row[0] * 1;
+ $result[$j] = $row[1];
+ $i++;
+ }
+ $this->db->free($resql);
+ } else {
+ dol_print_error($this->db);
+ }
- for ($i = 1; $i < 13; $i++)
- {
+ for ($i = 1; $i < 13; $i++) {
$res[$i] = (int) round((isset($result[$i]) ? $result[$i] : 0));
}
$data = array();
- for ($i = 1; $i < 13; $i++)
- {
+ for ($i = 1; $i < 13; $i++) {
$month = 'unknown';
- if ($format == 0) $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
- elseif ($format == 1) $month = $i;
- elseif ($format == 2) $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
+ if ($format == 0) {
+ $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
+ } elseif ($format == 1) {
+ $month = $i;
+ } elseif ($format == 2) {
+ $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
+ }
//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
//$month=dol_substr($month,0,3);
$data[$i - 1] = array($month, $res[$i]);
@@ -534,33 +537,35 @@ abstract class Stats
dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $this->db->num_rows($resql);
$i = 0; $j = 0;
- while ($i < $num)
- {
- $row = $this->db->fetch_row($resql);
- $j = $row[0] * 1;
- $result[$j] = $row[1];
- $i++;
- }
- $this->db->free($resql);
- } else dol_print_error($this->db);
+ while ($i < $num) {
+ $row = $this->db->fetch_row($resql);
+ $j = $row[0] * 1;
+ $result[$j] = $row[1];
+ $i++;
+ }
+ $this->db->free($resql);
+ } else {
+ dol_print_error($this->db);
+ }
- for ($i = 1; $i < 13; $i++)
- {
+ for ($i = 1; $i < 13; $i++) {
$res[$i] = (isset($result[$i]) ? $result[$i] : 0);
}
$data = array();
- for ($i = 1; $i < 13; $i++)
- {
+ for ($i = 1; $i < 13; $i++) {
$month = 'unknown';
- if ($format == 0) $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
- elseif ($format == 1) $month = $i;
- elseif ($format == 2) $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
+ if ($format == 0) {
+ $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
+ } elseif ($format == 1) {
+ $month = $i;
+ } elseif ($format == 2) {
+ $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
+ }
//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
//$month=dol_substr($month,0,3);
$data[$i - 1] = array($month, $res[$i]);
@@ -587,20 +592,25 @@ abstract class Stats
dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
$resql = $this->db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $this->db->num_rows($resql);
$i = 0; $other = 0;
- while ($i < $num)
- {
+ while ($i < $num) {
$row = $this->db->fetch_row($resql);
- if ($i < $limit || $num == $limit) $result[$i] = array($row[0], $row[1]); // Ref of product, nb
- else $other += $row[1];
- $i++;
+ if ($i < $limit || $num == $limit) {
+ $result[$i] = array($row[0], $row[1]); // Ref of product, nb
+ } else {
+ $other += $row[1];
+ }
+ $i++;
}
- if ($num > $limit) $result[$i] = array($langs->transnoentitiesnoconv("Other"), $other);
- $this->db->free($resql);
- } else dol_print_error($this->db);
+ if ($num > $limit) {
+ $result[$i] = array($langs->transnoentitiesnoconv("Other"), $other);
+ }
+ $this->db->free($resql);
+ } else {
+ dol_print_error($this->db);
+ }
return $result;
}
diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php
index c2850990ff5..0aa00153f5b 100644
--- a/htdocs/core/class/translate.class.php
+++ b/htdocs/core/class/translate.class.php
@@ -51,9 +51,14 @@ class Translate
*/
public function __construct($dir, $conf)
{
- if (!empty($conf->file->character_set_client)) $this->charset_output = $conf->file->character_set_client; // If charset output is forced
- if ($dir) $this->dir = array($dir);
- else $this->dir = $conf->file->dol_document_root;
+ if (!empty($conf->file->character_set_client)) {
+ $this->charset_output = $conf->file->character_set_client; // If charset output is forced
+ }
+ if ($dir) {
+ $this->dir = array($dir);
+ } else {
+ $this->dir = $conf->file->dol_document_root;
+ }
}
@@ -70,15 +75,12 @@ class Translate
//dol_syslog(get_class($this)."::setDefaultLang srclang=".$srclang,LOG_DEBUG);
// If a module ask to force a priority on langs directories (to use its own lang files)
- if (!empty($conf->global->MAIN_FORCELANGDIR))
- {
+ if (!empty($conf->global->MAIN_FORCELANGDIR)) {
$more = array();
$i = 0;
- foreach ($conf->file->dol_document_root as $dir)
- {
+ foreach ($conf->file->dol_document_root as $dir) {
$newdir = $dir.$conf->global->MAIN_FORCELANGDIR; // For example $conf->global->MAIN_FORCELANGDIR is '/mymodule' meaning we search files into '/mymodule/langs/xx_XX'
- if (!in_array($newdir, $this->dir))
- {
+ if (!in_array($newdir, $this->dir)) {
$more['module_'.$i] = $newdir; $i++; // We add the forced dir into the array $more. Just after, we add entries into $more to list of lang dir $this->dir.
}
}
@@ -87,30 +89,35 @@ class Translate
$this->origlang = $srclang;
- if (empty($srclang) || $srclang == 'auto')
- {
+ if (empty($srclang) || $srclang == 'auto') {
// $_SERVER['HTTP_ACCEPT_LANGUAGE'] can be 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7,it;q=0.6' but can contains also malicious content
$langpref = empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? '' : $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$langpref = preg_replace("/;([^,]*)/i", "", $langpref); // Remove the 'q=x.y,' part
$langpref = str_replace("-", "_", $langpref);
$langlist = preg_split("/[;,]/", $langpref);
$codetouse = preg_replace('/[^_a-zA-Z]/', '', $langlist[0]);
- } else $codetouse = $srclang;
+ } else {
+ $codetouse = $srclang;
+ }
// We redefine $srclang
$langpart = explode("_", $codetouse);
//print "Short code before _ : ".$langpart[0].' / Short code after _ : '.$langpart[1].' ';
- if (!empty($langpart[1])) // If it's for a codetouse that is a long code xx_YY
- {
+ if (!empty($langpart[1])) { // If it's for a codetouse that is a long code xx_YY
// Array force long code from first part, even if long code is defined
$longforshort = array('ar'=>'ar_SA');
$longforshortexcep = array('ar_EG');
- if (isset($longforshort[strtolower($langpart[0])]) && !in_array($codetouse, $longforshortexcep)) $srclang = $longforshort[strtolower($langpart[0])];
- elseif (!is_numeric($langpart[1])) { // Second part YY may be a numeric with some Chrome browser
+ if (isset($longforshort[strtolower($langpart[0])]) && !in_array($codetouse, $longforshortexcep)) {
+ $srclang = $longforshort[strtolower($langpart[0])];
+ } elseif (!is_numeric($langpart[1])) { // Second part YY may be a numeric with some Chrome browser
$srclang = strtolower($langpart[0])."_".strtoupper($langpart[1]);
$longforlong = array('no_nb'=>'nb_NO');
- if (isset($longforlong[strtolower($srclang)])) $srclang = $longforlong[strtolower($srclang)];
- } else $srclang = strtolower($langpart[0])."_".strtoupper($langpart[0]);
+ if (isset($longforlong[strtolower($srclang)])) {
+ $srclang = $longforlong[strtolower($srclang)];
+ }
+ } else {
+ $srclang = strtolower($langpart[0])."_".strtoupper($langpart[0]);
+ }
} else { // If it's for a codetouse that is a short code xx
// Array to convert short lang code into long code.
$longforshort = array(
@@ -119,9 +126,13 @@ class Translate
'ka'=>'ka_GE', 'km'=>'km_KH', 'kn'=>'kn_IN', 'ko'=>'ko_KR', 'lo'=>'lo_LA', 'nb'=>'nb_NO', 'no'=>'nb_NO', 'ne'=>'ne_NP',
'sl'=>'sl_SI', 'sq'=>'sq_AL', 'sr'=>'sr_RS', 'sv'=>'sv_SE', 'uk'=>'uk_UA', 'vi'=>'vi_VN', 'zh'=>'zh_CN'
);
- if (isset($longforshort[strtolower($langpart[0])])) $srclang = $longforshort[strtolower($langpart[0])];
- elseif (!empty($langpart[0])) $srclang = strtolower($langpart[0])."_".strtoupper($langpart[0]);
- else $srclang = 'en_US';
+ if (isset($longforshort[strtolower($langpart[0])])) {
+ $srclang = $longforshort[strtolower($langpart[0])];
+ } elseif (!empty($langpart[0])) {
+ $srclang = strtolower($langpart[0])."_".strtoupper($langpart[0]);
+ } else {
+ $srclang = 'en_US';
+ }
}
$this->defaultlang = $srclang;
@@ -139,8 +150,11 @@ class Translate
*/
public function getDefaultLang($mode = 0)
{
- if (empty($mode)) return $this->defaultlang;
- else return substr($this->defaultlang, 0, 2);
+ if (empty($mode)) {
+ return $this->defaultlang;
+ } else {
+ return substr($this->defaultlang, 0, 2);
+ }
}
@@ -152,8 +166,7 @@ class Translate
*/
public function loadLangs($domains)
{
- foreach ($domains as $domain)
- {
+ foreach ($domains as $domain) {
$this->load($domain);
}
}
@@ -186,16 +199,19 @@ class Translate
//dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
// Check parameters
- if (empty($domain))
- {
+ if (empty($domain)) {
dol_print_error('', get_class($this)."::Load ErrorWrongParameters");
return -1;
}
- if ($this->defaultlang == 'none_NONE') return 0; // Special language code to not translate keys
+ if ($this->defaultlang == 'none_NONE') {
+ return 0; // Special language code to not translate keys
+ }
// Load $this->tab_translate[] from database
- if (empty($loadfromfileonly) && count($this->tab_translate) == 0) $this->loadFromDatabase($db); // No translation was never loaded yet, so we load database.
+ if (empty($loadfromfileonly) && count($this->tab_translate) == 0) {
+ $this->loadFromDatabase($db); // No translation was never loaded yet, so we load database.
+ }
$newdomain = $domain;
@@ -203,16 +219,14 @@ class Translate
// Search if a module directory name is provided into lang file name
$regs = array();
- if (preg_match('/^([^@]+)@([^@]+)$/i', $domain, $regs))
- {
+ if (preg_match('/^([^@]+)@([^@]+)$/i', $domain, $regs)) {
$newdomain = $regs[1];
$modulename = $regs[2];
}
// Check cache
if (!empty($this->_tab_loaded[$newdomain])
- && ($this->_tab_loaded[$newdomain] != 2 || empty($forceloadifalreadynotfound))) // File already loaded and found and not forced for this domain
- {
+ && ($this->_tab_loaded[$newdomain] != 2 || empty($forceloadifalreadynotfound))) { // File already loaded and found and not forced for this domain
//dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
return 0;
}
@@ -222,17 +236,19 @@ class Translate
// Redefine alt
$langarray = explode('_', $langofdir);
- if ($alt < 1 && isset($langarray[1]) && (strtolower($langarray[0]) == strtolower($langarray[1]) || in_array(strtolower($langofdir), array('el_gr')))) $alt = 1;
- if ($alt < 2 && strtolower($langofdir) == 'en_us') $alt = 2;
+ if ($alt < 1 && isset($langarray[1]) && (strtolower($langarray[0]) == strtolower($langarray[1]) || in_array(strtolower($langofdir), array('el_gr')))) {
+ $alt = 1;
+ }
+ if ($alt < 2 && strtolower($langofdir) == 'en_us') {
+ $alt = 2;
+ }
- if (empty($langofdir)) // This may occurs when load is called without setting the language and without providing a value for forcelangdir
- {
+ if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
dol_syslog("Error: ".get_class($this)."::load was called for domain=".$domain." but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
return -1;
}
- foreach ($this->dir as $searchdir)
- {
+ foreach ($this->dir as $searchdir) {
// Directory of translation files
$file_lang = $searchdir.($modulename ? '/'.$modulename : '')."/langs/".$langofdir."/".$newdomain.".lang";
$file_lang_osencoded = dol_osencode($file_lang);
@@ -242,61 +258,55 @@ class Translate
//dol_syslog(get_class($this).'::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' domain='.$domain.' newdomain='.$newdomain.' modulename='.$modulename.' file_lang='.$file_lang." => filelangexists=".$filelangexists);
//print 'Try to read for alt='.$alt.' langofdir='.$langofdir.' domain='.$domain.' newdomain='.$newdomain.' modulename='.$modulename.' this->_tab_loaded[newdomain]='.$this->_tab_loaded[$newdomain].' file_lang='.$file_lang." => filelangexists=".$filelangexists."\n";
- if ($filelangexists)
- {
+ if ($filelangexists) {
// TODO Move cache read out of loop on dirs or at least filelangexists
$found = false;
// Enable caching of lang file in memory (not by default)
$usecachekey = '';
// Using a memcached server
- if (!empty($conf->memcached->enabled) && !empty($conf->global->MEMCACHED_SERVER))
- {
+ if (!empty($conf->memcached->enabled) && !empty($conf->global->MEMCACHED_SERVER)) {
$usecachekey = $newdomain.'_'.$langofdir.'_'.md5($file_lang); // Should not contains special chars
}
// Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
- elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02))
- {
+ elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) {
$usecachekey = $newdomain;
}
- if ($usecachekey)
- {
+ if ($usecachekey) {
//dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
//global $aaa; $aaa+=1;
//print $aaa." ".$usecachekey."\n";
require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
$tmparray = dol_getcache($usecachekey);
- if (is_array($tmparray) && count($tmparray))
- {
+ if (is_array($tmparray) && count($tmparray)) {
$this->tab_translate += $tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a value already exists into tab_translate, value into tmparaay is not added.
//print $newdomain."\n";
//var_dump($this->tab_translate);
- if ($alt == 2) $fileread = 1;
+ if ($alt == 2) {
+ $fileread = 1;
+ }
$found = true; // Found in dolibarr PHP cache
}
}
- if (!$found)
- {
- if ($fp = @fopen($file_lang, "rt"))
- {
- if ($usecachekey) $tabtranslatedomain = array(); // To save lang content in cache
+ if (!$found) {
+ if ($fp = @fopen($file_lang, "rt")) {
+ if ($usecachekey) {
+ $tabtranslatedomain = array(); // To save lang content in cache
+ }
/**
* Read each lines until a '=' (with any combination of spaces around it)
* and split the rest until a line feed.
* This is more efficient than fgets + explode + trim by a factor of ~2.
*/
- while ($line = fscanf($fp, "%[^= ]%*[ =]%[^\n\r]"))
- {
- if (isset($line[1]))
- {
+ while ($line = fscanf($fp, "%[^= ]%*[ =]%[^\n\r]")) {
+ if (isset($line[1])) {
list($key, $value) = $line;
//if ($domain == 'orders') print "Domain=$domain, found a string for $tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]." ";
//if ($key == 'Order') print "Domain=$domain, found a string for key=$key=$tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]." ";
- if (empty($this->tab_translate[$key]))
- { // If translation was already found, we must not continue, even if MAIN_FORCELANGDIR is set (MAIN_FORCELANGDIR is to replace lang dir, not to overwrite entries)
+ if (empty($this->tab_translate[$key])) { // If translation was already found, we must not continue, even if MAIN_FORCELANGDIR is set (MAIN_FORCELANGDIR is to replace lang dir, not to overwrite entries)
if ($key == 'DIRECTION') { // This is to declare direction of language
if ($alt < 2 || empty($this->tab_translate[$key])) { // We load direction only for primary files or if not yet loaded
$this->tab_translate[$key] = $value;
@@ -306,8 +316,7 @@ class Translate
$tabtranslatedomain[$key] = $value;
}
}
- } elseif ($key[0] == '#')
- {
+ } elseif ($key[0] == '#') {
continue;
} else {
// Convert some strings: Parse and render carriage returns. Also, change '\\s' into '\s' because transifex sync pull the string '\s' into string '\\s'
@@ -324,36 +333,38 @@ class Translate
// TODO Move cache write out of loop on dirs
// To save lang content for usecachekey into cache
- if ($usecachekey && count($tabtranslatedomain))
- {
+ if ($usecachekey && count($tabtranslatedomain)) {
$ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
- if ($ressetcache < 0)
- {
+ if ($ressetcache < 0) {
$error = 'Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache;
dol_syslog($error, LOG_ERR);
}
}
- if (empty($conf->global->MAIN_FORCELANGDIR)) break; // Break loop on each root dir. If a module has forced dir, we do not stop loop.
+ if (empty($conf->global->MAIN_FORCELANGDIR)) {
+ break; // Break loop on each root dir. If a module has forced dir, we do not stop loop.
+ }
}
}
}
}
// Now we complete with next file (fr_CA->fr_FR, es_MX->ex_ES, ...)
- if ($alt == 0)
- {
+ if ($alt == 0) {
// This function MUST NOT contains call to syslog
//dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
$langofdir = strtolower($langarray[0]).'_'.strtoupper($langarray[0]);
- if ($langofdir == 'el_EL') $langofdir = 'el_GR'; // main parent for el_CY is not 'el_EL' but 'el_GR'
- if ($langofdir == 'ar_AR') $langofdir = 'ar_SA'; // main parent for ar_EG is not 'ar_AR' but 'ar_SA'
+ if ($langofdir == 'el_EL') {
+ $langofdir = 'el_GR'; // main parent for el_CY is not 'el_EL' but 'el_GR'
+ }
+ if ($langofdir == 'ar_AR') {
+ $langofdir = 'ar_SA'; // main parent for ar_EG is not 'ar_AR' but 'ar_SA'
+ }
$this->load($domain, $alt + 1, $stopafterdirection, $langofdir);
}
// Now we complete with reference file (en_US)
- if ($alt == 1)
- {
+ if ($alt == 1) {
// This function MUST NOT contains call to syslog
//dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
$langofdir = 'en_US';
@@ -361,33 +372,37 @@ class Translate
}
// We are in the pass of the reference file. No more files to scan to complete.
- if ($alt == 2)
- {
- if ($fileread) $this->_tab_loaded[$newdomain] = 1; // Set domain file as found so loaded
+ if ($alt == 2) {
+ if ($fileread) {
+ $this->_tab_loaded[$newdomain] = 1; // Set domain file as found so loaded
+ }
- if (empty($this->_tab_loaded[$newdomain])) $this->_tab_loaded[$newdomain] = 2; // Set this file as not found
+ if (empty($this->_tab_loaded[$newdomain])) {
+ $this->_tab_loaded[$newdomain] = 2; // Set this file as not found
+ }
}
// This part is deprecated and replaced with table llx_overwrite_trans
// Kept for backward compatibility.
- if (empty($loadfromfileonly))
- {
+ if (empty($loadfromfileonly)) {
$overwritekey = 'MAIN_OVERWRITE_TRANS_'.$this->defaultlang;
- if (!empty($conf->global->$overwritekey)) // Overwrite translation with key1:newstring1,key2:newstring2
- {
+ if (!empty($conf->global->$overwritekey)) { // Overwrite translation with key1:newstring1,key2:newstring2
// Overwrite translation with param MAIN_OVERWRITE_TRANS_xx_XX
$tmparray = explode(',', $conf->global->$overwritekey);
- foreach ($tmparray as $tmp)
- {
+ foreach ($tmparray as $tmp) {
$tmparray2 = explode(':', $tmp);
- if (!empty($tmparray2[1])) $this->tab_translate[$tmparray2[0]] = $tmparray2[1];
+ if (!empty($tmparray2[1])) {
+ $this->tab_translate[$tmparray2[0]] = $tmparray2[1];
+ }
}
}
}
// Check to be sure that SeparatorDecimal differs from SeparatorThousand
if (!empty($this->tab_translate["SeparatorDecimal"]) && !empty($this->tab_translate["SeparatorThousand"])
- && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]) $this->tab_translate["SeparatorThousand"] = '';
+ && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]) {
+ $this->tab_translate["SeparatorThousand"] = '';
+ }
return 1;
}
@@ -411,15 +426,16 @@ class Translate
$domain = 'database';
// Check parameters
- if (empty($db)) return 0; // Database handler can't be used
+ if (empty($db)) {
+ return 0; // Database handler can't be used
+ }
//dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
$newdomain = $domain;
// Check cache
- if (!empty($this->_tab_loaded[$newdomain])) // File already loaded for this domain 'database'
- {
+ if (!empty($this->_tab_loaded[$newdomain])) { // File already loaded for this domain 'database'
//dol_syslog("Translate::Load already loaded for newdomain=".$newdomain);
return 0;
}
@@ -429,8 +445,7 @@ class Translate
$fileread = 0;
$langofdir = $this->defaultlang;
- if (empty($langofdir)) // This may occurs when load is called without setting the language and without providing a value for forcelangdir
- {
+ if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
dol_syslog("Error: ".get_class($this)."::loadFromDatabase was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
return -1;
}
@@ -441,25 +456,21 @@ class Translate
// Enable caching of lang file in memory (not by default)
$usecachekey = '';
// Using a memcached server
- if (!empty($conf->memcached->enabled) && !empty($conf->global->MEMCACHED_SERVER))
- {
+ if (!empty($conf->memcached->enabled) && !empty($conf->global->MEMCACHED_SERVER)) {
$usecachekey = $newdomain.'_'.$langofdir; // Should not contains special chars
}
// Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
- elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02))
- {
+ elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) {
$usecachekey = $newdomain;
}
- if ($usecachekey)
- {
+ if ($usecachekey) {
//dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
//global $aaa; $aaa+=1;
//print $aaa." ".$usecachekey."\n";
require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
$tmparray = dol_getcache($usecachekey);
- if (is_array($tmparray) && count($tmparray))
- {
+ if (is_array($tmparray) && count($tmparray)) {
$this->tab_translate += $tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a value already exists into tab_translate, value into tmparaay is not added.
//print $newdomain."\n";
//var_dump($this->tab_translate);
@@ -468,36 +479,35 @@ class Translate
}
}
- if (!$found && !empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION))
- {
+ if (!$found && !empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) {
// Overwrite translation with database read
$sql = "SELECT transkey, transvalue FROM ".MAIN_DB_PREFIX."overwrite_trans where lang='".$db->escape($this->defaultlang)."' OR lang IS NULL";
$sql .= " AND entity IN (0, ".getEntity('overwrite_trans').")";
$sql .= $db->order("lang", "DESC");
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $db->num_rows($resql);
- if ($num)
- {
- if ($usecachekey) $tabtranslatedomain = array(); // To save lang content in cache
+ if ($num) {
+ if ($usecachekey) {
+ $tabtranslatedomain = array(); // To save lang content in cache
+ }
$i = 0;
- while ($i < $num) // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents
- {
+ while ($i < $num) { // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents
$obj = $db->fetch_object($resql);
$key = $obj->transkey;
$value = $obj->transvalue;
//print "Domain=$domain, found a string for $tab[0] with value $tab[1] ";
- if (empty($this->tab_translate[$key])) // If translation was already found, we must not continue, even if MAIN_FORCELANGDIR is set (MAIN_FORCELANGDIR is to replace lang dir, not to overwrite entries)
- {
+ if (empty($this->tab_translate[$key])) { // If translation was already found, we must not continue, even if MAIN_FORCELANGDIR is set (MAIN_FORCELANGDIR is to replace lang dir, not to overwrite entries)
// Convert some strings: Parse and render carriage returns. Also, change '\\s' int '\s' because transifex sync pull the string '\s' into string '\\s'
$this->tab_translate[$key] = str_replace(array('\\n', '\\\\s'), array("\n", '\s'), $value);
- if ($usecachekey) $tabtranslatedomain[$key] = $value; // To save lang content in cache
+ if ($usecachekey) {
+ $tabtranslatedomain[$key] = $value; // To save lang content in cache
+ }
}
$i++;
@@ -507,11 +517,9 @@ class Translate
// TODO Move cache write out of loop on dirs
// To save lang content for usecachekey into cache
- if ($usecachekey && count($tabtranslatedomain))
- {
+ if ($usecachekey && count($tabtranslatedomain)) {
$ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
- if ($ressetcache < 0)
- {
+ if ($ressetcache < 0) {
$error = 'Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache;
dol_syslog($error, LOG_ERR);
}
@@ -522,9 +530,13 @@ class Translate
}
}
- if ($fileread) $this->_tab_loaded[$newdomain] = 1; // Set domain file as loaded
+ if ($fileread) {
+ $this->_tab_loaded[$newdomain] = 1; // Set domain file as loaded
+ }
- if (empty($this->_tab_loaded[$newdomain])) $this->_tab_loaded[$newdomain] = 2; // Mark this case as not found (no lines found for language)
+ if (empty($this->_tab_loaded[$newdomain])) {
+ $this->_tab_loaded[$newdomain] = 2; // Mark this case as not found (no lines found for language)
+ }
return 1;
}
@@ -561,32 +573,26 @@ class Translate
}
$newstr = $key;
- if (preg_match('/^Civility([0-9A-Z]+)$/i', $key, $reg))
- {
+ if (preg_match('/^Civility([0-9A-Z]+)$/i', $key, $reg)) {
$newstr = $this->getLabelFromKey($db, $reg[1], 'c_civility', 'code', 'label');
- } elseif (preg_match('/^Currency([A-Z][A-Z][A-Z])$/i', $key, $reg))
- {
+ } elseif (preg_match('/^Currency([A-Z][A-Z][A-Z])$/i', $key, $reg)) {
$newstr = $this->getLabelFromKey($db, $reg[1], 'c_currencies', 'code_iso', 'label');
- } elseif (preg_match('/^SendingMethod([0-9A-Z]+)$/i', $key, $reg))
- {
+ } elseif (preg_match('/^SendingMethod([0-9A-Z]+)$/i', $key, $reg)) {
$newstr = $this->getLabelFromKey($db, $reg[1], 'c_shipment_mode', 'code', 'libelle');
- } elseif (preg_match('/^PaymentTypeShort([0-9A-Z]+)$/i', $key, $reg))
- {
+ } elseif (preg_match('/^PaymentTypeShort([0-9A-Z]+)$/i', $key, $reg)) {
$newstr = $this->getLabelFromKey($db, $reg[1], 'c_paiement', 'code', 'libelle', '', 1);
- } elseif (preg_match('/^OppStatus([0-9A-Z]+)$/i', $key, $reg))
- {
+ } elseif (preg_match('/^OppStatus([0-9A-Z]+)$/i', $key, $reg)) {
$newstr = $this->getLabelFromKey($db, $reg[1], 'c_lead_status', 'code', 'label');
- } elseif (preg_match('/^OrderSource([0-9A-Z]+)$/i', $key, $reg))
- {
+ } elseif (preg_match('/^OrderSource([0-9A-Z]+)$/i', $key, $reg)) {
// TODO OrderSourceX must be replaced with content of table llx_c_input_reason or llx_c_input_method
//$newstr=$this->getLabelFromKey($db,$reg[1],'c_ordersource','code','label');
}
/* Disabled. There is too many cases where translation of $newstr is not defined is normal (like when output with setEventMessage an already translated string)
- if (! empty($conf->global->MAIN_FEATURES_LEVEL) && $conf->global->MAIN_FEATURES_LEVEL >= 2)
- {
- dol_syslog(__METHOD__." MAIN_FEATURES_LEVEL=DEVELOP: missing translation for key '".$newstr."' in ".$_SERVER["PHP_SELF"], LOG_DEBUG);
- }*/
+ if (! empty($conf->global->MAIN_FEATURES_LEVEL) && $conf->global->MAIN_FEATURES_LEVEL >= 2)
+ {
+ dol_syslog(__METHOD__." MAIN_FEATURES_LEVEL=DEVELOP: missing translation for key '".$newstr."' in ".$_SERVER["PHP_SELF"], LOG_DEBUG);
+ }*/
return $newstr;
}
@@ -609,17 +615,14 @@ class Translate
{
global $conf;
- if (!empty($this->tab_translate[$key])) // Translation is available
- {
+ if (!empty($this->tab_translate[$key])) { // Translation is available
$str = $this->tab_translate[$key];
// Make some string replacement after translation
$replacekey = 'MAIN_REPLACE_TRANS_'.$this->defaultlang;
- if (!empty($conf->global->$replacekey)) // Replacement translation variable with string1:newstring1;string2:newstring2
- {
+ if (!empty($conf->global->$replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
$tmparray = explode(';', $conf->global->$replacekey);
- foreach ($tmparray as $tmp)
- {
+ foreach ($tmparray as $tmp) {
$tmparray2 = explode(':', $tmp);
$str = preg_replace('/'.preg_quote($tmparray2[0]).'/', $tmparray2[1], $str);
}
@@ -633,8 +636,7 @@ class Translate
$str
);
- if (strpos($key, 'Format') !== 0)
- {
+ if (strpos($key, 'Format') !== 0) {
$str = sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings.
}
@@ -648,7 +650,9 @@ class Translate
$str
);
- if ($maxsize) $str = dol_trunc($str, $maxsize);
+ if ($maxsize) {
+ $str = dol_trunc($str, $maxsize);
+ }
return $str;
} else { // Translation is not available
@@ -697,31 +701,29 @@ class Translate
{
global $conf;
- if (!empty($this->tab_translate[$key])) // Translation is available
- {
+ if (!empty($this->tab_translate[$key])) { // Translation is available
$str = $this->tab_translate[$key];
// Make some string replacement after translation
$replacekey = 'MAIN_REPLACE_TRANS_'.$this->defaultlang;
- if (!empty($conf->global->$replacekey)) // Replacement translation variable with string1:newstring1;string2:newstring2
- {
+ if (!empty($conf->global->$replacekey)) { // Replacement translation variable with string1:newstring1;string2:newstring2
$tmparray = explode(';', $conf->global->$replacekey);
- foreach ($tmparray as $tmp)
- {
+ foreach ($tmparray as $tmp) {
$tmparray2 = explode(':', $tmp);
$str = preg_replace('/'.preg_quote($tmparray2[0]).'/', $tmparray2[1], $str);
}
}
- if (!preg_match('/^Format/', $key))
- {
+ if (!preg_match('/^Format/', $key)) {
//print $str;
- $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings.
+ $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings.
}
return $str;
} else {
- if ($key[0] == '$') { return dol_eval($key, 1); }
+ if ($key[0] == '$') {
+ return dol_eval($key, 1);
+ }
return $this->getTradFromKey($key);
}
}
@@ -736,8 +738,11 @@ class Translate
*/
public function transcountry($str, $countrycode)
{
- if (!empty($this->tab_translate["$str$countrycode"])) return $this->trans("$str$countrycode");
- else return $this->trans($str);
+ if (!empty($this->tab_translate["$str$countrycode"])) {
+ return $this->trans("$str$countrycode");
+ } else {
+ return $this->trans($str);
+ }
}
@@ -750,8 +755,11 @@ class Translate
*/
public function transcountrynoentities($str, $countrycode)
{
- if (!empty($this->tab_translate["$str$countrycode"])) return $this->transnoentities("$str$countrycode");
- else return $this->transnoentities($str);
+ if (!empty($this->tab_translate["$str$countrycode"])) {
+ return $this->transnoentities("$str$countrycode");
+ } else {
+ return $this->transnoentities($str);
+ }
}
@@ -764,8 +772,12 @@ class Translate
*/
public function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
{
- if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8') $str = utf8_encode($str);
- if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1') $str = utf8_decode(str_replace('€', chr(128), $str));
+ if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8') {
+ $str = utf8_encode($str);
+ }
+ if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1') {
+ $str = utf8_decode(str_replace('€', chr(128), $str));
+ }
return $str;
}
@@ -790,11 +802,9 @@ class Translate
// We scan directory langs to detect available languages
$handle = opendir($langdir."/langs");
$langs_available = array();
- while ($dir = trim(readdir($handle)))
- {
+ while ($dir = trim(readdir($handle))) {
$regs = array();
- if (preg_match('/^([a-z]+)_([A-Z]+)/i', $dir, $regs))
- {
+ if (preg_match('/^([a-z]+)_([A-Z]+)/i', $dir, $regs)) {
// We must keep only main languages
if ($mainlangonly) {
$arrayofspecialmainlanguages = array(
@@ -827,18 +837,20 @@ class Translate
'vi'=>'vi_VN',
'zh'=>'zh_CN'
);
- if (strtolower($regs[1]) != strtolower($regs[2]) && !in_array($dir, $arrayofspecialmainlanguages)) continue;
+ if (strtolower($regs[1]) != strtolower($regs[2]) && !in_array($dir, $arrayofspecialmainlanguages)) {
+ continue;
+ }
}
// We must keep only languages into MAIN_LANGUAGES_ALLOWED
- if (!empty($conf->global->MAIN_LANGUAGES_ALLOWED) && !in_array($dir, explode(',', $conf->global->MAIN_LANGUAGES_ALLOWED))) continue;
+ if (!empty($conf->global->MAIN_LANGUAGES_ALLOWED) && !in_array($dir, explode(',', $conf->global->MAIN_LANGUAGES_ALLOWED))) {
+ continue;
+ }
- if ($usecode == 2)
- {
+ if ($usecode == 2) {
$langs_available[$dir] = $dir;
}
- if ($usecode == 1 || !empty($conf->global->MAIN_SHOW_LANGUAGE_CODE))
- {
+ if ($usecode == 1 || !empty($conf->global->MAIN_SHOW_LANGUAGE_CODE)) {
$langs_available[$dir] = $dir.': '.dol_trunc($this->trans('Language_'.$dir), $maxlength);
} else {
$langs_available[$dir] = $this->trans('Language_'.$dir);
@@ -864,16 +876,20 @@ class Translate
{
// phpcs:enable
// Test si fichier dans repertoire de la langue
- foreach ($this->dir as $searchdir)
- {
- if (is_readable(dol_osencode($searchdir."/langs/".$this->defaultlang."/".$filename))) return true;
+ foreach ($this->dir as $searchdir) {
+ if (is_readable(dol_osencode($searchdir."/langs/".$this->defaultlang."/".$filename))) {
+ return true;
+ }
- if ($searchalt)
- {
+ if ($searchalt) {
// Test si fichier dans repertoire de la langue alternative
- if ($this->defaultlang != "en_US") $filenamealt = $searchdir."/langs/en_US/".$filename;
+ if ($this->defaultlang != "en_US") {
+ $filenamealt = $searchdir."/langs/en_US/".$filename;
+ }
//else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
- if (is_readable(dol_osencode($filenamealt))) return true;
+ if (is_readable(dol_osencode($filenamealt))) {
+ return true;
+ }
}
}
@@ -899,17 +915,17 @@ class Translate
$newnumber = $number;
$dirsubstitutions = array_merge(array(), $conf->modules_parts['substitutions']);
- foreach ($dirsubstitutions as $reldir)
- {
+ foreach ($dirsubstitutions as $reldir) {
$dir = dol_buildpath($reldir, 0);
$newdir = dol_osencode($dir);
// Check if directory exists
- if (!is_dir($newdir)) continue; // We must not use dol_is_dir here, function may not be loaded
+ if (!is_dir($newdir)) {
+ continue; // We must not use dol_is_dir here, function may not be loaded
+ }
$fonc = 'numberwords';
- if (file_exists($newdir.'/functions_'.$fonc.'.lib.php'))
- {
+ if (file_exists($newdir.'/functions_'.$fonc.'.lib.php')) {
include_once $newdir.'/functions_'.$fonc.'.lib.php';
$newnumber = numberwords_getLabelFromNumber($this, $number, $isamount);
break;
@@ -938,34 +954,38 @@ class Translate
public function getLabelFromKey($db, $key, $tablename, $fieldkey, $fieldlabel, $keyforselect = '', $filteronentity = 0)
{
// If key empty
- if ($key == '') return '';
+ if ($key == '') {
+ return '';
+ }
//print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit;
// Check if a translation is available (this can call getTradFromKey)
$tmp = $this->transnoentitiesnoconv($key);
- if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString')
- {
+ if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') {
return $tmp; // Found in language array
}
// Check in cache
- if (isset($this->cache_labels[$tablename][$key])) // Can be defined to 0 or ''
- {
+ if (isset($this->cache_labels[$tablename][$key])) { // Can be defined to 0 or ''
return $this->cache_labels[$tablename][$key]; // Found in cache
}
$sql = "SELECT ".$fieldlabel." as label";
$sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
$sql .= " WHERE ".$fieldkey." = '".$db->escape($keyforselect ? $keyforselect : $key)."'";
- if ($filteronentity) $sql .= " AND entity IN (".getEntity($tablename).')';
+ if ($filteronentity) {
+ $sql .= " AND entity IN (".getEntity($tablename).')';
+ }
dol_syslog(get_class($this).'::getLabelFromKey', LOG_DEBUG);
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $db->fetch_object($resql);
- if ($obj) $this->cache_labels[$tablename][$key] = $obj->label;
- else $this->cache_labels[$tablename][$key] = $key;
+ if ($obj) {
+ $this->cache_labels[$tablename][$key] = $obj->label;
+ } else {
+ $this->cache_labels[$tablename][$key] = $key;
+ }
$db->free($resql);
return $this->cache_labels[$tablename][$key];
@@ -989,8 +1009,11 @@ class Translate
{
$symbol = $this->getCurrencySymbol($currency_code);
- if (in_array($currency_code, array('USD'))) return $symbol.$amount;
- else return $amount.$symbol;
+ if (in_array($currency_code, array('USD'))) {
+ return $symbol.$amount;
+ } else {
+ return $amount.$symbol;
+ }
}
/**
@@ -1005,14 +1028,11 @@ class Translate
{
$currency_sign = ''; // By default return iso code
- if (function_exists("mb_convert_encoding"))
- {
+ if (function_exists("mb_convert_encoding")) {
$this->loadCacheCurrencies($forceloadall ? '' : $currency_code);
- if (isset($this->cache_currencies[$currency_code]) && !empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode']))
- {
- foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode)
- {
+ if (isset($this->cache_currencies[$currency_code]) && !empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode'])) {
+ foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode) {
$currency_sign .= mb_convert_encoding("{$unicode};", "UTF-8", 'HTML-ENTITIES');
}
}
@@ -1031,27 +1051,35 @@ class Translate
{
global $db;
- if ($this->cache_currencies_all_loaded) return 0; // Cache already loaded for all
- if (!empty($currency_code) && isset($this->cache_currencies[$currency_code])) return 0; // Cache already loaded for the currency
+ if ($this->cache_currencies_all_loaded) {
+ return 0; // Cache already loaded for all
+ }
+ if (!empty($currency_code) && isset($this->cache_currencies[$currency_code])) {
+ return 0; // Cache already loaded for the currency
+ }
$sql = "SELECT code_iso, label, unicode";
$sql .= " FROM ".MAIN_DB_PREFIX."c_currencies";
$sql .= " WHERE active = 1";
- if (!empty($currency_code)) $sql .= " AND code_iso = '".$db->escape($currency_code)."'";
+ if (!empty($currency_code)) {
+ $sql .= " AND code_iso = '".$db->escape($currency_code)."'";
+ }
//$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
dol_syslog(get_class($this).'::loadCacheCurrencies', LOG_DEBUG);
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$this->load("dict");
$label = array();
- if (!empty($currency_code)) foreach ($this->cache_currencies as $key => $val) $label[$key] = $val['label']; // Label in already loaded cache
+ if (!empty($currency_code)) {
+ foreach ($this->cache_currencies as $key => $val) {
+ $label[$key] = $val['label']; // Label in already loaded cache
+ }
+ }
$num = $db->num_rows($resql);
$i = 0;
- while ($i < $num)
- {
+ while ($i < $num) {
$obj = $db->fetch_object($resql);
// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
@@ -1060,7 +1088,9 @@ class Translate
$label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
$i++;
}
- if (empty($currency_code)) $this->cache_currencies_all_loaded = true;
+ if (empty($currency_code)) {
+ $this->cache_currencies_all_loaded = true;
+ }
//print count($label).' '.count($this->cache_currencies);
// Resort cache
diff --git a/htdocs/core/class/utils.class.php b/htdocs/core/class/utils.class.php
index 9cf8439483a..3806e5bda4d 100644
--- a/htdocs/core/class/utils.class.php
+++ b/htdocs/core/class/utils.class.php
@@ -77,58 +77,53 @@ class Utils
foreach ($choicesarray as $choice) {
$filesarray = array();
- if ($choice == 'tempfiles' || $choice == 'tempfilesold')
- {
+ if ($choice == 'tempfiles' || $choice == 'tempfilesold') {
// Delete temporary files
- if ($dolibarr_main_data_root)
- {
+ if ($dolibarr_main_data_root) {
$filesarray = dol_dir_list($dolibarr_main_data_root, "directories", 1, '^temp$', '', 'name', SORT_ASC, 2, 0, '', 1); // Do not follow symlinks
- if ($choice == 'tempfilesold')
- {
+ if ($choice == 'tempfilesold') {
$now = dol_now();
- foreach ($filesarray as $key => $val)
- {
- if ($val['date'] > ($now - ($nbsecondsold))) unset($filesarray[$key]); // Discard temp dir not older than $nbsecondsold
+ foreach ($filesarray as $key => $val) {
+ if ($val['date'] > ($now - ($nbsecondsold))) {
+ unset($filesarray[$key]); // Discard temp dir not older than $nbsecondsold
+ }
}
}
}
}
- if ($choice == 'allfiles')
- {
+ if ($choice == 'allfiles') {
// Delete all files (except install.lock, do not follow symbolic links)
- if ($dolibarr_main_data_root)
- {
+ if ($dolibarr_main_data_root) {
$filesarray = dol_dir_list($dolibarr_main_data_root, "all", 0, '', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1);
}
}
- if ($choice == 'logfile' || $choice == 'logfiles')
- {
+ if ($choice == 'logfile' || $choice == 'logfiles') {
// Define files log
- if ($dolibarr_main_data_root)
- {
+ if ($dolibarr_main_data_root) {
$filesarray = dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*(\.gz)?$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1);
}
- if (!empty($conf->syslog->enabled))
- {
+ if (!empty($conf->syslog->enabled)) {
$filelog = $conf->global->SYSLOG_FILE;
$filelog = preg_replace('/DOL_DATA_ROOT/i', DOL_DATA_ROOT, $filelog);
$alreadyincluded = false;
- foreach ($filesarray as $tmpcursor)
- {
- if ($tmpcursor['fullname'] == $filelog) { $alreadyincluded = true; }
+ foreach ($filesarray as $tmpcursor) {
+ if ($tmpcursor['fullname'] == $filelog) {
+ $alreadyincluded = true;
+ }
+ }
+ if (!$alreadyincluded) {
+ $filesarray[] = array('fullname'=>$filelog, 'type'=>'file');
}
- if (!$alreadyincluded) $filesarray[] = array('fullname'=>$filelog, 'type'=>'file');
}
}
if (is_array($filesarray) && count($filesarray)) {
- foreach ($filesarray as $key => $value)
- {
+ foreach ($filesarray as $key => $value) {
//print "x ".$filesarray[$key]['fullname']."-".$filesarray[$key]['type']." \n";
if ($filesarray[$key]['type'] == 'dir') {
$startcount = 0;
@@ -142,8 +137,7 @@ class Utils
}
} elseif ($filesarray[$key]['type'] == 'file') {
// If (file that is not logfile) or (if mode is logfile)
- if ($filesarray[$key]['fullname'] != $filelog || $choice == 'logfile' || $choice == 'logfiles')
- {
+ if ($filesarray[$key]['fullname'] != $filelog || $choice == 'logfile' || $choice == 'logfiles') {
$result = dol_delete_file($filesarray[$key]['fullname'], 1, 1);
if ($result) {
$count++;
@@ -156,8 +150,7 @@ class Utils
}
// Update cachenbofdoc
- if (!empty($conf->ecm->enabled) && $choice == 'allfiles')
- {
+ if (!empty($conf->ecm->enabled) && $choice == 'allfiles') {
require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
$ecmdirstatic = new EcmDirectory($this->db);
$result = $ecmdirstatic->refreshcachenboffile(1);
@@ -208,30 +201,33 @@ class Utils
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
// Check compression parameter
- if (!in_array($compression, array('none', 'gz', 'bz', 'zip')))
- {
+ if (!in_array($compression, array('none', 'gz', 'bz', 'zip'))) {
$langs->load("errors");
$this->error = $langs->transnoentitiesnoconv("ErrorBadValueForParameter", $compression, "Compression");
return -1;
}
// Check type parameter
- if ($type == 'auto') $type = $this->db->type;
- if (!in_array($type, array('postgresql', 'pgsql', 'mysql', 'mysqli', 'mysqlnobin')))
- {
+ if ($type == 'auto') {
+ $type = $this->db->type;
+ }
+ if (!in_array($type, array('postgresql', 'pgsql', 'mysql', 'mysqli', 'mysqlnobin'))) {
$langs->load("errors");
$this->error = $langs->transnoentitiesnoconv("ErrorBadValueForParameter", $type, "Basetype");
return -1;
}
// Check file parameter
- if ($file == 'auto')
- {
+ if ($file == 'auto') {
$prefix = 'dump';
$ext = 'sql';
- if (in_array($type, array('mysql', 'mysqli'))) { $prefix = 'mysqldump'; $ext = 'sql'; }
+ if (in_array($type, array('mysql', 'mysqli'))) {
+ $prefix = 'mysqldump'; $ext = 'sql';
+ }
//if ($label == 'PostgreSQL') { $prefix='pg_dump'; $ext='dump'; }
- if (in_array($type, array('pgsql'))) { $prefix = 'pg_dump'; $ext = 'sql'; }
+ if (in_array($type, array('pgsql'))) {
+ $prefix = 'pg_dump'; $ext = 'sql';
+ }
$file = $prefix.'_'.$dolibarr_main_db_name.'_'.dol_sanitizeFileName(DOL_VERSION).'_'.strftime("%Y%m%d%H%M").'.'.$ext;
}
@@ -240,58 +236,88 @@ class Utils
$errormsg = '';
// MYSQL
- if ($type == 'mysql' || $type == 'mysqli')
- {
+ if ($type == 'mysql' || $type == 'mysqli') {
$cmddump = $conf->global->SYSTEMTOOLS_MYSQLDUMP;
$outputfile = $outputdir.'/'.$file;
// for compression format, we add extension
$compression = $compression ? $compression : 'none';
- if ($compression == 'gz') $outputfile .= '.gz';
- if ($compression == 'bz') $outputfile .= '.bz2';
+ if ($compression == 'gz') {
+ $outputfile .= '.gz';
+ }
+ if ($compression == 'bz') {
+ $outputfile .= '.bz2';
+ }
$outputerror = $outputfile.'.err';
dol_mkdir($conf->admin->dir_output.'/backup');
// Parameteres execution
$command = $cmddump;
$command = preg_replace('/(\$|%)/', '', $command); // We removed chars that can be used to inject vars that contains space inside path of command without seeing there is a space to bypass the escapeshellarg.
- if (preg_match("/\s/", $command)) $command = escapeshellarg($command); // If there is spaces, we add quotes on command to be sure $command is only a program and not a program+parameters
+ if (preg_match("/\s/", $command)) {
+ $command = escapeshellarg($command); // If there is spaces, we add quotes on command to be sure $command is only a program and not a program+parameters
+ }
//$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
$param = $dolibarr_main_db_name." -h ".$dolibarr_main_db_host;
$param .= " -u ".$dolibarr_main_db_user;
- if (!empty($dolibarr_main_db_port)) $param .= " -P ".$dolibarr_main_db_port;
- if (!GETPOST("use_transaction", "alpha")) $param .= " -l --single-transaction";
- if (GETPOST("disable_fk", "alpha") || $usedefault) $param .= " -K";
- if (GETPOST("sql_compat", "alpha") && GETPOST("sql_compat", "alpha") != 'NONE') $param .= " --compatible=".escapeshellarg(GETPOST("sql_compat", "alpha"));
- if (GETPOST("drop_database", "alpha")) $param .= " --add-drop-database";
- if (GETPOST("use_mysql_quick_param", "alpha"))$param .= " --quick";
- if (GETPOST("sql_structure", "alpha") || $usedefault)
- {
- if (GETPOST("drop", "alpha") || $usedefault) $param .= " --add-drop-table=TRUE";
- else $param .= " --add-drop-table=FALSE";
+ if (!empty($dolibarr_main_db_port)) {
+ $param .= " -P ".$dolibarr_main_db_port;
+ }
+ if (!GETPOST("use_transaction", "alpha")) {
+ $param .= " -l --single-transaction";
+ }
+ if (GETPOST("disable_fk", "alpha") || $usedefault) {
+ $param .= " -K";
+ }
+ if (GETPOST("sql_compat", "alpha") && GETPOST("sql_compat", "alpha") != 'NONE') {
+ $param .= " --compatible=".escapeshellarg(GETPOST("sql_compat", "alpha"));
+ }
+ if (GETPOST("drop_database", "alpha")) {
+ $param .= " --add-drop-database";
+ }
+ if (GETPOST("use_mysql_quick_param", "alpha")) {
+ $param .= " --quick";
+ }
+ if (GETPOST("sql_structure", "alpha") || $usedefault) {
+ if (GETPOST("drop", "alpha") || $usedefault) {
+ $param .= " --add-drop-table=TRUE";
+ } else {
+ $param .= " --add-drop-table=FALSE";
+ }
} else {
$param .= " -t";
}
- if (GETPOST("disable-add-locks", "alpha")) $param .= " --add-locks=FALSE";
- if (GETPOST("sql_data", "alpha") || $usedefault)
- {
+ if (GETPOST("disable-add-locks", "alpha")) {
+ $param .= " --add-locks=FALSE";
+ }
+ if (GETPOST("sql_data", "alpha") || $usedefault) {
$param .= " --tables";
- if (GETPOST("showcolumns", "alpha") || $usedefault) $param .= " -c";
- if (GETPOST("extended_ins", "alpha") || $usedefault) $param .= " -e";
- else $param .= " --skip-extended-insert";
- if (GETPOST("delayed", "alpha")) $param .= " --delayed-insert";
- if (GETPOST("sql_ignore", "alpha")) $param .= " --insert-ignore";
- if (GETPOST("hexforbinary", "alpha") || $usedefault) $param .= " --hex-blob";
+ if (GETPOST("showcolumns", "alpha") || $usedefault) {
+ $param .= " -c";
+ }
+ if (GETPOST("extended_ins", "alpha") || $usedefault) {
+ $param .= " -e";
+ } else {
+ $param .= " --skip-extended-insert";
+ }
+ if (GETPOST("delayed", "alpha")) {
+ $param .= " --delayed-insert";
+ }
+ if (GETPOST("sql_ignore", "alpha")) {
+ $param .= " --insert-ignore";
+ }
+ if (GETPOST("hexforbinary", "alpha") || $usedefault) {
+ $param .= " --hex-blob";
+ }
} else {
$param .= " -d"; // No row information (no data)
}
$param .= " --default-character-set=utf8"; // We always save output into utf8 charset
$paramcrypted = $param;
$paramclear = $param;
- if (!empty($dolibarr_main_db_pass))
- {
+ if (!empty($dolibarr_main_db_pass)) {
$paramcrypted .= ' -p"'.preg_replace('/./i', '*', $dolibarr_main_db_pass).'"';
$paramclear .= ' -p"'.str_replace(array('"', '`', '$'), array('\"', '\`', '\$'), $dolibarr_main_db_pass).'"';
}
@@ -301,69 +327,89 @@ class Utils
// Start call method to execute dump
$fullcommandcrypted = $command." ".$paramcrypted." 2>&1";
$fullcommandclear = $command." ".$paramclear." 2>&1";
- if ($compression == 'none') $handle = fopen($outputfile, 'w');
- if ($compression == 'gz') $handle = gzopen($outputfile, 'w');
- if ($compression == 'bz') $handle = bzopen($outputfile, 'w');
+ if ($compression == 'none') {
+ $handle = fopen($outputfile, 'w');
+ }
+ if ($compression == 'gz') {
+ $handle = gzopen($outputfile, 'w');
+ }
+ if ($compression == 'bz') {
+ $handle = bzopen($outputfile, 'w');
+ }
$ok = 0;
- if ($handle)
- {
- if (!empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod = $conf->global->MAIN_EXEC_USE_POPEN;
- if (empty($execmethod)) $execmethod = 1;
+ if ($handle) {
+ if (!empty($conf->global->MAIN_EXEC_USE_POPEN)) {
+ $execmethod = $conf->global->MAIN_EXEC_USE_POPEN;
+ }
+ if (empty($execmethod)) {
+ $execmethod = 1;
+ }
dol_syslog("Utils::dumpDatabase execmethod=".$execmethod." command:".$fullcommandcrypted, LOG_DEBUG);
// TODO Replace with executeCLI function
- if ($execmethod == 1)
- {
+ if ($execmethod == 1) {
$output_arr = array(); $retval = null;
exec($fullcommandclear, $output_arr, $retval);
- if ($retval != 0)
- {
+ if ($retval != 0) {
$langs->load("errors");
dol_syslog("Datadump retval after exec=".$retval, LOG_ERR);
$errormsg = 'Error '.$retval;
$ok = 0;
} else {
$i = 0;
- if (!empty($output_arr))
- {
- foreach ($output_arr as $key => $read)
- {
+ if (!empty($output_arr)) {
+ foreach ($output_arr as $key => $read) {
$i++; // output line number
- if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue;
+ if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) {
+ continue;
+ }
fwrite($handle, $read.($execmethod == 2 ? '' : "\n"));
- if (preg_match('/'.preg_quote('-- Dump completed').'/i', $read)) $ok = 1;
- elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i', $read)) $ok = 1;
+ if (preg_match('/'.preg_quote('-- Dump completed').'/i', $read)) {
+ $ok = 1;
+ } elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i', $read)) {
+ $ok = 1;
+ }
}
}
}
}
- if ($execmethod == 2) // With this method, there is no way to get the return code, only output
- {
+ if ($execmethod == 2) { // With this method, there is no way to get the return code, only output
$handlein = popen($fullcommandclear, 'r');
$i = 0;
- while (!feof($handlein))
- {
+ while (!feof($handlein)) {
$i++; // output line number
$read = fgets($handlein);
// Exclude warning line we don't want
- if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue;
+ if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) {
+ continue;
+ }
fwrite($handle, $read);
- if (preg_match('/'.preg_quote('-- Dump completed').'/i', $read)) $ok = 1;
- elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i', $read)) $ok = 1;
+ if (preg_match('/'.preg_quote('-- Dump completed').'/i', $read)) {
+ $ok = 1;
+ } elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i', $read)) {
+ $ok = 1;
+ }
}
pclose($handlein);
}
- if ($compression == 'none') fclose($handle);
- if ($compression == 'gz') gzclose($handle);
- if ($compression == 'bz') bzclose($handle);
+ if ($compression == 'none') {
+ fclose($handle);
+ }
+ if ($compression == 'gz') {
+ gzclose($handle);
+ }
+ if ($compression == 'bz') {
+ bzclose($handle);
+ }
- if (!empty($conf->global->MAIN_UMASK))
+ if (!empty($conf->global->MAIN_UMASK)) {
@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
+ }
} else {
$langs->load("errors");
dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
@@ -371,19 +417,30 @@ class Utils
}
// Get errorstring
- if ($compression == 'none') $handle = fopen($outputfile, 'r');
- if ($compression == 'gz') $handle = gzopen($outputfile, 'r');
- if ($compression == 'bz') $handle = bzopen($outputfile, 'r');
- if ($handle)
- {
+ if ($compression == 'none') {
+ $handle = fopen($outputfile, 'r');
+ }
+ if ($compression == 'gz') {
+ $handle = gzopen($outputfile, 'r');
+ }
+ if ($compression == 'bz') {
+ $handle = bzopen($outputfile, 'r');
+ }
+ if ($handle) {
// Get 2048 first chars of error message.
$errormsg = fgets($handle, 2048);
//$ok=0;$errormsg=''; To force error
// Close file
- if ($compression == 'none') fclose($handle);
- if ($compression == 'gz') gzclose($handle);
- if ($compression == 'bz') bzclose($handle);
+ if ($compression == 'none') {
+ fclose($handle);
+ }
+ if ($compression == 'gz') {
+ gzclose($handle);
+ }
+ if ($compression == 'bz') {
+ bzclose($handle);
+ }
if ($ok && preg_match('/^-- (MySql|MariaDB)/i', $errormsg)) { // No error
$errormsg = '';
} else {
@@ -392,8 +449,7 @@ class Utils
@dol_delete_file($outputerror, 1, 0, 0, null, false, 0);
@rename($outputfile, $outputerror);
// Si safe_mode on et command hors du parametre exec, on a un fichier out vide donc errormsg vide
- if (!$errormsg)
- {
+ if (!$errormsg) {
$langs->load("errors");
$errormsg = $langs->trans("ErrorFailedToRunExternalCommand");
}
@@ -408,19 +464,21 @@ class Utils
}
// MYSQL NO BIN
- if ($type == 'mysqlnobin')
- {
+ if ($type == 'mysqlnobin') {
$outputfile = $outputdir.'/'.$file;
$outputfiletemp = $outputfile.'-TMP.sql';
// for compression format, we add extension
$compression = $compression ? $compression : 'none';
- if ($compression == 'gz') $outputfile .= '.gz';
- if ($compression == 'bz') $outputfile .= '.bz2';
+ if ($compression == 'gz') {
+ $outputfile .= '.gz';
+ }
+ if ($compression == 'bz') {
+ $outputfile .= '.bz2';
+ }
$outputerror = $outputfile.'.err';
dol_mkdir($conf->admin->dir_output.'/backup');
- if ($compression == 'gz' or $compression == 'bz')
- {
+ if ($compression == 'gz' or $compression == 'bz') {
$this->backupTables($outputfiletemp);
dol_compress_file($outputfiletemp, $outputfile, $compression);
unlink($outputfiletemp);
@@ -433,44 +491,63 @@ class Utils
}
// POSTGRESQL
- if ($type == 'postgresql' || $type == 'pgsql')
- {
+ if ($type == 'postgresql' || $type == 'pgsql') {
$cmddump = $conf->global->SYSTEMTOOLS_POSTGRESQLDUMP;
$outputfile = $outputdir.'/'.$file;
// for compression format, we add extension
$compression = $compression ? $compression : 'none';
- if ($compression == 'gz') $outputfile .= '.gz';
- if ($compression == 'bz') $outputfile .= '.bz2';
+ if ($compression == 'gz') {
+ $outputfile .= '.gz';
+ }
+ if ($compression == 'bz') {
+ $outputfile .= '.bz2';
+ }
$outputerror = $outputfile.'.err';
dol_mkdir($conf->admin->dir_output.'/backup');
// Parameteres execution
$command = $cmddump;
$command = preg_replace('/(\$|%)/', '', $command); // We removed chars that can be used to inject vars that contains space inside path of command without seeing there is a space to bypass the escapeshellarg.
- if (preg_match("/\s/", $command)) $command = escapeshellarg($command); // If there is spaces, we add quotes on command to be sure $command is only a program and not a program+parameters
+ if (preg_match("/\s/", $command)) {
+ $command = escapeshellarg($command); // If there is spaces, we add quotes on command to be sure $command is only a program and not a program+parameters
+ }
//$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
//$param="-F c";
$param = "-F p";
$param .= " --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
$param .= " -U ".$dolibarr_main_db_user;
- if (!empty($dolibarr_main_db_port)) $param .= " -p ".$dolibarr_main_db_port;
- if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') $param .= " --disable-dollar-quoting";
- if (GETPOST("drop_database")) $param .= " -c -C";
- if (GETPOST("sql_structure"))
- {
- if (GETPOST("drop")) $param .= " --add-drop-table";
- if (!GETPOST("sql_data")) $param .= " -s";
+ if (!empty($dolibarr_main_db_port)) {
+ $param .= " -p ".$dolibarr_main_db_port;
}
- if (GETPOST("sql_data"))
- {
- if (!GETPOST("sql_structure")) $param .= " -a";
- if (GETPOST("showcolumns")) $param .= " -c";
+ if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') {
+ $param .= " --disable-dollar-quoting";
+ }
+ if (GETPOST("drop_database")) {
+ $param .= " -c -C";
+ }
+ if (GETPOST("sql_structure")) {
+ if (GETPOST("drop")) {
+ $param .= " --add-drop-table";
+ }
+ if (!GETPOST("sql_data")) {
+ $param .= " -s";
+ }
+ }
+ if (GETPOST("sql_data")) {
+ if (!GETPOST("sql_structure")) {
+ $param .= " -a";
+ }
+ if (GETPOST("showcolumns")) {
+ $param .= " -c";
+ }
}
$param .= ' -f "'.$outputfile.'"';
//if ($compression == 'none')
- if ($compression == 'gz') $param .= ' -Z 9';
+ if ($compression == 'gz') {
+ $param .= ' -Z 9';
+ }
//if ($compression == 'bz')
$paramcrypted = $param;
$paramclear = $param;
@@ -487,14 +564,14 @@ class Utils
}
// Clean old files
- if (!$errormsg && $keeplastnfiles > 0)
- {
+ if (!$errormsg && $keeplastnfiles > 0) {
$tmpfiles = dol_dir_list($conf->admin->dir_output.'/backup', 'files', 0, '', '(\.err|\.old|\.sav)$', 'date', SORT_DESC);
$i = 0;
- foreach ($tmpfiles as $key => $val)
- {
+ foreach ($tmpfiles as $key => $val) {
$i++;
- if ($i <= $keeplastnfiles) continue;
+ if ($i <= $keeplastnfiles) {
+ continue;
+ }
dol_delete_file($val['fullname'], 0, 0, 0, null, false, 0);
}
}
@@ -523,34 +600,33 @@ class Utils
$command = escapeshellcmd($command);
$command .= " 2>&1";
- if (!empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod = $conf->global->MAIN_EXEC_USE_POPEN;
- if (empty($execmethod)) $execmethod = 1;
+ if (!empty($conf->global->MAIN_EXEC_USE_POPEN)) {
+ $execmethod = $conf->global->MAIN_EXEC_USE_POPEN;
+ }
+ if (empty($execmethod)) {
+ $execmethod = 1;
+ }
//$execmethod=1;
dol_syslog("Utils::executeCLI execmethod=".$execmethod." system:".$command, LOG_DEBUG);
$output_arr = array();
- if ($execmethod == 1)
- {
+ if ($execmethod == 1) {
$retval = null;
exec($command, $output_arr, $retval);
$result = $retval;
- if ($retval != 0)
- {
+ if ($retval != 0) {
$langs->load("errors");
dol_syslog("Utils::executeCLI retval after exec=".$retval, LOG_ERR);
$error = 'Error '.$retval;
}
}
- if ($execmethod == 2) // With this method, there is no way to get the return code, only output
- {
+ if ($execmethod == 2) { // With this method, there is no way to get the return code, only output
$handle = fopen($outputfile, 'w+b');
- if ($handle)
- {
+ if ($handle) {
dol_syslog("Utils::executeCLI run command ".$command);
$handlein = popen($command, 'r');
- while (!feof($handlein))
- {
+ while (!feof($handlein)) {
$read = fgets($handlein);
fwrite($handle, $read);
$output_arr[] = $read;
@@ -558,14 +634,14 @@ class Utils
pclose($handlein);
fclose($handle);
}
- if (!empty($conf->global->MAIN_UMASK)) @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
+ if (!empty($conf->global->MAIN_UMASK)) {
+ @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
+ }
}
// Update with result
- if (is_array($output_arr) && count($output_arr) > 0)
- {
- foreach ($output_arr as $val)
- {
+ if (is_array($output_arr) && count($output_arr) > 0) {
+ foreach ($output_arr as $val) {
$output .= $val.($execmethod == 2 ? '' : "\n");
}
}
@@ -600,12 +676,10 @@ class Utils
dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php');
$class = 'mod'.$module;
- if (class_exists($class))
- {
+ if (class_exists($class)) {
try {
$moduleobj = new $class($this->db);
- } catch (Exception $e)
- {
+ } catch (Exception $e) {
$error++;
dol_print_error($e->getMessage());
}
@@ -617,8 +691,7 @@ class Utils
}
$arrayversion = explode('.', $moduleobj->version, 3);
- if (count($arrayversion))
- {
+ if (count($arrayversion)) {
$FILENAMEASCII = strtolower($module).'.asciidoc';
$FILENAMEDOC = strtolower($module).'.html';
$FILENAMEDOCPDF = strtolower($module).'.pdf';
@@ -627,18 +700,19 @@ class Utils
$dirofmoduledoc = dol_buildpath(strtolower($module), 0).'/doc';
$dirofmoduletmp = dol_buildpath(strtolower($module), 0).'/doc/temp';
$outputfiledoc = $dirofmoduledoc.'/'.$FILENAMEDOC;
- if ($dirofmoduledoc)
- {
- if (!dol_is_dir($dirofmoduledoc)) dol_mkdir($dirofmoduledoc);
- if (!dol_is_dir($dirofmoduletmp)) dol_mkdir($dirofmoduletmp);
- if (!is_writable($dirofmoduletmp))
- {
+ if ($dirofmoduledoc) {
+ if (!dol_is_dir($dirofmoduledoc)) {
+ dol_mkdir($dirofmoduledoc);
+ }
+ if (!dol_is_dir($dirofmoduletmp)) {
+ dol_mkdir($dirofmoduletmp);
+ }
+ if (!is_writable($dirofmoduletmp)) {
$this->error = 'Dir '.$dirofmoduletmp.' does not exists or is not writable';
return -1;
}
- if (empty($conf->global->MODULEBUILDER_ASCIIDOCTOR) && empty($conf->global->MODULEBUILDER_ASCIIDOCTORPDF))
- {
+ if (empty($conf->global->MODULEBUILDER_ASCIIDOCTOR) && empty($conf->global->MODULEBUILDER_ASCIIDOCTORPDF)) {
$this->error = 'Setup of module ModuleBuilder not complete';
return -1;
}
@@ -659,24 +733,29 @@ class Utils
$destfile = $dirofmoduletmp.'/'.$FILENAMEASCII;
$fhandle = fopen($destfile, 'w+');
- if ($fhandle)
- {
+ if ($fhandle) {
$specs = dol_dir_list(dol_buildpath(strtolower($module).'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/'));
$i = 0;
- foreach ($specs as $spec)
- {
- if (preg_match('/notindoc/', $spec['relativename'])) continue; // Discard file
- if (preg_match('/example/', $spec['relativename'])) continue; // Discard file
- if (preg_match('/disabled/', $spec['relativename'])) continue; // Discard file
+ foreach ($specs as $spec) {
+ if (preg_match('/notindoc/', $spec['relativename'])) {
+ continue; // Discard file
+ }
+ if (preg_match('/example/', $spec['relativename'])) {
+ continue; // Discard file
+ }
+ if (preg_match('/disabled/', $spec['relativename'])) {
+ continue; // Discard file
+ }
$pathtofile = strtolower($module).'/doc/'.$spec['relativename'];
$format = 'asciidoc';
- if (preg_match('/\.md$/i', $spec['name'])) $format = 'markdown';
+ if (preg_match('/\.md$/i', $spec['name'])) {
+ $format = 'markdown';
+ }
$filecursor = @file_get_contents($spec['fullname']);
- if ($filecursor)
- {
+ if ($filecursor) {
fwrite($fhandle, ($i ? "\n<<<\n\n" : "").$filecursor."\n");
} else {
$this->error = 'Failed to concat content of file '.$spec['fullname'];
@@ -729,8 +808,7 @@ class Utils
$outfile = $dirofmoduletmp.'/out.tmp';
$resarray = $utils->executeCLI($command, $outfile);
- if ($resarray['result'] != '0')
- {
+ if ($resarray['result'] != '0') {
$this->error = $resarray['error'].' '.$resarray['output'];
}
$result = ($resarray['result'] == 0) ? 1 : 0;
@@ -739,8 +817,7 @@ class Utils
$command = $conf->global->MODULEBUILDER_ASCIIDOCTORPDF.' '.$destfile.' -n -o '.$dirofmoduledoc.'/'.$FILENAMEDOCPDF;
$outfile = $dirofmoduletmp.'/outpdf.tmp';
$resarray = $utils->executeCLI($command, $outfile);
- if ($resarray['result'] != '0')
- {
+ if ($resarray['result'] != '0') {
$this->error = $resarray['error'].' '.$resarray['output'];
}
$result = ($resarray['result'] == 0) ? 1 : 0;
@@ -750,8 +827,7 @@ class Utils
$result = 0;
}
- if ($result > 0)
- {
+ if ($result > 0) {
return 1;
} else {
$error++;
@@ -807,8 +883,7 @@ class Utils
$logname = $file['name'];
$logpath = $file['path'];
- if (dol_is_file($logpath.'/'.$logname) && dol_filesize($logpath.'/'.$logname) > 0) // If log file exists and is not empty
- {
+ if (dol_is_file($logpath.'/'.$logname) && dol_filesize($logpath.'/'.$logname) > 0) { // If log file exists and is not empty
// Handle already compressed files to rename them and add +1
$filter = '^'.preg_quote($logname, '/').'\.([0-9]+)\.gz$';
@@ -907,12 +982,10 @@ class Utils
}
//get all of the tables
- if ($tables == '*')
- {
+ if ($tables == '*') {
$tables = array();
$result = $db->query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
- while ($row = $db->fetch_row($result))
- {
+ while ($row = $db->fetch_row($result)) {
$tables[] = $row[0];
}
} else {
@@ -921,8 +994,7 @@ class Utils
//cycle through
$handle = fopen($outputfile, 'w+');
- if (fwrite($handle, '') === false)
- {
+ if (fwrite($handle, '') === false) {
$langs->load("errors");
dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
$errormsg = $langs->trans("ErrorFailedToWriteInDir");
@@ -950,30 +1022,38 @@ class Utils
";
- if (GETPOST("nobin_disable_fk")) $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
+ if (GETPOST("nobin_disable_fk")) {
+ $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
+ }
//$sqlhead .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
- if (GETPOST("nobin_use_transaction")) $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
+ if (GETPOST("nobin_use_transaction")) {
+ $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
+ }
fwrite($handle, $sqlhead);
$ignore = '';
- if (GETPOST("nobin_sql_ignore")) $ignore = 'IGNORE ';
+ if (GETPOST("nobin_sql_ignore")) {
+ $ignore = 'IGNORE ';
+ }
$delayed = '';
- if (GETPOST("nobin_delayed")) $delayed = 'DELAYED ';
+ if (GETPOST("nobin_delayed")) {
+ $delayed = 'DELAYED ';
+ }
// Process each table and print their definition + their datas
- foreach ($tables as $table)
- {
+ foreach ($tables as $table) {
// Saving the table structure
fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
- if (GETPOST("nobin_drop")) fwrite($handle, "DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
+ if (GETPOST("nobin_drop")) {
+ fwrite($handle, "DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
+ }
fwrite($handle, "/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
fwrite($handle, "/*!40101 SET character_set_client = utf8 */;\n");
$resqldrop = $db->query('SHOW CREATE TABLE '.$table);
$row2 = $db->fetch_row($resqldrop);
- if (empty($row2[1]))
- {
+ if (empty($row2[1])) {
fwrite($handle, "\n-- WARNING: Show create table ".$table." return empy string when it should not.\n");
} else {
fwrite($handle, $row2[1].";\n");
@@ -981,14 +1061,18 @@ class Utils
// Dumping the data (locking the table and disabling the keys check while doing the process)
fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n");
- if (!GETPOST("nobin_nolocks")) fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
- if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
- else fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
+ if (!GETPOST("nobin_nolocks")) {
+ fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
+ }
+ if (GETPOST("nobin_disable_fk")) {
+ fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
+ } else {
+ fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
+ }
$sql = 'SELECT * FROM '.$table; // Here SELECT * is allowed because we don't have definition of columns to take
$result = $db->query($sql);
- while ($row = $db->fetch_row($result))
- {
+ while ($row = $db->fetch_row($result)) {
// For each row of data we print a line of INSERT
fwrite($handle, 'INSERT '.$delayed.$ignore.'INTO `'.$table.'` VALUES (');
$columns = count($row);
@@ -1011,8 +1095,12 @@ class Utils
}
fwrite($handle, implode(',', $row).");\n");
}
- if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
- if (!GETPOST("nobin_nolocks")) fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
+ if (GETPOST("nobin_disable_fk")) {
+ fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
+ }
+ if (!GETPOST("nobin_nolocks")) {
+ fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
+ }
fwrite($handle, "\n\n\n");
}
}
@@ -1038,8 +1126,12 @@ class Utils
// Write the footer (restore the previous database settings)
$sqlfooter = "\n\n";
- if (GETPOST("nobin_use_transaction")) $sqlfooter .= "COMMIT;\n";
- if (GETPOST("nobin_disable_fk")) $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
+ if (GETPOST("nobin_use_transaction")) {
+ $sqlfooter .= "COMMIT;\n";
+ }
+ if (GETPOST("nobin_disable_fk")) {
+ $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
+ }
$sqlfooter .= "\n\n-- Dump completed on ".date('Y-m-d G-i-s');
fwrite($handle, $sqlfooter);
diff --git a/htdocs/core/class/vcard.class.php b/htdocs/core/class/vcard.class.php
index 9c03475453f..229966468c1 100644
--- a/htdocs/core/class/vcard.class.php
+++ b/htdocs/core/class/vcard.class.php
@@ -53,8 +53,7 @@ function dol_quoted_printable_encode($input, $line_max = 76)
$output = "";
$num = count($lines);
- for ($j = 0; $j < $num; $j++)
- {
+ for ($j = 0; $j < $num; $j++) {
$line = $lines[$j];
$linlen = strlen($line);
$newline = "";
@@ -74,7 +73,9 @@ function dol_quoted_printable_encode($input, $line_max = 76)
$newline .= $c;
} // end of for
$output .= $newline;
- if ($j < count($lines) - 1) $output .= $linebreak;
+ if ($j < count($lines) - 1) {
+ $output .= $linebreak;
+ }
}
return trim($output);
}
@@ -112,7 +113,9 @@ class vCard
{
// type may be PREF | WORK | HOME | VOICE | FAX | MSG | CELL | PAGER | BBS | CAR | MODEM | ISDN | VIDEO or any senseful combination, e.g. "PREF;WORK;VOICE"
$key = "TEL";
- if ($type != "") $key .= ";".$type;
+ if ($type != "") {
+ $key .= ";".$type;
+ }
$key .= ";CHARSET=".$this->encoding;
$this->properties[$key] = encode($number);
}
@@ -156,7 +159,9 @@ class vCard
{
$this->properties["N;CHARSET=".$this->encoding] = encode($family).";".encode($first).";".encode($additional).";".encode($prefix).";".encode($suffix);
$this->filename = "$first%20$family.vcf";
- if (empty($this->properties["FN"])) $this->setFormattedName(trim("$prefix $first $additional $family $suffix"));
+ if (empty($this->properties["FN"])) {
+ $this->setFormattedName(trim("$prefix $first $additional $family $suffix"));
+ }
}
/**
@@ -188,12 +193,13 @@ class vCard
{
// $type may be DOM | INTL | POSTAL | PARCEL | HOME | WORK or any combination of these: e.g. "WORK;PARCEL;POSTAL"
$key = "ADR";
- if ($type != "") $key .= ";$type";
+ if ($type != "") {
+ $key .= ";$type";
+ }
$key .= ";CHARSET=".$this->encoding;
$this->properties[$key] = ";".encode($extended).";".encode($street).";".encode($city).";".encode($region).";".encode($zip).";".encode($country);
- if ($this->properties["LABEL;$type;CHARSET=".$this->encoding] == "")
- {
+ if ($this->properties["LABEL;$type;CHARSET=".$this->encoding] == "") {
//$this->setLabel($postoffice, $extended, $street, $city, $region, $zip, $country, $type);
}
}
@@ -214,13 +220,27 @@ class vCard
public function setLabel($postoffice = "", $extended = "", $street = "", $city = "", $region = "", $zip = "", $country = "", $type = "HOME;POSTAL")
{
$label = "";
- if ($postoffice != "") $label .= "$postoffice\r\n";
- if ($extended != "") $label .= "$extended\r\n";
- if ($street != "") $label .= "$street\r\n";
- if ($zip != "") $label .= "$zip ";
- if ($city != "") $label .= "$city\r\n";
- if ($region != "") $label .= "$region\r\n";
- if ($country != "") $country .= "$country\r\n";
+ if ($postoffice != "") {
+ $label .= "$postoffice\r\n";
+ }
+ if ($extended != "") {
+ $label .= "$extended\r\n";
+ }
+ if ($street != "") {
+ $label .= "$street\r\n";
+ }
+ if ($zip != "") {
+ $label .= "$zip ";
+ }
+ if ($city != "") {
+ $label .= "$city\r\n";
+ }
+ if ($region != "") {
+ $label .= "$region\r\n";
+ }
+ if ($country != "") {
+ $country .= "$country\r\n";
+ }
$this->properties["LABEL;$type;CHARSET=".$this->encoding] = encode($label);
}
@@ -235,7 +255,9 @@ class vCard
public function setEmail($address, $type = "TYPE=INTERNET;PREF")
{
$key = "EMAIL";
- if ($type != "") $key .= ";".$type;
+ if ($type != "") {
+ $key .= ";".$type;
+ }
$this->properties[$key] = $address;
}
@@ -309,7 +331,9 @@ class vCard
{
// $type may be WORK | HOME
$key = "URL";
- if ($type != "") $key .= ";$type";
+ if ($type != "") {
+ $key .= ";$type";
+ }
$this->properties[$key] = $url;
}
@@ -323,8 +347,7 @@ class vCard
$text = "BEGIN:VCARD\r\n";
$text .= "VERSION:3.0\r\n";
//$text.= "VERSION:2.1\r\n";
- foreach ($this->properties as $key => $value)
- {
+ foreach ($this->properties as $key => $value) {
$text .= "$key:$value\r\n";
}
$text .= "REV:".date("Y-m-d")."T".date("H:i:s")."Z\r\n";
@@ -345,29 +368,29 @@ class vCard
/* Example from Microsoft Outlook 2019
- BEGIN:VCARD
- VERSION:2.1
+ BEGIN:VCARD
+ VERSION:2.1
- N;LANGUAGE=de:surename;forename;secondname;Sir;jun.
- FN:Sir surename secondname forename jun.
- ORG:Companyname
- TITLE:position
- TEL;WORK;VOICE:work-phone-number
- TEL;HOME;VOICE:private-phone-number
- TEL;CELL;VOICE:mobile-phone-number
- TEL;WORK;FAX:fax-phone-number
- ADR;WORK;PREF:;;street and number;town;region;012345;Deutschland
- LABEL;WORK;PREF;ENCODING=QUOTED-PRINTABLE:street and number=0D=0A=
- =0D=0A=
- 012345 town region
- X-MS-OL-DEFAULT-POSTAL-ADDRESS:2
- URL;WORK:www.mywebpage.de
- EMAIL;PREF;INTERNET:test1@test1.de
- EMAIL;INTERNET:test2@test2.de
- EMAIL;INTERNET:test3@test3.de
- X-MS-IMADDRESS:test@jabber.org
- REV:20200424T104242Z
+ N;LANGUAGE=de:surename;forename;secondname;Sir;jun.
+ FN:Sir surename secondname forename jun.
+ ORG:Companyname
+ TITLE:position
+ TEL;WORK;VOICE:work-phone-number
+ TEL;HOME;VOICE:private-phone-number
+ TEL;CELL;VOICE:mobile-phone-number
+ TEL;WORK;FAX:fax-phone-number
+ ADR;WORK;PREF:;;street and number;town;region;012345;Deutschland
+ LABEL;WORK;PREF;ENCODING=QUOTED-PRINTABLE:street and number=0D=0A=
+ =0D=0A=
+ 012345 town region
+ X-MS-OL-DEFAULT-POSTAL-ADDRESS:2
+ URL;WORK:www.mywebpage.de
+ EMAIL;PREF;INTERNET:test1@test1.de
+ EMAIL;INTERNET:test2@test2.de
+ EMAIL;INTERNET:test3@test3.de
+ X-MS-IMADDRESS:test@jabber.org
+ REV:20200424T104242Z
- END:VCARD
- */
+ END:VCARD
+ */
}
diff --git a/htdocs/core/commonfieldsinexport.inc.php b/htdocs/core/commonfieldsinexport.inc.php
index 5db67f36c78..a02a21afdd6 100644
--- a/htdocs/core/commonfieldsinexport.inc.php
+++ b/htdocs/core/commonfieldsinexport.inc.php
@@ -1,21 +1,20 @@
db);
// Add common fields
- foreach ($tmpobject->fields as $keyfield => $valuefield)
- {
+ foreach ($tmpobject->fields as $keyfield => $valuefield) {
$fieldname = $keyforalias.'.'.$keyfield;
$fieldlabel = ucfirst($valuefield['label']);
$typeFilter = "Text";
diff --git a/htdocs/core/customreports.php b/htdocs/core/customreports.php
index 901a0aa0f59..2d3210cad66 100644
--- a/htdocs/core/customreports.php
+++ b/htdocs/core/customreports.php
@@ -25,8 +25,7 @@
* \brief Page to make custom reports
*/
-if (!defined('USE_CUSTOME_REPORT_AS_INCLUDE'))
-{
+if (!defined('USE_CUSTOME_REPORT_AS_INCLUDE')) {
require '../main.inc.php';
// Get parameters
@@ -37,17 +36,25 @@ if (!defined('USE_CUSTOME_REPORT_AS_INCLUDE'))
$objecttype = GETPOST('objecttype', 'aZ09');
$tabfamily = GETPOST('tabfamily', 'aZ09');
- if (empty($objecttype)) $objecttype = 'thirdparty';
+ if (empty($objecttype)) {
+ $objecttype = 'thirdparty';
+ }
$search_filters = GETPOST('search_filters', 'array');
$search_measures = GETPOST('search_measures', 'array');
//$search_xaxis = GETPOST('search_xaxis', 'array');
- if (GETPOST('search_xaxis', 'alpha') && GETPOST('search_xaxis', 'alpha') != '-1') $search_xaxis = array(GETPOST('search_xaxis', 'alpha'));
- else $search_xaxis = array();
+ if (GETPOST('search_xaxis', 'alpha') && GETPOST('search_xaxis', 'alpha') != '-1') {
+ $search_xaxis = array(GETPOST('search_xaxis', 'alpha'));
+ } else {
+ $search_xaxis = array();
+ }
//$search_groupby = GETPOST('search_groupby', 'array');
- if (GETPOST('search_groupby', 'alpha') && GETPOST('search_groupby', 'alpha') != '-1') $search_groupby = array(GETPOST('search_groupby', 'alpha'));
- else $search_groupby = array();
+ if (GETPOST('search_groupby', 'alpha') && GETPOST('search_groupby', 'alpha') != '-1') {
+ $search_groupby = array(GETPOST('search_groupby', 'alpha'));
+ } else {
+ $search_groupby = array();
+ }
$search_yaxis = GETPOST('search_yaxis', 'array');
$search_graph = GETPOST('search_graph', 'none');
@@ -57,7 +64,9 @@ if (!defined('USE_CUSTOME_REPORT_AS_INCLUDE'))
$sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
- if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
+ if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
+ $page = 0;
+ } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
@@ -102,8 +111,9 @@ $arrayoftype = array(
// Complete $arrayoftype by external modules
$parameters = array('objecttype'=>$objecttype, 'tabfamily'=>$tabfamily);
$reshook = $hookmanager->executeHooks('loadDataForCustomReports', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
-elseif (is_array($hookmanager->resArray)) {
+if ($reshook < 0) {
+ setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+} elseif (is_array($hookmanager->resArray)) {
if (!empty($hookmanager->resArray['title'])) { // Add entries for tabs
$title = $hookmanager->resArray['title'];
}
@@ -136,8 +146,7 @@ if ($objecttype) {
// Security check
$socid = 0;
-if ($user->socid > 0) // Protection if external user
-{
+if ($user->socid > 0) { // Protection if external user
//$socid = $user->socid;
accessforbidden();
}
@@ -262,7 +271,9 @@ if (is_array($search_groupby) && count($search_groupby)) {
$regs = array();
if (!empty($object->fields[$gvalwithoutprefix]['arrayofkeyval'])) {
$valuetranslated = $object->fields[$gvalwithoutprefix]['arrayofkeyval'][$obj->val];
- if (is_null($valuetranslated)) $valuetranslated = $langs->transnoentitiesnoconv("UndefinedKey");
+ if (is_null($valuetranslated)) {
+ $valuetranslated = $langs->transnoentitiesnoconv("UndefinedKey");
+ }
$valuetranslated = $langs->trans($valuetranslated);
} elseif (preg_match('/integer:([^:]+):([^:]+)$/', $object->fields[$gvalwithoutprefix]['type'], $regs)) {
$classname = $regs[1];
@@ -337,8 +348,9 @@ foreach ($arrayoftype as $key => $val) {
}
}
print $form->selectarray('objecttype', $newarrayoftype, $objecttype, 0, 0, 0, '', 1, 0, 0, '', 'minwidth200', 1);
-if (empty($conf->use_javascript_ajax)) print ' ';
-else {
+if (empty($conf->use_javascript_ajax)) {
+ print ' ';
+} else {
print ''."\n";
} else {
print ''.$langs->trans("Calendar").' ';
@@ -80,8 +95,7 @@ $tradTemp = array(
);
print '';
- if ($addlink) $out .= ' '.$langs->trans("Link").' ';
+ if ($addlink) {
+ $out .= ' '.$langs->trans("Link").' ';
+ }
return $out;
}
@@ -8349,15 +8767,21 @@ function dolIsAllowedForPreview($file)
global $conf;
// Check .noexe extension in filename
- if (preg_match('/\.noexe$/i', $file)) return 0;
+ if (preg_match('/\.noexe$/i', $file)) {
+ return 0;
+ }
// Check mime types
$mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
- if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) $mime_preview[] = 'svg+xml';
+ if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
+ $mime_preview[] = 'svg+xml';
+ }
//$mime_preview[]='vnd.oasis.opendocument.presentation';
//$mime_preview[]='archive';
$num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
- if ($num_mime !== false) return 1;
+ if ($num_mime !== false) {
+ return 1;
+ }
// By default, not allowed for preview
return 0;
@@ -8383,102 +8807,224 @@ function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
$tmpfile = preg_replace('/\.noexe$/', '', $file);
// Plain text files
- if (preg_match('/\.txt$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
- if (preg_match('/\.rtx$/i', $tmpfile)) { $mime = 'text/richtext'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
- if (preg_match('/\.csv$/i', $tmpfile)) { $mime = 'text/csv'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
- if (preg_match('/\.tsv$/i', $tmpfile)) { $mime = 'text/tab-separated-values'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
- if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
- if (preg_match('/\.ini$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'ini'; $famime = 'file-text-o'; }
- if (preg_match('/\.md$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'md'; $famime = 'file-text-o'; }
- if (preg_match('/\.css$/i', $tmpfile)) { $mime = 'text/css'; $imgmime = 'css.png'; $srclang = 'css'; $famime = 'file-text-o'; }
- if (preg_match('/\.lang$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'lang'; $famime = 'file-text-o'; }
+ if (preg_match('/\.txt$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.rtx$/i', $tmpfile)) {
+ $mime = 'text/richtext'; $imgmime = 'text.png'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.csv$/i', $tmpfile)) {
+ $mime = 'text/csv'; $imgmime = 'text.png'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.tsv$/i', $tmpfile)) {
+ $mime = 'text/tab-separated-values'; $imgmime = 'text.png'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.ini$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'ini'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.md$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'md'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.css$/i', $tmpfile)) {
+ $mime = 'text/css'; $imgmime = 'css.png'; $srclang = 'css'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.lang$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'lang'; $famime = 'file-text-o';
+ }
// Certificate files
- if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
+ if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o';
+ }
// XML based (HTML/XML/XAML)
- if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { $mime = 'text/html'; $imgmime = 'html.png'; $srclang = 'html'; $famime = 'file-text-o'; }
- if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xml'; $famime = 'file-text-o'; }
- if (preg_match('/\.xaml$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xaml'; $famime = 'file-text-o'; }
+ if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
+ $mime = 'text/html'; $imgmime = 'html.png'; $srclang = 'html'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
+ $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xml'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.xaml$/i', $tmpfile)) {
+ $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xaml'; $famime = 'file-text-o';
+ }
// Languages
- if (preg_match('/\.bas$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'bas'; $famime = 'file-code-o'; }
- if (preg_match('/\.(c)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'c'; $famime = 'file-code-o'; }
- if (preg_match('/\.(cpp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cpp'; $famime = 'file-code-o'; }
- if (preg_match('/\.cs$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cs'; $famime = 'file-code-o'; }
- if (preg_match('/\.(h)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'h'; $famime = 'file-code-o'; }
- if (preg_match('/\.(java|jsp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'java'; $famime = 'file-code-o'; }
- if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; }
- if (preg_match('/\.phtml$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; }
- if (preg_match('/\.(pl|pm)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'pl.png'; $srclang = 'perl'; $famime = 'file-code-o'; }
- if (preg_match('/\.sql$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'sql'; $famime = 'file-code-o'; }
- if (preg_match('/\.js$/i', $tmpfile)) { $mime = 'text/x-javascript'; $imgmime = 'jscript.png'; $srclang = 'js'; $famime = 'file-code-o'; }
+ if (preg_match('/\.bas$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'bas'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.(c)$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'c'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.(cpp)$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cpp'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.cs$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cs'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.(h)$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'h'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'java'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.phtml$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'pl.png'; $srclang = 'perl'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.sql$/i', $tmpfile)) {
+ $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'sql'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.js$/i', $tmpfile)) {
+ $mime = 'text/x-javascript'; $imgmime = 'jscript.png'; $srclang = 'js'; $famime = 'file-code-o';
+ }
// Open office
- if (preg_match('/\.odp$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.presentation'; $imgmime = 'ooffice.png'; $famime = 'file-powerpoint-o'; }
- if (preg_match('/\.ods$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.spreadsheet'; $imgmime = 'ooffice.png'; $famime = 'file-excel-o'; }
- if (preg_match('/\.odt$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.text'; $imgmime = 'ooffice.png'; $famime = 'file-word-o'; }
+ if (preg_match('/\.odp$/i', $tmpfile)) {
+ $mime = 'application/vnd.oasis.opendocument.presentation'; $imgmime = 'ooffice.png'; $famime = 'file-powerpoint-o';
+ }
+ if (preg_match('/\.ods$/i', $tmpfile)) {
+ $mime = 'application/vnd.oasis.opendocument.spreadsheet'; $imgmime = 'ooffice.png'; $famime = 'file-excel-o';
+ }
+ if (preg_match('/\.odt$/i', $tmpfile)) {
+ $mime = 'application/vnd.oasis.opendocument.text'; $imgmime = 'ooffice.png'; $famime = 'file-word-o';
+ }
// MS Office
- if (preg_match('/\.mdb$/i', $tmpfile)) { $mime = 'application/msaccess'; $imgmime = 'mdb.png'; $famime = 'file-o'; }
- if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; }
- if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; }
- if (preg_match('/\.xlt(x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
- if (preg_match('/\.xla(m)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
- if (preg_match('/\.xls$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
- if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) { $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
- if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-powerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; }
- if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) { $mime = 'application/x-mspowerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; }
+ if (preg_match('/\.mdb$/i', $tmpfile)) {
+ $mime = 'application/msaccess'; $imgmime = 'mdb.png'; $famime = 'file-o';
+ }
+ if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) {
+ $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o';
+ }
+ if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) {
+ $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o';
+ }
+ if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
+ $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o';
+ }
+ if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
+ $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o';
+ }
+ if (preg_match('/\.xls$/i', $tmpfile)) {
+ $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o';
+ }
+ if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) {
+ $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime = 'xls.png'; $famime = 'file-excel-o';
+ }
+ if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) {
+ $mime = 'application/vnd.ms-powerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o';
+ }
+ if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) {
+ $mime = 'application/x-mspowerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o';
+ }
// Other
- if (preg_match('/\.pdf$/i', $tmpfile)) { $mime = 'application/pdf'; $imgmime = 'pdf.png'; $famime = 'file-pdf-o'; }
+ if (preg_match('/\.pdf$/i', $tmpfile)) {
+ $mime = 'application/pdf'; $imgmime = 'pdf.png'; $famime = 'file-pdf-o';
+ }
// Scripts
- if (preg_match('/\.bat$/i', $tmpfile)) { $mime = 'text/x-bat'; $imgmime = 'script.png'; $srclang = 'dos'; $famime = 'file-code-o'; }
- if (preg_match('/\.sh$/i', $tmpfile)) { $mime = 'text/x-sh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
- if (preg_match('/\.ksh$/i', $tmpfile)) { $mime = 'text/x-ksh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
- if (preg_match('/\.bash$/i', $tmpfile)) { $mime = 'text/x-bash'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
+ if (preg_match('/\.bat$/i', $tmpfile)) {
+ $mime = 'text/x-bat'; $imgmime = 'script.png'; $srclang = 'dos'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.sh$/i', $tmpfile)) {
+ $mime = 'text/x-sh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.ksh$/i', $tmpfile)) {
+ $mime = 'text/x-ksh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o';
+ }
+ if (preg_match('/\.bash$/i', $tmpfile)) {
+ $mime = 'text/x-bash'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o';
+ }
// Images
- if (preg_match('/\.ico$/i', $tmpfile)) { $mime = 'image/x-icon'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
- if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) { $mime = 'image/jpeg'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
- if (preg_match('/\.png$/i', $tmpfile)) { $mime = 'image/png'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
- if (preg_match('/\.gif$/i', $tmpfile)) { $mime = 'image/gif'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
- if (preg_match('/\.bmp$/i', $tmpfile)) { $mime = 'image/bmp'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
- if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) { $mime = 'image/tiff'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
- if (preg_match('/\.svg$/i', $tmpfile)) { $mime = 'image/svg+xml'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
- if (preg_match('/\.webp$/i', $tmpfile)) { $mime = 'image/webp'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
+ if (preg_match('/\.ico$/i', $tmpfile)) {
+ $mime = 'image/x-icon'; $imgmime = 'image.png'; $famime = 'file-image-o';
+ }
+ if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
+ $mime = 'image/jpeg'; $imgmime = 'image.png'; $famime = 'file-image-o';
+ }
+ if (preg_match('/\.png$/i', $tmpfile)) {
+ $mime = 'image/png'; $imgmime = 'image.png'; $famime = 'file-image-o';
+ }
+ if (preg_match('/\.gif$/i', $tmpfile)) {
+ $mime = 'image/gif'; $imgmime = 'image.png'; $famime = 'file-image-o';
+ }
+ if (preg_match('/\.bmp$/i', $tmpfile)) {
+ $mime = 'image/bmp'; $imgmime = 'image.png'; $famime = 'file-image-o';
+ }
+ if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
+ $mime = 'image/tiff'; $imgmime = 'image.png'; $famime = 'file-image-o';
+ }
+ if (preg_match('/\.svg$/i', $tmpfile)) {
+ $mime = 'image/svg+xml'; $imgmime = 'image.png'; $famime = 'file-image-o';
+ }
+ if (preg_match('/\.webp$/i', $tmpfile)) {
+ $mime = 'image/webp'; $imgmime = 'image.png'; $famime = 'file-image-o';
+ }
// Calendar
- if (preg_match('/\.vcs$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; }
- if (preg_match('/\.ics$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; }
+ if (preg_match('/\.vcs$/i', $tmpfile)) {
+ $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o';
+ }
+ if (preg_match('/\.ics$/i', $tmpfile)) {
+ $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o';
+ }
// Other
- if (preg_match('/\.torrent$/i', $tmpfile)) { $mime = 'application/x-bittorrent'; $imgmime = 'other.png'; $famime = 'file-o'; }
+ if (preg_match('/\.torrent$/i', $tmpfile)) {
+ $mime = 'application/x-bittorrent'; $imgmime = 'other.png'; $famime = 'file-o';
+ }
// Audio
- if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { $mime = 'audio'; $imgmime = 'audio.png'; $famime = 'file-audio-o'; }
+ if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
+ $mime = 'audio'; $imgmime = 'audio.png'; $famime = 'file-audio-o';
+ }
// Video
- if (preg_match('/\.ogv$/i', $tmpfile)) { $mime = 'video/ogg'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
- if (preg_match('/\.webm$/i', $tmpfile)) { $mime = 'video/webm'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
- if (preg_match('/\.avi$/i', $tmpfile)) { $mime = 'video/x-msvideo'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
- if (preg_match('/\.divx$/i', $tmpfile)) { $mime = 'video/divx'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
- if (preg_match('/\.xvid$/i', $tmpfile)) { $mime = 'video/xvid'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
- if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) { $mime = 'video'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
+ if (preg_match('/\.ogv$/i', $tmpfile)) {
+ $mime = 'video/ogg'; $imgmime = 'video.png'; $famime = 'file-video-o';
+ }
+ if (preg_match('/\.webm$/i', $tmpfile)) {
+ $mime = 'video/webm'; $imgmime = 'video.png'; $famime = 'file-video-o';
+ }
+ if (preg_match('/\.avi$/i', $tmpfile)) {
+ $mime = 'video/x-msvideo'; $imgmime = 'video.png'; $famime = 'file-video-o';
+ }
+ if (preg_match('/\.divx$/i', $tmpfile)) {
+ $mime = 'video/divx'; $imgmime = 'video.png'; $famime = 'file-video-o';
+ }
+ if (preg_match('/\.xvid$/i', $tmpfile)) {
+ $mime = 'video/xvid'; $imgmime = 'video.png'; $famime = 'file-video-o';
+ }
+ if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
+ $mime = 'video'; $imgmime = 'video.png'; $famime = 'file-video-o';
+ }
// Archive
- if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i', $tmpfile)) { $mime = 'archive'; $imgmime = 'archive.png'; $famime = 'file-archive-o'; } // application/xxx where zzz is zip, ...
+ if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i', $tmpfile)) {
+ $mime = 'archive'; $imgmime = 'archive.png'; $famime = 'file-archive-o';
+ } // application/xxx where zzz is zip, ...
// Exe
- if (preg_match('/\.(exe|com)$/i', $tmpfile)) { $mime = 'application/octet-stream'; $imgmime = 'other.png'; $famime = 'file-o'; }
+ if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
+ $mime = 'application/octet-stream'; $imgmime = 'other.png'; $famime = 'file-o';
+ }
// Lib
- if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { $mime = 'library'; $imgmime = 'library.png'; $famime = 'file-o'; }
+ if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
+ $mime = 'library'; $imgmime = 'library.png'; $famime = 'file-o';
+ }
// Err
- if (preg_match('/\.err$/i', $tmpfile)) { $mime = 'error'; $imgmime = 'error.png'; $famime = 'file-text-o'; }
+ if (preg_match('/\.err$/i', $tmpfile)) {
+ $mime = 'error'; $imgmime = 'error.png'; $famime = 'file-text-o';
+ }
// Return string
- if ($mode == 1)
- {
+ if ($mode == 1) {
$tmp = explode('/', $mime);
return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
}
- if ($mode == 2)
- {
+ if ($mode == 2) {
return $imgmime;
}
- if ($mode == 3)
- {
+ if ($mode == 3) {
return $srclang;
}
- if ($mode == 4)
- {
+ if ($mode == 4) {
return $famime;
}
return $mime;
@@ -8498,17 +9044,16 @@ function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield
{
global $dictvalues, $db, $langs;
- if (!isset($dictvalues[$tablename]))
- {
+ if (!isset($dictvalues[$tablename])) {
$dictvalues[$tablename] = array();
$sql = 'SELECT * FROM '.$tablename.' WHERE 1'; // Here select * is allowed as it is generic code and we don't have list of fields
- if ($checkentity) $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
+ if ($checkentity) {
+ $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
+ }
$resql = $db->query($sql);
- if ($resql)
- {
- while ($obj = $db->fetch_object($resql))
- {
+ if ($resql) {
+ while ($obj = $db->fetch_object($resql)) {
$dictvalues[$tablename][$obj->{$rowidfield}] = $obj;
}
} else {
@@ -8516,10 +9061,13 @@ function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield
}
}
- if (!empty($dictvalues[$tablename][$id])) return $dictvalues[$tablename][$id]->{$field}; // Found
- else // Not found
+ if (!empty($dictvalues[$tablename][$id])) {
+ return $dictvalues[$tablename][$id]->{$field}; // Found
+ } else // Not found
{
- if ($id > 0) return $id;
+ if ($id > 0) {
+ return $id;
+ }
return '';
}
}
@@ -8534,12 +9082,10 @@ function colorIsLight($stringcolor)
{
$stringcolor = str_replace('#', '', $stringcolor);
$res = -1;
- if (!empty($stringcolor))
- {
+ if (!empty($stringcolor)) {
$res = 0;
$tmp = explode(',', $stringcolor);
- if (count($tmp) > 1) // This is a comma RGB ('255','255','255')
- {
+ if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
$r = $tmp[0];
$g = $tmp[1];
$b = $tmp[2];
@@ -8552,7 +9098,9 @@ function colorIsLight($stringcolor)
$b = hexdec($hexb);
}
$bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
- if ($bright > 0.6) $res = 1;
+ if ($bright > 0.6) {
+ $res = 1;
+ }
}
return $res;
}
@@ -8571,22 +9119,30 @@ function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal
//print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
//print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
- if (empty($menuentry['enabled'])) return 0; // Entry disabled by condition
- if ($type_user && $menuentry['module'])
- {
+ if (empty($menuentry['enabled'])) {
+ return 0; // Entry disabled by condition
+ }
+ if ($type_user && $menuentry['module']) {
$tmploops = explode('|', $menuentry['module']);
$found = 0;
- foreach ($tmploops as $tmploop)
- {
+ foreach ($tmploops as $tmploop) {
if (in_array($tmploop, $listofmodulesforexternal)) {
$found++; break;
}
}
- if (!$found) return 0; // Entry is for menus all excluded to external users
+ if (!$found) {
+ return 0; // Entry is for menus all excluded to external users
+ }
+ }
+ if (!$menuentry['perms'] && $type_user) {
+ return 0; // No permissions and user is external
+ }
+ if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
+ return 0; // No permissions and option to hide when not allowed, even for internal user, is on
+ }
+ if (!$menuentry['perms']) {
+ return 2; // No permissions and user is external
}
- if (!$menuentry['perms'] && $type_user) return 0; // No permissions and user is external
- if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) return 0; // No permissions and option to hide when not allowed, even for internal user, is on
- if (!$menuentry['perms']) return 2; // No permissions and user is external
return 1;
}
@@ -8636,7 +9192,7 @@ function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '
// Override attr
if (!empty($params['attr']) && is_array($params['attr'])) {
- foreach ($params['attr']as $key => $value) {
+ foreach ($params['attr'] as $key => $value) {
if ($key == 'class') {
$attr['class'] .= ' '.$value;
} elseif ($key == 'classOverride') {
@@ -8700,11 +9256,14 @@ function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $st
$htmlLabelShort = (in_array($displayMode, array(1, 2, 5)) ? '' : '').(!empty($html) ? $html : (!empty($statusLabelShort) ? $statusLabelShort : $statusLabel)).(in_array($displayMode, array(1, 2, 5)) ? ' ' : '');
// For small screen, we always use the short label instead of long label.
- if (!empty($conf->dol_optimize_smallscreen))
- {
- if ($displayMode == 0) $displayMode = 1;
- elseif ($displayMode == 4) $displayMode = 2;
- elseif ($displayMode == 6) $displayMode = 5;
+ if (!empty($conf->dol_optimize_smallscreen)) {
+ if ($displayMode == 0) {
+ $displayMode = 1;
+ } elseif ($displayMode == 4) {
+ $displayMode = 2;
+ } elseif ($displayMode == 6) {
+ $displayMode = 5;
+ }
}
// For backward compatibility. Image's filename are still in French, so we use this array to convert
@@ -8853,10 +9412,14 @@ function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $u
}
$class = 'btnTitle';
- if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-comment-dots'))) $class .= ' btnTitlePlus';
+ if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-comment-dots'))) {
+ $class .= ' btnTitlePlus';
+ }
$useclassfortooltip = 1;
- if (!empty($params['morecss'])) $class .= ' '.$params['morecss'];
+ if (!empty($params['morecss'])) {
+ $class .= ' '.$params['morecss'];
+ }
$attr = array(
'class' => $class,
@@ -9042,9 +9605,15 @@ function getElementProperties($element_type)
$subelement = 'product';
}
- if (empty($classfile)) $classfile = strtolower($subelement);
- if (empty($classname)) $classname = ucfirst($subelement);
- if (empty($classpath)) $classpath = $module.'/class';
+ if (empty($classfile)) {
+ $classfile = strtolower($subelement);
+ }
+ if (empty($classname)) {
+ $classname = ucfirst($subelement);
+ }
+ if (empty($classpath)) {
+ $classpath = $module.'/class';
+ }
$element_properties = array(
'module' => $module,
@@ -9071,14 +9640,12 @@ function fetchObjectByElement($element_id, $element_type, $element_ref = '')
global $conf, $db;
$element_prop = getElementProperties($element_type);
- if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
- {
+ if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) {
dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
$objecttmp = new $element_prop['classname']($db);
$ret = $objecttmp->fetch($element_id, $element_ref);
- if ($ret >= 0)
- {
+ if ($ret >= 0) {
return $objecttmp;
}
}
@@ -9093,8 +9660,7 @@ function fetchObjectByElement($element_id, $element_type, $element_ref = '')
*/
function isAFileWithExecutableContent($filename)
{
- if (preg_match('/\.(htm|html|js|phar|php|php\d+|phtml|pht|pl|py|cgi|ksh|sh|shtml|bash|bat|cmd|wpk|exe|dmg)$/i', $filename))
- {
+ if (preg_match('/\.(htm|html|js|phar|php|php\d+|phtml|pht|pl|py|cgi|ksh|sh|shtml|bash|bat|cmd|wpk|exe|dmg)$/i', $filename)) {
return true;
}
@@ -9226,16 +9792,14 @@ function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0,
return;
}
- if ($nbofloop === 0)
- {
+ if ($nbofloop === 0) {
// don't show a summary line
return;
}
if ($num === 0) {
$colspan = $tableColumnCount;
- }
- elseif ($num > $nbofloop) {
+ } elseif ($num > $nbofloop) {
$colspan = $tableColumnCount;
} else {
$colspan = $tableColumnCount - 1;
@@ -9275,12 +9839,18 @@ function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
if ($method == -1) {
$method = 0;
- if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1;
- if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2;
+ if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
+ $method = 1;
+ }
+ if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
+ $method = 2;
+ }
}
// Be sure we don't have output buffering enabled to have readfile working correctly
- while (ob_get_level()) ob_end_flush();
+ while (ob_get_level()) {
+ ob_end_flush();
+ }
// Solution 0
if ($method == 0) {
diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php
index fcac069183e..feb96859544 100644
--- a/htdocs/core/lib/functions2.lib.php
+++ b/htdocs/core/lib/functions2.lib.php
@@ -83,8 +83,7 @@ function dolGetModulesDirs($subdir = '')
$modulesdir = array();
- foreach ($conf->file->dol_document_root as $type => $dirroot)
- {
+ foreach ($conf->file->dol_document_root as $type => $dirroot) {
// Default core/modules dir
if ($type === 'main') {
$modulesdir[$dirroot.'/core/modules'.$subdir.'/'] = $dirroot.'/core/modules'.$subdir.'/';
@@ -92,16 +91,14 @@ function dolGetModulesDirs($subdir = '')
// Scan dir from external modules
$handle = @opendir($dirroot);
- if (is_resource($handle))
- {
- while (($file = readdir($handle)) !== false)
- {
- if (preg_match('/disabled/', $file)) continue; // We discard module if it contains disabled into name.
+ if (is_resource($handle)) {
+ while (($file = readdir($handle)) !== false) {
+ if (preg_match('/disabled/', $file)) {
+ continue; // We discard module if it contains disabled into name.
+ }
- if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes')
- {
- if (is_dir($dirroot.'/'.$file.'/core/modules'.$subdir.'/'))
- {
+ if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes') {
+ if (is_dir($dirroot.'/'.$file.'/core/modules'.$subdir.'/')) {
$modulesdir[$dirroot.'/'.$file.'/core/modules'.$subdir.'/'] = $dirroot.'/'.$file.'/core/modules'.$subdir.'/';
}
}
@@ -128,8 +125,12 @@ function dol_getDefaultFormat(Translate $outputlangs = null)
$outputlangs = $langs;
}
- if ($outputlangs->defaultlang == 'ca_CA') $selected = 'CAP4'; // Canada
- if ($outputlangs->defaultlang == 'en_US') $selected = 'USLetter'; // US
+ if ($outputlangs->defaultlang == 'ca_CA') {
+ $selected = 'CAP4'; // Canada
+ }
+ if ($outputlangs->defaultlang == 'en_US') {
+ $selected = 'USLetter'; // US
+ }
return $selected;
}
@@ -146,35 +147,47 @@ function dol_print_file($langs, $filename, $searchalt = 0)
global $conf;
// Test if file is in lang directory
- foreach ($langs->dir as $searchdir)
- {
+ foreach ($langs->dir as $searchdir) {
$formfile = ($searchdir."/langs/".$langs->defaultlang."/".$filename);
dol_syslog('functions2::dol_print_file search file '.$formfile, LOG_DEBUG);
- if (is_readable($formfile))
- {
+ if (is_readable($formfile)) {
$content = file_get_contents($formfile);
$isutf8 = utf8_check($content);
- if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
- elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
- else print $content;
+ if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') {
+ print utf8_encode($content);
+ } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') {
+ print utf8_decode($content);
+ } else {
+ print $content;
+ }
return true;
- } else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
+ } else {
+ dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
+ }
if ($searchalt) {
// Test si fichier dans repertoire de la langue alternative
- if ($langs->defaultlang != "en_US") $formfilealt = $searchdir."/langs/en_US/".$filename;
- else $formfilealt = $searchdir."/langs/fr_FR/".$filename;
+ if ($langs->defaultlang != "en_US") {
+ $formfilealt = $searchdir."/langs/en_US/".$filename;
+ } else {
+ $formfilealt = $searchdir."/langs/fr_FR/".$filename;
+ }
dol_syslog('functions2::dol_print_file search alt file '.$formfilealt, LOG_DEBUG);
//print 'getcwd='.getcwd().' htmlfilealt='.$formfilealt.' X '.file_exists(getcwd().'/'.$formfilealt);
- if (is_readable($formfilealt))
- {
+ if (is_readable($formfilealt)) {
$content = file_get_contents($formfilealt);
$isutf8 = utf8_check($content);
- if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
- elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
- else print $content;
+ if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') {
+ print utf8_encode($content);
+ } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') {
+ print utf8_decode($content);
+ } else {
+ print $content;
+ }
return true;
- } else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
+ } else {
+ dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
+ }
}
}
@@ -204,268 +217,437 @@ function dol_print_object_info($object, $usetable = 0)
$deltadateforuser = round($deltadateforclient - $deltadateforserver);
//print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser;
- if ($usetable) print '';
+ if ($usetable) {
+ print '';
+ }
// Import key
- if (!empty($object->import_key))
- {
- if ($usetable) print '';
+ if (!empty($object->import_key)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("ImportedWithSet");
- if ($usetable) print ' ';
- else print ': ';
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
print $object->import_key;
- if ($usetable) print ' ';
- else print ' ';
+ if ($usetable) {
+ print '';
+ } else {
+ print ' ';
+ }
}
// User creation (old method using already loaded object and not id is kept for backward compatibility)
- if (!empty($object->user_creation) || !empty($object->user_creation_id))
- {
- if ($usetable) print '';
+ if (!empty($object->user_creation) || !empty($object->user_creation_id)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("CreatedBy");
- if ($usetable) print ' ';
- else print ': ';
- if (is_object($object->user_creation))
- {
- if ($object->user_creation->id) print $object->user_creation->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
+ if (is_object($object->user_creation)) {
+ if ($object->user_creation->id) {
+ print $object->user_creation->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
} else {
$userstatic = new User($db);
$userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation);
- if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($userstatic->id) {
+ print $userstatic->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
+ }
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ' ';
}
- if ($usetable) print '';
- else print ' ';
}
// Date creation
- if (!empty($object->date_creation))
- {
- if ($usetable) print '';
+ if (!empty($object->date_creation)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("DateCreation");
- if ($usetable) print ' ';
- else print ': ';
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
print dol_print_date($object->date_creation, 'dayhour', 'tzserver');
- if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_creation, "dayhour", "tzuserrel").' '.$langs->trans("ClientHour");
- if ($usetable) print ' ';
- else print ' ';
+ if ($deltadateforuser) {
+ print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_creation, "dayhour", "tzuserrel").' '.$langs->trans("ClientHour");
+ }
+ if ($usetable) {
+ print '';
+ } else {
+ print ' ';
+ }
}
// User change (old method using already loaded object and not id is kept for backward compatibility)
- if (!empty($object->user_modification) || !empty($object->user_modification_id))
- {
- if ($usetable) print '';
+ if (!empty($object->user_modification) || !empty($object->user_modification_id)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("ModifiedBy");
- if ($usetable) print ' ';
- else print ': ';
- if (is_object($object->user_modification))
- {
- if ($object->user_modification->id) print $object->user_modification->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
+ if (is_object($object->user_modification)) {
+ if ($object->user_modification->id) {
+ print $object->user_modification->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
} else {
$userstatic = new User($db);
$userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification);
- if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($userstatic->id) {
+ print $userstatic->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
+ }
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ' ';
}
- if ($usetable) print '';
- else print ' ';
}
// Date change
- if (!empty($object->date_modification))
- {
- if ($usetable) print '';
+ if (!empty($object->date_modification)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("DateLastModification");
- if ($usetable) print ' ';
- else print ': ';
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
print dol_print_date($object->date_modification, 'dayhour', 'tzserver');
- if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_modification, "dayhour", "tzuserrel").' '.$langs->trans("ClientHour");
- if ($usetable) print ' ';
- else print ' ';
+ if ($deltadateforuser) {
+ print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_modification, "dayhour", "tzuserrel").' '.$langs->trans("ClientHour");
+ }
+ if ($usetable) {
+ print '';
+ } else {
+ print ' ';
+ }
}
// User validation (old method using already loaded object and not id is kept for backward compatibility)
- if (!empty($object->user_validation) || !empty($object->user_validation_id))
- {
- if ($usetable) print '';
+ if (!empty($object->user_validation) || !empty($object->user_validation_id)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("ValidatedBy");
- if ($usetable) print ' ';
- else print ': ';
- if (is_object($object->user_validation))
- {
- if ($object->user_validation->id) print $object->user_validation->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
+ if (is_object($object->user_validation)) {
+ if ($object->user_validation->id) {
+ print $object->user_validation->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
} else {
$userstatic = new User($db);
$userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
- if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($userstatic->id) {
+ print $userstatic->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
+ }
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ' ';
}
- if ($usetable) print '';
- else print ' ';
}
// Date validation
- if (!empty($object->date_validation))
- {
- if ($usetable) print '';
+ if (!empty($object->date_validation)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("DateValidation");
- if ($usetable) print ' ';
- else print ': ';
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
print dol_print_date($object->date_validation, 'dayhour', 'tzserver');
- if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_validation, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
- if ($usetable) print ' ';
- else print ' ';
+ if ($deltadateforuser) {
+ print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_validation, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
+ }
+ if ($usetable) {
+ print '';
+ } else {
+ print ' ';
+ }
}
// User approve (old method using already loaded object and not id is kept for backward compatibility)
- if (!empty($object->user_approve) || !empty($object->user_approve_id))
- {
- if ($usetable) print '';
+ if (!empty($object->user_approve) || !empty($object->user_approve_id)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("ApprovedBy");
- if ($usetable) print ' ';
- else print ': ';
- if (is_object($object->user_approve))
- {
- if ($object->user_approve->id) print $object->user_approve->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
+ if (is_object($object->user_approve)) {
+ if ($object->user_approve->id) {
+ print $object->user_approve->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
} else {
$userstatic = new User($db);
$userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
- if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($userstatic->id) {
+ print $userstatic->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
+ }
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ' ';
}
- if ($usetable) print '';
- else print ' ';
}
// Date approve
- if (!empty($object->date_approve))
- {
- if ($usetable) print '';
+ if (!empty($object->date_approve)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("DateApprove");
- if ($usetable) print ' ';
- else print ': ';
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
print dol_print_date($object->date_approve, 'dayhour', 'tzserver');
- if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_approve, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
- if ($usetable) print ' ';
- else print ' ';
+ if ($deltadateforuser) {
+ print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_approve, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
+ }
+ if ($usetable) {
+ print '';
+ } else {
+ print ' ';
+ }
}
// User approve
- if (!empty($object->user_approve_id2))
- {
- if ($usetable) print '';
+ if (!empty($object->user_approve_id2)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("ApprovedBy");
- if ($usetable) print ' ';
- else print ': ';
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
$userstatic = new User($db);
$userstatic->fetch($object->user_approve_id2);
- if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
- if ($usetable) print ' ';
- else print ' ';
+ if ($userstatic->id) {
+ print $userstatic->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
+ if ($usetable) {
+ print '';
+ } else {
+ print ' ';
+ }
}
// Date approve
- if (!empty($object->date_approve2))
- {
- if ($usetable) print '';
+ if (!empty($object->date_approve2)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("DateApprove2");
- if ($usetable) print ' ';
- else print ': ';
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
print dol_print_date($object->date_approve2, 'dayhour', 'tzserver');
- if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_approve2, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
- if ($usetable) print ' ';
- else print ' ';
+ if ($deltadateforuser) {
+ print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_approve2, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
+ }
+ if ($usetable) {
+ print '';
+ } else {
+ print ' ';
+ }
}
// User close
- if (!empty($object->user_cloture) || !empty($object->user_closing))
- {
- if (isset($object->user_cloture) && !empty($object->user_cloture)) $object->user_closing = $object->user_cloture;
- if ($usetable) print '';
+ if (!empty($object->user_cloture) || !empty($object->user_closing)) {
+ if (isset($object->user_cloture) && !empty($object->user_cloture)) {
+ $object->user_closing = $object->user_cloture;
+ }
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("ClosedBy");
- if ($usetable) print ' ';
- else print ': ';
- if (is_object($object->user_closing))
- {
- if ($object->user_closing->id) print $object->user_closing->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
+ if (is_object($object->user_closing)) {
+ if ($object->user_closing->id) {
+ print $object->user_closing->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
} else {
$userstatic = new User($db);
$userstatic->fetch($object->user_closing);
- if ($userstatic->id) print $userstatic->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($userstatic->id) {
+ print $userstatic->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
+ }
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ' ';
}
- if ($usetable) print '';
- else print ' ';
}
// Date close
- if (!empty($object->date_cloture) || !empty($object->date_closing))
- {
- if (isset($object->date_cloture) && !empty($object->date_cloture)) $object->date_closing = $object->date_cloture;
- if ($usetable) print '';
+ if (!empty($object->date_cloture) || !empty($object->date_closing)) {
+ if (isset($object->date_cloture) && !empty($object->date_cloture)) {
+ $object->date_closing = $object->date_cloture;
+ }
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("DateClosing");
- if ($usetable) print ' ';
- else print ': ';
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
print dol_print_date($object->date_closing, 'dayhour', 'tzserver');
- if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_closing, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
- if ($usetable) print ' ';
- else print ' ';
+ if ($deltadateforuser) {
+ print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_closing, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
+ }
+ if ($usetable) {
+ print '';
+ } else {
+ print ' ';
+ }
}
// User conciliate
- if (!empty($object->user_rappro))
- {
- if ($usetable) print '';
+ if (!empty($object->user_rappro)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("ConciliatedBy");
- if ($usetable) print ' ';
- else print ': ';
- if (is_object($object->user_rappro))
- {
- if ($object->user_rappro->id) print $object->user_rappro->getNomUrl(-1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
+ if (is_object($object->user_rappro)) {
+ if ($object->user_rappro->id) {
+ print $object->user_rappro->getNomUrl(-1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
} else {
$userstatic = new User($db);
$userstatic->fetch($object->user_rappro);
- if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
- else print $langs->trans("Unknown");
+ if ($userstatic->id) {
+ print $userstatic->getNomUrl(1, '', 0, 0, 0);
+ } else {
+ print $langs->trans("Unknown");
+ }
+ }
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ' ';
}
- if ($usetable) print '';
- else print ' ';
}
// Date conciliate
- if (!empty($object->date_rappro))
- {
- if ($usetable) print '';
+ if (!empty($object->date_rappro)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("DateConciliating");
- if ($usetable) print ' ';
- else print ': ';
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
print dol_print_date($object->date_rappro, 'dayhour', 'tzserver');
- if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_rappro, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
- if ($usetable) print ' ';
- else print ' ';
+ if ($deltadateforuser) {
+ print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_rappro, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
+ }
+ if ($usetable) {
+ print '';
+ } else {
+ print ' ';
+ }
}
// Date send
- if (!empty($object->date_envoi))
- {
- if ($usetable) print '';
+ if (!empty($object->date_envoi)) {
+ if ($usetable) {
+ print ' ';
+ }
print $langs->trans("DateLastSend");
- if ($usetable) print ' ';
- else print ': ';
+ if ($usetable) {
+ print ' ';
+ } else {
+ print ': ';
+ }
print dol_print_date($object->date_envoi, 'dayhour', 'tzserver');
- if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_envoi, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
- if ($usetable) print ' ';
- else print ' ';
+ if ($deltadateforuser) {
+ print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_envoi, "dayhour", 'tzuserrel').' '.$langs->trans("ClientHour");
+ }
+ if ($usetable) {
+ print '';
+ } else {
+ print ' ';
+ }
}
- if ($usetable) print '
';
+ if ($usetable) {
+ print '
';
+ }
}
@@ -514,10 +696,14 @@ function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0
$urlregex = '';
// SCHEME
- if ($http) $urlregex .= "^(http:\/\/|https:\/\/)";
+ if ($http) {
+ $urlregex .= "^(http:\/\/|https:\/\/)";
+ }
// USER AND PASS
- if ($pass) $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
+ if ($pass) {
+ $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
+ }
// HOSTNAME OR IP
//$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*"; // x allowed (ex. http://localhost, http://routerlogin)
@@ -526,17 +712,24 @@ function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0
//use only one of the above
// PORT
- if ($port) $urlregex .= "(\:[0-9]{2,5})";
+ if ($port) {
+ $urlregex .= "(\:[0-9]{2,5})";
+ }
// PATH
- if ($path) $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
+ if ($path) {
+ $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
+ }
// GET Query
- if ($query) $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
+ if ($query) {
+ $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
+ }
// ANCHOR
- if ($anchor) $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
+ if ($anchor) {
+ $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
+ }
// check
- if (preg_match('/'.$urlregex.'/i', $url))
- {
+ if (preg_match('/'.$urlregex.'/i', $url)) {
$ValidUrl = 1;
}
//print $urlregex.' - '.$url.' - '.$ValidUrl;
@@ -552,16 +745,14 @@ function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0
*/
function isValidVATID($company)
{
- if ($company->isInEEC()) // Syntax check rules for EEC countries
- {
+ if ($company->isInEEC()) { // Syntax check rules for EEC countries
/* Disabled because some companies can have an address in Irland and a vat number in France.
- $vatprefix = $company->country_code;
- if ($vatprefix == 'GR') $vatprefix = '(EL|GR)';
- elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers
- else $vatprefix = preg_quote($vatprefix, '/');*/
+ $vatprefix = $company->country_code;
+ if ($vatprefix == 'GR') $vatprefix = '(EL|GR)';
+ elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers
+ else $vatprefix = preg_quote($vatprefix, '/');*/
$vatprefix = '[a-zA-Z][a-zA-Z]';
- if (!preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra)))
- {
+ if (!preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra))) {
return 0;
}
}
@@ -582,8 +773,7 @@ function clean_url($url, $http = 1)
// To include the minus sign in a char class, we must not escape it but put it at the end of the class
// Also, there's no need of escape a dot sign in a class
$regs = array();
- if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs))
- {
+ if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs)) {
$proto = $regs[1];
$domain = $regs[2];
$port = isset($regs[3]) ? $regs[3] : '';
@@ -593,10 +783,8 @@ function clean_url($url, $http = 1)
// Si http: defini on supprime le http (Si https on ne supprime pas)
$newproto = $proto;
- if ($http == 0)
- {
- if (preg_match('/^http:[\\/]+/i', $url))
- {
+ if ($http == 0) {
+ if (preg_match('/^http:[\\/]+/i', $url)) {
$url = preg_replace('/^http:[\\/]+/i', '', $url);
$newproto = '';
}
@@ -606,7 +794,9 @@ function clean_url($url, $http = 1)
$CleanUrl = preg_replace('/^'.preg_quote($proto.$domain, '/').'/i', $newproto.strtolower($domain), $url);
return $CleanUrl;
- } else return $url;
+ } else {
+ return $url;
+ }
}
@@ -624,7 +814,9 @@ function clean_url($url, $http = 1)
*/
function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail = 4, $nbdisplaydomain = 3, $displaytld = true)
{
- if (!isValidEmail($mail))return '';
+ if (!isValidEmail($mail)) {
+ return '';
+ }
$tab = explode('@', $mail);
$tab2 = explode('.', $tab[1]);
$string_replace = '';
@@ -633,8 +825,7 @@ function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail
$mail_tld = '';
$nbofelem = count($tab2);
- for ($i = 1; $i < $nbofelem && $displaytld; $i++)
- {
+ for ($i = 1; $i < $nbofelem && $displaytld; $i++) {
$mail_tld .= '.'.$tab2[$i];
}
@@ -686,7 +877,9 @@ function array2tr($data, $troptions = '', $tdoptions = '')
function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '')
{
$text = '';
- if ($tableMarkup) $text = '';
+ if ($tableMarkup) {
+ $text = '';
+ }
foreach ($data as $key => $item) {
if (is_array($item)) {
$text .= array2tr($item, $troptions, $tdoptions);
@@ -697,7 +890,9 @@ function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '
$text .= '';
}
}
- if ($tableMarkup) $text .= '
';
+ if ($tableMarkup) {
+ $text .= '
';
+ }
return $text;
}
@@ -721,15 +916,23 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
{
global $conf, $user;
- if (!is_object($objsoc)) $valueforccc = $objsoc;
- elseif ($table == "commande_fournisseur" || $table == "facture_fourn") $valueforccc = dol_string_unaccent($objsoc->code_fournisseur);
- else $valueforccc = dol_string_unaccent($objsoc->code_client);
+ if (!is_object($objsoc)) {
+ $valueforccc = $objsoc;
+ } elseif ($table == "commande_fournisseur" || $table == "facture_fourn") {
+ $valueforccc = dol_string_unaccent($objsoc->code_fournisseur);
+ } else {
+ $valueforccc = dol_string_unaccent($objsoc->code_client);
+ }
$sharetable = $table;
- if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function
+ if ($table == 'facture' || $table == 'invoice') {
+ $sharetable = 'invoicenumber'; // for getEntity function
+ }
// Clean parameters
- if ($date == '') $date = dol_now(); // We use local year and month of PHP server to search numbers
+ if ($date == '') {
+ $date = dol_now(); // We use local year and month of PHP server to search numbers
+ }
// but we should use local year and month of user
// For debugging
@@ -742,8 +945,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$hasglobalcounter = false;
$reg = array();
// Extract value for mask counter, mask raz and mask offset
- if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg))
- {
+ if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg)) {
$masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : '');
$maskcounter = $reg[1];
$hasglobalcounter = true;
@@ -756,12 +958,13 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$maskraz = -1;
$maskoffset = 0;
$resetEveryMonth = false;
- if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits';
+ if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) {
+ return 'ErrorCounterMustHaveMoreThan3Digits';
+ }
// Extract value for third party mask counter
$regClientRef = array();
- if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef))
- {
+ if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) {
$maskrefclient = $regClientRef[1].$regClientRef[2];
$maskrefclient_maskclientcode = $regClientRef[1];
$maskrefclient_maskcounter = $regClientRef[2];
@@ -769,19 +972,21 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$maskrefclient_clientcode = substr($valueforccc, 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code where n is length in mask
$maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
$maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
- if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
- } else $maskrefclient = '';
+ if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
+ return 'ErrorCounterMustHaveMoreThan3Digits';
+ }
+ } else {
+ $maskrefclient = '';
+ }
// fail if there is neither a global nor a third party counter
- if (!$hasglobalcounter && ($maskrefclient_maskcounter == ''))
- {
+ if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) {
return 'ErrorBadMask';
}
// Extract value for third party type
$regType = array();
- if (preg_match('/\{(t+)\}/i', $mask, $regType))
- {
+ if (preg_match('/\{(t+)\}/i', $mask, $regType)) {
$masktype = $regType[1];
$masktype_value = substr(preg_replace('/^TE_/', '', $objsoc->typent_code), 0, dol_strlen($regType[1])); // get n first characters of thirdpaty typent_code (where n is length in mask)
$masktype_value = str_pad($masktype_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
@@ -791,10 +996,12 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
}
// Extract value for user
- $regType = array();
+ $regType = array();
if (preg_match('/\{(u+)\}/i', $mask, $regType)) {
$lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
- if (is_object($objuser)) $lastname = $objuser->lastname;
+ if (is_object($objuser)) {
+ $lastname = $objuser->lastname;
+ }
$maskuser = $regType[1];
$maskuser_value = substr($lastname, 0, dol_strlen($regType[1])); // get n first characters of user firstname (where n is length in mask)
@@ -809,15 +1016,13 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$maskpersonew = array();
$tmpmask = $mask;
$regKey = array();
- while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey))
- {
+ while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey)) {
$maskperso[$regKey[1]] = '{'.$regKey[1].'-'.$regKey[2].'}';
$maskpersonew[$regKey[1]] = str_pad('', $regKey[2], '_', STR_PAD_RIGHT);
$tmpmask = preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
}
- if (strstr($mask, 'user_extra_'))
- {
+ if (strstr($mask, 'user_extra_')) {
$start = "{user_extra_";
$end = "\}";
$extra = get_string_between($mask, "user_extra_", "}");
@@ -831,8 +1036,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
$maskwithonlyymcode = preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode);
$maskwithonlyymcode = preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode);
- foreach ($maskperso as $key => $val)
- {
+ foreach ($maskperso as $key => $val) {
$maskwithonlyymcode = preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
}
$maskwithnocode = $maskwithonlyymcode;
@@ -846,8 +1050,12 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
//var_dump($reg);
// If an offset is asked
- if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]);
- if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]);
+ if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) {
+ $maskoffset = preg_replace('/^\+/', '', $reg[2]);
+ }
+ if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) {
+ $maskoffset = preg_replace('/^\+/', '', $reg[3]);
+ }
// Define $sqlwhere
$sqlwhere = '';
@@ -855,14 +1063,19 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$yearoffsettype = false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
// If a restore to zero after a month is asked we check if there is already a value for this year.
- if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) $yearoffsettype = preg_replace('/^@/', '', $reg[2]);
- if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) $yearoffsettype = preg_replace('/^@/', '', $reg[3]);
+ if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) {
+ $yearoffsettype = preg_replace('/^@/', '', $reg[2]);
+ }
+ if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) {
+ $yearoffsettype = preg_replace('/^@/', '', $reg[3]);
+ }
//print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
- if (is_numeric($yearoffsettype) && $yearoffsettype >= 1)
+ if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) {
$maskraz = $yearoffsettype; // For backward compatibility
- elseif ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
+ } elseif ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1)) {
$maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
+ }
//print "maskraz=".$maskraz; // -1=no reset
if ($maskraz > 0) { // A reset is required
@@ -870,27 +1083,44 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$maskraz = date('m', $date);
$resetEveryMonth = true;
}
- if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
+ if ($maskraz > 12) {
+ return 'ErrorBadMaskBadRazMonth';
+ }
// Define posy, posm and reg
- if ($maskraz > 1) // if reset is not first month, we need month and year into mask
- {
- if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; } else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
+ if ($maskraz > 1) { // if reset is not first month, we need month and year into mask
+ if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
+ $posy = 2; $posm = 3;
+ } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
+ $posy = 3; $posm = 2;
+ } else {
+ return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
+ }
- if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit';
+ if (dol_strlen($reg[$posy]) < 2) {
+ return 'ErrorCantUseRazWithYearOnOneDigit';
+ }
} else // if reset is for a specific month in year, we need year
{
- if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; } elseif (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; } elseif (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 0; } else return 'ErrorCantUseRazIfNoYearInMask';
+ if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
+ $posy = 3; $posm = 2;
+ } elseif (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
+ $posy = 2; $posm = 3;
+ } elseif (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
+ $posy = 2; $posm = 0;
+ } else {
+ return 'ErrorCantUseRazIfNoYearInMask';
+ }
}
// Define length
$yearlen = $posy ?dol_strlen($reg[$posy]) : 0;
$monthlen = $posm ?dol_strlen($reg[$posm]) : 0;
// Define pos
- $yearpos = (dol_strlen($reg[1]) + 1);
+ $yearpos = (dol_strlen($reg[1]) + 1);
$monthpos = ($yearpos + $yearlen);
if ($posy == 3 && $posm == 2) { // if month is before year
- $monthpos = (dol_strlen($reg[1]) + 1);
- $yearpos = ($monthpos + $monthlen);
+ $monthpos = (dol_strlen($reg[1]) + 1);
+ $yearpos = ($monthpos + $monthlen);
}
//print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
@@ -898,8 +1128,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$monthcomp = $maskraz;
$yearcomp = 0;
- if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') // $yearoffsettype is - or +
- {
+ if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // $yearoffsettype is - or +
$currentyear = date("Y", $date);
$fiscaldate = dol_mktime('0', '0', '0', $maskraz, '1', $currentyear);
$newyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear);
@@ -907,22 +1136,33 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
//echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').' ';
// If after or equal of current fiscal date
- if ($date >= $fiscaldate)
- {
+ if ($date >= $fiscaldate) {
// If before of next new year date
- if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset = 1;
+ if ($date < $nextnewyeardate && $yearoffsettype == '+') {
+ $yearoffset = 1;
+ }
} // If after or equal of current new year date
- elseif ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset = -1;
+ elseif ($date >= $newyeardate && $yearoffsettype == '-') {
+ $yearoffset = -1;
+ }
} // For backward compatibility
- elseif (date("m", $date) < $maskraz && empty($resetEveryMonth)) { $yearoffset = -1; } // If current month lower that month of return to zero, year is previous year
+ elseif (date("m", $date) < $maskraz && empty($resetEveryMonth)) {
+ $yearoffset = -1;
+ } // If current month lower that month of return to zero, year is previous year
- if ($yearlen == 4) $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset);
- elseif ($yearlen == 2) $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset);
- elseif ($yearlen == 1) $yearcomp = substr(date("y", $date), 2, 1) + $yearoffset;
- if ($monthcomp > 1 && empty($resetEveryMonth)) // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
- {
- if ($yearlen == 4) $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1);
- elseif ($yearlen == 2) $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1);
+ if ($yearlen == 4) {
+ $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset);
+ } elseif ($yearlen == 2) {
+ $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset);
+ } elseif ($yearlen == 1) {
+ $yearcomp = substr(date("y", $date), 2, 1) + $yearoffset;
+ }
+ if ($monthcomp > 1 && empty($resetEveryMonth)) { // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
+ if ($yearlen == 4) {
+ $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1);
+ } elseif ($yearlen == 2) {
+ $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1);
+ }
$sqlwhere .= "(";
$sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."'";
@@ -947,7 +1187,9 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
} else {
$posnumstart = strrpos($maskwithnocode, $maskcounter);
} // Pos of counter in final string (from 0 to ...)
- if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
+ if ($posnumstart < 0) {
+ return 'ErrorBadMaskFailedToLocatePosOfSequence';
+ }
$sqlstring = 'SUBSTRING('.$field.', '.($posnumstart + 1).', '.dol_strlen($maskcounter).')';
// Define $maskLike
@@ -961,11 +1203,16 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
$maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
$maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskLike);
- if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
- if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
- if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
- foreach ($maskperso as $key => $val)
- {
+ if ($maskrefclient) {
+ $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
+ }
+ if ($masktype) {
+ $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
+ }
+ if ($maskuser) {
+ $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
+ }
+ foreach ($maskperso as $key => $val) {
$maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike);
}
@@ -975,32 +1222,39 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$sql .= " FROM ".MAIN_DB_PREFIX.$table;
$sql .= " WHERE ".$field." LIKE '".$db->escape($maskLike)."'";
$sql .= " AND ".$field." NOT LIKE '(PROV%)'";
- if ($bentityon) // only if entity enable
+ if ($bentityon) { // only if entity enable
$sql .= " AND entity IN (".getEntity($sharetable).")";
- elseif (!empty($forceentity))
+ } elseif (!empty($forceentity)) {
$sql .= " AND entity IN (".$forceentity.")";
- if ($where) $sql .= $where;
- if ($sqlwhere) $sql .= ' AND '.$sqlwhere;
+ }
+ if ($where) {
+ $sql .= $where;
+ }
+ if ($sqlwhere) {
+ $sql .= ' AND '.$sqlwhere;
+ }
//print $sql.' ';
dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $db->fetch_object($resql);
$counter = $obj->val;
- } else dol_print_error($db);
+ } else {
+ dol_print_error($db);
+ }
// Check if we must force counter to maskoffset
- if (empty($counter)) $counter = $maskoffset;
- elseif (preg_match('/[^0-9]/i', $counter))
- {
+ if (empty($counter)) {
+ $counter = $maskoffset;
+ } elseif (preg_match('/[^0-9]/i', $counter)) {
$counter = 0;
dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
- } elseif ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter = $maskoffset;
+ } elseif ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) {
+ $counter = $maskoffset;
+ }
- if ($mode == 'last') // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
- {
+ if ($mode == 'last') { // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
$counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
// Define $maskLike
@@ -1013,47 +1267,61 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
$maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
$maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), $counterpadded, $maskLike);
- if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
- if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
- if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
+ if ($maskrefclient) {
+ $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
+ }
+ if ($masktype) {
+ $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
+ }
+ if ($maskuser) {
+ $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
+ }
$ref = '';
$sql = "SELECT ".$field." as ref";
$sql .= " FROM ".MAIN_DB_PREFIX.$table;
$sql .= " WHERE ".$field." LIKE '".$db->escape($maskLike)."'";
$sql .= " AND ".$field." NOT LIKE '%PROV%'";
- if ($bentityon) // only if entity enable
+ if ($bentityon) { // only if entity enable
$sql .= " AND entity IN (".getEntity($sharetable).")";
- elseif (!empty($forceentity))
+ } elseif (!empty($forceentity)) {
$sql .= " AND entity IN (".$forceentity.")";
- if ($where) $sql .= $where;
- if ($sqlwhere) $sql .= ' AND '.$sqlwhere;
+ }
+ if ($where) {
+ $sql .= $where;
+ }
+ if ($sqlwhere) {
+ $sql .= ' AND '.$sqlwhere;
+ }
dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $db->fetch_object($resql);
- if ($obj) $ref = $obj->ref;
- } else dol_print_error($db);
+ if ($obj) {
+ $ref = $obj->ref;
+ }
+ } else {
+ dol_print_error($db);
+ }
$numFinal = $ref;
} elseif ($mode == 'next') {
$counter++;
// If value for $counter has a length higher than $maskcounter chars
- if ($counter >= pow(10, dol_strlen($maskcounter)))
- {
+ if ($counter >= pow(10, dol_strlen($maskcounter))) {
$counter = 'ErrorMaxNumberReachForThisMask';
}
- if (!empty($maskrefclient_maskcounter))
- {
+ if (!empty($maskrefclient_maskcounter)) {
//print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n ";
// Define $sqlstring
$maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...)
- if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask';
+ if ($maskrefclient_posnumstart <= 0) {
+ return 'ErrorBadMask';
+ }
$maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')';
//print "x".$sqlstring;
@@ -1075,23 +1343,31 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table;
//$sql.= " WHERE ".$field." not like '(%'";
$maskrefclient_sql .= " WHERE ".$field." LIKE '".$db->escape($maskrefclient_maskLike)."'";
- if ($bentityon) // only if entity enable
+ if ($bentityon) { // only if entity enable
$maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")";
- elseif (!empty($forceentity))
+ } elseif (!empty($forceentity)) {
$sql .= " AND entity IN (".$forceentity.")";
- if ($where) $maskrefclient_sql .= $where; //use the same optional where as general mask
- if ($sqlwhere) $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask
+ }
+ if ($where) {
+ $maskrefclient_sql .= $where; //use the same optional where as general mask
+ }
+ if ($sqlwhere) {
+ $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask
+ }
$maskrefclient_sql .= ' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode, $maskrefclient) + 1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$db->escape($maskrefclient_clientcode)."')";
dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
$maskrefclient_resql = $db->query($maskrefclient_sql);
- if ($maskrefclient_resql)
- {
+ if ($maskrefclient_resql) {
$maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
$maskrefclient_counter = $maskrefclient_obj->val;
- } else dol_print_error($db);
+ } else {
+ dol_print_error($db);
+ }
- if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) $maskrefclient_counter = $maskrefclient_maskoffset;
+ if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) {
+ $maskrefclient_counter = $maskrefclient_maskoffset;
+ }
$maskrefclient_counter++;
}
@@ -1099,8 +1375,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$numFinal = $mask;
// We replace special codes except refclient
- if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') // yearoffsettype is - or +, so we don't want current year
- {
+ if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // yearoffsettype is - or +, so we don't want current year
$numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date) + $yearoffset, $numFinal);
$numFinal = preg_replace('/\{yy\}/i', date("y", $date) + $yearoffset, $numFinal);
$numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1) + $yearoffset, $numFinal);
@@ -1120,8 +1395,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
$numFinal = str_replace($maskbefore, $maskafter, $numFinal);
// Now we replace the refclient
- if ($maskrefclient)
- {
+ if ($maskrefclient) {
//print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskrefclient_clientcode=".$maskrefclient_clientcode."\n ";exit;
$maskrefclient_maskbefore = '{'.$maskrefclient.'}';
$maskrefclient_maskafter = $maskrefclient_clientcode.str_pad($maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT);
@@ -1129,16 +1403,14 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
}
// Now we replace the type
- if ($masktype)
- {
+ if ($masktype) {
$masktype_maskbefore = '{'.$masktype.'}';
$masktype_maskafter = $masktype_value;
$numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal);
}
// Now we replace the user
- if ($maskuser)
- {
+ if ($maskuser) {
$maskuser_maskbefore = '{'.$maskuser.'}';
$maskuser_maskafter = $maskuser_value;
$numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal);
@@ -1161,7 +1433,9 @@ function get_string_between($string, $start, $end)
{
$string = " ".$string;
$ini = strpos($string, $start);
- if ($ini == 0) return "";
+ if ($ini == 0) {
+ return "";
+ }
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
@@ -1192,12 +1466,13 @@ function check_value($mask, $value)
}
$maskraz = -1;
$maskoffset = 0;
- if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
+ if (dol_strlen($maskcounter) < 3) {
+ return 'ErrorCounterMustHaveMoreThan3Digits';
+ }
// Extract value for third party mask counter
$regClientRef = array();
- if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef))
- {
+ if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) {
$maskrefclient = $regClientRef[1].$regClientRef[2];
$maskrefclient_maskclientcode = $regClientRef[1];
$maskrefclient_maskcounter = $regClientRef[2];
@@ -1205,12 +1480,15 @@ function check_value($mask, $value)
$maskrefclient_clientcode = substr('', 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code to form maskrefclient_clientcode
$maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
$maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
- if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
- } else $maskrefclient = '';
+ if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
+ return 'ErrorCounterMustHaveMoreThan3Digits';
+ }
+ } else {
+ $maskrefclient = '';
+ }
// fail if there is neither a global nor a third party counter
- if (!$hasglobalcounter && ($maskrefclient_maskcounter == ''))
- {
+ if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) {
return 'ErrorBadMask';
}
@@ -1228,46 +1506,62 @@ function check_value($mask, $value)
//print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n ";
// If an offset is asked
- if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]);
- if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]);
+ if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) {
+ $maskoffset = preg_replace('/^\+/', '', $reg[2]);
+ }
+ if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) {
+ $maskoffset = preg_replace('/^\+/', '', $reg[3]);
+ }
// Define $sqlwhere
// If a restore to zero after a month is asked we check if there is already a value for this year.
- if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) $maskraz = preg_replace('/^@/', '', $reg[2]);
- if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) $maskraz = preg_replace('/^@/', '', $reg[3]);
- if ($maskraz >= 0)
- {
+ if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) {
+ $maskraz = preg_replace('/^@/', '', $reg[2]);
+ }
+ if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) {
+ $maskraz = preg_replace('/^@/', '', $reg[3]);
+ }
+ if ($maskraz >= 0) {
if ($maskraz == 99) {
$maskraz = date('m');
$resetEveryMonth = true;
}
- if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
+ if ($maskraz > 12) {
+ return 'ErrorBadMaskBadRazMonth';
+ }
// Define reg
- if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
- if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazIfNoYearInMask';
+ if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
+ return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
+ }
+ if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
+ return 'ErrorCantUseRazIfNoYearInMask';
+ }
//print "x".$maskwithonlyymcode." ".$maskraz;
}
//print "masktri=".$masktri." maskcounter=".$maskcounter." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskraz=".$maskraz." maskoffset=".$maskoffset." \n";
if (function_exists('mb_strrpos')) {
$posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 0, 'UTF-8');
- }
- else {
+ } else {
$posnumstart = strrpos($maskwithnocode, $maskcounter);
} // Pos of counter in final string (from 0 to ...)
- if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
+ if ($posnumstart < 0) {
+ return 'ErrorBadMaskFailedToLocatePosOfSequence';
+ }
// Check we have a number in $value at position ($posnumstart+1).', '.dol_strlen($maskcounter)
// TODO
- // Check length
- $len = dol_strlen($maskwithnocode);
- if (dol_strlen($value) != $len) $result = -1;
+ // Check length
+ $len = dol_strlen($maskwithnocode);
+ if (dol_strlen($value) != $len) {
+ $result = -1;
+ }
- dol_syslog("functions2::check_value result=".$result, LOG_DEBUG);
- return $result;
+ dol_syslog("functions2::check_value result=".$result, LOG_DEBUG);
+ return $result;
}
/**
@@ -1281,10 +1575,18 @@ function check_value($mask, $value)
function binhex($bin, $pad = false, $upper = false)
{
$last = dol_strlen($bin) - 1;
- for ($i = 0; $i <= $last; $i++) { $x += $bin[$last - $i] * pow(2, $i); }
+ for ($i = 0; $i <= $last; $i++) {
+ $x += $bin[$last - $i] * pow(2, $i);
+ }
$x = dechex($x);
- if ($pad) { while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) { $x = "0$x"; } }
- if ($upper) { $x = strtoupper($x); }
+ if ($pad) {
+ while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) {
+ $x = "0$x";
+ }
+ }
+ if ($upper) {
+ $x = strtoupper($x);
+ }
return $x;
}
@@ -1298,8 +1600,7 @@ function hexbin($hexa)
{
$bin = '';
$strLength = dol_strlen($hexa);
- for ($i = 0; $i < $strLength; $i++)
- {
+ for ($i = 0; $i < $strLength; $i++) {
$bin .= str_pad(decbin(hexdec($hexa[$i])), 4, '0', STR_PAD_LEFT);
}
return $bin;
@@ -1315,8 +1616,7 @@ function numero_semaine($time)
{
$stime = strftime('%Y-%m-%d', $time);
- if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg))
- {
+ if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg)) {
// Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS'
$annee = $reg[1];
$mois = $reg[2];
@@ -1324,31 +1624,29 @@ function numero_semaine($time)
}
/*
- * Norme ISO-8601:
- * - La semaine 1 de toute annee est celle qui contient le 4 janvier ou que la semaine 1 de toute annee est celle qui contient le 1er jeudi de janvier.
- * - La majorite des annees ont 52 semaines mais les annees qui commence un jeudi et les annees bissextiles commencant un mercredi en possede 53.
- * - Le 1er jour de la semaine est le Lundi
- */
+ * Norme ISO-8601:
+ * - La semaine 1 de toute annee est celle qui contient le 4 janvier ou que la semaine 1 de toute annee est celle qui contient le 1er jeudi de janvier.
+ * - La majorite des annees ont 52 semaines mais les annees qui commence un jeudi et les annees bissextiles commencant un mercredi en possede 53.
+ * - Le 1er jour de la semaine est le Lundi
+ */
// Definition du Jeudi de la semaine
- if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) // Dimanche
- $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60;
- elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) // du Lundi au Mercredi
- $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60;
- elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) // du Vendredi au Samedi
- $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60;
- else // Jeudi
- $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee);
+ if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) { // Dimanche
+ $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60;
+ } elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) { // du Lundi au Mercredi
+ $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60;
+ } elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) { // du Vendredi au Samedi
+ $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60;
+ } else { // Jeudi
+ $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee);
+ }
// Definition du premier Jeudi de l'annee
- if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) // Dimanche
- {
+ if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) { // Dimanche
$premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + 4 * 24 * 60 * 60;
- } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) // du Lundi au Mercredi
- {
+ } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) { // du Lundi au Mercredi
$premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (4 - date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)))) * 24 * 60 * 60;
- } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) // du Vendredi au Samedi
- {
+ } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) { // du Vendredi au Samedi
$premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (7 - (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) - 4)) * 24 * 60 * 60;
} else // Jeudi
{
@@ -1365,11 +1663,9 @@ function numero_semaine($time)
) + 1;
// Cas particulier de la semaine 53
- if ($numeroSemaine == 53)
- {
+ if ($numeroSemaine == 53) {
// Les annees qui commence un Jeudi et les annees bissextiles commencant un Mercredi en possede 53
- if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 4 || (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 3 && date("z", mktime(12, 0, 0, 12, 31, date("Y", $jeudiSemaine))) == 365))
- {
+ if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 4 || (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 3 && date("z", mktime(12, 0, 0, 12, 31, date("Y", $jeudiSemaine))) == 365)) {
$numeroSemaine = 53;
} else {
$numeroSemaine = 1;
@@ -1392,20 +1688,17 @@ function numero_semaine($time)
function weight_convert($weight, &$from_unit, $to_unit)
{
/* Pour convertire 320 gr en Kg appeler
- * $f = -3
- * weigh_convert(320, $f, 0) retournera 0.32
- *
- */
- while ($from_unit <> $to_unit)
- {
- if ($from_unit > $to_unit)
- {
+ * $f = -3
+ * weigh_convert(320, $f, 0) retournera 0.32
+ *
+ */
+ while ($from_unit <> $to_unit) {
+ if ($from_unit > $to_unit) {
$weight = $weight * 10;
$from_unit = $from_unit - 1;
$weight = weight_convert($weight, $from_unit, $to_unit);
}
- if ($from_unit < $to_unit)
- {
+ if ($from_unit < $to_unit) {
$weight = $weight / 10;
$from_unit = $from_unit + 1;
$weight = weight_convert($weight, $from_unit, $to_unit);
@@ -1429,7 +1722,9 @@ function weight_convert($weight, &$from_unit, $to_unit)
function dol_set_user_param($db, $conf, &$user, $tab)
{
// Verification parametres
- if (count($tab) < 1) return -1;
+ if (count($tab) < 1) {
+ return -1;
+ }
$db->begin();
@@ -1439,9 +1734,10 @@ function dol_set_user_param($db, $conf, &$user, $tab)
$sql .= " AND entity = ".$conf->entity;
$sql .= " AND param in (";
$i = 0;
- foreach ($tab as $key => $value)
- {
- if ($i > 0) $sql .= ',';
+ foreach ($tab as $key => $value) {
+ if ($i > 0) {
+ $sql .= ',';
+ }
$sql .= "'".$db->escape($key)."'";
$i++;
}
@@ -1449,26 +1745,22 @@ function dol_set_user_param($db, $conf, &$user, $tab)
dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
$resql = $db->query($sql);
- if (!$resql)
- {
+ if (!$resql) {
dol_print_error($db);
$db->rollback();
return -1;
}
- foreach ($tab as $key => $value)
- {
+ foreach ($tab as $key => $value) {
// Set new parameters
- if ($value)
- {
+ if ($value) {
$sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)";
$sql .= " VALUES (".$user->id.",".$conf->entity.",";
$sql .= " '".$db->escape($key)."','".$db->escape($value)."')";
dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
$result = $db->query($sql);
- if (!$result)
- {
+ if (!$result) {
dol_print_error($db);
$db->rollback();
return -1;
@@ -1494,8 +1786,7 @@ function dol_set_user_param($db, $conf, &$user, $tab)
function dol_print_reduction($reduction, $langs)
{
$string = '';
- if ($reduction == 100)
- {
+ if ($reduction == 100) {
$string = $langs->transnoentities("Offered");
} else {
$string = vatrate($reduction, true);
@@ -1513,8 +1804,11 @@ function dol_print_reduction($reduction, $langs)
*/
function version_os($option = '')
{
- if ($option == 'smr') $osversion = php_uname('s').' '.php_uname('m').' '.php_uname('r');
- else $osversion = php_uname();
+ if ($option == 'smr') {
+ $osversion = php_uname('s').' '.php_uname('m').' '.php_uname('r');
+ } else {
+ $osversion = php_uname();
+ }
return $osversion;
}
@@ -1573,20 +1867,17 @@ function getListOfModels($db, $type, $maxfilenamelength = 0)
dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG);
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $db->num_rows($resql);
$i = 0;
- while ($i < $num)
- {
+ while ($i < $num) {
$found = 1;
$obj = $db->fetch_object($resql);
// If this generation module needs to scan a directory, then description field is filled
// with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
- if (!empty($obj->description)) // A list of directories to scan is defined
- {
+ if (!empty($obj->description)) { // A list of directories to scan is defined
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$const = $obj->description;
@@ -1597,23 +1888,23 @@ function getListOfModels($db, $type, $maxfilenamelength = 0)
// Now we add models found in directories scanned
$listofdir = explode(',', $dirtoscan);
- foreach ($listofdir as $key=>$tmpdir)
- {
+ foreach ($listofdir as $key => $tmpdir) {
$tmpdir = trim($tmpdir);
$tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
- if (!$tmpdir) { unset($listofdir[$key]); continue; }
- if (is_dir($tmpdir))
- {
+ if (!$tmpdir) {
+ unset($listofdir[$key]); continue;
+ }
+ if (is_dir($tmpdir)) {
// all type of template is allowed
$tmpfiles = dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
- if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles);
+ if (count($tmpfiles)) {
+ $listoffiles = array_merge($listoffiles, $tmpfiles);
+ }
}
}
- if (count($listoffiles))
- {
- foreach ($listoffiles as $record)
- {
+ if (count($listoffiles)) {
+ foreach ($listoffiles as $record) {
$max = ($maxfilenamelength ? $maxfilenamelength : 28);
$liste[$obj->id.':'.$record['fullname']] = dol_trunc($record['name'], $max, 'middle');
}
@@ -1621,12 +1912,10 @@ function getListOfModels($db, $type, $maxfilenamelength = 0)
$liste[0] = $obj->label.': '.$langs->trans("None");
}
} else {
- if ($type == 'member' && $obj->doc_template_name == 'standard') // Special case, if member template, we add variant per format
- {
+ if ($type == 'member' && $obj->doc_template_name == 'standard') { // Special case, if member template, we add variant per format
global $_Avery_Labels;
include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
- foreach ($_Avery_Labels as $key => $val)
- {
+ foreach ($_Avery_Labels as $key => $val) {
$liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->doc_template_name).' '.$val['name'];
}
} else {
@@ -1641,8 +1930,11 @@ function getListOfModels($db, $type, $maxfilenamelength = 0)
return -1;
}
- if ($found) return $liste;
- else return 0;
+ if ($found) {
+ return $liste;
+ } else {
+ return 0;
+ }
}
/**
@@ -1657,10 +1949,14 @@ function is_ip($ip)
// First we test if it is a valid IPv4
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
// Then we test if it is a private range
- if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
+ if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
+ return 2;
+ }
// Then we test if it is a reserved range
- if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
+ if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) {
+ return 0;
+ }
return 1;
}
@@ -1715,8 +2011,7 @@ function getSoapParams()
$timeout = (empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout
$response_timeout = (empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout
//print extension_loaded('soap');
- if ($proxyuse)
- {
+ if ($proxyuse) {
$params = array('connection_timeout'=>$timeout,
'response_timeout'=>$response_timeout,
'proxy_use' => 1,
@@ -1761,12 +2056,10 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
if (preg_match('/^([^@]+)@([^@]+)$/i', $objecttype, $regs)) {
$myobject = $regs[1];
$module = $regs[2];
- }
- else {
+ } else {
// Parse $objecttype (ex: project_task)
$module = $myobject = $objecttype;
- if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
- {
+ if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
$module = $regs[1];
$myobject = $regs[2];
}
@@ -1829,6 +2122,11 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
$module = 'mrp';
$myobject = 'mo';
}
+ elseif ($objecttype == 'productlot') {
+ $classpath = 'product/stock/class';
+ $module = 'stock';
+ $myobject = 'productlot';
+ }
// Generic case for $classfile and $classname
$classfile = strtolower($myobject); $classname = ucfirst($myobject);
@@ -1844,26 +2142,21 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
$classname = 'CommandeFournisseur';
$classpath = 'fourn/class';
$module = 'fournisseur';
- }
- elseif ($objecttype == 'supplier_proposal') {
+ } elseif ($objecttype == 'supplier_proposal') {
$classfile = 'supplier_proposal';
$classname = 'SupplierProposal';
$classpath = 'supplier_proposal/class';
$module = 'supplier_proposal';
- }
- elseif ($objecttype == 'stock') {
+ } elseif ($objecttype == 'stock') {
$classpath = 'product/stock/class';
$classfile = 'entrepot';
$classname = 'Entrepot';
}
- if (!empty($conf->$module->enabled))
- {
+ if (!empty($conf->$module->enabled)) {
$res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
- if ($res)
- {
- if (class_exists($classname))
- {
+ if ($res) {
+ if (class_exists($classname)) {
$object = new $classname($db);
$res = $object->fetch($objectid);
if ($res > 0) {
@@ -1872,7 +2165,9 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
$ret = $langs->trans('Deleted');
}
unset($object);
- } else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
+ } else {
+ dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
+ }
}
}
return $ret;
@@ -1896,33 +2191,30 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
// Get list of all id in array listofid and all parents in array listofparentid
$sql = 'SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$num = $db->num_rows($resql);
$i = 0;
- while ($i < $num)
- {
+ while ($i < $num) {
$obj = $db->fetch_object($resql);
$listofid[] = $obj->rowid;
- if ($obj->parent_id > 0) $listofparentid[$obj->rowid] = $obj->parent_id;
+ if ($obj->parent_id > 0) {
+ $listofparentid[$obj->rowid] = $obj->parent_id;
+ }
$i++;
}
} else {
dol_print_error($db);
}
- if (count($listofid))
- {
+ if (count($listofid)) {
print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'." \n";
// Check loops on each other
$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$nb = $db->affected_rows($sql);
- if ($nb > 0)
- {
+ if ($nb > 0) {
print ' Some record that were parent of themself were cleaned.';
}
@@ -1932,17 +2224,14 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
// Check other loops
$listofidtoclean = array();
- foreach ($listofparentid as $id => $pid)
- {
+ foreach ($listofparentid as $id => $pid) {
// Check depth
//print 'Analyse record id='.$id.' with parent '.$pid.' ';
$cursor = $id; $arrayidparsed = array(); // We start from child $id
- while ($cursor > 0)
- {
+ while ($cursor > 0) {
$arrayidparsed[$cursor] = 1;
- if ($arrayidparsed[$listofparentid[$cursor]]) // We detect a loop. A record with a parent that was already into child
- {
+ if ($arrayidparsed[$listofparentid[$cursor]]) { // We detect a loop. A record with a parent that was already into child
print 'Found a loop between id '.$id.' - '.$cursor.' ';
unset($arrayidparsed);
$listofidtoclean[$cursor] = $id;
@@ -1951,18 +2240,18 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
$cursor = $listofparentid[$cursor];
}
- if (count($listofidtoclean)) break;
+ if (count($listofidtoclean)) {
+ break;
+ }
}
$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
$sql .= " SET ".$fieldfkparent." = 0";
$sql .= " WHERE rowid IN (".join(',', $listofidtoclean).")"; // So we update only records detected wrong
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$nb = $db->affected_rows($sql);
- if ($nb > 0)
- {
+ if ($nb > 0) {
// Removed orphelins records
print ' Some records were detected to have parent that is a child, we set them as root record for id: ';
print join(',', $listofidtoclean);
@@ -1977,11 +2266,9 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
$sql .= " SET ".$fieldfkparent." = 0";
$sql .= " WHERE ".$fieldfkparent." NOT IN (".join(',', $listofid).")"; // So we update only records linked to a non existing parent
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$nb = $db->affected_rows($sql);
- if ($nb > 0)
- {
+ if ($nb > 0) {
// Removed orphelins records
print ' Some orphelins were found and modified to be parent so records are visible again for id: ';
print join(',', $listofid);
@@ -2008,8 +2295,12 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
*/
function colorArrayToHex($arraycolor, $colorifnotfound = '888888')
{
- if (!is_array($arraycolor)) return $colorifnotfound;
- if (empty($arraycolor)) return $colorifnotfound;
+ if (!is_array($arraycolor)) {
+ return $colorifnotfound;
+ }
+ if (empty($arraycolor)) {
+ return $colorifnotfound;
+ }
return sprintf("%02s", dechex($arraycolor[0])).sprintf("%02s", dechex($arraycolor[1])).sprintf("%02s", dechex($arraycolor[2]));
}
@@ -2025,13 +2316,16 @@ function colorArrayToHex($arraycolor, $colorifnotfound = '888888')
*/
function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
{
- if (is_array($stringcolor)) return $stringcolor; // If already into correct output format, we return as is
+ if (is_array($stringcolor)) {
+ return $stringcolor; // If already into correct output format, we return as is
+ }
$reg = array();
$tmp = preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/', $stringcolor, $reg);
- if (!$tmp)
- {
+ if (!$tmp) {
$tmp = explode(',', $stringcolor);
- if (count($tmp) < 3) return $colorifnotfound;
+ if (count($tmp) < 3) {
+ return $colorifnotfound;
+ }
return $tmp;
}
return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3]));
@@ -2044,10 +2338,11 @@ function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
*/
function colorValidateHex($color, $allow_white = true)
{
- if (!$allow_white && ($color === '#fff' || $color === '#ffffff')) return false;
+ if (!$allow_white && ($color === '#fff' || $color === '#ffffff')) {
+ return false;
+ }
- if (preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid
- {
+ if (preg_match('/^#[a-f0-9]{6}$/i', $color)) { //hex color is valid
return true;
}
return false;
@@ -2064,7 +2359,9 @@ function colorValidateHex($color, $allow_white = true)
*/
function colorAgressiveness($hex, $ratio = -50, $brightness = 0)
{
- if (empty($ratio)) $ratio = 0; // To avoid null
+ if (empty($ratio)) {
+ $ratio = 0; // To avoid null
+ }
// Steps should be between -255 and 255. Negative = darker, positive = lighter
$ratio = max(-100, min(100, $ratio));
@@ -2081,17 +2378,23 @@ function colorAgressiveness($hex, $ratio = -50, $brightness = 0)
foreach ($color_parts as $color) {
$color = hexdec($color); // Convert to decimal
- if ($ratio > 0) // We increase aggressivity
- {
- if ($color > 127) $color += ((255 - $color) * ($ratio / 100));
- if ($color < 128) $color -= ($color * ($ratio / 100));
+ if ($ratio > 0) { // We increase aggressivity
+ if ($color > 127) {
+ $color += ((255 - $color) * ($ratio / 100));
+ }
+ if ($color < 128) {
+ $color -= ($color * ($ratio / 100));
+ }
} else // We decrease agressiveness
{
- if ($color > 128) $color -= (($color - 128) * (abs($ratio) / 100));
- if ($color < 127) $color += ((128 - $color) * (abs($ratio) / 100));
+ if ($color > 128) {
+ $color -= (($color - 128) * (abs($ratio) / 100));
+ }
+ if ($color < 127) {
+ $color += ((128 - $color) * (abs($ratio) / 100));
+ }
}
- if ($brightness > 0)
- {
+ if ($brightness > 0) {
$color = ($color * (100 + abs($brightness)) / 100);
} else {
$color = ($color * (100 - abs($brightness)) / 100);
@@ -2228,7 +2531,9 @@ function cartesianArray(array $input)
function getModuleDirForApiClass($moduleobject)
{
$moduledirforclass = $moduleobject;
- if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass);
+ if ($moduledirforclass != 'api') {
+ $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass);
+ }
if ($moduleobject == 'contracts') {
$moduledirforclass = 'contrat';
@@ -2298,8 +2603,7 @@ function randomColor($min = 0, $max = 255)
}
-if (!function_exists('dolEscapeXML'))
-{
+if (!function_exists('dolEscapeXML')) {
/**
* Encode string for xml usage
*
@@ -2325,25 +2629,40 @@ function autoOrManual($automaticmanual, $case = 1, $color = 0)
{
global $langs;
$result = 'unknown'; $classname = '';
- if ($automaticmanual == 1 || strtolower($automaticmanual) == 'automatic' || strtolower($automaticmanual) == 'true') // A mettre avant test sur no a cause du == 0
- {
+ if ($automaticmanual == 1 || strtolower($automaticmanual) == 'automatic' || strtolower($automaticmanual) == 'true') { // A mettre avant test sur no a cause du == 0
$result = $langs->trans('automatic');
- if ($case == 1 || $case == 3) $result = $langs->trans("Automatic");
- if ($case == 2) $result = ' ';
- if ($case == 3) $result = ' '.$result;
+ if ($case == 1 || $case == 3) {
+ $result = $langs->trans("Automatic");
+ }
+ if ($case == 2) {
+ $result = ' ';
+ }
+ if ($case == 3) {
+ $result = ' '.$result;
+ }
$classname = 'ok';
- } elseif ($automaticmanual == 0 || strtolower($automaticmanual) == 'manual' || strtolower($automaticmanual) == 'false')
- {
+ } elseif ($automaticmanual == 0 || strtolower($automaticmanual) == 'manual' || strtolower($automaticmanual) == 'false') {
$result = $langs->trans("manual");
- if ($case == 1 || $case == 3) $result = $langs->trans("Manual");
- if ($case == 2) $result = ' ';
- if ($case == 3) $result = ' '.$result;
+ if ($case == 1 || $case == 3) {
+ $result = $langs->trans("Manual");
+ }
+ if ($case == 2) {
+ $result = ' ';
+ }
+ if ($case == 3) {
+ $result = ' '.$result;
+ }
- if ($color == 2) $classname = 'ok';
- else $classname = 'error';
+ if ($color == 2) {
+ $classname = 'ok';
+ } else {
+ $classname = 'error';
+ }
+ }
+ if ($color) {
+ return ''.$result.' ';
}
- if ($color) return ''.$result.' ';
return $result;
}
@@ -2378,7 +2697,9 @@ function price2fec($amount)
global $conf;
// Clean parameters
- if (empty($amount)) $amount = 0; // To have a numeric value if amount not defined or = ''
+ if (empty($amount)) {
+ $amount = 0; // To have a numeric value if amount not defined or = ''
+ }
$amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
// Output decimal number by default
@@ -2402,9 +2723,15 @@ function price2fec($amount)
*/
function phpSyntaxError($code)
{
- if (!defined("CR")) define("CR", "\r");
- if (!defined("LF")) define("LF", "\n");
- if (!defined("CRLF")) define("CRLF", "\r\n");
+ if (!defined("CR")) {
+ define("CR", "\r");
+ }
+ if (!defined("LF")) {
+ define("LF", "\n");
+ }
+ if (!defined("CRLF")) {
+ define("CRLF", "\r\n");
+ }
$braces = 0;
$inString = 0;
@@ -2413,27 +2740,39 @@ function phpSyntaxError($code)
switch ($token[0]) {
case T_CURLY_OPEN:
case T_DOLLAR_OPEN_CURLY_BRACES:
- case T_START_HEREDOC: ++$inString; break;
- case T_END_HEREDOC: --$inString; break;
+ case T_START_HEREDOC:
+ ++$inString;
+ break;
+ case T_END_HEREDOC:
+ --$inString;
+ break;
}
} elseif ($inString & 1) {
switch ($token) {
case '`':
case '\'':
- case '"': --$inString; break;
+ case '"':
+ --$inString;
+ break;
}
} else {
switch ($token) {
case '`':
case '\'':
- case '"': ++$inString; break;
- case '{': ++$braces; break;
+ case '"':
+ ++$inString;
+ break;
+ case '{':
+ ++$braces;
+ break;
case '}':
if ($inString) {
--$inString;
} else {
--$braces;
- if ($braces < 0) break 2;
+ if ($braces < 0) {
+ break 2;
+ }
}
break;
}
@@ -2458,7 +2797,9 @@ function phpSyntaxError($code)
$code = $code[2] <= $braces
? array($code[1], $code[2])
: array('unexpected $end'.substr($code[1], 14), $braces);
- } else $code = array('syntax error', 0);
+ } else {
+ $code = array('syntax error', 0);
+ }
} else {
ob_end_clean();
$code = false;
diff --git a/htdocs/core/lib/functions_ch.lib.php b/htdocs/core/lib/functions_ch.lib.php
index 04e74837853..cb683ceec1f 100644
--- a/htdocs/core/lib/functions_ch.lib.php
+++ b/htdocs/core/lib/functions_ch.lib.php
@@ -158,8 +158,7 @@ function dol_ch_controle_bvrb($bvrb)
// Make control
$report = 0;
- while (dol_strlen($bv) > 1)
- {
+ while (dol_strlen($bv) > 1) {
$match = substr($bv, 0, 1);
$report = $tableau[$report][$match];
$bv = substr($bv, 1);
diff --git a/htdocs/core/lib/functionsnumtoword.lib.php b/htdocs/core/lib/functionsnumtoword.lib.php
index 930c6d06a9e..6de1e69de1f 100644
--- a/htdocs/core/lib/functionsnumtoword.lib.php
+++ b/htdocs/core/lib/functionsnumtoword.lib.php
@@ -142,10 +142,14 @@ function dol_convertToWord($num, $langs, $currency = '', $centimes = false)
$decimalpart = empty($TNum[1]) ? '' : preg_replace('/0+$/', '', $TNum[1]);
if ($decimalpart) {
- if (!empty($currency)) $concatWords .= ' '.$langs->transnoentities('and');
+ if (!empty($currency)) {
+ $concatWords .= ' '.$langs->transnoentities('and');
+ }
$concatWords .= ' '.dol_convertToWord($decimalpart, $langs, '', true);
- if (!empty($currency)) $concatWords .= ' '.$langs->transnoentities('centimes');
+ if (!empty($currency)) {
+ $concatWords .= ' '.$langs->transnoentities('centimes');
+ }
}
return $concatWords;
}
@@ -164,7 +168,9 @@ function dol_convertToWord($num, $langs, $currency = '', $centimes = false)
function dolNumberToWord($numero, $langs, $numorcurrency = 'number')
{
// If the number is negative convert to positive and return -1 if it is too long
- if ($numero < 0) $numero *= -1;
+ if ($numero < 0) {
+ $numero *= -1;
+ }
if ($numero >= 1000000000001) {
return -1;
}
@@ -172,8 +178,7 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number')
// Get 2 decimals to cents, another functions round or truncate
$strnumber = number_format($numero, 10);
$len = strlen($strnumber);
- for ($i = 0; $i < $len; $i++)
- {
+ for ($i = 0; $i < $len; $i++) {
if ($strnumber[$i] == '.') {
$parte_decimal = $strnumber[$i + 1].$strnumber[$i + 2];
break;
@@ -182,8 +187,7 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number')
/*In dolibarr 3.6.2 (my current version) doesn't have $langs->default and
in case exist why ask $lang like a parameter?*/
- if (((is_object($langs) && $langs->default == 'es_MX') || (!is_object($langs) && $langs == 'es_MX')) && $numorcurrency == 'currency')
- {
+ if (((is_object($langs) && $langs->default == 'es_MX') || (!is_object($langs) && $langs == 'es_MX')) && $numorcurrency == 'currency') {
if ($numero >= 1 && $numero < 2) {
return ("UN PESO ".$parte_decimal." / 100 M.N.");
} elseif ($numero >= 0 && $numero < 1) {
@@ -213,9 +217,11 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number')
$udMILLON = (int) ($numero / 1000000);
$numero = $numero - $udMILLON * 1000000;
$entexto .= hundreds2text($CdMILLON, $DdMILLON, $udMILLON);
- if (!$CdMMillon && !$DdMMillon && !$UdMMillon && !$CdMILLON && !$DdMILLON && $udMILLON == 1)
+ if (!$CdMMillon && !$DdMMillon && !$UdMMillon && !$CdMILLON && !$DdMILLON && $udMILLON == 1) {
$entexto .= " MILLÓN ";
- else $entexto .= " MILLONES ";
+ } else {
+ $entexto .= " MILLONES ";
+ }
}
if ($number >= 1000) {
$cdm = (int) ($numero / 100000);
@@ -225,16 +231,18 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number')
$udm = (int) ($numero / 1000);
$numero = $numero - $udm * 1000;
$entexto .= hundreds2text($cdm, $ddm, $udm);
- if ($cdm || $ddm || $udm)
+ if ($cdm || $ddm || $udm) {
$entexto .= " MIL ";
+ }
}
$c = (int) ($numero / 100);
$numero = $numero - $c * 100;
$d = (int) ($numero / 10);
$u = (int) $numero - $d * 10;
$entexto .= hundreds2text($c, $d, $u);
- if (!$cdm && !$ddm && !$udm && !$c && !$d && !$u && $number > 1000000)
+ if (!$cdm && !$ddm && !$udm && !$c && !$d && !$u && $number > 1000000) {
$entexto .= " DE";
+ }
$entexto .= " PESOS ".$parte_decimal." / 100 M.N.";
}
return $entexto;
@@ -264,7 +272,9 @@ function hundreds2text($hundreds, $tens, $units)
$entexto .= $centenas[$hundreds - 1];
}
if ($tens > 2) {
- if ($hundreds != 0) $entexto .= " ";
+ if ($hundreds != 0) {
+ $entexto .= " ";
+ }
$entexto .= $decenas[$tens - 1];
if ($units != 0) {
$entexto .= " Y ";
@@ -272,16 +282,22 @@ function hundreds2text($hundreds, $tens, $units)
}
return $entexto;
} elseif ($tens == 2) {
- if ($hundreds != 0) $entexto .= " ";
+ if ($hundreds != 0) {
+ $entexto .= " ";
+ }
$entexto .= " ".$veintis[$units];
return $entexto;
} elseif ($tens == 1) {
- if ($hundreds != 0) $entexto .= " ";
+ if ($hundreds != 0) {
+ $entexto .= " ";
+ }
$entexto .= $diecis[$units];
return $entexto;
}
if ($units != 0) {
- if ($hundreds != 0 || $tens != 0) $entexto .= " ";
+ if ($hundreds != 0 || $tens != 0) {
+ $entexto .= " ";
+ }
$entexto .= $unidades[$units - 1];
}
return $entexto;
diff --git a/htdocs/core/lib/geturl.lib.php b/htdocs/core/lib/geturl.lib.php
index 7e93623f3c1..d624e2e0ace 100644
--- a/htdocs/core/lib/geturl.lib.php
+++ b/htdocs/core/lib/geturl.lib.php
@@ -51,9 +51,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation =
$ch = curl_init();
/*print $API_Endpoint."-".$API_version."-".$PAYPAL_API_USER."-".$PAYPAL_API_PASSWORD."-".$PAYPAL_API_SIGNATURE." ";
- print $USE_PROXY."-".$gv_ApiErrorURL." ";
- print $nvpStr;
- exit;*/
+ print $USE_PROXY."-".$gv_ApiErrorURL." ";
+ print $nvpStr;
+ exit;*/
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Dolibarr geturl function');
@@ -61,12 +61,16 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation =
// We force value to false so we will manage redirection ourself later.
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
- if (is_array($addheaders) && count($addheaders)) curl_setopt($ch, CURLOPT_HTTPHEADER, $addheaders);
+ if (is_array($addheaders) && count($addheaders)) {
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $addheaders);
+ }
curl_setopt($ch, CURLINFO_HEADER_OUT, true); // To be able to retrieve request header and log it
// By default use tls decied by PHP.
// You can force, if supported a version like TLSv1 or TLSv1.2
- if (!empty($conf->global->MAIN_CURL_SSLVERSION)) curl_setopt($ch, CURLOPT_SSLVERSION, $conf->global->MAIN_CURL_SSLVERSION);
+ if (!empty($conf->global->MAIN_CURL_SSLVERSION)) {
+ curl_setopt($ch, CURLOPT_SSLVERSION, $conf->global->MAIN_CURL_SSLVERSION);
+ }
//curl_setopt($ch, CURLOPT_SSLVERSION, 6); for tls 1.2
// Turning off the server and peer verification(TrustManager Concept).
@@ -77,8 +81,12 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation =
$protocols = 0;
if (is_array($allowedschemes)) {
foreach ($allowedschemes as $allowedscheme) {
- if ($allowedscheme == 'http') $protocols |= CURLPROTO_HTTP;
- if ($allowedscheme == 'https') $protocols |= CURLPROTO_HTTPS;
+ if ($allowedscheme == 'http') {
+ $protocols |= CURLPROTO_HTTP;
+ }
+ if ($allowedscheme == 'https') {
+ $protocols |= CURLPROTO_HTTPS;
+ }
}
curl_setopt($ch, CURLOPT_PROTOCOLS, $protocols);
curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS, $protocols);
@@ -98,8 +106,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation =
} elseif ($postorget == 'PUT') {
$array_param = null;
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // HTTP request is 'PUT'
- if (!is_array($param)) parse_str($param, $array_param);
- else {
+ if (!is_array($param)) {
+ parse_str($param, $array_param);
+ } else {
dol_syslog("parameter param must be a string", LOG_WARNING);
$array_param = $param;
}
@@ -121,7 +130,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation =
dol_syslog("getURLContent set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS);
//curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10
curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT);
- if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS);
+ if ($PROXY_USER) {
+ curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS);
+ }
}
$newUrl = $url;
@@ -130,7 +141,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation =
$response = '';
do {
- if ($maxRedirection < 1) break;
+ if ($maxRedirection < 1) {
+ break;
+ }
curl_setopt($ch, CURLOPT_URL, $newUrl);
@@ -185,8 +198,7 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation =
} else {
$http_code = 0;
}
- }
- while ($http_code);
+ } while ($http_code);
$request = curl_getinfo($ch, CURLINFO_HEADER_OUT); // Reading of request must be done after sending request
@@ -263,7 +275,9 @@ function getRootURLFromURL($url)
$prefix = '';
$tmpurl = $url;
$reg = null;
- if (preg_match('/^(https?:\/\/)/i', $tmpurl, $reg)) $prefix = $reg[1];
+ if (preg_match('/^(https?:\/\/)/i', $tmpurl, $reg)) {
+ $prefix = $reg[1];
+ }
$tmpurl = preg_replace('/^https?:\/\//i', '', $tmpurl); // Remove http(s)://
$tmpurl = preg_replace('/\/.*$/i', '', $tmpurl); // Remove part after domain
diff --git a/htdocs/core/lib/holiday.lib.php b/htdocs/core/lib/holiday.lib.php
index 7b9c5d46da2..4f6da9f6d51 100644
--- a/htdocs/core/lib/holiday.lib.php
+++ b/htdocs/core/lib/holiday.lib.php
@@ -47,7 +47,9 @@ function holiday_prepare_head($object)
$nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = DOL_URL_ROOT.'/holiday/document.php?id='.$object->id;
$head[$h][1] = $langs->trans('Documents');
- if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ if (($nbFiles + $nbLinks) > 0) {
+ $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ }
$head[$h][2] = 'documents';
$h++;
diff --git a/htdocs/core/lib/images.lib.php b/htdocs/core/lib/images.lib.php
index bd392760cc5..ed7d5b1efcc 100644
--- a/htdocs/core/lib/images.lib.php
+++ b/htdocs/core/lib/images.lib.php
@@ -47,23 +47,41 @@ function image_format_supported($file, $acceptsvg = 0)
// Case filename is not a format image
$reg = array();
- if (!preg_match('/('.$regeximgext.')$/i', $file, $reg)) return -1;
+ if (!preg_match('/('.$regeximgext.')$/i', $file, $reg)) {
+ return -1;
+ }
// Case filename is a format image but not supported by this PHP
$imgfonction = '';
- if (strtolower($reg[1]) == '.gif') $imgfonction = 'imagecreatefromgif';
- if (strtolower($reg[1]) == '.jpg') $imgfonction = 'imagecreatefromjpeg';
- if (strtolower($reg[1]) == '.jpeg') $imgfonction = 'imagecreatefromjpeg';
- if (strtolower($reg[1]) == '.png') $imgfonction = 'imagecreatefrompng';
- if (strtolower($reg[1]) == '.bmp') $imgfonction = 'imagecreatefromwbmp';
- if (strtolower($reg[1]) == '.webp') $imgfonction = 'imagecreatefromwebp';
- if (strtolower($reg[1]) == '.xpm') $imgfonction = 'imagecreatefromxpm';
- if (strtolower($reg[1]) == '.xbm') $imgfonction = 'imagecreatefromxbm';
- if (strtolower($reg[1]) == '.svg') $imgfonction = 'imagecreatefromsvg'; // Never available
- if ($imgfonction)
- {
- if (!function_exists($imgfonction))
- {
+ if (strtolower($reg[1]) == '.gif') {
+ $imgfonction = 'imagecreatefromgif';
+ }
+ if (strtolower($reg[1]) == '.jpg') {
+ $imgfonction = 'imagecreatefromjpeg';
+ }
+ if (strtolower($reg[1]) == '.jpeg') {
+ $imgfonction = 'imagecreatefromjpeg';
+ }
+ if (strtolower($reg[1]) == '.png') {
+ $imgfonction = 'imagecreatefrompng';
+ }
+ if (strtolower($reg[1]) == '.bmp') {
+ $imgfonction = 'imagecreatefromwbmp';
+ }
+ if (strtolower($reg[1]) == '.webp') {
+ $imgfonction = 'imagecreatefromwebp';
+ }
+ if (strtolower($reg[1]) == '.xpm') {
+ $imgfonction = 'imagecreatefromxpm';
+ }
+ if (strtolower($reg[1]) == '.xbm') {
+ $imgfonction = 'imagecreatefromxbm';
+ }
+ if (strtolower($reg[1]) == '.svg') {
+ $imgfonction = 'imagecreatefromsvg'; // Never available
+ }
+ if ($imgfonction) {
+ if (!function_exists($imgfonction)) {
// Fonctions of conversion not available in this PHP
return 0;
}
@@ -87,16 +105,16 @@ function dol_getImageSize($file, $url = false)
{
$ret = array();
- if (image_format_supported($file) < 0) return $ret;
+ if (image_format_supported($file) < 0) {
+ return $ret;
+ }
$filetoread = $file;
- if (!$url)
- {
+ if (!$url) {
$filetoread = realpath(dol_osencode($file)); // Chemin canonique absolu de l'image
}
- if ($filetoread)
- {
+ if ($filetoread) {
$infoImg = getimagesize($filetoread); // Recuperation des infos de l'image
$ret['width'] = $infoImg[0]; // Largeur de l'image
$ret['height'] = $infoImg[1]; // Hauteur de l'image
@@ -129,25 +147,19 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0,
$file = trim($file);
// Check parameters
- if (!$file)
- {
+ if (!$file) {
// Si le fichier n'a pas ete indique
return 'Bad parameter file';
- } elseif (!file_exists($file))
- {
+ } elseif (!file_exists($file)) {
// Si le fichier passe en parametre n'existe pas
return $langs->trans("ErrorFileNotFound", $file);
- } elseif (image_format_supported($file) < 0)
- {
+ } elseif (image_format_supported($file) < 0) {
return 'This filename '.$file.' does not seem to be an image filename.';
- } elseif (!is_numeric($newWidth) && !is_numeric($newHeight))
- {
+ } elseif (!is_numeric($newWidth) && !is_numeric($newHeight)) {
return 'Wrong value for parameter newWidth or newHeight';
- } elseif ($mode == 0 && $newWidth <= 0 && $newHeight <= 0)
- {
+ } elseif ($mode == 0 && $newWidth <= 0 && $newHeight <= 0) {
return 'At least newHeight or newWidth must be defined for resizing';
- } elseif ($mode == 1 && ($newWidth <= 0 || $newHeight <= 0))
- {
+ } elseif ($mode == 1 && ($newWidth <= 0 || $newHeight <= 0)) {
return 'Both newHeight or newWidth must be defined for croping';
}
@@ -157,21 +169,17 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0,
$imgWidth = $infoImg[0]; // Largeur de l'image
$imgHeight = $infoImg[1]; // Hauteur de l'image
- if ($mode == 0) // If resize, we check parameters
- {
- if ($newWidth <= 0)
- {
+ if ($mode == 0) { // If resize, we check parameters
+ if ($newWidth <= 0) {
$newWidth = intval(($newHeight / $imgHeight) * $imgWidth); // Keep ratio
}
- if ($newHeight <= 0)
- {
+ if ($newHeight <= 0) {
$newHeight = intval(($newWidth / $imgWidth) * $imgHeight); // Keep ratio
}
}
$imgfonction = '';
- switch ($infoImg[2])
- {
+ switch ($infoImg[2]) {
case 1: // IMG_GIF
$imgfonction = 'imagecreatefromgif';
break;
@@ -188,18 +196,15 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0,
$imgfonction = 'imagecreatefromwebp';
break;
}
- if ($imgfonction)
- {
- if (!function_exists($imgfonction))
- {
+ if ($imgfonction) {
+ if (!function_exists($imgfonction)) {
// Fonctions de conversion non presente dans ce PHP
return 'Resize not possible. This PHP does not support GD functions '.$imgfonction;
}
}
// Initialisation des variables selon l'extension de l'image
- switch ($infoImg[2])
- {
+ switch ($infoImg[2]) {
case 1: // Gif
$img = imagecreatefromgif($filetoread);
$extImg = '.gif'; // File name extension of image
@@ -228,8 +233,7 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0,
}
// Create empty image
- if ($infoImg[2] == 1)
- {
+ if ($infoImg[2] == 1) {
// Compatibilite image GIF
$imgThumb = imagecreate($newWidth, $newHeight);
} else {
@@ -237,20 +241,17 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0,
}
// Activate antialiasing for better quality
- if (function_exists('imageantialias'))
- {
+ if (function_exists('imageantialias')) {
imageantialias($imgThumb, true);
}
// This is to keep transparent alpha channel if exists (PHP >= 4.2)
- if (function_exists('imagesavealpha'))
- {
+ if (function_exists('imagesavealpha')) {
imagesavealpha($imgThumb, true);
}
// Initialisation des variables selon l'extension de l'image
- switch ($infoImg[2])
- {
+ switch ($infoImg[2]) {
case 1: // Gif
$trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // On procede autrement pour le format GIF
imagecolortransparent($imgThumb, $trans_colour);
@@ -269,7 +270,9 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0,
$trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 127);
break;
}
- if (function_exists("imagefill")) imagefill($imgThumb, 0, 0, $trans_colour);
+ if (function_exists("imagefill")) {
+ imagefill($imgThumb, 0, 0, $trans_colour);
+ }
dol_syslog("dol_imageResizeOrCrop: convert image from ($imgWidth x $imgHeight) at position ($src_x x $src_y) to ($newWidth x $newHeight) as $extImg, newquality=$newquality");
//imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee
@@ -282,8 +285,7 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0,
//fclose($fp);
// Create image on disk
- switch ($infoImg[2])
- {
+ switch ($infoImg[2]) {
case 1: // Gif
imagegif($imgThumb, $imgThumbName);
break;
@@ -302,7 +304,9 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0,
}
// Set permissions on file
- if (!empty($conf->global->MAIN_UMASK)) @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK));
+ if (!empty($conf->global->MAIN_UMASK)) {
+ @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK));
+ }
// Free memory. This does not delete image.
imagedestroy($img);
@@ -359,8 +363,7 @@ function correctExifImageOrientation($fileSource, $fileDest, $quality = 95)
break;
}
if ($deg) {
- if ($infoImg[2] === 'IMAGETYPE_PNG') // In fact there is no exif on PNG but just in case
- {
+ if ($infoImg[2] === 'IMAGETYPE_PNG') { // In fact there is no exif on PNG but just in case
imagealphablending($img, false);
imagesavealpha($img, true);
$img = imagerotate($img, $deg, imageColorAllocateAlpha($img, 0, 0, 0, 127));
@@ -378,8 +381,7 @@ function correctExifImageOrientation($fileSource, $fileDest, $quality = 95)
// Create image on disk
$image = false;
- switch ($infoImg[2])
- {
+ switch ($infoImg[2]) {
case IMAGETYPE_GIF: // 1
$image = imagegif($img, $fileDest);
break;
@@ -434,17 +436,14 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
$file = trim($file);
// Check parameters
- if (!$file)
- {
+ if (!$file) {
// Si le fichier n'a pas ete indique
return 'ErrorBadParameters';
- } elseif (!file_exists($file))
- {
+ } elseif (!file_exists($file)) {
// Si le fichier passe en parametre n'existe pas
dol_syslog($langs->trans("ErrorFileNotFound", $file), LOG_ERR);
return $langs->trans("ErrorFileNotFound", $file);
- } elseif (image_format_supported($file) < 0)
- {
+ } elseif (image_format_supported($file) < 0) {
dol_syslog('This file '.$file.' does not seem to be an image format file name.', LOG_WARNING);
return 'ErrorBadImageFormat';
} elseif (!is_numeric($maxWidth) || empty($maxWidth) || $maxWidth < -1) {
@@ -471,20 +470,22 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
}
}
- if ($maxWidth == -1) $maxWidth = $infoImg[0]; // If size is -1, we keep unchanged
- if ($maxHeight == -1) $maxHeight = $infoImg[1]; // If size is -1, we keep unchanged
+ if ($maxWidth == -1) {
+ $maxWidth = $infoImg[0]; // If size is -1, we keep unchanged
+ }
+ if ($maxHeight == -1) {
+ $maxHeight = $infoImg[1]; // If size is -1, we keep unchanged
+ }
// Si l'image est plus petite que la largeur et la hauteur max, on ne cree pas de vignette
- if ($infoImg[0] < $maxWidth && $infoImg[1] < $maxHeight)
- {
+ if ($infoImg[0] < $maxWidth && $infoImg[1] < $maxHeight) {
// On cree toujours les vignettes
dol_syslog("File size is smaller than thumb size", LOG_DEBUG);
//return 'Le fichier '.$file.' ne necessite pas de creation de vignette';
}
$imgfonction = '';
- switch ($infoImg[2])
- {
+ switch ($infoImg[2]) {
case IMAGETYPE_GIF: // 1
$imgfonction = 'imagecreatefromgif';
break;
@@ -501,10 +502,8 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
$imgfonction = 'imagecreatefromwbmp';
break;
}
- if ($imgfonction)
- {
- if (!function_exists($imgfonction))
- {
+ if ($imgfonction) {
+ if (!function_exists($imgfonction)) {
// Fonctions de conversion non presente dans ce PHP
return 'Error: Creation of thumbs not possible. This PHP does not support GD function '.$imgfonction;
}
@@ -516,8 +515,7 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
// Initialisation des variables selon l'extension de l'image
$img = null;
- switch ($infoImg[2])
- {
+ switch ($infoImg[2]) {
case IMAGETYPE_GIF: // 1
$img = imagecreatefromgif($filetoread);
$extImg = '.gif'; // Extension de l'image
@@ -540,16 +538,14 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
break;
}
- if (!is_resource($img))
- {
+ if (!is_resource($img)) {
dol_syslog('Failed to detect type of image. We found infoImg[2]='.$infoImg[2], LOG_WARNING);
return 0;
}
$exifAngle = false;
if ($ort && !empty($conf->global->MAIN_USE_EXIF_ROTATION)) {
- switch ($ort)
- {
+ switch ($ort) {
case 3: // 180 rotate left
$exifAngle = 180;
break;
@@ -568,12 +564,10 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
}
}
- if ($exifAngle)
- {
+ if ($exifAngle) {
$rotated = false;
- if ($infoImg[2] === 'IMAGETYPE_PNG') // In fact there is no exif on PNG but just in case
- {
+ if ($infoImg[2] === 'IMAGETYPE_PNG') { // In fact there is no exif on PNG but just in case
imagealphablending($img, false);
imagesavealpha($img, true);
$rotated = imagerotate($img, $exifAngle, imageColorAllocateAlpha($img, 0, 0, 0, 127));
@@ -592,15 +586,18 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
}
// Initialisation des dimensions de la vignette si elles sont superieures a l'original
- if ($maxWidth > $imgWidth) { $maxWidth = $imgWidth; }
- if ($maxHeight > $imgHeight) { $maxHeight = $imgHeight; }
+ if ($maxWidth > $imgWidth) {
+ $maxWidth = $imgWidth;
+ }
+ if ($maxHeight > $imgHeight) {
+ $maxHeight = $imgHeight;
+ }
$whFact = $maxWidth / $maxHeight; // Facteur largeur/hauteur des dimensions max de la vignette
$imgWhFact = $imgWidth / $imgHeight; // Facteur largeur/hauteur de l'original
// Fixe les dimensions de la vignette
- if ($whFact < $imgWhFact)
- {
+ if ($whFact < $imgWhFact) {
// Si largeur determinante
$thumbWidth = $maxWidth;
$thumbHeight = $thumbWidth / $imgWhFact;
@@ -613,11 +610,12 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
$thumbWidth = round($thumbWidth);
// Define target format
- if (empty($targetformat)) $targetformat = $infoImg[2];
+ if (empty($targetformat)) {
+ $targetformat = $infoImg[2];
+ }
// Create empty image
- if ($targetformat == IMAGETYPE_GIF)
- {
+ if ($targetformat == IMAGETYPE_GIF) {
// Compatibilite image GIF
$imgThumb = imagecreate($thumbWidth, $thumbHeight);
} else {
@@ -625,21 +623,18 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
}
// Activate antialiasing for better quality
- if (function_exists('imageantialias'))
- {
+ if (function_exists('imageantialias')) {
imageantialias($imgThumb, true);
}
// This is to keep transparent alpha channel if exists (PHP >= 4.2)
- if (function_exists('imagesavealpha'))
- {
+ if (function_exists('imagesavealpha')) {
imagesavealpha($imgThumb, true);
}
// Initialisation des variables selon l'extension de l'image
// $targetformat is 0 by default, in such case, we keep original extension
- switch ($targetformat)
- {
+ switch ($targetformat) {
case IMAGETYPE_GIF: // 1
$trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // On procede autrement pour le format GIF
imagecolortransparent($imgThumb, $trans_colour);
@@ -669,7 +664,9 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
$newquality = 'NU';
break;
}
- if (function_exists("imagefill")) imagefill($imgThumb, 0, 0, $trans_colour);
+ if (function_exists("imagefill")) {
+ imagefill($imgThumb, 0, 0, $trans_colour);
+ }
dol_syslog("vignette: convert image from ($imgWidth x $imgHeight) to ($thumbWidth x $thumbHeight) as $extImg, newquality=$newquality");
//imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee
@@ -686,8 +683,7 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
//fclose($fp);
// Create image on disk
- switch ($targetformat)
- {
+ switch ($targetformat) {
case IMAGETYPE_GIF: // 1
imagegif($imgThumb, $imgThumbName);
break;
@@ -706,7 +702,9 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small',
}
// Set permissions on file
- if (!empty($conf->global->MAIN_UMASK)) @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK));
+ if (!empty($conf->global->MAIN_UMASK)) {
+ @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK));
+ }
// Free memory. This does not delete image.
imagedestroy($img);
diff --git a/htdocs/core/lib/import.lib.php b/htdocs/core/lib/import.lib.php
index 385dee32a86..a9663795988 100644
--- a/htdocs/core/lib/import.lib.php
+++ b/htdocs/core/lib/import.lib.php
@@ -36,13 +36,14 @@ function import_prepare_head($param, $maxstep = 0)
{
global $langs;
- if (empty($maxstep)) $maxstep = 6;
+ if (empty($maxstep)) {
+ $maxstep = 6;
+ }
$h = 0;
$head = array();
$i = 1;
- while ($i <= $maxstep)
- {
+ while ($i <= $maxstep) {
if ($i < 6) {
$head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step='.$i.$param;
} else {
diff --git a/htdocs/core/lib/invoice.lib.php b/htdocs/core/lib/invoice.lib.php
index eda1a901986..89e7f8c8e55 100644
--- a/htdocs/core/lib/invoice.lib.php
+++ b/htdocs/core/lib/invoice.lib.php
@@ -45,32 +45,37 @@ function facture_prepare_head($object)
$head[$h][2] = 'compta';
$h++;
- if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
- {
+ if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
$nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external'));
$head[$h][0] = DOL_URL_ROOT.'/compta/facture/contact.php?facid='.$object->id;
$head[$h][1] = $langs->trans('ContactsAddresses');
- if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.' ';
+ if ($nbContact > 0) {
+ $head[$h][1] .= ''.$nbContact.' ';
+ }
$head[$h][2] = 'contact';
$h++;
}
- if (!empty($conf->prelevement->enabled))
- {
+ if (!empty($conf->prelevement->enabled)) {
$nbStandingOrders = 0;
$sql = "SELECT COUNT(pfd.rowid) as nb";
$sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
$sql .= " WHERE pfd.fk_facture = ".$object->id;
$sql .= " AND pfd.ext_payment_id IS NULL";
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $db->fetch_object($resql);
- if ($obj) $nbStandingOrders = $obj->nb;
- } else dol_print_error($db);
+ if ($obj) {
+ $nbStandingOrders = $obj->nb;
+ }
+ } else {
+ dol_print_error($db);
+ }
$head[$h][0] = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$object->id;
$head[$h][1] = $langs->trans('StandingOrders');
- if ($nbStandingOrders > 0) $head[$h][1] .= ''.$nbStandingOrders.' ';
+ if ($nbStandingOrders > 0) {
+ $head[$h][1] .= ''.$nbStandingOrders.' ';
+ }
$head[$h][2] = 'standingorders';
$h++;
}
@@ -81,14 +86,19 @@ function facture_prepare_head($object)
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $h, 'invoice');
- if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
- {
+ if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
$nbNote = 0;
- if (!empty($object->note_private)) $nbNote++;
- if (!empty($object->note_public)) $nbNote++;
+ if (!empty($object->note_private)) {
+ $nbNote++;
+ }
+ if (!empty($object->note_public)) {
+ $nbNote++;
+ }
$head[$h][0] = DOL_URL_ROOT.'/compta/facture/note.php?facid='.$object->id;
$head[$h][1] = $langs->trans('Notes');
- if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.' ';
+ if ($nbNote > 0) {
+ $head[$h][1] .= ''.$nbNote.' ';
+ }
$head[$h][2] = 'note';
$h++;
}
@@ -100,7 +110,9 @@ function facture_prepare_head($object)
$nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = DOL_URL_ROOT.'/compta/facture/document.php?facid='.$object->id;
$head[$h][1] = $langs->trans('Documents');
- if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ if (($nbFiles + $nbLinks) > 0) {
+ $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ }
$head[$h][2] = 'documents';
$h++;
diff --git a/htdocs/core/lib/invoice2.lib.php b/htdocs/core/lib/invoice2.lib.php
index f38292cb50d..ca5fc61b60a 100644
--- a/htdocs/core/lib/invoice2.lib.php
+++ b/htdocs/core/lib/invoice2.lib.php
@@ -53,85 +53,106 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
$sqlwhere = '';
$sqlorder = '';
- if (in_array('all', $filter))
- {
+ if (in_array('all', $filter)) {
$sqlorder = " ORDER BY f.ref ASC";
}
- if (in_array('date', $filter))
- {
- if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
- else $sqlwhere .= " AND";
+ if (in_array('date', $filter)) {
+ if (empty($sqlwhere)) {
+ $sqlwhere = ' WHERE ';
+ } else {
+ $sqlwhere .= " AND";
+ }
$sqlwhere .= " f.fk_statut > 0";
$sqlwhere .= " AND f.datef >= '".$db->idate($dateafterdate)."'";
$sqlwhere .= " AND f.datef <= '".$db->idate($datebeforedate)."'";
$sqlorder = " ORDER BY f.datef ASC";
}
- if (in_array('nopayment', $filter))
- {
+ if (in_array('nopayment', $filter)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
- if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
- else $sqlwhere .= " AND";
+ if (empty($sqlwhere)) {
+ $sqlwhere = ' WHERE ';
+ } else {
+ $sqlwhere .= " AND";
+ }
$sqlwhere .= " f.fk_statut > 0";
$sqlwhere .= " AND pf.fk_paiement IS NULL";
}
- if (in_array('payments', $filter) || in_array('bank', $filter))
- {
+ if (in_array('payments', $filter) || in_array('bank', $filter)) {
$sql .= ", ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."paiement as p";
- if (in_array('bank', $filter)) $sql .= ", ".MAIN_DB_PREFIX."bank as b";
- if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
- else $sqlwhere .= " AND";
+ if (in_array('bank', $filter)) {
+ $sql .= ", ".MAIN_DB_PREFIX."bank as b";
+ }
+ if (empty($sqlwhere)) {
+ $sqlwhere = ' WHERE ';
+ } else {
+ $sqlwhere .= " AND";
+ }
$sqlwhere .= " f.fk_statut > 0";
$sqlwhere .= " AND f.rowid = pf.fk_facture";
$sqlwhere .= " AND pf.fk_paiement = p.rowid";
- if (in_array('payments', $filter))
- {
+ if (in_array('payments', $filter)) {
$sqlwhere .= " AND p.datep >= '".$db->idate($paymentdateafter)."'";
$sqlwhere .= " AND p.datep <= '".$db->idate($paymentdatebefore)."'";
}
- if (in_array('bank', $filter))
- {
+ if (in_array('bank', $filter)) {
$sqlwhere .= " AND p.fk_bank = b.rowid";
$sqlwhere .= " AND b.fk_account = ".$paymentbankid;
}
$sqlorder = " ORDER BY p.datep ASC";
}
- if (in_array('nodeposit', $filter))
- {
- if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
- else $sqlwhere .= " AND";
+ if (in_array('nodeposit', $filter)) {
+ if (empty($sqlwhere)) {
+ $sqlwhere = ' WHERE ';
+ } else {
+ $sqlwhere .= " AND";
+ }
$sqlwhere .= ' type <> 3';
}
- if (in_array('noreplacement', $filter))
- {
- if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
- else $sqlwhere .= " AND";
+ if (in_array('noreplacement', $filter)) {
+ if (empty($sqlwhere)) {
+ $sqlwhere = ' WHERE ';
+ } else {
+ $sqlwhere .= " AND";
+ }
$sqlwhere .= ' type <> 1';
}
- if (in_array('nocreditnote', $filter))
- {
- if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
- else $sqlwhere .= " AND";
+ if (in_array('nocreditnote', $filter)) {
+ if (empty($sqlwhere)) {
+ $sqlwhere = ' WHERE ';
+ } else {
+ $sqlwhere .= " AND";
+ }
$sqlwhere .= ' type <> 2';
}
- if (in_array('excludethirdparties', $filter) && is_array($thirdpartiesid))
- {
- if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
- else $sqlwhere .= " AND";
+ if (in_array('excludethirdparties', $filter) && is_array($thirdpartiesid)) {
+ if (empty($sqlwhere)) {
+ $sqlwhere = ' WHERE ';
+ } else {
+ $sqlwhere .= " AND";
+ }
$sqlwhere .= ' f.fk_soc NOT IN ('.join(',', $thirdpartiesid).')';
}
- if (in_array('onlythirdparties', $filter) && is_array($thirdpartiesid))
- {
- if (empty($sqlwhere)) $sqlwhere = ' WHERE ';
- else $sqlwhere .= " AND";
+ if (in_array('onlythirdparties', $filter) && is_array($thirdpartiesid)) {
+ if (empty($sqlwhere)) {
+ $sqlwhere = ' WHERE ';
+ } else {
+ $sqlwhere .= " AND";
+ }
$sqlwhere .= ' f.fk_soc IN ('.join(',', $thirdpartiesid).')';
}
- if ($sqlwhere) $sql .= $sqlwhere;
- if ($sqlorder) $sql .= $sqlorder;
+ if ($sqlwhere) {
+ $sql .= $sqlwhere;
+ }
+ if ($sqlorder) {
+ $sql .= $sqlorder;
+ }
//print $sql; exit;
dol_syslog("scripts/invoices/rebuild_merge.php:", LOG_DEBUG);
- if ($usestdout) print '--- start'."\n";
+ if ($usestdout) {
+ print '--- start'."\n";
+ }
// Start of transaction
//$db->begin();
@@ -141,54 +162,53 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
$files = array(); // liste les fichiers
dol_syslog("scripts/invoices/rebuild_merge.php", LOG_DEBUG);
- if ($resql = $db->query($sql))
- {
+ if ($resql = $db->query($sql)) {
$num = $db->num_rows($resql);
$cpt = 0;
$oldemail = '';
$message = '';
$total = '';
- if ($num)
- {
+ if ($num) {
// First loop on each resultset to build PDF
// -----------------------------------------
- while ($cpt < $num)
- {
+ while ($cpt < $num) {
$obj = $db->fetch_object($resql);
$fac = new Facture($db);
$result = $fac->fetch($obj->rowid);
- if ($result > 0)
- {
+ if ($result > 0) {
$outputlangs = $langs;
- if (!empty($newlangid))
- {
- if ($outputlangs->defaultlang != $newlangid)
- {
+ if (!empty($newlangid)) {
+ if ($outputlangs->defaultlang != $newlangid) {
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlangid);
}
}
$filename = $conf->facture->dir_output.'/'.$fac->ref.'/'.$fac->ref.'.pdf';
- if ($regenerate || !dol_is_file($filename))
- {
- if ($usestdout) print "Build PDF for invoice ".$obj->ref." - Lang = ".$outputlangs->defaultlang."\n";
+ if ($regenerate || !dol_is_file($filename)) {
+ if ($usestdout) {
+ print "Build PDF for invoice ".$obj->ref." - Lang = ".$outputlangs->defaultlang."\n";
+ }
$result = $fac->generateDocument($regenerate ? $regenerate : $fac->model_pdf, $outputlangs);
} else {
- if ($usestdout) print "PDF for invoice ".$obj->ref." already exists\n";
+ if ($usestdout) {
+ print "PDF for invoice ".$obj->ref." already exists\n";
+ }
}
// Add file into files array
$files[] = $filename;
}
- if ($result <= 0)
- {
+ if ($result <= 0) {
$error++;
- if ($usestdout) print "Error: Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid)."\n";
- else dol_syslog("Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid), LOG_ERR);
+ if ($usestdout) {
+ print "Error: Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid)."\n";
+ } else {
+ dol_syslog("Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid), LOG_ERR);
+ }
}
$cpt++;
@@ -201,8 +221,11 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
$page_hauteur = $formatarray['height'];
$format = array($page_largeur, $page_hauteur);
- if ($usestdout) print "Using output PDF format ".join('x', $format)."\n";
- else dol_syslog("Using output PDF format ".join('x', $format), LOG_ERR);
+ if ($usestdout) {
+ print "Using output PDF format ".join('x', $format)."\n";
+ } else {
+ dol_syslog("Using output PDF format ".join('x', $format), LOG_ERR);
+ }
// Now, build a merged files with all files in $files array
@@ -210,26 +233,28 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
// Create empty PDF
$pdf = pdf_getInstance($format);
- if (class_exists('TCPDF'))
- {
+ if (class_exists('TCPDF')) {
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
}
$pdf->SetFont(pdf_getPDFFont($langs));
- if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);
+ if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) {
+ $pdf->SetCompression(false);
+ }
//$pdf->SetCompression(false);
// Add all others
- foreach ($files as $file)
- {
- if ($usestdout) print "Merge PDF file for invoice ".$file."\n";
- else dol_syslog("Merge PDF file for invoice ".$file);
+ foreach ($files as $file) {
+ if ($usestdout) {
+ print "Merge PDF file for invoice ".$file."\n";
+ } else {
+ dol_syslog("Merge PDF file for invoice ".$file);
+ }
// Charge un document PDF depuis un fichier.
$pagecount = $pdf->setSourceFile($file);
- for ($i = 1; $i <= $pagecount; $i++)
- {
+ for ($i = 1; $i <= $pagecount; $i++) {
$tplidx = $pdf->importPage($i);
$s = $pdf->getTemplatesize($tplidx);
$pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
@@ -242,27 +267,36 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
// Save merged file
$filename = $fileprefix;
- if (empty($filename)) $filename = 'mergedpdf';
- if (!empty($filesuffix)) $filename .= '_'.$filesuffix;
+ if (empty($filename)) {
+ $filename = 'mergedpdf';
+ }
+ if (!empty($filesuffix)) {
+ $filename .= '_'.$filesuffix;
+ }
$file = $diroutputpdf.'/'.$filename.'.pdf';
- if (!$error && $pagecount)
- {
+ if (!$error && $pagecount) {
$pdf->Output($file, 'F');
- if (!empty($conf->global->MAIN_UMASK))
+ if (!empty($conf->global->MAIN_UMASK)) {
@chmod($file, octdec($conf->global->MAIN_UMASK));
+ }
}
- if ($usestdout)
- {
- if (!$error) print "Merged PDF has been built in ".$file."\n";
- else print "Can't build PDF ".$file."\n";
+ if ($usestdout) {
+ if (!$error) {
+ print "Merged PDF has been built in ".$file."\n";
+ } else {
+ print "Can't build PDF ".$file."\n";
+ }
}
$result = 1;
} else {
- if ($usestdout) print "No invoices found for criteria.\n";
- else dol_syslog("No invoices found for criteria");
+ if ($usestdout) {
+ print "No invoices found for criteria.\n";
+ } else {
+ dol_syslog("No invoices found for criteria");
+ }
$result = 0;
}
} else {
@@ -271,6 +305,9 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
$error++;
}
- if ($error) return -1;
- else return $result;
+ if ($error) {
+ return -1;
+ } else {
+ return $result;
+ }
}
diff --git a/htdocs/core/lib/json.lib.php b/htdocs/core/lib/json.lib.php
index cd48bbcb3c7..fe50503ed99 100644
--- a/htdocs/core/lib/json.lib.php
+++ b/htdocs/core/lib/json.lib.php
@@ -23,8 +23,7 @@
* \ingroup core
*/
-if (!function_exists('json_encode'))
-{
+if (!function_exists('json_encode')) {
/**
* Implement json_encode for PHP that does not have module enabled.
*
@@ -50,26 +49,32 @@ function dol_json_encode($elements)
dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING);
$num = 0;
- if (is_object($elements)) // Count number of properties for an object
- {
- foreach ($elements as $key => $value) $num++;
+ if (is_object($elements)) { // Count number of properties for an object
+ foreach ($elements as $key => $value) {
+ $num++;
+ }
} else {
$num = count($elements);
}
//var_dump($num);
// determine type
- if (is_numeric(key($elements)) && key($elements) == 0)
- {
+ if (is_numeric(key($elements)) && key($elements) == 0) {
// indexed (list)
$keysofelements = array_keys($elements); // Elements array mus have key that does not start with 0 and end with num-1, so we will use this later.
$output = '[';
- for ($i = 0, $last = ($num - 1); $i < $num; $i++)
- {
- if (!isset($elements[$keysofelements[$i]])) continue;
- if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) $output .= json_encode($elements[$keysofelements[$i]]);
- else $output .= _val($elements[$keysofelements[$i]]);
- if ($i !== $last) $output .= ',';
+ for ($i = 0, $last = ($num - 1); $i < $num; $i++) {
+ if (!isset($elements[$keysofelements[$i]])) {
+ continue;
+ }
+ if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) {
+ $output .= json_encode($elements[$keysofelements[$i]]);
+ } else {
+ $output .= _val($elements[$keysofelements[$i]]);
+ }
+ if ($i !== $last) {
+ $output .= ',';
+ }
}
$output .= ']';
} else {
@@ -78,14 +83,22 @@ function dol_json_encode($elements)
$last = $num - 1;
$i = 0;
$tmpelements = array();
- if (is_array($elements)) $tmpelements = $elements;
- if (is_object($elements)) $tmpelements = get_object_vars($elements);
- foreach ($tmpelements as $key => $value)
- {
+ if (is_array($elements)) {
+ $tmpelements = $elements;
+ }
+ if (is_object($elements)) {
+ $tmpelements = get_object_vars($elements);
+ }
+ foreach ($tmpelements as $key => $value) {
$output .= '"'.$key.'":';
- if (is_array($value)) $output .= json_encode($value);
- else $output .= _val($value);
- if ($i !== $last) $output .= ',';
+ if (is_array($value)) {
+ $output .= json_encode($value);
+ } else {
+ $output .= _val($value);
+ }
+ if ($i !== $last) {
+ $output .= ',';
+ }
++$i;
}
$output .= '}';
@@ -109,9 +122,9 @@ function _val($val)
$strlen_var = strlen($val);
/*
- * Iterate over every character in the string,
- * escaping with a slash or encoding to UTF-8 where necessary
- */
+ * Iterate over every character in the string,
+ * escaping with a slash or encoding to UTF-8 where necessary
+ */
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($val[$c]);
@@ -192,14 +205,18 @@ function _val($val)
}
return '"'.$ascii.'"';
- } elseif (is_int($val)) return sprintf('%d', $val);
- elseif (is_float($val)) return sprintf('%F', $val);
- elseif (is_bool($val)) return ($val ? 'true' : 'false');
- else return 'null';
+ } elseif (is_int($val)) {
+ return sprintf('%d', $val);
+ } elseif (is_float($val)) {
+ return sprintf('%F', $val);
+ } elseif (is_bool($val)) {
+ return ($val ? 'true' : 'false');
+ } else {
+ return 'null';
+ }
}
-if (!function_exists('json_decode'))
-{
+if (!function_exists('json_decode')) {
/**
* Implement json_decode for PHP that does not support it
*
@@ -230,16 +247,23 @@ function dol_json_decode($json, $assoc = false)
$out = '';
$strLength = strlen($json); // Must stay strlen and not dol_strlen because we want technical length, not visible length
- for ($i = 0; $i < $strLength; $i++)
- {
- if (!$comment)
- {
- if (($json[$i] == '{') || ($json[$i] == '[')) $out .= 'array(';
- elseif (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')';
- elseif ($json[$i] == ':') $out .= ' => ';
- else $out .= $json[$i];
- } else $out .= $json[$i];
- if ($json[$i] == '"' && $json[($i - 1)] != "\\") $comment = !$comment;
+ for ($i = 0; $i < $strLength; $i++) {
+ if (!$comment) {
+ if (($json[$i] == '{') || ($json[$i] == '[')) {
+ $out .= 'array(';
+ } elseif (($json[$i] == '}') || ($json[$i] == ']')) {
+ $out .= ')';
+ } elseif ($json[$i] == ':') {
+ $out .= ' => ';
+ } else {
+ $out .= $json[$i];
+ }
+ } else {
+ $out .= $json[$i];
+ }
+ if ($json[$i] == '"' && $json[($i - 1)] != "\\") {
+ $comment = !$comment;
+ }
}
$out = _unval($out);
@@ -256,17 +280,16 @@ function dol_json_decode($json, $assoc = false)
}
// Return an object
- if (!$assoc)
- {
- if (!empty($array))
- {
+ if (!$assoc) {
+ if (!empty($array)) {
$object = false;
if (count($array) > 0) {
$object = (object) array();
}
- foreach ($array as $key => $value)
- {
- if ($key) $object->{$key} = $value;
+ foreach ($array as $key => $value) {
+ if ($key) {
+ $object->{$key} = $value;
+ }
}
return $object;
@@ -287,8 +310,7 @@ function dol_json_decode($json, $assoc = false)
function _unval($val)
{
$reg = array();
- while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg))
- {
+ while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg)) {
// single, escaped unicode character
$utf16 = chr(hexdec($reg[1])).chr(hexdec($reg[2]));
$utf8 = utf162utf8($utf16);
@@ -320,18 +342,18 @@ function utf162utf8($utf16)
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
- return chr($bytes);
+ return chr($bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
- return chr(0xC0 | (($bytes >> 6) & 0x1F))
+ return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
- return chr(0xE0 | (($bytes >> 12) & 0x0F))
+ return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
diff --git a/htdocs/core/lib/ldap.lib.php b/htdocs/core/lib/ldap.lib.php
index 640152d5999..9d6e0193108 100644
--- a/htdocs/core/lib/ldap.lib.php
+++ b/htdocs/core/lib/ldap.lib.php
@@ -43,40 +43,35 @@ function ldap_prepare_head()
$head[$h][2] = 'ldap';
$h++;
- if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE))
- {
+ if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE)) {
$head[$h][0] = DOL_URL_ROOT."/admin/ldap_users.php";
$head[$h][1] = $langs->trans("LDAPUsersSynchro");
$head[$h][2] = 'users';
$h++;
}
- if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE))
- {
+ if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE)) {
$head[$h][0] = DOL_URL_ROOT."/admin/ldap_groups.php";
$head[$h][1] = $langs->trans("LDAPGroupsSynchro");
$head[$h][2] = 'groups';
$h++;
}
- if (!empty($conf->societe->enabled) && !empty($conf->global->LDAP_CONTACT_ACTIVE))
- {
+ if (!empty($conf->societe->enabled) && !empty($conf->global->LDAP_CONTACT_ACTIVE)) {
$head[$h][0] = DOL_URL_ROOT."/admin/ldap_contacts.php";
$head[$h][1] = $langs->trans("LDAPContactsSynchro");
$head[$h][2] = 'contacts';
$h++;
}
- if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE))
- {
+ if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE)) {
$head[$h][0] = DOL_URL_ROOT."/admin/ldap_members.php";
$head[$h][1] = $langs->trans("LDAPMembersSynchro");
$head[$h][2] = 'members';
$h++;
}
- if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE))
- {
+ if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE)) {
$head[$h][0] = DOL_URL_ROOT."/admin/ldap_members_types.php";
$head[$h][1] = $langs->trans("LDAPMembersTypesSynchro");
$head[$h][2] = 'memberstypes';
@@ -111,14 +106,11 @@ function show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass)
//print 'key='.$key.' dn='.$dn.' objectclass='.$objectclass;
print ' ';
- if (!function_exists("ldap_connect"))
- {
+ if (!function_exists("ldap_connect")) {
print ''.$butlabel.' ';
- } elseif (empty($conf->global->LDAP_SERVER_HOST))
- {
+ } elseif (empty($conf->global->LDAP_SERVER_HOST)) {
print ''.$butlabel.' ';
- } elseif (empty($key) || empty($dn) || empty($objectclass))
- {
+ } elseif (empty($key) || empty($dn) || empty($objectclass)) {
$langs->load("errors");
print ''.$butlabel.' ';
} else {
@@ -144,39 +136,54 @@ function show_ldap_content($result, $level, $count, $var, $hide = 0, $subcount =
global $bc, $conf;
$count--;
- if ($count == 0) return -1; // To stop loop
- if (!is_array($result)) return -1;
+ if ($count == 0) {
+ return -1; // To stop loop
+ }
+ if (!is_array($result)) {
+ return -1;
+ }
- foreach ($result as $key => $val)
- {
- if ("$key" == "objectclass") continue;
- if ("$key" == "count") continue;
- if ("$key" == "dn") continue;
- if ("$val" == "objectclass") continue;
+ foreach ($result as $key => $val) {
+ if ("$key" == "objectclass") {
+ continue;
+ }
+ if ("$key" == "count") {
+ continue;
+ }
+ if ("$key" == "dn") {
+ continue;
+ }
+ if ("$val" == "objectclass") {
+ continue;
+ }
$lastkey[$level] = $key;
- if (is_array($val))
- {
+ if (is_array($val)) {
$hide = 0;
- if (!is_numeric($key))
- {
+ if (!is_numeric($key)) {
print '';
print '';
print $key;
print ' ';
- if (strtolower($key) == 'userpassword') $hide = 1;
+ if (strtolower($key) == 'userpassword') {
+ $hide = 1;
+ }
}
show_ldap_content($val, $level + 1, $count, $var, $hide, $val["count"]);
- } elseif ($subcount)
- {
+ } elseif ($subcount) {
$subcount--;
$newstring = dol_htmlentitiesbr($val);
- if ($hide) print preg_replace('/./i', '*', $newstring);
- else print $newstring;
+ if ($hide) {
+ print preg_replace('/./i', '*', $newstring);
+ } else {
+ print $newstring;
+ }
print ' ';
}
- if ("$val" != $lastkey[$level] && !$subcount) print ' ';
+ if ("$val" != $lastkey[$level] && !$subcount) {
+ print ' ';
+ }
}
return 1;
}
diff --git a/htdocs/core/lib/loan.lib.php b/htdocs/core/lib/loan.lib.php
index 3a34d3e57c4..c86d0ecce13 100644
--- a/htdocs/core/lib/loan.lib.php
+++ b/htdocs/core/lib/loan.lib.php
@@ -60,7 +60,9 @@ function loan_prepare_head($object)
$nbLinks = Link::count($db, $object->element, $object->id);
$head[$tab][0] = DOL_URL_ROOT.'/loan/document.php?id='.$object->id;
$head[$tab][1] = $langs->trans("Documents");
- if (($nbFiles + $nbLinks) > 0) $head[$tab][1] .= ''.($nbFiles + $nbLinks).' ';
+ if (($nbFiles + $nbLinks) > 0) {
+ $head[$tab][1] .= ''.($nbFiles + $nbLinks).' ';
+ }
$head[$tab][2] = 'documents';
$tab++;
@@ -68,7 +70,9 @@ function loan_prepare_head($object)
$nbNote = (empty($object->note_private) ? 0 : 1) + (empty($object->note_public) ? 0 : 1);
$head[$tab][0] = DOL_URL_ROOT."/loan/note.php?id=".$object->id;
$head[$tab][1] = $langs->trans("Notes");
- if ($nbNote > 0) $head[$tab][1] .= ''.$nbNote.' ';
+ if ($nbNote > 0) {
+ $head[$tab][1] .= ''.$nbNote.' ';
+ }
$head[$tab][2] = 'note';
$tab++;
}
diff --git a/htdocs/core/lib/member.lib.php b/htdocs/core/lib/member.lib.php
index 50330686805..93378d77390 100644
--- a/htdocs/core/lib/member.lib.php
+++ b/htdocs/core/lib/member.lib.php
@@ -43,8 +43,7 @@ function member_prepare_head(Adherent $object)
$h++;
if ((!empty($conf->ldap->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE))
- && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin)))
- {
+ && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin))) {
$langs->load("ldap");
$head[$h][0] = DOL_URL_ROOT.'/adherents/ldap.php?id='.$object->id;
@@ -53,13 +52,14 @@ function member_prepare_head(Adherent $object)
$h++;
}
- if (!empty($user->rights->adherent->cotisation->lire))
- {
+ if (!empty($user->rights->adherent->cotisation->lire)) {
$nbSubscription = is_array($object->subscriptions) ?count($object->subscriptions) : 0;
$head[$h][0] = DOL_URL_ROOT.'/adherents/subscription.php?rowid='.$object->id;
$head[$h][1] = $langs->trans("Subscriptions");
$head[$h][2] = 'subscription';
- if ($nbSubscription > 0) $head[$h][1] .= ''.$nbSubscription.' ';
+ if ($nbSubscription > 0) {
+ $head[$h][1] .= ''.$nbSubscription.' ';
+ }
$h++;
}
@@ -70,13 +70,21 @@ function member_prepare_head(Adherent $object)
complete_head_from_modules($conf, $langs, $object, $head, $h, 'member');
$nbNote = 0;
- if (!empty($object->note)) $nbNote++;
- if (!empty($object->note_private)) $nbNote++;
- if (!empty($object->note_public)) $nbNote++;
+ if (!empty($object->note)) {
+ $nbNote++;
+ }
+ if (!empty($object->note_private)) {
+ $nbNote++;
+ }
+ if (!empty($object->note_public)) {
+ $nbNote++;
+ }
$head[$h][0] = DOL_URL_ROOT.'/adherents/note.php?id='.$object->id;
$head[$h][1] = $langs->trans("Note");
$head[$h][2] = 'note';
- if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.' ';
+ if ($nbNote > 0) {
+ $head[$h][1] .= ''.$nbNote.' ';
+ }
$h++;
// Attachments
@@ -87,17 +95,17 @@ function member_prepare_head(Adherent $object)
$nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = DOL_URL_ROOT.'/adherents/document.php?id='.$object->id;
$head[$h][1] = $langs->trans('Documents');
- if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ if (($nbFiles + $nbLinks) > 0) {
+ $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ }
$head[$h][2] = 'document';
$h++;
// Show agenda tab
- if (!empty($conf->agenda->enabled))
- {
+ if (!empty($conf->agenda->enabled)) {
$head[$h][0] = DOL_URL_ROOT."/adherents/agenda.php?id=".$object->id;
$head[$h][1] = $langs->trans("Events");
- if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read)))
- {
+ if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
$head[$h][1] .= '/';
$head[$h][1] .= $langs->trans("Agenda");
}
@@ -129,8 +137,7 @@ function member_type_prepare_head(AdherentType $object)
$h++;
// Multilangs
- if (!empty($conf->global->MAIN_MULTILANGS))
- {
+ if (!empty($conf->global->MAIN_MULTILANGS)) {
$head[$h][0] = DOL_URL_ROOT."/adherents/type_translation.php?rowid=".$object->id;
$head[$h][1] = $langs->trans("Translation");
$head[$h][2] = 'translation';
@@ -138,8 +145,7 @@ function member_type_prepare_head(AdherentType $object)
}
if ((!empty($conf->ldap->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE))
- && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin)))
- {
+ && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin))) {
$langs->load("ldap");
$head[$h][0] = DOL_URL_ROOT.'/adherents/type_ldap.php?rowid='.$object->id;
diff --git a/htdocs/core/lib/memory.lib.php b/htdocs/core/lib/memory.lib.php
index 484b3933e42..ce603415009 100644
--- a/htdocs/core/lib/memory.lib.php
+++ b/htdocs/core/lib/memory.lib.php
@@ -71,7 +71,9 @@ function dol_setcache($memoryid, $data, $expire = 0)
$result = 0;
if (strpos($memoryid, 'count_') === 0) { // The memoryid key start with 'count_...'
- if (empty($conf->global->MAIN_CACHE_COUNT)) return 0;
+ if (empty($conf->global->MAIN_CACHE_COUNT)) {
+ return 0;
+ }
}
if (!empty($conf->memcached->enabled) && class_exists('Memcached')) {
@@ -81,7 +83,9 @@ function dol_setcache($memoryid, $data, $expire = 0)
$dolmemcache = new Memcached();
$tmparray = explode(':', $conf->global->MEMCACHED_SERVER);
$result = $dolmemcache->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211);
- if (!$result) return -1;
+ if (!$result) {
+ return -1;
+ }
}
$memoryid = session_name() . '_' . $memoryid;
@@ -100,7 +104,9 @@ function dol_setcache($memoryid, $data, $expire = 0)
$dolmemcache = new Memcache();
$tmparray = explode(':', $conf->global->MEMCACHED_SERVER);
$result = $dolmemcache->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211);
- if (!$result) return -1;
+ if (!$result) {
+ return -1;
+ }
}
$memoryid = session_name() . '_' . $memoryid;
@@ -131,7 +137,9 @@ function dol_getcache($memoryid)
global $conf;
if (strpos($memoryid, 'count_') === 0) { // The memoryid key start with 'count_...'
- if (empty($conf->global->MAIN_CACHE_COUNT)) return null;
+ if (empty($conf->global->MAIN_CACHE_COUNT)) {
+ return null;
+ }
}
// Using a memcached server
@@ -141,7 +149,9 @@ function dol_getcache($memoryid)
$m = new Memcached();
$tmparray = explode(':', $conf->global->MEMCACHED_SERVER);
$result = $m->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211);
- if (!$result) return -1;
+ if (!$result) {
+ return -1;
+ }
}
$memoryid = session_name() . '_' . $memoryid;
@@ -164,7 +174,9 @@ function dol_getcache($memoryid)
$m = new Memcache();
$tmparray = explode(':', $conf->global->MEMCACHED_SERVER);
$result = $m->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211);
- if (!$result) return -1;
+ if (!$result) {
+ return -1;
+ }
}
$memoryid = session_name() . '_' . $memoryid;
@@ -235,9 +247,13 @@ function dol_setshmop($memoryid, $data, $expire)
global $shmkeys, $shmoffset;
//print 'dol_setshmop memoryid='.$memoryid." \n";
- if (empty($shmkeys[$memoryid]) || !function_exists("shmop_write")) return 0;
+ if (empty($shmkeys[$memoryid]) || !function_exists("shmop_write")) {
+ return 0;
+ }
$shmkey = dol_getshmopaddress($memoryid);
- if (empty($shmkey)) return 0; // No key reserved for this memoryid, we can't cache this memoryid
+ if (empty($shmkey)) {
+ return 0; // No key reserved for this memoryid, we can't cache this memoryid
+ }
$newdata = serialize($data);
$size = strlen($newdata);
@@ -273,14 +289,19 @@ function dol_getshmop($memoryid)
return null;
}
$shmkey = dol_getshmopaddress($memoryid);
- if (empty($shmkey)) return null; // No key reserved for this memoryid, we can't cache this memoryid
+ if (empty($shmkey)) {
+ return null; // No key reserved for this memoryid, we can't cache this memoryid
+ }
//print 'dol_getshmop memoryid='.$memoryid." shmkey=".$shmkey." \n";
$handle = @shmop_open($shmkey, 'a', 0, 0);
if ($handle) {
$size = trim(shmop_read($handle, 0, 6));
- if ($size) $data = unserialize(shmop_read($handle, 6, $size));
- else return -1;
+ if ($size) {
+ $data = unserialize(shmop_read($handle, 6, $size));
+ } else {
+ return -1;
+ }
shmop_close($handle);
} else {
return null; // Can't open existing block, so we suppose it was not created, so nothing were cached yet for the memoryid
diff --git a/htdocs/core/lib/modulebuilder.lib.php b/htdocs/core/lib/modulebuilder.lib.php
index ff14ec56e18..0c6029ebb00 100644
--- a/htdocs/core/lib/modulebuilder.lib.php
+++ b/htdocs/core/lib/modulebuilder.lib.php
@@ -41,31 +41,30 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir =
{
global $db, $langs;
- if (empty($objectname)) return -1;
- if (empty($readdir)) $readdir = $destdir;
+ if (empty($objectname)) {
+ return -1;
+ }
+ if (empty($readdir)) {
+ $readdir = $destdir;
+ }
- if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval']))
- {
+ if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) {
dol_print_error('', 'Bad parameter addfieldentry with a property arrayofkeyval defined but that is not an array.');
return -1;
}
// Check parameters
- if (count($addfieldentry) > 0)
- {
- if (empty($addfieldentry['name']))
- {
+ if (count($addfieldentry) > 0) {
+ if (empty($addfieldentry['name'])) {
setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Name")), null, 'errors');
return -2;
}
- if (empty($addfieldentry['label']))
- {
+ if (empty($addfieldentry['label'])) {
setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Label")), null, 'errors');
return -2;
}
if (!preg_match('/^(integer|price|sellist|varchar|double|text|html|duration)/', $addfieldentry['type'])
- && !preg_match('/^(boolean|real|date|datetime|timestamp)$/', $addfieldentry['type']))
- {
+ && !preg_match('/^(boolean|real|date|datetime|timestamp)$/', $addfieldentry['type'])) {
setEventMessages($langs->trans('BadValueForType', $objectname), null, 'errors');
return -2;
}
@@ -73,8 +72,7 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir =
$pathoffiletoeditsrc = $readdir.'/class/'.strtolower($objectname).'.class.php';
$pathoffiletoedittarget = $destdir.'/class/'.strtolower($objectname).'.class.php'.($readdir != $destdir ? '.new' : '');
- if (!dol_is_file($pathoffiletoeditsrc))
- {
+ if (!dol_is_file($pathoffiletoeditsrc)) {
$langs->load("errors");
setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
return -3;
@@ -85,8 +83,11 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir =
try {
include_once $pathoffiletoeditsrc;
- if (class_exists($objectname)) $object = new $objectname($db);
- else return -4;
+ if (class_exists($objectname)) {
+ $object = new $objectname($db);
+ } else {
+ return -4;
+ }
// Backup old file
dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
@@ -95,17 +96,14 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir =
$contentclass = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
// Update ->fields (add or remove entries)
- if (count($object->fields))
- {
- if (is_array($addfieldentry) && count($addfieldentry))
- {
+ if (count($object->fields)) {
+ if (is_array($addfieldentry) && count($addfieldentry)) {
$name = $addfieldentry['name'];
unset($addfieldentry['name']);
$object->fields[$name] = $addfieldentry;
}
- if (!empty($delfieldentry))
- {
+ if (!empty($delfieldentry)) {
$name = $delfieldentry;
unset($object->fields[$name]);
}
@@ -120,40 +118,62 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir =
$texttoinsert .= "\t".' */'."\n";
$texttoinsert .= "\t".'public $fields=array('."\n";
- if (count($object->fields))
- {
- foreach ($object->fields as $key => $val)
- {
+ if (count($object->fields)) {
+ foreach ($object->fields as $key => $val) {
$i++;
$texttoinsert .= "\t\t'".$key."' => array('type'=>'".$val['type']."', 'label'=>'".$val['label']."',";
$texttoinsert .= " 'enabled'=>'".($val['enabled'] !== '' ? $val['enabled'] : 1)."',";
$texttoinsert .= " 'position'=>".($val['position'] !== '' ? $val['position'] : 50).",";
$texttoinsert .= " 'notnull'=>".(empty($val['notnull']) ? 0 : $val['notnull']).",";
$texttoinsert .= " 'visible'=>".($val['visible'] !== '' ? $val['visible'] : -1).",";
- if ($val['noteditable']) $texttoinsert .= " 'noteditable'=>'".$val['noteditable']."',";
- if ($val['default'] || $val['default'] === '0') $texttoinsert .= " 'default'=>'".$val['default']."',";
- if ($val['index']) $texttoinsert .= " 'index'=>".$val['index'].",";
- if ($val['foreignkey']) $texttoinsert .= " 'foreignkey'=>'".$val['foreignkey']."',";
- if ($val['searchall']) $texttoinsert .= " 'searchall'=>".$val['searchall'].",";
- if ($val['isameasure']) $texttoinsert .= " 'isameasure'=>'".$val['isameasure']."',";
- if ($val['css']) $texttoinsert .= " 'css'=>'".$val['css']."',";
- if ($val['help']) $texttoinsert .= " 'help'=>\"".preg_replace('/"/', '', $val['help'])."\",";
- if ($val['showoncombobox']) $texttoinsert .= " 'showoncombobox'=>'".$val['showoncombobox']."',";
- if ($val['disabled']) $texttoinsert .= " 'disabled'=>'".$val['disabled']."',";
- if ($val['autofocusoncreate']) $texttoinsert .= " 'autofocusoncreate'=>'".$val['autofocusoncreate']."',";
- if ($val['arrayofkeyval'])
- {
+ if ($val['noteditable']) {
+ $texttoinsert .= " 'noteditable'=>'".$val['noteditable']."',";
+ }
+ if ($val['default'] || $val['default'] === '0') {
+ $texttoinsert .= " 'default'=>'".$val['default']."',";
+ }
+ if ($val['index']) {
+ $texttoinsert .= " 'index'=>".$val['index'].",";
+ }
+ if ($val['foreignkey']) {
+ $texttoinsert .= " 'foreignkey'=>'".$val['foreignkey']."',";
+ }
+ if ($val['searchall']) {
+ $texttoinsert .= " 'searchall'=>".$val['searchall'].",";
+ }
+ if ($val['isameasure']) {
+ $texttoinsert .= " 'isameasure'=>'".$val['isameasure']."',";
+ }
+ if ($val['css']) {
+ $texttoinsert .= " 'css'=>'".$val['css']."',";
+ }
+ if ($val['help']) {
+ $texttoinsert .= " 'help'=>\"".preg_replace('/"/', '', $val['help'])."\",";
+ }
+ if ($val['showoncombobox']) {
+ $texttoinsert .= " 'showoncombobox'=>'".$val['showoncombobox']."',";
+ }
+ if ($val['disabled']) {
+ $texttoinsert .= " 'disabled'=>'".$val['disabled']."',";
+ }
+ if ($val['autofocusoncreate']) {
+ $texttoinsert .= " 'autofocusoncreate'=>'".$val['autofocusoncreate']."',";
+ }
+ if ($val['arrayofkeyval']) {
$texttoinsert .= " 'arrayofkeyval'=>array(";
$i = 0;
- foreach ($val['arrayofkeyval'] as $key2 => $val2)
- {
- if ($i) $texttoinsert .= ", ";
+ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
+ if ($i) {
+ $texttoinsert .= ", ";
+ }
$texttoinsert .= "'".$key2."'=>'".$val2."'";
$i++;
}
$texttoinsert .= "),";
}
- if ($val['comment']) $texttoinsert .= " 'comment'=>\"".preg_replace('/"/', '', $val['comment'])."\"";
+ if ($val['comment']) {
+ $texttoinsert .= " 'comment'=>\"".preg_replace('/"/', '', $val['comment'])."\"";
+ }
$texttoinsert .= "),\n";
}
@@ -162,12 +182,10 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir =
$texttoinsert .= "\t".');'."\n";
//print ($texttoinsert);exit;
- if (count($object->fields))
- {
+ if (count($object->fields)) {
//$typetotypephp=array('integer'=>'integer', 'duration'=>'integer', 'varchar'=>'string');
- foreach ($object->fields as $key => $val)
- {
+ foreach ($object->fields as $key => $val) {
$i++;
//$typephp=$typetotypephp[$val['type']];
$texttoinsert .= "\t".'public $'.$key.";";
@@ -192,8 +210,7 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir =
@chmod($pathoffiletoedittarget, octdec($newmask));
return $object;
- } catch (Exception $e)
- {
+ } catch (Exception $e) {
print $e->getMessage();
return -5;
}
@@ -218,8 +235,12 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '
$error = 0;
- if (empty($objectname)) return -1;
- if (empty($readdir)) $readdir = $destdir;
+ if (empty($objectname)) {
+ return -1;
+ }
+ if (empty($readdir)) {
+ $readdir = $destdir;
+ }
$pathoffiletoclasssrc = $readdir.'/class/'.strtolower($objectname).'.class.php';
@@ -232,8 +253,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '
$pathoffiletoedittarget = $destdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql'.($readdir != $destdir ? '.new' : '');
}
- if (!dol_is_file($pathoffiletoeditsrc))
- {
+ if (!dol_is_file($pathoffiletoeditsrc)) {
$langs->load("errors");
setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
return -1;
@@ -241,14 +261,15 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '
// Load object from myobject.class.php
try {
- if (!is_object($object))
- {
+ if (!is_object($object)) {
include_once $pathoffiletoclasssrc;
- if (class_exists($objectname)) $object = new $objectname($db);
- else return -1;
+ if (class_exists($objectname)) {
+ $object = new $objectname($db);
+ } else {
+ return -1;
+ }
}
- } catch (Exception $e)
- {
+ } catch (Exception $e) {
print $e->getMessage();
}
@@ -259,31 +280,41 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '
$i = 0;
$texttoinsert = '-- BEGIN MODULEBUILDER FIELDS'."\n";
- if (count($object->fields))
- {
- foreach ($object->fields as $key => $val)
- {
+ if (count($object->fields)) {
+ foreach ($object->fields as $key => $val) {
$i++;
$type = $val['type'];
$type = preg_replace('/:.*$/', '', $type); // For case type = 'integer:Societe:societe/class/societe.class.php'
- if ($type == 'html') $type = 'text'; // html modulebuilder type is a text type in database
- elseif ($type == 'price') $type = 'double'; // html modulebuilder type is a text type in database
- elseif (in_array($type, array('link', 'sellist', 'duration'))) $type = 'integer';
+ if ($type == 'html') {
+ $type = 'text'; // html modulebuilder type is a text type in database
+ } elseif ($type == 'price') {
+ $type = 'double'; // html modulebuilder type is a text type in database
+ } elseif (in_array($type, array('link', 'sellist', 'duration'))) {
+ $type = 'integer';
+ }
$texttoinsert .= "\t".$key." ".$type;
- if ($key == 'rowid') $texttoinsert .= ' AUTO_INCREMENT PRIMARY KEY';
- if ($key == 'entity') $texttoinsert .= ' DEFAULT 1';
- else {
- if ($val['default'] != '')
- {
- if (preg_match('/^null$/i', $val['default'])) $texttoinsert .= " DEFAULT NULL";
- elseif (preg_match('/varchar/', $type)) $texttoinsert .= " DEFAULT '".$db->escape($val['default'])."'";
- else $texttoinsert .= (($val['default'] > 0) ? ' DEFAULT '.$val['default'] : '');
+ if ($key == 'rowid') {
+ $texttoinsert .= ' AUTO_INCREMENT PRIMARY KEY';
+ }
+ if ($key == 'entity') {
+ $texttoinsert .= ' DEFAULT 1';
+ } else {
+ if ($val['default'] != '') {
+ if (preg_match('/^null$/i', $val['default'])) {
+ $texttoinsert .= " DEFAULT NULL";
+ } elseif (preg_match('/varchar/', $type)) {
+ $texttoinsert .= " DEFAULT '".$db->escape($val['default'])."'";
+ } else {
+ $texttoinsert .= (($val['default'] > 0) ? ' DEFAULT '.$val['default'] : '');
+ }
}
}
$texttoinsert .= (($val['notnull'] > 0) ? ' NOT NULL' : '');
- if ($i < count($object->fields)) $texttoinsert .= ", ";
+ if ($i < count($object->fields)) {
+ $texttoinsert .= ", ";
+ }
$texttoinsert .= "\n";
}
}
@@ -292,8 +323,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '
$contentsql = preg_replace('/-- BEGIN MODULEBUILDER FIELDS.*END MODULEBUILDER FIELDS/ims', $texttoinsert, $contentsql);
$result = file_put_contents($pathoffiletoedittarget, $contentsql);
- if ($result)
- {
+ if ($result) {
@chmod($pathoffiletoedittarget, octdec($newmask));
} else {
$error++;
@@ -312,21 +342,16 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '
$i = 0;
$texttoinsert = '-- BEGIN MODULEBUILDER INDEXES'."\n";
- if (count($object->fields))
- {
- foreach ($object->fields as $key => $val)
- {
+ if (count($object->fields)) {
+ foreach ($object->fields as $key => $val) {
$i++;
- if (!empty($val['index']))
- {
+ if (!empty($val['index'])) {
$texttoinsert .= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD INDEX idx_".strtolower($module).'_'.strtolower($objectname)."_".$key." (".$key.");";
$texttoinsert .= "\n";
}
- if (!empty($val['foreignkey']))
- {
+ if (!empty($val['foreignkey'])) {
$tmp = explode('.', $val['foreignkey']);
- if (!empty($tmp[0]) && !empty($tmp[1]))
- {
+ if (!empty($tmp[0]) && !empty($tmp[1])) {
$texttoinsert .= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD CONSTRAINT llx_".strtolower($module).'_'.strtolower($objectname)."_".$key." FOREIGN KEY (".$key.") REFERENCES llx_".preg_replace('/^llx_/', '', $tmp[0])."(".$tmp[1].");";
$texttoinsert .= "\n";
}
@@ -340,8 +365,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '
dol_mkdir(dirname($pathoffiletoedittarget));
$result2 = file_put_contents($pathoffiletoedittarget, $contentsql);
- if ($result)
- {
+ if ($result) {
@chmod($pathoffiletoedittarget, octdec($newmask));
} else {
$error++;
diff --git a/htdocs/core/lib/multicurrency.lib.php b/htdocs/core/lib/multicurrency.lib.php
index a3f7d56ec90..e77a9ee8081 100644
--- a/htdocs/core/lib/multicurrency.lib.php
+++ b/htdocs/core/lib/multicurrency.lib.php
@@ -65,8 +65,7 @@ function multicurrencyLimitPrepareHead($aCurrencies)
$i = 0;
$head = array();
- foreach ($aCurrencies as $currency)
- {
+ foreach ($aCurrencies as $currency) {
$head[$i][0] = $_SERVER['PHP_SELF'].'?currencycode='.$currency;
$head[$i][1] = $langs->trans("Currency".$currency).' ('.$langs->getCurrencySymbol($currency).')';
$head[$i][2] = $currency;
diff --git a/htdocs/core/lib/oauth.lib.php b/htdocs/core/lib/oauth.lib.php
index a006aad8964..48356868143 100644
--- a/htdocs/core/lib/oauth.lib.php
+++ b/htdocs/core/lib/oauth.lib.php
@@ -27,8 +27,7 @@
$supportedoauth2array = array(
'OAUTH_GOOGLE_NAME'=>'google',
);
-if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
-{
+if ($conf->global->MAIN_FEATURES_LEVEL >= 2) {
$supportedoauth2array['OAUTH_STRIPE_TEST_NAME'] = 'stripetest';
$supportedoauth2array['OAUTH_STRIPE_LIVE_NAME'] = 'stripelive';
}
diff --git a/htdocs/core/lib/order.lib.php b/htdocs/core/lib/order.lib.php
index 9bd92a2c79b..9e7d4f8d55a 100644
--- a/htdocs/core/lib/order.lib.php
+++ b/htdocs/core/lib/order.lib.php
@@ -34,43 +34,58 @@
function commande_prepare_head(Commande $object)
{
global $db, $langs, $conf, $user;
- if (!empty($conf->expedition->enabled)) $langs->load("sendings");
+ if (!empty($conf->expedition->enabled)) {
+ $langs->load("sendings");
+ }
$langs->load("orders");
$h = 0;
$head = array();
- if (!empty($conf->commande->enabled) && $user->rights->commande->lire)
- {
+ if (!empty($conf->commande->enabled) && $user->rights->commande->lire) {
$head[$h][0] = DOL_URL_ROOT.'/commande/card.php?id='.$object->id;
$head[$h][1] = $langs->trans("CustomerOrder");
$head[$h][2] = 'order';
$h++;
}
- if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
- {
+ if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
$nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external'));
$head[$h][0] = DOL_URL_ROOT.'/commande/contact.php?id='.$object->id;
$head[$h][1] = $langs->trans('ContactsAddresses');
- if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.' ';
+ if ($nbContact > 0) {
+ $head[$h][1] .= ''.$nbContact.' ';
+ }
$head[$h][2] = 'contact';
$h++;
}
if (($conf->expedition_bon->enabled && $user->rights->expedition->lire)
- || ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire))
- {
+ || ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire)) {
$nbShipments = $object->getNbOfShipments(); $nbReceiption = 0;
$head[$h][0] = DOL_URL_ROOT.'/expedition/shipment.php?id='.$object->id;
$text = '';
- if ($conf->expedition_bon->enabled) $text .= $langs->trans("Shipments");
- if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled) $text .= ' - ';
- if ($conf->delivery_note->enabled) $text .= $langs->trans("Receivings");
- if ($nbShipments > 0 || $nbReceiption > 0) $text .= ''.($nbShipments ? $nbShipments : 0);
- if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) $text .= ' - ';
- if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) $text .= ($nbReceiption ? $nbReceiption : 0);
- if ($nbShipments > 0 || $nbReceiption > 0) $text .= ' ';
+ if ($conf->expedition_bon->enabled) {
+ $text .= $langs->trans("Shipments");
+ }
+ if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled) {
+ $text .= ' - ';
+ }
+ if ($conf->delivery_note->enabled) {
+ $text .= $langs->trans("Receivings");
+ }
+ if ($nbShipments > 0 || $nbReceiption > 0) {
+ $text .= ''.($nbShipments ? $nbShipments : 0);
+ }
+ if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) {
+ $text .= ' - ';
+ }
+ if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) {
+ $text .= ($nbReceiption ? $nbReceiption : 0);
+ }
+ if ($nbShipments > 0 || $nbReceiption > 0) {
+ $text .= ' ';
+ }
$head[$h][1] = $text;
$head[$h][2] = 'shipping';
$h++;
@@ -82,14 +97,19 @@ function commande_prepare_head(Commande $object)
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $h, 'order');
- if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
- {
+ if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
$nbNote = 0;
- if (!empty($object->note_private)) $nbNote++;
- if (!empty($object->note_public)) $nbNote++;
+ if (!empty($object->note_private)) {
+ $nbNote++;
+ }
+ if (!empty($object->note_public)) {
+ $nbNote++;
+ }
$head[$h][0] = DOL_URL_ROOT.'/commande/note.php?id='.$object->id;
$head[$h][1] = $langs->trans('Notes');
- if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.' ';
+ if ($nbNote > 0) {
+ $head[$h][1] .= ''.$nbNote.' ';
+ }
$head[$h][2] = 'note';
$h++;
}
@@ -101,7 +121,9 @@ function commande_prepare_head(Commande $object)
$nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = DOL_URL_ROOT.'/commande/document.php?id='.$object->id;
$head[$h][1] = $langs->trans('Documents');
- if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ if (($nbFiles + $nbLinks) > 0) {
+ $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ }
$head[$h][2] = 'documents';
$h++;
diff --git a/htdocs/core/lib/parsemd.lib.php b/htdocs/core/lib/parsemd.lib.php
index ef0de8c1298..72903dd9e76 100644
--- a/htdocs/core/lib/parsemd.lib.php
+++ b/htdocs/core/lib/parsemd.lib.php
@@ -31,17 +31,14 @@
*/
function dolMd2Html($content, $parser = 'parsedown', $replaceimagepath = null)
{
- if (is_array($replaceimagepath))
- {
- foreach ($replaceimagepath as $key => $val)
- {
+ if (is_array($replaceimagepath)) {
+ foreach ($replaceimagepath as $key => $val) {
$keytoreplace = ']('.$key;
$valafter = ']('.$val;
$content = preg_replace('/'.preg_quote($keytoreplace, '/').'/m', $valafter, $content);
}
}
- if ($parser == 'parsedown')
- {
+ if ($parser == 'parsedown') {
include_once DOL_DOCUMENT_ROOT.'/includes/parsedown/Parsedown.php';
$Parsedown = new Parsedown();
$content = $Parsedown->text($content);
@@ -63,10 +60,8 @@ function dolMd2Html($content, $parser = 'parsedown', $replaceimagepath = null)
*/
function dolMd2Asciidoc($content, $parser = 'dolibarr', $replaceimagepath = null)
{
- if (is_array($replaceimagepath))
- {
- foreach ($replaceimagepath as $key => $val)
- {
+ if (is_array($replaceimagepath)) {
+ foreach ($replaceimagepath as $key => $val) {
$keytoreplace = ']('.$key;
$valafter = ']('.$val;
$content = preg_replace('/'.preg_quote($keytoreplace, '/').'/m', $valafter, $content);
diff --git a/htdocs/core/lib/payments.lib.php b/htdocs/core/lib/payments.lib.php
index 601dad3275d..835986f5f83 100644
--- a/htdocs/core/lib/payments.lib.php
+++ b/htdocs/core/lib/payments.lib.php
@@ -137,18 +137,15 @@ function getValidOnlinePaymentMethods($paymentmethod = '')
$validpaymentmethod = array();
- if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled))
- {
+ if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled)) {
$langs->load("paypal");
$validpaymentmethod['paypal'] = 'valid';
}
- if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled))
- {
+ if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) {
$langs->load("paybox");
$validpaymentmethod['paybox'] = 'valid';
}
- if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled))
- {
+ if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) {
$langs->load("stripe");
$validpaymentmethod['stripe'] = 'valid';
}
@@ -205,102 +202,142 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
$urltouse = DOL_MAIN_URL_ROOT;
- if ($localorexternal) $urltouse = $urlwithroot;
+ if ($localorexternal) {
+ $urltouse = $urlwithroot;
+ }
- if ($type == 'free')
- {
+ if ($type == 'free') {
$out = $urltouse.'/public/payment/newpayment.php?amount='.($mode ? '' : '').$amount.($mode ? ' ' : '').'&tag='.($mode ? '' : '').$freetag.($mode ? ' ' : '');
- if (!empty($conf->global->PAYMENT_SECURITY_TOKEN))
- {
- if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
- else $out .= '&securekey='.dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
+ if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
+ if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
+ $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
+ } else {
+ $out .= '&securekey='.dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
+ }
}
//if ($mode) $out.='&noidempotency=1';
- } elseif ($type == 'order')
- {
+ } elseif ($type == 'order') {
$out = $urltouse.'/public/payment/newpayment.php?source=order&ref='.($mode ? '' : '');
- if ($mode == 1) $out .= 'order_ref';
- if ($mode == 0) $out .= urlencode($ref);
+ if ($mode == 1) {
+ $out .= 'order_ref';
+ }
+ if ($mode == 0) {
+ $out .= urlencode($ref);
+ }
$out .= ($mode ? ' ' : '');
- if (!empty($conf->global->PAYMENT_SECURITY_TOKEN))
- {
- if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
- else {
+ if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
+ if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
+ $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
+ } else {
$out .= '&securekey='.($mode ? '' : '');
- if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + order_ref)";
- if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2);
+ if ($mode == 1) {
+ $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + order_ref)";
+ }
+ if ($mode == 0) {
+ $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2);
+ }
$out .= ($mode ? ' ' : '');
}
}
- } elseif ($type == 'invoice')
- {
+ } elseif ($type == 'invoice') {
$out = $urltouse.'/public/payment/newpayment.php?source=invoice&ref='.($mode ? '' : '');
- if ($mode == 1) $out .= 'invoice_ref';
- if ($mode == 0) $out .= urlencode($ref);
+ if ($mode == 1) {
+ $out .= 'invoice_ref';
+ }
+ if ($mode == 0) {
+ $out .= urlencode($ref);
+ }
$out .= ($mode ? ' ' : '');
- if (!empty($conf->global->PAYMENT_SECURITY_TOKEN))
- {
- if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
- else {
+ if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
+ if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
+ $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
+ } else {
$out .= '&securekey='.($mode ? '' : '');
- if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + invoice_ref)";
- if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2);
+ if ($mode == 1) {
+ $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + invoice_ref)";
+ }
+ if ($mode == 0) {
+ $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2);
+ }
$out .= ($mode ? ' ' : '');
}
}
- } elseif ($type == 'contractline')
- {
+ } elseif ($type == 'contractline') {
$out = $urltouse.'/public/payment/newpayment.php?source=contractline&ref='.($mode ? '' : '');
- if ($mode == 1) $out .= 'contractline_ref';
- if ($mode == 0) $out .= urlencode($ref);
+ if ($mode == 1) {
+ $out .= 'contractline_ref';
+ }
+ if ($mode == 0) {
+ $out .= urlencode($ref);
+ }
$out .= ($mode ? ' ' : '');
- if (!empty($conf->global->PAYMENT_SECURITY_TOKEN))
- {
- if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
- else {
+ if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
+ if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
+ $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
+ } else {
$out .= '&securekey='.($mode ? '' : '');
- if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + contractline_ref)";
- if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2);
+ if ($mode == 1) {
+ $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + contractline_ref)";
+ }
+ if ($mode == 0) {
+ $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2);
+ }
$out .= ($mode ? ' ' : '');
}
}
- } elseif ($type == 'member' || $type == 'membersubscription')
- {
+ } elseif ($type == 'member' || $type == 'membersubscription') {
$out = $urltouse.'/public/payment/newpayment.php?source=membersubscription&ref='.($mode ? '' : '');
- if ($mode == 1) $out .= 'member_ref';
- if ($mode == 0) $out .= urlencode($ref);
+ if ($mode == 1) {
+ $out .= 'member_ref';
+ }
+ if ($mode == 0) {
+ $out .= urlencode($ref);
+ }
$out .= ($mode ? ' ' : '');
- if (!empty($conf->global->PAYMENT_SECURITY_TOKEN))
- {
- if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
- else {
+ if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
+ if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
+ $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
+ } else {
$out .= '&securekey='.($mode ? '' : '');
- if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + member_ref)";
- if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2);
+ if ($mode == 1) {
+ $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + member_ref)";
+ }
+ if ($mode == 0) {
+ $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2);
+ }
$out .= ($mode ? ' ' : '');
}
}
}
- if ($type == 'donation')
- {
+ if ($type == 'donation') {
$out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '' : '');
- if ($mode == 1) $out .= 'donation_ref';
- if ($mode == 0) $out .= urlencode($ref);
+ if ($mode == 1) {
+ $out .= 'donation_ref';
+ }
+ if ($mode == 0) {
+ $out .= urlencode($ref);
+ }
$out .= ($mode ? ' ' : '');
- if (!empty($conf->global->PAYMENT_SECURITY_TOKEN))
- {
- if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
- else {
+ if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
+ if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
+ $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
+ } else {
$out .= '&securekey='.($mode ? '' : '');
- if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + donation_ref)";
- if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2);
+ if ($mode == 1) {
+ $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + donation_ref)";
+ }
+ if ($mode == 0) {
+ $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2);
+ }
$out .= ($mode ? ' ' : '');
}
}
}
// For multicompany
- if (!empty($out) && !empty($conf->multicompany->enabled)) $out .= "&entity=".$conf->entity; // Check the entity because we may have the same reference in several entities
+ if (!empty($out) && !empty($conf->multicompany->enabled)) {
+ $out .= "&entity=".$conf->entity; // Check the entity because we may have the same reference in several entities
+ }
return $out;
}
@@ -323,78 +360,86 @@ function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0,
// Juridical status
$line1 = "";
- if ($fromcompany->forme_juridique_code)
- {
+ if ($fromcompany->forme_juridique_code) {
$line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code);
}
// Capital
- if ($fromcompany->capital)
- {
+ if ($fromcompany->capital) {
$line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency);
}
// Prof Id 1
- if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2))
- {
+ if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) {
$field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code);
- if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+ if (preg_match('/\((.*)\)/i', $field, $reg)) {
+ $field = $reg[1];
+ }
$line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1;
}
// Prof Id 2
- if ($fromcompany->idprof2)
- {
+ if ($fromcompany->idprof2) {
$field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code);
- if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+ if (preg_match('/\((.*)\)/i', $field, $reg)) {
+ $field = $reg[1];
+ }
$line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2;
}
// Second line of company infos
$line2 = "";
// Prof Id 3
- if ($fromcompany->idprof3)
- {
+ if ($fromcompany->idprof3) {
$field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code);
- if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+ if (preg_match('/\((.*)\)/i', $field, $reg)) {
+ $field = $reg[1];
+ }
$line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3;
}
// Prof Id 4
- if ($fromcompany->idprof4)
- {
+ if ($fromcompany->idprof4) {
$field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code);
- if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+ if (preg_match('/\((.*)\)/i', $field, $reg)) {
+ $field = $reg[1];
+ }
$line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4;
}
// IntraCommunautary VAT
- if ($fromcompany->tva_intra != '')
- {
+ if ($fromcompany->tva_intra != '') {
$line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra;
}
print ' ';
print ''."\n";
- if ($addformmessage)
- {
+ if ($addformmessage) {
print '';
print ' ';
$parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix;
- if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform);
- elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM);
+ if (!empty($conf->global->$parammessageform)) {
+ print $langs->transnoentities($conf->global->$parammessageform);
+ } elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) {
+ print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM);
+ }
// Add other message if VAT exists
- if ($object->total_vat != 0 || $object->total_tva != 0)
- {
+ if ($object->total_vat != 0 || $object->total_tva != 0) {
$parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix;
- if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform);
- elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT);
+ if (!empty($conf->global->$parammessageform)) {
+ print $langs->transnoentities($conf->global->$parammessageform);
+ } elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) {
+ print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT);
+ }
}
}
print ' '."\n";
print $fromcompany->name.' ';
print $line1;
- if (strlen($line1.$line2) > 50) print ' ';
- else print ' - ';
+ if (strlen($line1.$line2) > 50) {
+ print ' ';
+ } else {
+ print ' - ';
+ }
print $line2;
print '
'."\n";
}
diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php
index 613a68b56d8..08559c3ebd6 100644
--- a/htdocs/core/lib/pdf.lib.php
+++ b/htdocs/core/lib/pdf.lib.php
@@ -51,8 +51,7 @@ function pdf_getFormat(Translate $outputlangs = null, $mode = 'setup')
// Default value if setup was not done and/or entry into c_paper_format not defined
$width = 210; $height = 297; $unit = 'mm';
- if ($mode == 'auto' || empty($conf->global->MAIN_PDF_FORMAT) || $conf->global->MAIN_PDF_FORMAT == 'auto')
- {
+ if ($mode == 'auto' || empty($conf->global->MAIN_PDF_FORMAT) || $conf->global->MAIN_PDF_FORMAT == 'auto') {
include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
$pdfformat = dol_getDefaultFormat($outputlangs);
} else {
@@ -62,11 +61,9 @@ function pdf_getFormat(Translate $outputlangs = null, $mode = 'setup')
$sql = "SELECT code, label, width, height, unit FROM ".MAIN_DB_PREFIX."c_paper_format";
$sql .= " WHERE code = '".$db->escape($pdfformat)."'";
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $db->fetch_object($resql);
- if ($obj)
- {
+ if ($obj) {
$width = (int) $obj->width;
$height = (int) $obj->height;
$unit = $obj->unit;
@@ -90,8 +87,7 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P')
global $conf;
// Define constant for TCPDF
- if (!defined('K_TCPDF_EXTERNAL_CONFIG'))
- {
+ if (!defined('K_TCPDF_EXTERNAL_CONFIG')) {
define('K_TCPDF_EXTERNAL_CONFIG', 1); // this avoid using tcpdf_config file
define('K_PATH_CACHE', DOL_DATA_ROOT.'/admin/temp/');
define('K_PATH_URL_CACHE', DOL_DATA_ROOT.'/admin/temp/');
@@ -133,21 +129,27 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P')
require_once TCPDF_PATH.'tcpdf.php';
// We need to instantiate tcpdi object (instead of tcpdf) to use merging features. But we can disable it (this will break all merge features).
- if (empty($conf->global->MAIN_DISABLE_TCPDI)) require_once TCPDI_PATH.'tcpdi.php';
+ if (empty($conf->global->MAIN_DISABLE_TCPDI)) {
+ require_once TCPDI_PATH.'tcpdi.php';
+ }
//$arrayformat=pdf_getFormat();
//$format=array($arrayformat['width'],$arrayformat['height']);
//$metric=$arrayformat['unit'];
$pdfa = false; // PDF-1.3
- if (!empty($conf->global->PDF_USE_1A)) $pdfa = true; // PDF1/A
+ if (!empty($conf->global->PDF_USE_1A)) {
+ $pdfa = true; // PDF1/A
+ }
- if (class_exists('TCPDI')) $pdf = new TCPDI($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa);
- else $pdf = new TCPDF($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa);
+ if (class_exists('TCPDI')) {
+ $pdf = new TCPDI($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa);
+ } else {
+ $pdf = new TCPDF($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa);
+ }
// Protection and encryption of pdf
- if (!empty($conf->global->PDF_SECURITY_ENCRYPTION))
- {
+ if (!empty($conf->global->PDF_SECURITY_ENCRYPTION)) {
/* Permission supported by TCPDF
- print : Print the document;
- modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';
@@ -223,13 +225,13 @@ function pdf_getPDFFont($outputlangs)
{
global $conf;
- if (!empty($conf->global->MAIN_PDF_FORCE_FONT)) return $conf->global->MAIN_PDF_FORCE_FONT;
+ if (!empty($conf->global->MAIN_PDF_FORCE_FONT)) {
+ return $conf->global->MAIN_PDF_FORCE_FONT;
+ }
$font = 'Helvetica'; // By default, for FPDI, or ISO language on TCPDF
- if (class_exists('TCPDF')) // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
- {
- if ($outputlangs->trans('FONTFORPDF') != 'FONTFORPDF')
- {
+ if (class_exists('TCPDF')) { // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
+ if ($outputlangs->trans('FONTFORPDF') != 'FONTFORPDF') {
$font = $outputlangs->trans('FONTFORPDF');
}
}
@@ -247,14 +249,14 @@ function pdf_getPDFFontSize($outputlangs)
global $conf;
$size = 10; // By default, for FPDI or ISO language on TCPDF
- if (class_exists('TCPDF')) // If TCPDF on, we can use an UTF8 font like DejaVuSans if required (slower)
- {
- if ($outputlangs->trans('FONTSIZEFORPDF') != 'FONTSIZEFORPDF')
- {
+ if (class_exists('TCPDF')) { // If TCPDF on, we can use an UTF8 font like DejaVuSans if required (slower)
+ if ($outputlangs->trans('FONTSIZEFORPDF') != 'FONTSIZEFORPDF') {
$size = (int) $outputlangs->trans('FONTSIZEFORPDF');
}
}
- if (!empty($conf->global->MAIN_PDF_FORCE_FONT_SIZE)) $size = $conf->global->MAIN_PDF_FORCE_FONT_SIZE;
+ if (!empty($conf->global->MAIN_PDF_FORCE_FONT_SIZE)) {
+ $size = $conf->global->MAIN_PDF_FORCE_FONT_SIZE;
+ }
return $size;
}
@@ -274,10 +276,11 @@ function pdf_getHeightForLogo($logo, $url = false)
$maxwidth = 130;
include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
$tmp = dol_getImageSize($logo, $url);
- if ($tmp['height'])
- {
+ if ($tmp['height']) {
$width = round($height * $tmp['width'] / $tmp['height']);
- if ($width > $maxwidth) $height = $height * $maxwidth / $width;
+ if ($width > $maxwidth) {
+ $height = $height * $maxwidth / $width;
+ }
}
//print $tmp['width'].' '.$tmp['height'].' '.$width; exit;
return $height;
@@ -377,82 +380,103 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t
{
global $conf, $hookmanager;
- if ($mode == 'source' && !is_object($sourcecompany)) return -1;
- if ($mode == 'target' && !is_object($targetcompany)) return -1;
+ if ($mode == 'source' && !is_object($sourcecompany)) {
+ return -1;
+ }
+ if ($mode == 'target' && !is_object($targetcompany)) {
+ return -1;
+ }
- if (!empty($sourcecompany->state_id) && empty($sourcecompany->state)) $sourcecompany->state = getState($sourcecompany->state_id);
- if (!empty($targetcompany->state_id) && empty($targetcompany->state)) $targetcompany->state = getState($targetcompany->state_id);
+ if (!empty($sourcecompany->state_id) && empty($sourcecompany->state)) {
+ $sourcecompany->state = getState($sourcecompany->state_id);
+ }
+ if (!empty($targetcompany->state_id) && empty($targetcompany->state)) {
+ $targetcompany->state = getState($targetcompany->state_id);
+ }
$reshook = 0;
$stringaddress = '';
- if (is_object($hookmanager))
- {
+ if (is_object($hookmanager)) {
$parameters = array('sourcecompany' => &$sourcecompany, 'targetcompany' => &$targetcompany, 'targetcontact' => &$targetcontact, 'outputlangs' => $outputlangs, 'mode' => $mode, 'usecontact' => $usecontact);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_build_address', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
$stringaddress .= $hookmanager->resPrint;
}
- if (empty($reshook))
- {
- if ($mode == 'source')
- {
+ if (empty($reshook)) {
+ if ($mode == 'source') {
$withCountry = 0;
- if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) $withCountry = 1;
+ if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) {
+ $withCountry = 1;
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($sourcecompany, $withCountry, "\n", $outputlangs))."\n";
- if (empty($conf->global->MAIN_PDF_DISABLESOURCEDETAILS))
- {
+ if (empty($conf->global->MAIN_PDF_DISABLESOURCEDETAILS)) {
// Phone
- if ($sourcecompany->phone) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone);
+ if ($sourcecompany->phone) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone);
+ }
// Fax
- if ($sourcecompany->fax) $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax);
+ if ($sourcecompany->fax) {
+ $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax);
+ }
// EMail
- if ($sourcecompany->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email);
+ if ($sourcecompany->email) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email);
+ }
// Web
- if ($sourcecompany->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url);
+ if ($sourcecompany->url) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url);
+ }
}
// Intra VAT
- if (!empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS))
- {
- if ($sourcecompany->tva_intra) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra);
+ if (!empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS)) {
+ if ($sourcecompany->tva_intra) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra);
+ }
}
// Professionnal Ids
$reg = array();
- if (!empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof1))
- {
+ if (!empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof1)) {
$tmp = $outputlangs->transcountrynoentities("ProfId1", $sourcecompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1);
}
- if (!empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof2))
- {
+ if (!empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof2)) {
$tmp = $outputlangs->transcountrynoentities("ProfId2", $sourcecompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2);
}
- if (!empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof3))
- {
+ if (!empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof3)) {
$tmp = $outputlangs->transcountrynoentities("ProfId3", $sourcecompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3);
}
- if (!empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof4))
- {
+ if (!empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof4)) {
$tmp = $outputlangs->transcountrynoentities("ProfId4", $sourcecompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4);
}
- if (!empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof5))
- {
+ if (!empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof5)) {
$tmp = $outputlangs->transcountrynoentities("ProfId5", $sourcecompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5);
}
- if (!empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof6))
- {
+ if (!empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof6)) {
$tmp = $outputlangs->transcountrynoentities("ProfId6", $sourcecompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6);
}
if (!empty($conf->global->PDF_ADD_MORE_AFTER_SOURCE_ADDRESS)) {
@@ -460,10 +484,8 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t
}
}
- if ($mode == 'target' || preg_match('/targetwithdetails/', $mode))
- {
- if ($usecontact)
- {
+ if ($mode == 'target' || preg_match('/targetwithdetails/', $mode)) {
+ if ($usecontact) {
$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs, 1));
if (!empty($targetcontact->address)) {
@@ -472,8 +494,7 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t
$companytouseforaddress = $targetcompany;
// Contact on a thirdparty that is a different thirdparty than the thirdparty of object
- if ($targetcontact->socid > 0 && $targetcontact->socid != $targetcompany->id)
- {
+ if ($targetcontact->socid > 0 && $targetcontact->socid != $targetcompany->id) {
$targetcontact->fetch_thirdparty();
$companytouseforaddress = $targetcontact->thirdparty;
}
@@ -487,118 +508,142 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t
$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
}
- if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode))
- {
+ if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode)) {
// Phone
- if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode))
- {
- if (!empty($targetcontact->phone_pro) || !empty($targetcontact->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": ";
- if (!empty($targetcontact->phone_pro)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro);
- if (!empty($targetcontact->phone_pro) && !empty($targetcontact->phone_mobile)) $stringaddress .= " / ";
- if (!empty($targetcontact->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile);
+ if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode)) {
+ if (!empty($targetcontact->phone_pro) || !empty($targetcontact->phone_mobile)) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": ";
+ }
+ if (!empty($targetcontact->phone_pro)) {
+ $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro);
+ }
+ if (!empty($targetcontact->phone_pro) && !empty($targetcontact->phone_mobile)) {
+ $stringaddress .= " / ";
+ }
+ if (!empty($targetcontact->phone_mobile)) {
+ $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile);
+ }
}
// Fax
- if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode))
- {
- if ($targetcontact->fax) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax);
+ if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode)) {
+ if ($targetcontact->fax) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax);
+ }
}
// EMail
- if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode))
- {
- if ($targetcontact->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email);
+ if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode)) {
+ if ($targetcontact->email) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email);
+ }
}
// Web
- if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode))
- {
- if ($targetcontact->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url);
+ if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode)) {
+ if ($targetcontact->url) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url);
+ }
}
}
} else {
$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($targetcompany));
// Country
- if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
+ if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
+ }
- if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode))
- {
+ if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode)) {
// Phone
- if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode))
- {
- if (!empty($targetcompany->phone) || !empty($targetcompany->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": ";
- if (!empty($targetcompany->phone)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone);
- if (!empty($targetcompany->phone) && !empty($targetcompany->phone_mobile)) $stringaddress .= " / ";
- if (!empty($targetcompany->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile);
+ if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode)) {
+ if (!empty($targetcompany->phone) || !empty($targetcompany->phone_mobile)) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": ";
+ }
+ if (!empty($targetcompany->phone)) {
+ $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone);
+ }
+ if (!empty($targetcompany->phone) && !empty($targetcompany->phone_mobile)) {
+ $stringaddress .= " / ";
+ }
+ if (!empty($targetcompany->phone_mobile)) {
+ $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile);
+ }
}
// Fax
- if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode))
- {
- if ($targetcompany->fax) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax);
+ if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode)) {
+ if ($targetcompany->fax) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax);
+ }
}
// EMail
- if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode))
- {
- if ($targetcompany->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email);
+ if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode)) {
+ if ($targetcompany->email) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email);
+ }
}
// Web
- if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode))
- {
- if ($targetcompany->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url);
+ if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode)) {
+ if ($targetcompany->url) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url);
+ }
}
}
}
// Intra VAT
- if (empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS))
- {
- if ($targetcompany->tva_intra) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra);
+ if (empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS)) {
+ if ($targetcompany->tva_intra) {
+ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra);
+ }
}
// Professionnal Ids
- if (!empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && !empty($targetcompany->idprof1))
- {
+ if (!empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && !empty($targetcompany->idprof1)) {
$tmp = $outputlangs->transcountrynoentities("ProfId1", $targetcompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1);
}
- if (!empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && !empty($targetcompany->idprof2))
- {
+ if (!empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && !empty($targetcompany->idprof2)) {
$tmp = $outputlangs->transcountrynoentities("ProfId2", $targetcompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2);
}
- if (!empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && !empty($targetcompany->idprof3))
- {
+ if (!empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && !empty($targetcompany->idprof3)) {
$tmp = $outputlangs->transcountrynoentities("ProfId3", $targetcompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3);
}
- if (!empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && !empty($targetcompany->idprof4))
- {
+ if (!empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && !empty($targetcompany->idprof4)) {
$tmp = $outputlangs->transcountrynoentities("ProfId4", $targetcompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4);
}
- if (!empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && !empty($targetcompany->idprof5))
- {
+ if (!empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && !empty($targetcompany->idprof5)) {
$tmp = $outputlangs->transcountrynoentities("ProfId5", $targetcompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5);
}
- if (!empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && !empty($targetcompany->idprof6))
- {
+ if (!empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && !empty($targetcompany->idprof6)) {
$tmp = $outputlangs->transcountrynoentities("ProfId6", $targetcompany->country_code);
- if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
+ if (preg_match('/\((.+)\)/', $tmp, $reg)) {
+ $tmp = $reg[1];
+ }
$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof6);
}
// Public note
- if (!empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS))
- {
- if ($mode == 'source' && !empty($sourcecompany->note_public))
- {
+ if (!empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS)) {
+ if ($mode == 'source' && !empty($sourcecompany->note_public)) {
$stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($sourcecompany->note_public);
}
- if (($mode == 'target' || preg_match('/targetwithdetails/', $mode)) && !empty($targetcompany->note_public))
- {
+ if (($mode == 'target' || preg_match('/targetwithdetails/', $mode)) && !empty($targetcompany->note_public)) {
$stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($targetcompany->note_public);
}
}
@@ -622,8 +667,7 @@ function pdf_pagehead(&$pdf, $outputlangs, $page_height)
global $conf;
// Add a background image on document
- if (!empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF)) // Warning, this option make TCPDF generation being crazy and some content disappeared behind the image
- {
+ if (!empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF)) { // Warning, this option make TCPDF generation being crazy and some content disappeared behind the image
$pdf->SetAutoPageBreak(0, 0); // Disable auto pagebreak before adding image
$pdf->Image($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_USE_BACKGROUND_ON_PDF, (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_X) ? $conf->global->MAIN_USE_BACKGROUND_ON_PDF_X : 0), (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y) ? $conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y : 0), 0, $page_height);
$pdf->SetAutoPageBreak(1, 0); // Restore pagebreak
@@ -665,10 +709,15 @@ function pdf_watermark(&$pdf, $outputlangs, $h, $w, $unit, $text)
global $langs, $mysoc, $user;
// Print Draft Watermark
- if ($unit == 'pt') $k = 1;
- elseif ($unit == 'mm') $k = 72 / 25.4;
- elseif ($unit == 'cm') $k = 72 / 2.54;
- elseif ($unit == 'in') $k = 72;
+ if ($unit == 'pt') {
+ $k = 1;
+ } elseif ($unit == 'mm') {
+ $k = 72 / 25.4;
+ } elseif ($unit == 'cm') {
+ $k = 72 / 2.54;
+ } elseif ($unit == 'in') {
+ $k = 72;
+ }
// Make substitution
$substitutionarray = pdf_getSubstitutionArray($outputlangs, null, null);
@@ -719,8 +768,7 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0,
$diffsizecontent = (empty($conf->global->PDF_DIFFSIZE_CONTENT) ? 4 : $conf->global->PDF_DIFFSIZE_CONTENT);
$pdf->SetXY($curx, $cury);
- if (empty($onlynumber))
- {
+ if (empty($onlynumber)) {
$pdf->SetFont('', 'B', $default_font_size - $diffsizetitle);
$pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByTransferOnThisBankAccount').':', 0, 'L', 0);
$cury += 4;
@@ -730,36 +778,36 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0,
// Use correct name of bank id according to country
$bickey = "BICNumber";
- if ($account->getCountryCode() == 'IN') $bickey = "SWIFT";
+ if ($account->getCountryCode() == 'IN') {
+ $bickey = "SWIFT";
+ }
// Get format of bank account according to its country
$usedetailedbban = $account->useDetailedBBAN();
//$onlynumber=0; $usedetailedbban=1; // For tests
- if ($usedetailedbban)
- {
+ if ($usedetailedbban) {
$savcurx = $curx;
- if (empty($onlynumber))
- {
+ if (empty($onlynumber)) {
$pdf->SetFont('', '', $default_font_size - $diffsizecontent);
$pdf->SetXY($curx, $cury);
$pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': '.$outputlangs->convToOutputCharset($account->bank), 0, 'L', 0);
$cury += 3;
}
- if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN)) // Note that some countries still need bank number, BIC/IBAN not enougth for them
- {
+ if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN)) { // Note that some countries still need bank number, BIC/IBAN not enougth for them
// Note:
// bank = code_banque (FR), sort code (GB, IR. Example: 12-34-56)
// desk = code guichet (FR), used only when $usedetailedbban = 1
// number = account number
// key = check control key used only when $usedetailedbban = 1
- if (empty($onlynumber)) $pdf->line($curx + 1, $cury + 1, $curx + 1, $cury + 6);
+ if (empty($onlynumber)) {
+ $pdf->line($curx + 1, $cury + 1, $curx + 1, $cury + 6);
+ }
- foreach ($account->getFieldsToShow() as $val)
- {
+ foreach ($account->getFieldsToShow() as $val) {
$pdf->SetXY($curx, $cury + 4);
$pdf->SetFont('', '', $default_font_size - 3);
@@ -812,7 +860,9 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0,
$pdf->MultiCell(100, 3, $outputlangs->transnoentities("BankAccountNumber").': '.$outputlangs->convToOutputCharset($account->number), 0, 'L', 0);
$cury += 3;
- if ($diffsizecontent <= 2) $cury += 1;
+ if ($diffsizecontent <= 2) {
+ $cury += 1;
+ }
}
$pdf->SetFont('', '', $default_font_size - $diffsizecontent);
@@ -840,17 +890,17 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0,
// Use correct name of bank id according to country
$ibankey = FormBank::getIBANLabel($account);
- if (!empty($account->iban))
- {
+ if (!empty($account->iban)) {
//Remove whitespaces to ensure we are dealing with the format we expect
$ibanDisplay_temp = str_replace(' ', '', $outputlangs->convToOutputCharset($account->iban));
$ibanDisplay = "";
$nbIbanDisplay_temp = dol_strlen($ibanDisplay_temp);
- for ($i = 0; $i < $nbIbanDisplay_temp; $i++)
- {
+ for ($i = 0; $i < $nbIbanDisplay_temp; $i++) {
$ibanDisplay .= $ibanDisplay_temp[$i];
- if ($i % 4 == 3 && $i > 0) $ibanDisplay .= " ";
+ if ($i % 4 == 3 && $i > 0) {
+ $ibanDisplay .= " ";
+ }
}
$pdf->SetFont('', 'B', $default_font_size - 3);
@@ -859,8 +909,7 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0,
$cury += 3;
}
- if (!empty($account->bic))
- {
+ if (!empty($account->bic)) {
$pdf->SetFont('', 'B', $default_font_size - 3);
$pdf->SetXY($curx, $cury);
$pdf->MultiCell(100, 3, $outputlangs->transnoentities($bickey).': '.$outputlangs->convToOutputCharset($account->bic), 0, 'L', 0);
@@ -894,8 +943,7 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_
$dims = $pdf->getPageDimensions();
// Line of free text
- if (empty($hidefreetext) && !empty($conf->global->$paramfreetext))
- {
+ if (empty($hidefreetext) && !empty($conf->global->$paramfreetext)) {
$substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object);
// More substitution keys
$substitutionarray['__FROM_NAME__'] = $fromcompany->name;
@@ -915,124 +963,118 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_
// First line of company infos
$line1 = ""; $line2 = ""; $line3 = ""; $line4 = "";
- if ($showdetails == 1 || $showdetails == 3)
- {
+ if ($showdetails == 1 || $showdetails == 3) {
// Company name
- if ($fromcompany->name)
- {
+ if ($fromcompany->name) {
$line1 .= ($line1 ? " - " : "").$outputlangs->transnoentities("RegisteredOffice").": ".$fromcompany->name;
}
// Address
- if ($fromcompany->address)
- {
+ if ($fromcompany->address) {
$line1 .= ($line1 ? " - " : "").str_replace("\n", ", ", $fromcompany->address);
}
// Zip code
- if ($fromcompany->zip)
- {
+ if ($fromcompany->zip) {
$line1 .= ($line1 ? " - " : "").$fromcompany->zip;
}
// Town
- if ($fromcompany->town)
- {
+ if ($fromcompany->town) {
$line1 .= ($line1 ? " " : "").$fromcompany->town;
}
// Country
- if ($fromcompany->country)
- {
+ if ($fromcompany->country) {
$line1 .= ($line1 ? ", " : "").$fromcompany->country;
}
// Phone
- if ($fromcompany->phone)
- {
+ if ($fromcompany->phone) {
$line2 .= ($line2 ? " - " : "").$outputlangs->transnoentities("Phone").": ".$fromcompany->phone;
}
// Fax
- if ($fromcompany->fax)
- {
+ if ($fromcompany->fax) {
$line2 .= ($line2 ? " - " : "").$outputlangs->transnoentities("Fax").": ".$fromcompany->fax;
}
// URL
- if ($fromcompany->url)
- {
+ if ($fromcompany->url) {
$line2 .= ($line2 ? " - " : "").$fromcompany->url;
}
// Email
- if ($fromcompany->email)
- {
+ if ($fromcompany->email) {
$line2 .= ($line2 ? " - " : "").$fromcompany->email;
}
}
- if ($showdetails == 2 || $showdetails == 3 || ($fromcompany->country_code == 'DE'))
- {
+ if ($showdetails == 2 || $showdetails == 3 || ($fromcompany->country_code == 'DE')) {
// Managers
- if ($fromcompany->managers)
- {
+ if ($fromcompany->managers) {
$line2 .= ($line2 ? " - " : "").$fromcompany->managers;
}
}
// Line 3 of company infos
// Juridical status
- if ($fromcompany->forme_juridique_code)
- {
+ if ($fromcompany->forme_juridique_code) {
$line3 .= ($line3 ? " - " : "").$outputlangs->convToOutputCharset(getFormeJuridiqueLabel($fromcompany->forme_juridique_code));
}
// Capital
- if ($fromcompany->capital)
- {
+ if ($fromcompany->capital) {
$tmpamounttoshow = price2num($fromcompany->capital); // This field is a free string
- if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency));
- else $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", $tmpamounttoshow, $outputlangs);
+ if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) {
+ $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency));
+ } else {
+ $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", $tmpamounttoshow, $outputlangs);
+ }
}
// Prof Id 1
- if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2))
- {
+ if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) {
$field = $outputlangs->transcountrynoentities("ProfId1", $fromcompany->country_code);
- if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+ if (preg_match('/\((.*)\)/i', $field, $reg)) {
+ $field = $reg[1];
+ }
$line3 .= ($line3 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof1);
}
// Prof Id 2
- if ($fromcompany->idprof2)
- {
+ if ($fromcompany->idprof2) {
$field = $outputlangs->transcountrynoentities("ProfId2", $fromcompany->country_code);
- if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+ if (preg_match('/\((.*)\)/i', $field, $reg)) {
+ $field = $reg[1];
+ }
$line3 .= ($line3 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof2);
}
// Line 4 of company infos
// Prof Id 3
- if ($fromcompany->idprof3)
- {
+ if ($fromcompany->idprof3) {
$field = $outputlangs->transcountrynoentities("ProfId3", $fromcompany->country_code);
- if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+ if (preg_match('/\((.*)\)/i', $field, $reg)) {
+ $field = $reg[1];
+ }
$line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof3);
}
// Prof Id 4
- if ($fromcompany->idprof4)
- {
+ if ($fromcompany->idprof4) {
$field = $outputlangs->transcountrynoentities("ProfId4", $fromcompany->country_code);
- if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+ if (preg_match('/\((.*)\)/i', $field, $reg)) {
+ $field = $reg[1];
+ }
$line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof4);
}
// Prof Id 5
- if ($fromcompany->idprof5)
- {
+ if ($fromcompany->idprof5) {
$field = $outputlangs->transcountrynoentities("ProfId5", $fromcompany->country_code);
- if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+ if (preg_match('/\((.*)\)/i', $field, $reg)) {
+ $field = $reg[1];
+ }
$line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof5);
}
// Prof Id 6
- if ($fromcompany->idprof6)
- {
+ if ($fromcompany->idprof6) {
$field = $outputlangs->transcountrynoentities("ProfId6", $fromcompany->country_code);
- if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+ if (preg_match('/\((.*)\)/i', $field, $reg)) {
+ $field = $reg[1];
+ }
$line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof6);
}
// IntraCommunautary VAT
- if ($fromcompany->tva_intra != '')
- {
+ if ($fromcompany->tva_intra != '') {
$line4 .= ($line4 ? " - " : "").$outputlangs->transnoentities("VATIntraShort").": ".$outputlangs->convToOutputCharset($fromcompany->tva_intra);
}
@@ -1041,11 +1083,9 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_
// The start of the bottom of this page footer is positioned according to # of lines
$freetextheight = 0;
- if ($line) // Free text
- {
+ if ($line) { // Free text
//$line="sample text \nfdsf sdf \nghfghg ";
- if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
- {
+ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) {
$width = 20000; $align = 'L'; // By default, ask a manual break: We use a large value 20000, to not have automatic wrap. This make user understand, he need to add CR on its text.
if (!empty($conf->global->MAIN_USE_AUTOWRAP_ON_FREETEXT)) {
$width = 200; $align = 'C';
@@ -1060,11 +1100,9 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_
$marginwithfooter = $marge_basse + $freetextheight + (!empty($line1) ? 3 : 0) + (!empty($line2) ? 3 : 0) + (!empty($line3) ? 3 : 0) + (!empty($line4) ? 3 : 0);
$posy = $marginwithfooter + 0;
- if ($line) // Free text
- {
+ if ($line) { // Free text
$pdf->SetXY($dims['lm'], -$posy);
- if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) // by default
- {
+ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { // by default
$pdf->MultiCell(0, 3, $line, 0, $align, 0);
} else {
$pdf->writeHTMLCell($pdf->page_largeur - $pdf->margin_left - $pdf->margin_right, $freetextheight, $dims['lm'], $dims['hk'] - $marginwithfooter, dol_htmlentitiesbr($line, 1, 'UTF-8', 0));
@@ -1076,8 +1114,7 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_
$pdf->line($dims['lm'], $dims['hk'] - $posy, $dims['wk'] - $dims['rm'], $dims['hk'] - $posy);
$posy--;
- if (!empty($line1))
- {
+ if (!empty($line1)) {
$pdf->SetFont('', 'B', 7);
$pdf->SetXY($dims['lm'], -$posy);
$pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line1, 0, 'C', 0);
@@ -1085,8 +1122,7 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_
$pdf->SetFont('', '', 7);
}
- if (!empty($line2))
- {
+ if (!empty($line2)) {
$pdf->SetFont('', 'B', 7);
$pdf->SetXY($dims['lm'], -$posy);
$pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line2, 0, 'C', 0);
@@ -1094,22 +1130,19 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_
$pdf->SetFont('', '', 7);
}
- if (!empty($line3))
- {
+ if (!empty($line3)) {
$pdf->SetXY($dims['lm'], -$posy);
$pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line3, 0, 'C', 0);
}
- if (!empty($line4))
- {
+ if (!empty($line4)) {
$posy -= 3;
$pdf->SetXY($dims['lm'], -$posy);
$pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line4, 0, 'C', 0);
}
// Show page nb only on iso languages (so default Helvetica font)
- if (strtolower(pdf_getPDFFont($outputlangs)) == 'helvetica')
- {
+ if (strtolower(pdf_getPDFFont($outputlangs)) == 'helvetica') {
$pdf->SetXY($dims['wk'] - $dims['rm'] - 15, -$posy);
//print 'xxx'.$pdf->PageNo().'-'.$pdf->getAliasNbPages().'-'.$pdf->getAliasNumPage();exit;
$pdf->MultiCell(15, 2, $pdf->PageNo().'/'.$pdf->getAliasNbPages(), 0, 'R', 0);
@@ -1135,13 +1168,10 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_
function pdf_writeLinkedObjects(&$pdf, $object, $outputlangs, $posx, $posy, $w, $h, $align, $default_font_size)
{
$linkedobjects = pdf_getLinkedObjects($object, $outputlangs);
- if (!empty($linkedobjects))
- {
- foreach ($linkedobjects as $linkedobject)
- {
+ if (!empty($linkedobjects)) {
+ foreach ($linkedobjects as $linkedobject) {
$reftoshow = $linkedobject["ref_title"].' : '.$linkedobject["ref_value"];
- if (!empty($linkedobject["date_value"]))
- {
+ if (!empty($linkedobject["date_value"])) {
$reftoshow .= ' / '.$linkedobject["date_value"];
}
@@ -1178,18 +1208,20 @@ function pdf_writelinedesc(&$pdf, $object, $i, $outputlangs, $w, $h, $posx, $pos
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = empty($object->lines[$i]->special_code) ? '' : $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('pdf'=>$pdf, 'i'=>$i, 'outputlangs'=>$outputlangs, 'w'=>$w, 'h'=>$h, 'posx'=>$posx, 'posy'=>$posy, 'hideref'=>$hideref, 'hidedesc'=>$hidedesc, 'issupplierline'=>$issupplierline, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_writelinedesc', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
+ if (empty($reshook)) {
$labelproductservice = pdf_getlinedesc($object, $i, $outputlangs, $hideref, $hidedesc, $issupplierline);
//var_dump($labelproductservice);exit;
@@ -1229,8 +1261,7 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0,
$note = (!empty($object->lines[$i]->note) ? $object->lines[$i]->note : '');
$dbatch = (!empty($object->lines[$i]->detail_batch) ? $object->lines[$i]->detail_batch : false);
- if ($issupplierline)
- {
+ if ($issupplierline) {
include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
$prodser = new ProductFournisseur($db);
} else {
@@ -1238,16 +1269,14 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0,
$prodser = new Product($db);
if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
- include_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
+ include_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
}
}
- if ($idprod)
- {
+ if ($idprod) {
$prodser->fetch($idprod);
// If a predefined product and multilang and on other lang, we renamed label with label translated
- if (!empty($conf->global->MAIN_MULTILANGS) && ($outputlangs->defaultlang != $langs->defaultlang))
- {
+ if (!empty($conf->global->MAIN_MULTILANGS) && ($outputlangs->defaultlang != $langs->defaultlang)) {
$translatealsoifmodified = (!empty($conf->global->MAIN_MULTILANG_TRANSLATE_EVEN_IF_MODIFIED)); // By default if value was modified manually, we keep it (no translation because we don't have it)
// TODO Instead of making a compare to see if param was modified, check that content contains reference translation. If yes, add the added part to the new translation
@@ -1269,11 +1298,15 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0,
} else {
$textwasmodified = ($desc == $prodser->description);
}
- if (!empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified)) $desc = $prodser->multilangs[$outputlangs->defaultlang]["description"];
+ if (!empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified)) {
+ $desc = $prodser->multilangs[$outputlangs->defaultlang]["description"];
+ }
// Set note
$textwasmodified = ($note == $prodser->note);
- if (!empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified)) $note = $prodser->multilangs[$outputlangs->defaultlang]["note"];
+ if (!empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified)) {
+ $note = $prodser->multilangs[$outputlangs->defaultlang]["note"];
+ }
}
} elseif ($object->element == 'facture' || $object->element == 'facturefourn') {
if ($object->type == $object::TYPE_DEPOSIT) {
@@ -1299,34 +1332,30 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0,
}
// Description long of product line
- if (!empty($desc) && ($desc != $label))
- {
- if ($libelleproduitservice && empty($hidedesc))
- {
+ if (!empty($desc) && ($desc != $label)) {
+ if ($libelleproduitservice && empty($hidedesc)) {
$libelleproduitservice .= '__N__';
}
- if ($desc == '(CREDIT_NOTE)' && $object->lines[$i]->fk_remise_except)
- {
+ if ($desc == '(CREDIT_NOTE)' && $object->lines[$i]->fk_remise_except) {
$discount = new DiscountAbsolute($db);
$discount->fetch($object->lines[$i]->fk_remise_except);
$sourceref = !empty($discount->discount_type) ? $discount->ref_invoive_supplier_source : $discount->ref_facture_source;
$libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromCreditNote", $sourceref);
- } elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except)
- {
+ } elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except) {
$discount = new DiscountAbsolute($db);
$discount->fetch($object->lines[$i]->fk_remise_except);
$sourceref = !empty($discount->discount_type) ? $discount->ref_invoive_supplier_source : $discount->ref_facture_source;
$libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromDeposit", $sourceref);
// Add date of deposit
- if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) $libelleproduitservice .= ' ('.dol_print_date($discount->datec, 'day', '', $outputlangs).')';
- } elseif ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except)
- {
+ if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) {
+ $libelleproduitservice .= ' ('.dol_print_date($discount->datec, 'day', '', $outputlangs).')';
+ }
+ } elseif ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except) {
$discount = new DiscountAbsolute($db);
$discount->fetch($object->lines[$i]->fk_remise_except);
$libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived", $discount->ref_facture_source);
- } elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except)
- {
+ } elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except) {
$discount = new DiscountAbsolute($db);
$discount->fetch($object->lines[$i]->fk_remise_except);
$libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid", $discount->ref_invoice_supplier_source);
@@ -1371,7 +1400,9 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0,
if ($issupplierline) {
if (empty($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES)) { // Common case
$ref_prodserv = $prodser->ref; // Show local ref
- if ($ref_supplier) $ref_prodserv .= ($prodser->ref ? ' (' : '').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref ? ')' : '');
+ if ($ref_supplier) {
+ $ref_prodserv .= ($prodser->ref ? ' (' : '').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref ? ')' : '');
+ }
} elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 1) {
$ref_prodserv = $ref_supplier;
} elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 2) {
@@ -1381,69 +1412,68 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0,
$ref_prodserv = $prodser->ref; // Show local ref only
if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
- $productCustomerPriceStatic = new Productcustomerprice($db);
- $filter = array('fk_product' => $idprod, 'fk_soc' => $object->socid);
+ $productCustomerPriceStatic = new Productcustomerprice($db);
+ $filter = array('fk_product' => $idprod, 'fk_soc' => $object->socid);
- $nbCustomerPrices = $productCustomerPriceStatic->fetch_all('', '', 1, 0, $filter);
+ $nbCustomerPrices = $productCustomerPriceStatic->fetch_all('', '', 1, 0, $filter);
- if ($nbCustomerPrices > 0) {
- $productCustomerPrice = $productCustomerPriceStatic->lines[0];
+ if ($nbCustomerPrices > 0) {
+ $productCustomerPrice = $productCustomerPriceStatic->lines[0];
- if (! empty($productCustomerPrice->ref_customer)) {
- switch ($conf->global->PRODUIT_CUSTOMER_PRICES_PDF_REF_MODE) {
- case 1:
- $ref_prodserv = $productCustomerPrice->ref_customer;
- break;
+ if (! empty($productCustomerPrice->ref_customer)) {
+ switch ($conf->global->PRODUIT_CUSTOMER_PRICES_PDF_REF_MODE) {
+ case 1:
+ $ref_prodserv = $productCustomerPrice->ref_customer;
+ break;
- case 2:
- $ref_prodserv = $productCustomerPrice->ref_customer . ' (' . $outputlangs->transnoentitiesnoconv('InternalRef') . ' ' . $ref_prodserv . ')';
- break;
+ case 2:
+ $ref_prodserv = $productCustomerPrice->ref_customer . ' (' . $outputlangs->transnoentitiesnoconv('InternalRef') . ' ' . $ref_prodserv . ')';
+ break;
- default:
- $ref_prodserv = $ref_prodserv . ' (' . $outputlangs->transnoentitiesnoconv('RefCustomer') . ' ' . $productCustomerPrice->ref_customer . ')';
- }
- }
- }
+ default:
+ $ref_prodserv = $ref_prodserv . ' (' . $outputlangs->transnoentitiesnoconv('RefCustomer') . ' ' . $productCustomerPrice->ref_customer . ')';
+ }
+ }
+ }
}
}
- if (!empty($libelleproduitservice) && !empty($ref_prodserv)) $ref_prodserv .= " - ";
+ if (!empty($libelleproduitservice) && !empty($ref_prodserv)) {
+ $ref_prodserv .= " - ";
+ }
}
- if (!empty($ref_prodserv) && !empty($conf->global->PDF_BOLD_PRODUCT_REF_AND_PERIOD)) { $ref_prodserv = ''.$ref_prodserv.' '; }
+ if (!empty($ref_prodserv) && !empty($conf->global->PDF_BOLD_PRODUCT_REF_AND_PERIOD)) {
+ $ref_prodserv = ''.$ref_prodserv.' ';
+ }
$libelleproduitservice = $prefix_prodserv.$ref_prodserv.$libelleproduitservice;
// Add an additional description for the category products
- if (!empty($conf->global->CATEGORY_ADD_DESC_INTO_DOC) && $idprod && !empty($conf->categorie->enabled))
- {
+ if (!empty($conf->global->CATEGORY_ADD_DESC_INTO_DOC) && $idprod && !empty($conf->categorie->enabled)) {
include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
$categstatic = new Categorie($db);
// recovering the list of all the categories linked to product
$tblcateg = $categstatic->containing($idprod, Categorie::TYPE_PRODUCT);
- foreach ($tblcateg as $cate)
- {
+ foreach ($tblcateg as $cate) {
// Adding the descriptions if they are filled
$desccateg = $cate->description;
- if ($desccateg)
+ if ($desccateg) {
$libelleproduitservice .= '__N__'.$desccateg;
+ }
}
}
- if (!empty($object->lines[$i]->date_start) || !empty($object->lines[$i]->date_end))
- {
+ if (!empty($object->lines[$i]->date_start) || !empty($object->lines[$i]->date_end)) {
$format = 'day';
$period = '';
// Show duration if exists
- if ($object->lines[$i]->date_start && $object->lines[$i]->date_end)
- {
+ if ($object->lines[$i]->date_start && $object->lines[$i]->date_end) {
$period = '('.$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs), dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')';
}
- if ($object->lines[$i]->date_start && !$object->lines[$i]->date_end)
- {
+ if ($object->lines[$i]->date_start && !$object->lines[$i]->date_end) {
$period = '('.$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs)).')';
}
- if (!$object->lines[$i]->date_start && $object->lines[$i]->date_end)
- {
+ if (!$object->lines[$i]->date_start && $object->lines[$i]->date_end) {
$period = '('.$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')';
}
//print '>'.$outputlangs->charset_output.','.$period;
@@ -1455,23 +1485,30 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0,
//print $libelleproduitservice;
}
- if ($dbatch)
- {
+ if ($dbatch) {
$format = 'day';
- foreach ($dbatch as $detail)
- {
+ foreach ($dbatch as $detail) {
$dte = array();
- if ($detail->eatby) $dte[] = $outputlangs->transnoentitiesnoconv('printEatby', dol_print_date($detail->eatby, $format, false, $outputlangs));
- if ($detail->sellby) $dte[] = $outputlangs->transnoentitiesnoconv('printSellby', dol_print_date($detail->sellby, $format, false, $outputlangs));
- if ($detail->batch) $dte[] = $outputlangs->transnoentitiesnoconv('printBatch', $detail->batch);
+ if ($detail->eatby) {
+ $dte[] = $outputlangs->transnoentitiesnoconv('printEatby', dol_print_date($detail->eatby, $format, false, $outputlangs));
+ }
+ if ($detail->sellby) {
+ $dte[] = $outputlangs->transnoentitiesnoconv('printSellby', dol_print_date($detail->sellby, $format, false, $outputlangs));
+ }
+ if ($detail->batch) {
+ $dte[] = $outputlangs->transnoentitiesnoconv('printBatch', $detail->batch);
+ }
$dte[] = $outputlangs->transnoentitiesnoconv('printQty', $detail->qty);
$libelleproduitservice .= "__N__ ".implode(" - ", $dte);
}
}
// Now we convert \n into br
- if (dol_textishtml($libelleproduitservice)) $libelleproduitservice = preg_replace('/__N__/', ' ', $libelleproduitservice);
- else $libelleproduitservice = preg_replace('/__N__/', "\n", $libelleproduitservice);
+ if (dol_textishtml($libelleproduitservice)) {
+ $libelleproduitservice = preg_replace('/__N__/', ' ', $libelleproduitservice);
+ } else {
+ $libelleproduitservice = preg_replace('/__N__/', "\n", $libelleproduitservice);
+ }
$libelleproduitservice = dol_htmlentitiesbr($libelleproduitservice, 1);
return $libelleproduitservice;
@@ -1493,17 +1530,17 @@ function pdf_getlinenum($object, $i, $outputlangs, $hidedetails = 0)
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlinenum', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
$result .= $hookmanager->resPrint;
}
- if (empty($reshook))
- {
+ if (empty($reshook)) {
$result .= dol_htmlentitiesbr($object->lines[$i]->num);
}
return $result;
@@ -1526,17 +1563,17 @@ function pdf_getlineref($object, $i, $outputlangs, $hidedetails = 0)
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineref', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
$result .= $hookmanager->resPrint;
}
- if (empty($reshook))
- {
+ if (empty($reshook)) {
$result .= dol_htmlentitiesbr($object->lines[$i]->product_ref);
}
return $result;
@@ -1558,17 +1595,17 @@ function pdf_getlineref_supplier($object, $i, $outputlangs, $hidedetails = 0)
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineref_supplier', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
$result .= $hookmanager->resPrint;
}
- if (empty($reshook))
- {
+ if (empty($reshook)) {
$result .= dol_htmlentitiesbr($object->lines[$i]->ref_supplier);
}
return $result;
@@ -1590,38 +1627,41 @@ function pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails = 0)
$result = '';
$reshook = 0;
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlinevatrate', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
- if (empty($hidedetails) || $hidedetails > 1)
- {
+ if (empty($reshook)) {
+ if (empty($hidedetails) || $hidedetails > 1) {
$tmpresult = '';
$tmpresult .= vatrate($object->lines[$i]->tva_tx, 0, $object->lines[$i]->info_bits, -1);
- if (empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX))
- {
- if ($object->lines[$i]->total_localtax1 != 0)
- {
- if (preg_replace('/[\s0%]/', '', $tmpresult)) $tmpresult .= '/';
- else $tmpresult = '';
+ if (empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX)) {
+ if ($object->lines[$i]->total_localtax1 != 0) {
+ if (preg_replace('/[\s0%]/', '', $tmpresult)) {
+ $tmpresult .= '/';
+ } else {
+ $tmpresult = '';
+ }
$tmpresult .= vatrate(abs($object->lines[$i]->localtax1_tx), 0);
}
}
- if (empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX))
- {
- if ($object->lines[$i]->total_localtax2 != 0)
- {
- if (preg_replace('/[\s0%]/', '', $tmpresult)) $tmpresult .= '/';
- else $tmpresult = '';
+ if (empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX)) {
+ if ($object->lines[$i]->total_localtax2 != 0) {
+ if (preg_replace('/[\s0%]/', '', $tmpresult)) {
+ $tmpresult .= '/';
+ } else {
+ $tmpresult = '';
+ }
$tmpresult .= vatrate(abs($object->lines[$i]->localtax2_tx), 0);
}
}
@@ -1647,25 +1687,28 @@ function pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails = 0)
global $conf, $hookmanager;
$sign = 1;
- if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1;
+ if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) {
+ $sign = -1;
+ }
$result = '';
$reshook = 0;
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineupexcltax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
- if (empty($hidedetails) || $hidedetails > 1)
- {
+ if (empty($reshook)) {
+ if (empty($hidedetails) || $hidedetails > 1) {
$subprice = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_subprice : $object->lines[$i]->subprice);
$result .= price($sign * $subprice, 0, $outputlangs);
}
@@ -1687,24 +1730,30 @@ function pdf_getlineupwithtax($object, $i, $outputlangs, $hidedetails = 0)
global $hookmanager, $conf;
$sign = 1;
- if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1;
+ if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) {
+ $sign = -1;
+ }
$result = '';
$reshook = 0;
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineupwithtax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
- if (empty($hidedetails) || $hidedetails > 1) $result .= price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice) * ($object->lines[$i]->tva_tx) / 100), 0, $outputlangs);
+ if (empty($reshook)) {
+ if (empty($hidedetails) || $hidedetails > 1) {
+ $result .= price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice) * ($object->lines[$i]->tva_tx) / 100), 0, $outputlangs);
+ }
}
return $result;
}
@@ -1725,20 +1774,26 @@ function pdf_getlineqty($object, $i, $outputlangs, $hidedetails = 0)
$result = '';
$reshook = 0;
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineqty', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result = $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ $result = $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
- if ($object->lines[$i]->special_code == 3) return '';
- if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty;
+ if (empty($reshook)) {
+ if ($object->lines[$i]->special_code == 3) {
+ return '';
+ }
+ if (empty($hidedetails) || $hidedetails > 1) {
+ $result .= $object->lines[$i]->qty;
+ }
}
return $result;
}
@@ -1759,20 +1814,26 @@ function pdf_getlineqty_asked($object, $i, $outputlangs, $hidedetails = 0)
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineqty_asked', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
- if ($object->lines[$i]->special_code == 3) return '';
- if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_asked;
+ if (empty($reshook)) {
+ if ($object->lines[$i]->special_code == 3) {
+ return '';
+ }
+ if (empty($hidedetails) || $hidedetails > 1) {
+ $result .= $object->lines[$i]->qty_asked;
+ }
}
return $result;
}
@@ -1793,20 +1854,26 @@ function pdf_getlineqty_shipped($object, $i, $outputlangs, $hidedetails = 0)
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineqty_shipped', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
- if ($object->lines[$i]->special_code == 3) return '';
- if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_shipped;
+ if (empty($reshook)) {
+ if ($object->lines[$i]->special_code == 3) {
+ return '';
+ }
+ if (empty($hidedetails) || $hidedetails > 1) {
+ $result .= $object->lines[$i]->qty_shipped;
+ }
}
return $result;
}
@@ -1827,20 +1894,26 @@ function pdf_getlineqty_keeptoship($object, $i, $outputlangs, $hidedetails = 0)
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineqty_keeptoship', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
- if ($object->lines[$i]->special_code == 3) return '';
- if (empty($hidedetails) || $hidedetails > 1) $result .= ($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped);
+ if (empty($reshook)) {
+ if ($object->lines[$i]->special_code == 3) {
+ return '';
+ }
+ if (empty($hidedetails) || $hidedetails > 1) {
+ $result .= ($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped);
+ }
}
return $result;
}
@@ -1862,8 +1935,7 @@ function pdf_getlineunit($object, $i, $outputlangs, $hidedetails = 0, $hookmanag
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
if (!empty($object->lines[$i]->fk_parent_line)) {
$special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
@@ -1877,11 +1949,14 @@ function pdf_getlineunit($object, $i, $outputlangs, $hidedetails = 0, $hookmanag
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineunit', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
- if (empty($hidedetails) || $hidedetails > 1) $result .= $langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short'));
+ if (empty($reshook)) {
+ if (empty($hidedetails) || $hidedetails > 1) {
+ $result .= $langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short'));
+ }
}
return $result;
}
@@ -1905,20 +1980,26 @@ function pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails = 0)
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineremisepercent', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
- if ($object->lines[$i]->special_code == 3) return '';
- if (empty($hidedetails) || $hidedetails > 1) $result .= dol_print_reduction($object->lines[$i]->remise_percent, $outputlangs);
+ if (empty($reshook)) {
+ if ($object->lines[$i]->special_code == 3) {
+ return '';
+ }
+ if (empty($hidedetails) || $hidedetails > 1) {
+ $result .= dol_print_reduction($object->lines[$i]->remise_percent, $outputlangs);
+ }
}
return $result;
}
@@ -1935,37 +2016,42 @@ function pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails = 0)
*/
function pdf_getlineprogress($object, $i, $outputlangs, $hidedetails = 0, $hookmanager = null)
{
- if (empty($hookmanager)) global $hookmanager;
+ if (empty($hookmanager)) {
+ global $hookmanager;
+ }
global $conf;
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i' => $i, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'special_code' => $special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlineprogress', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) return $hookmanager->resPrint;
+ if (!empty($hookmanager->resPrint)) {
+ return $hookmanager->resPrint;
+ }
}
- if (empty($reshook))
- {
- if ($object->lines[$i]->special_code == 3) return '';
- if (empty($hidedetails) || $hidedetails > 1)
- {
- if ($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF)
- {
+ if (empty($reshook)) {
+ if ($object->lines[$i]->special_code == 3) {
+ return '';
+ }
+ if (empty($hidedetails) || $hidedetails > 1) {
+ if ($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF) {
$prev_progress = 0;
- if (method_exists($object, 'get_prev_progress'))
- {
- $prev_progress = $object->lines[$i]->get_prev_progress($object->id);
+ if (method_exists($object, 'get_prev_progress')) {
+ $prev_progress = $object->lines[$i]->get_prev_progress($object->id);
}
- $result = ($object->lines[$i]->situation_percent - $prev_progress).'%';
- } else $result = $object->lines[$i]->situation_percent.'%';
- }
+ $result = ($object->lines[$i]->situation_percent - $prev_progress).'%';
+ } else {
+ $result = $object->lines[$i]->situation_percent.'%';
+ }
+ }
}
return $result;
}
@@ -1984,37 +2070,36 @@ function pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails = 0)
global $conf, $hookmanager;
$sign = 1;
- if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1;
+ if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) {
+ $sign = -1;
+ }
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code, 'sign'=>$sign);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlinetotalexcltax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
- }
- if (empty($reshook))
- {
- if ($object->lines[$i]->special_code == 3)
- {
- $result .= $outputlangs->transnoentities("Option");
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
}
- elseif (empty($hidedetails) || $hidedetails > 1)
- {
+ }
+ if (empty($reshook)) {
+ if ($object->lines[$i]->special_code == 3) {
+ $result .= $outputlangs->transnoentities("Option");
+ } elseif (empty($hidedetails) || $hidedetails > 1) {
$total_ht = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ht : $object->lines[$i]->total_ht);
- if (!empty($object->lines[$i]->situation_percent) && $object->lines[$i]->situation_percent > 0)
- {
+ if (!empty($object->lines[$i]->situation_percent) && $object->lines[$i]->situation_percent > 0) {
// TODO Remove this. The total should be saved correctly in database instead of being modified here.
$prev_progress = 0;
$progress = 1;
- if (method_exists($object->lines[$i], 'get_prev_progress'))
- {
+ if (method_exists($object->lines[$i], 'get_prev_progress')) {
$prev_progress = $object->lines[$i]->get_prev_progress($object->id);
$progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100;
}
@@ -2041,37 +2126,36 @@ function pdf_getlinetotalwithtax($object, $i, $outputlangs, $hidedetails = 0)
global $hookmanager, $conf;
$sign = 1;
- if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1;
+ if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) {
+ $sign = -1;
+ }
$reshook = 0;
$result = '';
//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
- if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
- {
+ if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getlinetotalwithtax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
- }
- if (empty($reshook))
- {
- if ($object->lines[$i]->special_code == 3)
- {
- $result .= $outputlangs->transnoentities("Option");
+ if (!empty($hookmanager->resPrint)) {
+ $result .= $hookmanager->resPrint;
}
- elseif (empty($hidedetails) || $hidedetails > 1)
- {
+ }
+ if (empty($reshook)) {
+ if ($object->lines[$i]->special_code == 3) {
+ $result .= $outputlangs->transnoentities("Option");
+ } elseif (empty($hidedetails) || $hidedetails > 1) {
$total_ttc = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ttc : $object->lines[$i]->total_ttc);
- if ($object->lines[$i]->situation_percent > 0)
- {
+ if ($object->lines[$i]->situation_percent > 0) {
// TODO Remove this. The total should be saved correctly in database instead of being modified here.
$prev_progress = 0;
$progress = 1;
- if (method_exists($object->lines[$i], 'get_prev_progress'))
- {
+ if (method_exists($object->lines[$i], 'get_prev_progress')) {
$prev_progress = $object->lines[$i]->get_prev_progress($object->id);
$progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100;
}
@@ -2101,26 +2185,22 @@ function pdf_getTotalQty($object, $type, $outputlangs)
$nblines = count($object->lines);
// Loop on each lines
- for ($i = 0; $i < $nblines; $i++)
- {
- if ($object->lines[$i]->special_code != 3)
- {
- if ($type == 'all')
- {
+ for ($i = 0; $i < $nblines; $i++) {
+ if ($object->lines[$i]->special_code != 3) {
+ if ($type == 'all') {
$total += $object->lines[$i]->qty;
- } elseif ($type == 9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && !empty($object->lines[$i]->special_code)) || !empty($object->lines[$i]->fk_parent_line)))
- {
+ } elseif ($type == 9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && !empty($object->lines[$i]->special_code)) || !empty($object->lines[$i]->fk_parent_line))) {
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
$action = '';
$reshook = $hookmanager->executeHooks('pdf_getTotalQty', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
return $hookmanager->resPrint;
- } elseif ($type == 0 && $object->lines[$i]->product_type == 0)
- {
+ } elseif ($type == 0 && $object->lines[$i]->product_type == 0) {
$total += $object->lines[$i]->qty;
- } elseif ($type == 1 && $object->lines[$i]->product_type == 1)
- {
+ } elseif ($type == 1 && $object->lines[$i]->product_type == 1) {
$total += $object->lines[$i]->qty;
}
}
@@ -2145,81 +2225,73 @@ function pdf_getLinkedObjects($object, $outputlangs)
$object->fetchObjectLinked();
- foreach ($object->linkedObjects as $objecttype => $objects)
- {
- if ($objecttype == 'facture')
- {
+ foreach ($object->linkedObjects as $objecttype => $objects) {
+ if ($objecttype == 'facture') {
// For invoice, we don't want to have a reference line on document. Image we are using recuring invoice, we will have a line longer than document width.
- } elseif ($objecttype == 'propal' || $objecttype == 'supplier_proposal')
- {
+ } elseif ($objecttype == 'propal' || $objecttype == 'supplier_proposal') {
$outputlangs->load('propal');
- foreach ($objects as $elementobject)
- {
+ foreach ($objects as $elementobject) {
$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefProposal");
$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref);
$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DatePropal");
$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date, 'day', '', $outputlangs);
}
- } elseif ($objecttype == 'commande' || $objecttype == 'supplier_order')
- {
+ } elseif ($objecttype == 'commande' || $objecttype == 'supplier_order') {
$outputlangs->load('orders');
- foreach ($objects as $elementobject)
- {
+ foreach ($objects as $elementobject) {
$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder");
$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref).($elementobject->ref_client ? ' ('.$elementobject->ref_client.')' : '').($elementobject->ref_supplier ? ' ('.$elementobject->ref_supplier.')' : '');
$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate");
$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date, 'day', '', $outputlangs);
}
- } elseif ($objecttype == 'contrat')
- {
+ } elseif ($objecttype == 'contrat') {
$outputlangs->load('contracts');
- foreach ($objects as $elementobject)
- {
+ foreach ($objects as $elementobject) {
$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefContract");
$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref);
$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateContract");
$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date_contrat, 'day', '', $outputlangs);
}
- } elseif ($objecttype == 'fichinter')
- {
+ } elseif ($objecttype == 'fichinter') {
$outputlangs->load('interventions');
- foreach ($objects as $elementobject)
- {
+ foreach ($objects as $elementobject) {
$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("InterRef");
$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref);
$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("InterDate");
$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->datec, 'day', '', $outputlangs);
}
- } elseif ($objecttype == 'shipping')
- {
+ } elseif ($objecttype == 'shipping') {
$outputlangs->loadLangs(array("orders", "sendings"));
- foreach ($objects as $x => $elementobject)
- {
+ foreach ($objects as $x => $elementobject) {
$order = null;
// We concat this record info into fields xxx_value. title is overwrote.
- if (empty($object->linkedObjects['commande']) && $object->element != 'commande') // There is not already a link to order and object is not the order, so we show also info with order
- {
+ if (empty($object->linkedObjects['commande']) && $object->element != 'commande') { // There is not already a link to order and object is not the order, so we show also info with order
$elementobject->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
if (!empty($elementobject->linkedObjectsIds['commande'])) {
include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
$order = new Commande($db);
$ret = $order->fetch(reset($elementobject->linkedObjectsIds['commande']));
- if ($ret < 1) { $order = null; }
+ if ($ret < 1) {
+ $order = null;
+ }
}
}
- if (!is_object($order))
- {
+ if (!is_object($order)) {
$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefSending");
- if (!empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] .= ' / ';
+ if (!empty($linkedobjects[$objecttype]['ref_value'])) {
+ $linkedobjects[$objecttype]['ref_value'] .= ' / ';
+ }
$linkedobjects[$objecttype]['ref_value'] .= $outputlangs->transnoentities($elementobject->ref);
//$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateShipment");
//if (! empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'].=' / ';
//$linkedobjects[$objecttype]['date_value'].= dol_print_date($elementobject->date_delivery,'day','',$outputlangs);
} else {
$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder").' / '.$outputlangs->transnoentities("RefSending");
- if (empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref).($order->ref_client ? ' ('.$order->ref_client.')' : '');
+ if (empty($linkedobjects[$objecttype]['ref_value'])) {
+ $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref).($order->ref_client ? ' ('.$order->ref_client.')' : '');
+ }
$linkedobjects[$objecttype]['ref_value'] .= ' / '.$outputlangs->transnoentities($elementobject->ref);
//$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate") . ($elementobject->date_delivery ? ' / ' . $outputlangs->transnoentities("DateShipment") : '');
//if (empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'] = dol_print_date($order->date,'day','',$outputlangs);
@@ -2230,12 +2302,13 @@ function pdf_getLinkedObjects($object, $outputlangs)
}
// For add external linked objects
- if (is_object($hookmanager))
- {
+ if (is_object($hookmanager)) {
$parameters = array('linkedobjects' => $linkedobjects, 'outputlangs'=>$outputlangs);
$action = '';
$hookmanager->executeHooks('pdf_getLinkedObjects', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if (!empty($hookmanager->resArray)) $linkedobjects = $hookmanager->resArray;
+ if (!empty($hookmanager->resArray)) {
+ $linkedobjects = $hookmanager->resArray;
+ }
}
return $linkedobjects;
@@ -2256,11 +2329,9 @@ function pdf_getSizeForImage($realpath)
$maxheight = (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT) ? 32 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT);
include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
$tmp = dol_getImageSize($realpath);
- if ($tmp['height'])
- {
+ if ($tmp['height']) {
$width = (int) round($maxheight * $tmp['width'] / $tmp['height']); // I try to use maxheight
- if ($width > $maxwidth) // Pb with maxheight, so i use maxwidth
- {
+ if ($width > $maxwidth) { // Pb with maxheight, so i use maxwidth
$width = $maxwidth;
$height = (int) round($maxwidth * $tmp['height'] / $tmp['width']);
} else // No pb with maxheight
@@ -2284,15 +2355,17 @@ function pdfGetLineTotalDiscountAmount($object, $i, $outputlangs, $hidedetails =
{
global $conf, $hookmanager;
$sign = 1;
- if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1;
- if ($object->lines[$i]->special_code == 3)
- {
+ if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) {
+ $sign = -1;
+ }
+ if ($object->lines[$i]->special_code == 3) {
return $outputlangs->transnoentities("Option");
} else {
- if (is_object($hookmanager))
- {
+ if (is_object($hookmanager)) {
$special_code = $object->lines[$i]->special_code;
- if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ if (!empty($object->lines[$i]->fk_parent_line)) {
+ $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
+ }
$parameters = array(
'i'=>$i,
@@ -2303,13 +2376,14 @@ function pdfGetLineTotalDiscountAmount($object, $i, $outputlangs, $hidedetails =
$action = '';
- if ($hookmanager->executeHooks('getlinetotalremise', $parameters, $object, $action) > 0)
- {
+ if ($hookmanager->executeHooks('getlinetotalremise', $parameters, $object, $action) > 0) {
return $hookmanager->resPrint; // Note that $action and $object may have been modified by some hooks
}
}
- if (empty($hidedetails) || $hidedetails > 1) return $sign * (($object->lines[$i]->subprice * $object->lines[$i]->qty) - $object->lines[$i]->total_ht);
+ if (empty($hidedetails) || $hidedetails > 1) {
+ return $sign * (($object->lines[$i]->subprice * $object->lines[$i]->qty) - $object->lines[$i]->total_ht);
+ }
}
return '';
}
diff --git a/htdocs/core/lib/prelevement.lib.php b/htdocs/core/lib/prelevement.lib.php
index 75bf914b964..bc81ee2bfbd 100644
--- a/htdocs/core/lib/prelevement.lib.php
+++ b/htdocs/core/lib/prelevement.lib.php
@@ -85,14 +85,22 @@ function prelevement_prepare_head(BonPrelevement $object)
function prelevement_check_config($type = 'direct-debit')
{
global $conf, $db;
- if ($type == 'bank-transfer'){
- if (empty($conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT)) return -1;
+ if ($type == 'bank-transfer') {
+ if (empty($conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT)) {
+ return -1;
+ }
//if (empty($conf->global->PRELEVEMENT_ICS)) return -1;
- if (empty($conf->global->PAYMENTBYBANKTRANSFER_USER)) return -1;
- }else {
- if (empty($conf->global->PRELEVEMENT_ID_BANKACCOUNT)) return -1;
+ if (empty($conf->global->PAYMENTBYBANKTRANSFER_USER)) {
+ return -1;
+ }
+ } else {
+ if (empty($conf->global->PRELEVEMENT_ID_BANKACCOUNT)) {
+ return -1;
+ }
//if (empty($conf->global->PRELEVEMENT_ICS)) return -1;
- if (empty($conf->global->PRELEVEMENT_USER)) return -1;
+ if (empty($conf->global->PRELEVEMENT_USER)) {
+ return -1;
+ }
}
return 0;
}
diff --git a/htdocs/core/lib/price.lib.php b/htdocs/core/lib/price.lib.php
index 98311d093cd..3a73f47a6a0 100644
--- a/htdocs/core/lib/price.lib.php
+++ b/htdocs/core/lib/price.lib.php
@@ -90,13 +90,15 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt
$result = array();
// Clean parameters
- if (empty($info_bits)) $info_bits = 0;
- if (empty($txtva)) $txtva = 0;
- if (empty($seller) || !is_object($seller))
- {
+ if (empty($info_bits)) {
+ $info_bits = 0;
+ }
+ if (empty($txtva)) {
+ $txtva = 0;
+ }
+ if (empty($seller) || !is_object($seller)) {
dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter seller that is missing", LOG_WARNING);
- if (!is_object($mysoc)) // mysoc may be not defined (during migration process)
- {
+ if (!is_object($mysoc)) { // mysoc may be not defined (during migration process)
$mysoc = new Societe($db);
$mysoc->setMysoc($conf);
}
@@ -116,11 +118,19 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt
$countryid = $seller->country_id;
- if (is_numeric($uselocaltax1_rate)) $uselocaltax1_rate = (float) $uselocaltax1_rate;
- if (is_numeric($uselocaltax2_rate)) $uselocaltax2_rate = (float) $uselocaltax2_rate;
+ if (is_numeric($uselocaltax1_rate)) {
+ $uselocaltax1_rate = (float) $uselocaltax1_rate;
+ }
+ if (is_numeric($uselocaltax2_rate)) {
+ $uselocaltax2_rate = (float) $uselocaltax2_rate;
+ }
- if ($uselocaltax1_rate < 0) $uselocaltax1_rate = $seller->localtax1_assuj;
- if ($uselocaltax2_rate < 0) $uselocaltax2_rate = $seller->localtax2_assuj;
+ if ($uselocaltax1_rate < 0) {
+ $uselocaltax1_rate = $seller->localtax1_assuj;
+ }
+ if ($uselocaltax2_rate < 0) {
+ $uselocaltax2_rate = $seller->localtax2_assuj;
+ }
//var_dump($uselocaltax1_rate.' - '.$uselocaltax2_rate);
dol_syslog('Price.lib::calcul_price_total qty='.$qty.' pu='.$pu.' remise_percent_ligne='.$remise_percent_ligne.' txtva='.$txtva.' uselocaltax1_rate='.$uselocaltax1_rate.' uselocaltax2_rate='.$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$price_base_type.' type='.$type.' progress='.$progress);
@@ -144,33 +154,37 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt
$sql .= " WHERE cv.taux = ".$txtva;
$sql .= " AND cv.fk_pays = ".$countryid;
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $db->fetch_object($resql);
- if ($obj)
- {
+ if ($obj) {
$localtax1_rate = (float) $obj->localtax1; // Use float to force to get first numeric value when value is x:y:z
$localtax2_rate = (float) $obj->localtax2; // Use float to force to get first numeric value when value is -19:-15:-9
$localtax1_type = $obj->localtax1_type;
$localtax2_type = $obj->localtax2_type;
//var_dump($localtax1_rate.' '.$localtax2_rate.' '.$localtax1_type.' '.$localtax2_type);
}
- } else dol_print_error($db);
+ } else {
+ dol_print_error($db);
+ }
}
// pu calculation from pu_devise if pu empty
if (empty($pu) && !empty($pu_devise)) {
- if (!empty($multicurrency_tx)) $pu = $pu_devise / $multicurrency_tx;
- else {
+ if (!empty($multicurrency_tx)) {
+ $pu = $pu_devise / $multicurrency_tx;
+ } else {
dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (multicurrency_tx empty when pu_devise not) ', LOG_ERR);
return array();
}
}
- if ($pu === '') $pu = 0;
+ if ($pu === '') {
+ $pu = 0;
+ }
// pu_devise calculation from pu
if (empty($pu_devise) && !empty($multicurrency_tx)) {
- if (is_numeric($pu) && is_numeric($multicurrency_tx)) $pu_devise = $pu * $multicurrency_tx;
- else {
+ if (is_numeric($pu) && is_numeric($multicurrency_tx)) {
+ $pu_devise = $pu * $multicurrency_tx;
+ } else {
dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (pu or multicurrency_tx are not numeric)', LOG_ERR);
return array();
}
@@ -182,13 +196,14 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt
$tot_avec_remise = $tot_avec_remise_ligne * (1 - ($remise_percent_global / 100));
// initialize result array
- for ($i = 0; $i <= 15; $i++) $result[$i] = 0;
+ for ($i = 0; $i <= 15; $i++) {
+ $result[$i] = 0;
+ }
// if there's some localtax including vat, we calculate localtaxes (we will add later)
// if input unit price is 'HT', we need to have the totals with main VAT for a correct calculation
- if ($price_base_type != 'TTC')
- {
+ if ($price_base_type != 'TTC') {
$tot_sans_remise_wt = price2num($tot_sans_remise * (1 + ($txtva / 100)), 'MU');
$tot_avec_remise_wt = price2num($tot_avec_remise * (1 + ($txtva / 100)), 'MU');
$pu_wt = price2num($pu * (1 + ($txtva / 100)), 'MU');
@@ -207,22 +222,26 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt
$apply_tax = true;
break;
case '4': // localtax on product
- if ($type == 0) $apply_tax = true;
+ if ($type == 0) {
+ $apply_tax = true;
+ }
break;
case '6': // localtax on service
- if ($type == 1) $apply_tax = true;
+ if ($type == 1) {
+ $apply_tax = true;
+ }
break;
}
if ($uselocaltax1_rate && $apply_tax) {
- $result[14] = price2num(($tot_sans_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_sans_remise_wt, 'MT');
- $localtaxes[0] += $result[14];
+ $result[14] = price2num(($tot_sans_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_sans_remise_wt, 'MT');
+ $localtaxes[0] += $result[14];
- $result[9] = price2num(($tot_avec_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_avec_remise_wt, 'MT');
- $localtaxes[1] += $result[9];
+ $result[9] = price2num(($tot_avec_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_avec_remise_wt, 'MT');
+ $localtaxes[1] += $result[9];
- $result[11] = price2num(($pu_wt * (1 + ($localtax1_rate / 100))) - $pu_wt, 'MU');
- $localtaxes[2] += $result[11];
+ $result[11] = price2num(($pu_wt * (1 + ($localtax1_rate / 100))) - $pu_wt, 'MU');
+ $localtaxes[2] += $result[11];
}
$apply_tax = false;
@@ -231,26 +250,29 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt
$apply_tax = true;
break;
case '4': // localtax on product
- if ($type == 0) $apply_tax = true;
+ if ($type == 0) {
+ $apply_tax = true;
+ }
break;
case '6': // localtax on service
- if ($type == 1) $apply_tax = true;
+ if ($type == 1) {
+ $apply_tax = true;
+ }
break;
}
if ($uselocaltax2_rate && $apply_tax) {
- $result[15] = price2num(($tot_sans_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_sans_remise_wt, 'MT');
- $localtaxes[0] += $result[15];
+ $result[15] = price2num(($tot_sans_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_sans_remise_wt, 'MT');
+ $localtaxes[0] += $result[15];
- $result[10] = price2num(($tot_avec_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_avec_remise_wt, 'MT');
- $localtaxes[1] += $result[10];
+ $result[10] = price2num(($tot_avec_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_avec_remise_wt, 'MT');
+ $localtaxes[1] += $result[10];
- $result[12] = price2num(($pu_wt * (1 + ($localtax2_rate / 100))) - $pu_wt, 'MU');
- $localtaxes[2] += $result[12];
+ $result[12] = price2num(($pu_wt * (1 + ($localtax2_rate / 100))) - $pu_wt, 'MU');
+ $localtaxes[2] += $result[12];
}
//dol_syslog("price.lib::calcul_price_total $qty, $pu, $remise_percent_ligne, $txtva, $price_base_type $info_bits");
- if ($price_base_type == 'HT')
- {
+ if ($price_base_type == 'HT') {
// We work to define prices using the price without tax
$result[6] = price2num($tot_sans_remise, 'MT');
$result[8] = price2num($tot_sans_remise * (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)) + $localtaxes[0], 'MT'); // Selon TVA NPR ou non
@@ -287,8 +309,7 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt
// if there's some localtax without vat, we calculate localtaxes (we will add them at end)
//If input unit price is 'TTC', we need to have the totals without main VAT for a correct calculation
- if ($price_base_type == 'TTC')
- {
+ if ($price_base_type == 'TTC') {
$tot_sans_remise = price2num($tot_sans_remise / (1 + ($txtva / 100)), 'MU');
$tot_avec_remise = price2num($tot_avec_remise / (1 + ($txtva / 100)), 'MU');
$pu = price2num($pu / (1 + ($txtva / 100)), 'MU');
@@ -300,21 +321,25 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt
$apply_tax = true;
break;
case '3': // localtax on product
- if ($type == 0) $apply_tax = true;
+ if ($type == 0) {
+ $apply_tax = true;
+ }
break;
case '5': // localtax on service
- if ($type == 1) $apply_tax = true;
+ if ($type == 1) {
+ $apply_tax = true;
+ }
break;
}
if ($uselocaltax1_rate && $apply_tax) {
- $result[14] = price2num(($tot_sans_remise * (1 + ($localtax1_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax1 for total_ht_without_discount
- $result[8] += $result[14]; // total_ttc_without_discount + tax1
+ $result[14] = price2num(($tot_sans_remise * (1 + ($localtax1_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax1 for total_ht_without_discount
+ $result[8] += $result[14]; // total_ttc_without_discount + tax1
- $result[9] = price2num(($tot_avec_remise * (1 + ($localtax1_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax1 for total_ht
- $result[2] += $result[9]; // total_ttc + tax1
+ $result[9] = price2num(($tot_avec_remise * (1 + ($localtax1_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax1 for total_ht
+ $result[2] += $result[9]; // total_ttc + tax1
- $result[11] = price2num(($pu * (1 + ($localtax1_rate / 100))) - $pu, 'MU'); // amount tax1 for pu_ht
- $result[5] += $result[11]; // pu_ht + tax1
+ $result[11] = price2num(($pu * (1 + ($localtax1_rate / 100))) - $pu, 'MU'); // amount tax1 for pu_ht
+ $result[5] += $result[11]; // pu_ht + tax1
}
$apply_tax = false;
@@ -323,28 +348,30 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt
$apply_tax = true;
break;
case '3': // localtax on product
- if ($type == 0) $apply_tax = true;
+ if ($type == 0) {
+ $apply_tax = true;
+ }
break;
case '5': // localtax on service
- if ($type == 1) $apply_tax = true;
+ if ($type == 1) {
+ $apply_tax = true;
+ }
break;
}
if ($uselocaltax2_rate && $apply_tax) {
- $result[15] = price2num(($tot_sans_remise * (1 + ($localtax2_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax2 for total_ht_without_discount
- $result[8] += $result[15]; // total_ttc_without_discount + tax2
+ $result[15] = price2num(($tot_sans_remise * (1 + ($localtax2_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax2 for total_ht_without_discount
+ $result[8] += $result[15]; // total_ttc_without_discount + tax2
- $result[10] = price2num(($tot_avec_remise * (1 + ($localtax2_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax2 for total_ht
- $result[2] += $result[10]; // total_ttc + tax2
+ $result[10] = price2num(($tot_avec_remise * (1 + ($localtax2_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax2 for total_ht
+ $result[2] += $result[10]; // total_ttc + tax2
- $result[12] = price2num(($pu * (1 + ($localtax2_rate / 100))) - $pu, 'MU'); // amount tax2 for pu_ht
- $result[5] += $result[12]; // pu_ht + tax2
+ $result[12] = price2num(($pu * (1 + ($localtax2_rate / 100))) - $pu, 'MU'); // amount tax2 for pu_ht
+ $result[5] += $result[12]; // pu_ht + tax2
}
// If rounding is not using base 10 (rare)
- if (!empty($conf->global->MAIN_ROUNDING_RULE_TOT))
- {
- if ($price_base_type == 'HT')
- {
+ if (!empty($conf->global->MAIN_ROUNDING_RULE_TOT)) {
+ if ($price_base_type == 'HT') {
$result[0] = round($result[0] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
$result[1] = round($result[1] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
$result[9] = round($result[9] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
@@ -360,8 +387,7 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt
}
// Multicurrency
- if ($multicurrency_tx != 1)
- {
+ if ($multicurrency_tx != 1) {
if ($multicurrency_code) {
$savMAIN_MAX_DECIMALS_UNIT = $conf->global->MAIN_MAX_DECIMALS_UNIT;
$savMAIN_MAX_DECIMALS_TOT = $conf->global->MAIN_MAX_DECIMALS_TOT;
diff --git a/htdocs/core/lib/product.lib.php b/htdocs/core/lib/product.lib.php
index 9ce8d84d7e3..d5d52761140 100644
--- a/htdocs/core/lib/product.lib.php
+++ b/htdocs/core/lib/product.lib.php
@@ -38,7 +38,9 @@ function product_prepare_head($object)
$langs->load("products");
$label = $langs->trans('Product');
- if ($object->isService()) $label = $langs->trans('Service');
+ if ($object->isService()) {
+ $label = $langs->trans('Service');
+ }
$h = 0;
$head = array();
@@ -48,20 +50,17 @@ function product_prepare_head($object)
$head[$h][2] = 'card';
$h++;
- if (!empty($object->status))
- {
+ if (!empty($object->status)) {
$head[$h][0] = DOL_URL_ROOT."/product/price.php?id=".$object->id;
$head[$h][1] = $langs->trans("SellingPrices");
$head[$h][2] = 'price';
$h++;
}
- if (!empty($object->status_buy) || (!empty($conf->margin->enabled) && !empty($object->status))) // If margin is on and product on sell, we may need the cost price even if product os not on purchase
- {
+ if (!empty($object->status_buy) || (!empty($conf->margin->enabled) && !empty($object->status))) { // If margin is on and product on sell, we may need the cost price even if product os not on purchase
if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->lire)
|| (!empty($conf->margin->enabled) && $user->rights->margin->liretous)
- )
- {
+ ) {
$head[$h][0] = DOL_URL_ROOT."/product/fournisseurs.php?id=".$object->id;
$head[$h][1] = $langs->trans("BuyingPrices");
$head[$h][2] = 'suppliers';
@@ -70,8 +69,7 @@ function product_prepare_head($object)
}
// Multilangs
- if (!empty($conf->global->MAIN_MULTILANGS))
- {
+ if (!empty($conf->global->MAIN_MULTILANGS)) {
$head[$h][0] = DOL_URL_ROOT."/product/traduction.php?id=".$object->id;
$head[$h][1] = $langs->trans("Translation");
$head[$h][2] = 'translation';
@@ -79,13 +77,14 @@ function product_prepare_head($object)
}
// Sub products
- if (!empty($conf->global->PRODUIT_SOUSPRODUITS))
- {
+ if (!empty($conf->global->PRODUIT_SOUSPRODUITS)) {
$head[$h][0] = DOL_URL_ROOT."/product/composition/card.php?id=".$object->id;
$head[$h][1] = $langs->trans('AssociatedProducts');
$nbFatherAndChild = $object->hasFatherOrChild();
- if ($nbFatherAndChild > 0) $head[$h][1] .= ''.$nbFatherAndChild.' ';
+ if ($nbFatherAndChild > 0) {
+ $head[$h][1] .= ''.$nbFatherAndChild.' ';
+ }
$head[$h][2] = 'subproduct';
$h++;
}
@@ -97,22 +96,21 @@ function product_prepare_head($object)
$prodcomb = new ProductCombination($db);
- if ($prodcomb->fetchByFkProductChild($object->id) <= 0)
- {
+ if ($prodcomb->fetchByFkProductChild($object->id) <= 0) {
$head[$h][0] = DOL_URL_ROOT."/variants/combinations.php?id=".$object->id;
$head[$h][1] = $langs->trans('ProductCombinations');
$head[$h][2] = 'combinations';
$nbVariant = $prodcomb->countNbOfCombinationForFkProductParent($object->id);
- if ($nbVariant > 0) $head[$h][1] .= ''.$nbVariant.' ';
+ if ($nbVariant > 0) {
+ $head[$h][1] .= ''.$nbVariant.' ';
+ }
}
$h++;
}
- if ($object->isProduct() || ($object->isService() && !empty($conf->global->STOCK_SUPPORTS_SERVICES))) // If physical product we can stock (or service with option)
- {
- if (!empty($conf->stock->enabled) && $user->rights->stock->lire)
- {
+ if ($object->isProduct() || ($object->isService() && !empty($conf->global->STOCK_SUPPORTS_SERVICES))) { // If physical product we can stock (or service with option)
+ if (!empty($conf->stock->enabled) && $user->rights->stock->lire) {
$head[$h][0] = DOL_URL_ROOT."/product/stock/product.php?id=".$object->id;
$head[$h][1] = $langs->trans("Stock");
$head[$h][2] = 'stock';
@@ -121,17 +119,14 @@ function product_prepare_head($object)
}
// Tab to link resources
- if (!empty($conf->resource->enabled))
- {
- if ($object->isProduct() && !empty($conf->global->RESOURCE_ON_PRODUCTS))
- {
+ if (!empty($conf->resource->enabled)) {
+ if ($object->isProduct() && !empty($conf->global->RESOURCE_ON_PRODUCTS)) {
$head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=product&ref='.$object->ref;
$head[$h][1] = $langs->trans("Resources");
$head[$h][2] = 'resources';
$h++;
}
- if ($object->isService() && !empty($conf->global->RESOURCE_ON_SERVICES))
- {
+ if ($object->isService() && !empty($conf->global->RESOURCE_ON_SERVICES)) {
$head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=service&ref='.$object->ref;
$head[$h][1] = $langs->trans("Resources");
$head[$h][2] = 'resources';
@@ -156,14 +151,19 @@ function product_prepare_head($object)
complete_head_from_modules($conf, $langs, $object, $head, $h, 'product');
// Notes
- if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
- {
+ if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
$nbNote = 0;
- if (!empty($object->note_private)) $nbNote++;
- if (!empty($object->note_public)) $nbNote++;
+ if (!empty($object->note_private)) {
+ $nbNote++;
+ }
+ if (!empty($object->note_public)) {
+ $nbNote++;
+ }
$head[$h][0] = DOL_URL_ROOT.'/product/note.php?id='.$object->id;
$head[$h][1] = $langs->trans('Notes');
- if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.' ';
+ if ($nbNote > 0) {
+ $head[$h][1] .= ''.$nbNote.' ';
+ }
$head[$h][2] = 'note';
$h++;
}
@@ -171,18 +171,28 @@ function product_prepare_head($object)
// Attachments
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
- if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
- if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
+ if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) {
+ $upload_dir = $conf->product->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
+ }
+ if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) {
+ $upload_dir = $conf->service->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
+ }
$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
- if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos';
- if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos';
+ if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) {
+ $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos';
+ }
+ if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) {
+ $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos';
+ }
$nbFiles += count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
}
$nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = DOL_URL_ROOT.'/product/document.php?id='.$object->id;
$head[$h][1] = $langs->trans('Documents');
- if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ if (($nbFiles + $nbLinks) > 0) {
+ $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ }
$head[$h][2] = 'documents';
$h++;
@@ -191,8 +201,7 @@ function product_prepare_head($object)
// Log
$head[$h][0] = DOL_URL_ROOT.'/product/agenda.php?id='.$object->id;
$head[$h][1] = $langs->trans("Events");
- if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read)))
- {
+ if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
$head[$h][1] .= '/';
$head[$h][1] .= $langs->trans("Agenda");
}
@@ -231,7 +240,9 @@ function productlot_prepare_head($object)
$nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = DOL_URL_ROOT."/product/stock/productlot_document.php?id=".$object->id;
$head[$h][1] = $langs->trans("Documents");
- if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ if (($nbFiles + $nbLinks) > 0) {
+ $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ }
$head[$h][2] = 'documents';
$h++;
@@ -245,11 +256,11 @@ function productlot_prepare_head($object)
// Log
/*
- $head[$h][0] = DOL_URL_ROOT.'/product/info.php?id='.$object->id;
- $head[$h][1] = $langs->trans("Info");
- $head[$h][2] = 'info';
- $h++;
- */
+ $head[$h][0] = DOL_URL_ROOT.'/product/info.php?id='.$object->id;
+ $head[$h][1] = $langs->trans("Info");
+ $head[$h][2] = 'info';
+ $h++;
+ */
return $head;
}
@@ -273,8 +284,7 @@ function product_admin_prepare_head()
$head[$h][2] = 'general';
$h++;
- if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL))
- {
+ if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL)) {
$head[$h] = array(
0 => DOL_URL_ROOT."/product/admin/price_rules.php",
1 => $langs->trans('MultipriceRules'),
@@ -358,14 +368,15 @@ function show_stats_for_company($product, $socid)
print '';
// Customer proposals
- if (!empty($conf->propal->enabled) && $user->rights->propale->lire)
- {
+ if (!empty($conf->propal->enabled) && $user->rights->propale->lire) {
$nblines++;
$ret = $product->load_stats_propale($socid);
- if ($ret < 0) dol_print_error($db);
+ if ($ret < 0) {
+ dol_print_error($db);
+ }
$langs->load("propal");
print '';
- print ''.img_object('', 'propal').' '.$langs->trans("Proposals").' ';
+ print ''.img_object('', 'propal', 'class="paddingright"').$langs->trans("Proposals").' ';
print ' ';
print $product->stats_propale['customers'];
print ' ';
@@ -376,14 +387,15 @@ function show_stats_for_company($product, $socid)
print ' ';
}
// Supplier proposals
- if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire)
- {
+ if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) {
$nblines++;
$ret = $product->load_stats_proposal_supplier($socid);
- if ($ret < 0) dol_print_error($db);
- $langs->load("propal");
+ if ($ret < 0) {
+ dol_print_error($db);
+ }
+ $langs->load("supplier_proposal");
print '';
- print ''.img_object('', 'supplier_proposal').' '.$langs->trans("SupplierProposals").' ';
+ print ''.img_object('', 'supplier_proposal', 'class="paddingright"').$langs->trans("SupplierProposals").' ';
print ' ';
print $product->stats_proposal_supplier['suppliers'];
print ' ';
@@ -394,14 +406,15 @@ function show_stats_for_company($product, $socid)
print ' ';
}
// Customer orders
- if (!empty($conf->commande->enabled) && $user->rights->commande->lire)
- {
+ if (!empty($conf->commande->enabled) && $user->rights->commande->lire) {
$nblines++;
$ret = $product->load_stats_commande($socid);
- if ($ret < 0) dol_print_error($db);
+ if ($ret < 0) {
+ dol_print_error($db);
+ }
$langs->load("orders");
print '';
- print ''.img_object('', 'order').' '.$langs->trans("CustomersOrders").' ';
+ print ''.img_object('', 'order', 'class="paddingright"').$langs->trans("CustomersOrders").' ';
print ' ';
print $product->stats_commande['customers'];
print ' ';
@@ -412,14 +425,15 @@ function show_stats_for_company($product, $socid)
print ' ';
}
// Supplier orders
- if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire)
- {
+ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) {
$nblines++;
$ret = $product->load_stats_commande_fournisseur($socid);
- if ($ret < 0) dol_print_error($db);
+ if ($ret < 0) {
+ dol_print_error($db);
+ }
$langs->load("orders");
print '';
- print ''.img_object('', 'supplier_order').' '.$langs->trans("SuppliersOrders").' ';
+ print ''.img_object('', 'supplier_order', 'class="paddingright"').$langs->trans("SuppliersOrders").' ';
print ' ';
print $product->stats_commande_fournisseur['suppliers'];
print ' ';
@@ -430,11 +444,12 @@ function show_stats_for_company($product, $socid)
print ' ';
}
// Customer invoices
- if (!empty($conf->facture->enabled) && $user->rights->facture->lire)
- {
+ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) {
$nblines++;
$ret = $product->load_stats_facture($socid);
- if ($ret < 0) dol_print_error($db);
+ if ($ret < 0) {
+ dol_print_error($db);
+ }
$langs->load("bills");
print '';
print ''.img_object('', 'bill').' '.$langs->trans("CustomersInvoices").' ';
@@ -448,14 +463,15 @@ function show_stats_for_company($product, $socid)
print ' ';
}
// Supplier invoices
- if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire)
- {
+ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) {
$nblines++;
$ret = $product->load_stats_facture_fournisseur($socid);
- if ($ret < 0) dol_print_error($db);
+ if ($ret < 0) {
+ dol_print_error($db);
+ }
$langs->load("bills");
print '';
- print ''.img_object('', 'supplier_invoice').' '.$langs->trans("SuppliersInvoices").' ';
+ print ''.img_object('', 'supplier_invoice', 'class="paddingright"').$langs->trans("SuppliersInvoices").' ';
print ' ';
print $product->stats_facture_fournisseur['suppliers'];
print ' ';
@@ -467,14 +483,15 @@ function show_stats_for_company($product, $socid)
}
// Contracts
- if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire)
- {
+ if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) {
$nblines++;
$ret = $product->load_stats_contrat($socid);
- if ($ret < 0) dol_print_error($db);
+ if ($ret < 0) {
+ dol_print_error($db);
+ }
$langs->load("contracts");
print ' ';
- print ''.img_object('', 'contract').' '.$langs->trans("Contracts").' ';
+ print ''.img_object('', 'contract', 'class="paddingright"').$langs->trans("Contracts").' ';
print ' ';
print $product->stats_contrat['customers'];
print ' ';
@@ -486,8 +503,7 @@ function show_stats_for_company($product, $socid)
}
// BOM
- if (!empty($conf->bom->enabled) && $user->rights->bom->read)
- {
+ if (!empty($conf->bom->enabled) && $user->rights->bom->read) {
$nblines++;
$ret = $product->load_stats_bom($socid);
if ($ret < 0) {
@@ -496,22 +512,21 @@ function show_stats_for_company($product, $socid)
$langs->load("mrp");
print ' ';
- print ''.img_object('', 'mrp').' '.$langs->trans("BOM").' ';
+ print ''.img_object('', 'bom', 'class="paddingright"').$langs->trans("BOM").' ';
print ' ';
print ' ';
- print $form->textwithpicto($product->stats_bom['nb_toproduce'], $langs->trans("QtyToProduce"));
- print $form->textwithpicto($product->stats_bom['nb_toconsume'], $langs->trans("ToConsume"));
+ print $form->textwithpicto($product->stats_bom['nb_toconsume'], $langs->trans("RowMaterial"));
+ print $form->textwithpicto($product->stats_bom['nb_toproduce'], $langs->trans("Finished"));
print ' ';
- print $form->textwithpicto($product->stats_bom['qty_toproduce'], $langs->trans("QtyToProduce"));
- print $form->textwithpicto($product->stats_bom['qty_toconsume'], $langs->trans("ToConsume"));
+ print $form->textwithpicto($product->stats_bom['qty_toconsume'], $langs->trans("RowMaterial"));
+ print $form->textwithpicto($product->stats_bom['qty_toproduce'], $langs->trans("Finished"));
print ' ';
print ' ';
}
// MO
- if (!empty($conf->mrp->enabled) && $user->rights->mrp->read)
- {
+ if (!empty($conf->mrp->enabled) && $user->rights->mrp->read) {
$nblines++;
$ret = $product->load_stats_mo($socid);
if ($ret < 0) {
@@ -519,7 +534,7 @@ function show_stats_for_company($product, $socid)
}
$langs->load("mrp");
print '';
- print ''.img_object('', 'mrp').' '.$langs->trans("MO").' ';
+ print ''.img_object('', 'mrp', 'class="paddingright"').$langs->trans("MO").' ';
print ' ';
print $form->textwithpicto($product->stats_mo['customers_toconsume'], $langs->trans("ToConsume"));
print $form->textwithpicto($product->stats_mo['customers_consumed'], $langs->trans("QtyAlreadyConsumed"));
@@ -579,19 +594,16 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho
$outputlangs = $langs;
}
- if (empty($measuring_unit_cache[$unit.'_'.$measuring_style.'_'.$scale.'_'.$use_short_label]))
- {
+ if (empty($measuring_unit_cache[$unit.'_'.$measuring_style.'_'.$scale.'_'.$use_short_label])) {
require_once DOL_DOCUMENT_ROOT.'/core/class/cunits.class.php';
$measuringUnits = new CUnits($db);
- if ($measuring_style == '' && $scale == '')
- {
+ if ($measuring_style == '' && $scale == '') {
$arrayforfilter = array(
't.rowid' => $unit,
't.active' => 1
);
- } elseif ($scale !== '')
- {
+ } elseif ($scale !== '') {
$arrayforfilter = array(
't.scale' => $scale,
't.unit_type' => $measuring_style,
@@ -610,8 +622,11 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho
return -1;
} else {
if (is_array($measuringUnits->records) && count($measuringUnits->records) > 0) {
- if ($use_short_label) $labeltoreturn = $measuringUnits->records[key($measuringUnits->records)]->short_label;
- else $labeltoreturn = $outputlangs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label);
+ if ($use_short_label) {
+ $labeltoreturn = $measuringUnits->records[key($measuringUnits->records)]->short_label;
+ } else {
+ $labeltoreturn = $outputlangs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label);
+ }
} else {
$labeltoreturn = '';
}
diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php
index d710f69b2d4..1222fa120fe 100644
--- a/htdocs/core/lib/project.lib.php
+++ b/htdocs/core/lib/project.lib.php
@@ -203,6 +203,19 @@ function project_prepare_head(Project $project)
$h++;
}
+ if ($conf->eventorganization->enabled) {
+ $langs->load('eventorganization');
+ //TODO : Count
+ $nbConfOrBooth = 1;
+ $head[$h][0] = DOL_URL_ROOT . '/projet/event.php?id=' . $project->id;
+ $head[$h][1] = $langs->trans("ConferenceOrBoothTab");
+ if ($nbContact > 0) {
+ $head[$h][1] .= '' . $nbConfOrBooth . ' ';
+ }
+ $head[$h][2] = 'eventorganisation';
+ $h++;
+ }
+
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
@@ -309,7 +322,9 @@ function task_prepare_head($object)
$nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external'));
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/contact.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : '');
$head[$h][1] = $langs->trans("TaskRessourceLinks");
- if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.' ';
+ if ($nbContact > 0) {
+ $head[$h][1] .= ''.$nbContact.' ';
+ }
$head[$h][2] = 'task_contact';
$h++;
@@ -321,15 +336,20 @@ function task_prepare_head($object)
$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
$sql .= " WHERE t.fk_task =".$object->id;
$resql = $db->query($sql);
- if ($resql)
- {
+ if ($resql) {
$obj = $db->fetch_object($resql);
- if ($obj) $nbTimeSpent = 1;
- } else dol_print_error($db);
+ if ($obj) {
+ $nbTimeSpent = 1;
+ }
+ } else {
+ dol_print_error($db);
+ }
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : '');
$head[$h][1] = $langs->trans("TimeSpent");
- if ($nbTimeSpent > 0) $head[$h][1] .= '... ';
+ if ($nbTimeSpent > 0) {
+ $head[$h][1] .= '... ';
+ }
$head[$h][2] = 'task_time';
$h++;
@@ -339,14 +359,19 @@ function task_prepare_head($object)
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $h, 'task');
- if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
- {
+ if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
$nbNote = 0;
- if (!empty($object->note_private)) $nbNote++;
- if (!empty($object->note_public)) $nbNote++;
+ if (!empty($object->note_private)) {
+ $nbNote++;
+ }
+ if (!empty($object->note_public)) {
+ $nbNote++;
+ }
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/note.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : '');
$head[$h][1] = $langs->trans('Notes');
- if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.' ';
+ if ($nbNote > 0) {
+ $head[$h][1] .= ''.$nbNote.' ';
+ }
$head[$h][2] = 'task_notes';
$h++;
}
@@ -358,17 +383,20 @@ function task_prepare_head($object)
$nbFiles = count(dol_dir_list($filesdir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
$nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][1] = $langs->trans('Documents');
- if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ if (($nbFiles + $nbLinks) > 0) {
+ $head[$h][1] .= ''.($nbFiles + $nbLinks).' ';
+ }
$head[$h][2] = 'task_document';
$h++;
// Manage discussion
- if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK))
- {
+ if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK)) {
$nbComments = $object->getNbComments();
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/comment.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : '');
$head[$h][1] = $langs->trans("CommentLink");
- if ($nbComments > 0) $head[$h][1] .= ''.$nbComments.' ';
+ if ($nbComments > 0) {
+ $head[$h][1] .= ''.$nbComments.' ';
+ }
$head[$h][2] = 'task_comment';
$h++;
}
@@ -395,26 +423,25 @@ function project_timesheet_prepare_head($mode, $fuser = null)
$param = '';
$param .= ($mode ? '&mode='.$mode : '');
- if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) $param .= '&search_usertoprocessid='.$fuser->id;
+ if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) {
+ $param .= '&search_usertoprocessid='.$fuser->id;
+ }
- if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERMONTH))
- {
+ if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERMONTH)) {
$head[$h][0] = DOL_URL_ROOT."/projet/activity/permonth.php".($param ? '?'.$param : '');
$head[$h][1] = $langs->trans("InputPerMonth");
$head[$h][2] = 'inputpermonth';
$h++;
}
- if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK))
- {
+ if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK)) {
$head[$h][0] = DOL_URL_ROOT."/projet/activity/perweek.php".($param ? '?'.$param : '');
$head[$h][1] = $langs->trans("InputPerWeek");
$head[$h][2] = 'inputperweek';
$h++;
}
- if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERTIME))
- {
+ if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERTIME)) {
$head[$h][0] = DOL_URL_ROOT."/projet/activity/perday.php".($param ? '?'.$param : '');
$head[$h][1] = $langs->trans("InputPerDay");
$head[$h][2] = 'inputperday';
@@ -467,6 +494,15 @@ function project_admin_prepare_head()
$head[$h][2] = 'attributes_task';
$h++;
+ if (! empty($conf->global->MAIN_FEATURES_LEVEL) && $conf->global->MAIN_FEATURES_LEVEL >= 2) {
+ $langs->load("members");
+
+ $head[$h][0] = DOL_URL_ROOT.'/projet/admin/website.php';
+ $head[$h][1] = $langs->trans("BlankSubscriptionForm");
+ $head[$h][2] = 'website';
+ $h++;
+ }
+
complete_head_from_modules($conf, $langs, null, $head, $h, 'project_admin', 'remove');
return $head;
@@ -500,7 +536,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
$projectsArrayId = explode(',', $projectsListId);
if ($filterprogresscalc !== '') {
- foreach ($lines as $key=>$line) {
+ foreach ($lines as $key => $line) {
if (!empty($line->planned_workload) && !empty($line->duration)) {
$filterprogresscalc = str_replace(' = ', ' == ', $filterprogresscalc);
if (!eval($filterprogresscalc)) {
@@ -515,8 +551,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
// We declare counter as global because we want to edit them into recursive call
global $total_projectlinesa_spent, $total_projectlinesa_planned, $total_projectlinesa_spent_if_planned, $total_projectlinesa_declared_if_planned, $total_projectlinesa_tobill, $total_projectlinesa_billed;
- if ($level == 0)
- {
+ if ($level == 0) {
$total_projectlinesa_spent = 0;
$total_projectlinesa_planned = 0;
$total_projectlinesa_spent_if_planned = 0;
@@ -525,31 +560,28 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
$total_projectlinesa_billed = 0;
}
- for ($i = 0; $i < $numlines; $i++)
- {
- if ($parent == 0 && $level >= 0) $level = 0; // if $level = -1, we dont' use sublevel recursion, we show all lines
+ for ($i = 0; $i < $numlines; $i++) {
+ if ($parent == 0 && $level >= 0) {
+ $level = 0; // if $level = -1, we dont' use sublevel recursion, we show all lines
+ }
// Process line
// print "i:".$i."-".$lines[$i]->fk_project.' ';
- if ($lines[$i]->fk_parent == $parent || $level < 0) // if $level = -1, we dont' use sublevel recursion, we show all lines
- {
+ if ($lines[$i]->fk_parent == $parent || $level < 0) { // if $level = -1, we dont' use sublevel recursion, we show all lines
// Show task line.
$showline = 1;
$showlineingray = 0;
// If there is filters to use
- if (is_array($taskrole))
- {
+ if (is_array($taskrole)) {
// If task not legitimate to show, search if a legitimate task exists later in tree
- if (!isset($taskrole[$lines[$i]->id]) && $lines[$i]->id != $lines[$i]->fk_parent)
- {
+ if (!isset($taskrole[$lines[$i]->id]) && $lines[$i]->id != $lines[$i]->fk_parent) {
// So search if task has a subtask legitimate to show
$foundtaskforuserdeeper = 0;
searchTaskInChild($foundtaskforuserdeeper, $lines[$i]->id, $lines, $taskrole);
//print '$foundtaskforuserpeeper='.$foundtaskforuserdeeper.' ';
- if ($foundtaskforuserdeeper > 0)
- {
+ if ($foundtaskforuserdeeper > 0) {
$showlineingray = 1; // We will show line but in gray
} else {
$showline = 0; // No reason to show line
@@ -558,11 +590,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
} else {
// Caller did not ask to filter on tasks of a specific user (this probably means he want also tasks of all users, into public project
// or into all other projects if user has permission to).
- if (empty($user->rights->projet->all->lire))
- {
+ if (empty($user->rights->projet->all->lire)) {
// User is not allowed on this project and project is not public, so we hide line
- if (!in_array($lines[$i]->fk_project, $projectsArrayId))
- {
+ if (!in_array($lines[$i]->fk_project, $projectsArrayId)) {
// Note that having a user assigned to a task into a project user has no permission on, should not be possible
// because assignement on task can be done only on contact of project.
// If assignement was done and after, was removed from contact of project, then we can hide the line.
@@ -571,11 +601,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
}
}
- if ($showline)
- {
+ if ($showline) {
// Break on a new project
- if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
- {
+ if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) {
$var = !$var;
$lastprojectid = $lines[$i]->fk_project;
}
@@ -602,13 +630,15 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
$taskstatic->duration_effective = $lines[$i]->duration;
- if ($showproject)
- {
+ if ($showproject) {
// Project ref
print " ";
//if ($showlineingray) print '';
- if ($lines[$i]->public || in_array($lines[$i]->fk_project, $projectsArrayId) || !empty($user->rights->projet->all->lire)) print $projectstatic->getNomUrl(1);
- else print $projectstatic->getNomUrl(1, 'nolink');
+ if ($lines[$i]->public || in_array($lines[$i]->fk_project, $projectsArrayId) || !empty($user->rights->projet->all->lire)) {
+ print $projectstatic->getNomUrl(1);
+ } else {
+ print $projectstatic->getNomUrl(1, 'nolink');
+ }
//if ($showlineingray) print ' ';
print " ";
@@ -633,8 +663,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
// Title of task
if (count($arrayfields) > 0 && !empty($arrayfields['t.label']['checked'])) {
print "";
- if ($showlineingray)
+ if ($showlineingray) {
print '';
+ }
//else print '';
for ($k = 0; $k < $level; $k++) {
print '';
@@ -643,8 +674,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
for ($k = 0; $k < $level; $k++) {
print '
';
}
- if ($showlineingray)
+ if ($showlineingray) {
print ' ';
+ }
//else print '';
print " \n";
}
@@ -666,15 +698,20 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
if (count($arrayfields) > 0 && !empty($arrayfields['t.datee']['checked'])) {
print '';
print dol_print_date($lines[$i]->date_end, 'dayhour');
- if ($taskstatic->hasDelay())
+ if ($taskstatic->hasDelay()) {
print img_warning($langs->trans("Late"));
+ }
print ' ';
}
$plannedworkloadoutputformat = 'allhourmin';
$timespentoutputformat = 'allhourmin';
- if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT;
- if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT;
+ if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) {
+ $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT;
+ }
+ if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) {
+ $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT;
+ }
// Planned Workload (in working hours)
if (count($arrayfields) > 0 && !empty($arrayfields['t.planned_workload']['checked'])) {
@@ -693,15 +730,21 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
// Time spent
if (count($arrayfields) > 0 && !empty($arrayfields['t.duration_effective']['checked'])) {
print '';
- if ($showlineingray)
+ if ($showlineingray) {
print '';
- else print '';
- if ($lines[$i]->duration)
+ } else {
+ print ' ';
+ }
+ if ($lines[$i]->duration) {
print convertSecondToTime($lines[$i]->duration, $timespentoutputformat);
- else print '--:--';
- if ($showlineingray)
+ } else {
+ print '--:--';
+ }
+ if ($showlineingray) {
print ' ';
- else print '';
+ } else {
+ print '';
+ }
print ' ';
}
@@ -709,9 +752,11 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
if (count($arrayfields) > 0 && !empty($arrayfields['t.progress_calculated']['checked'])) {
print '';
if ($lines[$i]->planned_workload || $lines[$i]->duration) {
- if ($lines[$i]->planned_workload)
+ if ($lines[$i]->planned_workload) {
print round(100 * $lines[$i]->duration / $lines[$i]->planned_workload, 2).' %';
- else print ''.$langs->trans('WorkloadNotDefined').' ';
+ } else {
+ print ''.$langs->trans('WorkloadNotDefined').' ';
+ }
}
print ' ';
}
@@ -734,8 +779,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
print '';
}
- if ($showbilltime)
- {
+ if ($showbilltime) {
// Time not billed
if (count($arrayfields) > 0 && !empty($arrayfields['t.tobill']['checked'])) {
print '';
@@ -762,18 +806,19 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
}
// Contacts of task
- if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST))
- {
+ if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) {
print ' ';
- foreach (array('internal', 'external') as $source)
- {
+ foreach (array('internal', 'external') as $source) {
$tab = $lines[$i]->liste_contact(-1, $source);
$num = count($tab);
if (!empty($num)) {
foreach ($tab as $contacttask) {
//var_dump($contacttask);
- if ($source == 'internal') $c = new User($db);
- else $c = new Contact($db);
+ if ($source == 'internal') {
+ $c = new User($db);
+ } else {
+ $c = new Contact($db);
+ }
$c->fetch($contacttask['id']);
print $c->getNomUrl(1).' ('.$contacttask['libelle'].') ';
}
@@ -796,19 +841,26 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
print " \n";
- if (!$showlineingray) $inc++;
+ if (!$showlineingray) {
+ $inc++;
+ }
- if ($level >= 0) // Call sublevels
- {
+ if ($level >= 0) { // Call sublevels
$level++;
- if ($lines[$i]->id) projectLinesa($inc, $lines[$i]->id, $lines, $level, $var, $showproject, $taskrole, $projectsListId, $addordertick, $projectidfortotallink, $filterprogresscalc, $showbilltime, $arrayfields);
+ if ($lines[$i]->id) {
+ projectLinesa($inc, $lines[$i]->id, $lines, $level, $var, $showproject, $taskrole, $projectsListId, $addordertick, $projectidfortotallink, $filterprogresscalc, $showbilltime, $arrayfields);
+ }
$level--;
}
$total_projectlinesa_spent += $lines[$i]->duration;
$total_projectlinesa_planned += $lines[$i]->planned_workload;
- if ($lines[$i]->planned_workload) $total_projectlinesa_spent_if_planned += $lines[$i]->duration;
- if ($lines[$i]->planned_workload) $total_projectlinesa_declared_if_planned += $lines[$i]->planned_workload * $lines[$i]->progress / 100;
+ if ($lines[$i]->planned_workload) {
+ $total_projectlinesa_spent_if_planned += $lines[$i]->duration;
+ }
+ if ($lines[$i]->planned_workload) {
+ $total_projectlinesa_declared_if_planned += $lines[$i]->planned_workload * $lines[$i]->progress / 100;
+ }
}
} else {
//$level--;
@@ -816,14 +868,21 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
}
if (($total_projectlinesa_planned > 0 || $total_projectlinesa_spent > 0 || $total_projectlinesa_tobill > 0 || $total_projectlinesa_billed > 0)
- && $level <= 0)
- {
+ && $level <= 0) {
print '';
print ''.$langs->trans("Total").' ';
- if ($showproject) print ' ';
- if (count($arrayfields) > 0 && !empty($arrayfields['t.label']['checked'])) print ' ';
- if (count($arrayfields) > 0 && !empty($arrayfields['t.dateo']['checked'])) print ' ';
- if (count($arrayfields) > 0 && !empty($arrayfields['t.datee']['checked'])) print ' ';
+ if ($showproject) {
+ print ' ';
+ }
+ if (count($arrayfields) > 0 && !empty($arrayfields['t.label']['checked'])) {
+ print ' ';
+ }
+ if (count($arrayfields) > 0 && !empty($arrayfields['t.dateo']['checked'])) {
+ print ' ';
+ }
+ if (count($arrayfields) > 0 && !empty($arrayfields['t.datee']['checked'])) {
+ print ' ';
+ }
if (count($arrayfields) > 0 && !empty($arrayfields['t.planned_workload']['checked'])) {
print '';
print convertSecondToTime($total_projectlinesa_planned, 'allhourmin');
@@ -831,11 +890,13 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
}
if (count($arrayfields) > 0 && !empty($arrayfields['t.duration_effective']['checked'])) {
print ' ';
- if ($projectidfortotallink > 0)
+ if ($projectidfortotallink > 0) {
print '';
+ }
print convertSecondToTime($total_projectlinesa_spent, 'allhourmin');
- if ($projectidfortotallink > 0)
+ if ($projectidfortotallink > 0) {
print ' ';
+ }
print ' ';
}
@@ -864,14 +925,16 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
if (count($arrayfields) > 0 && !empty($arrayfields['t.progress_calculated']['checked'])) {
print '';
- if ($total_projectlinesa_planned)
+ if ($total_projectlinesa_planned) {
print $totalCalculatedProgress.' %';
+ }
print ' ';
}
if (count($arrayfields) > 0 && !empty($arrayfields['t.progress']['checked'])) {
print '';
- if ($total_projectlinesa_planned)
+ if ($total_projectlinesa_planned) {
print ''.$totalAverageDeclaredProgress.' % ';
+ }
print ' ';
}
@@ -889,8 +952,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
print '';
}
- if ($showbilltime)
- {
+ if ($showbilltime) {
if (count($arrayfields) > 0 && !empty($arrayfields['t.tobill']['checked'])) {
print '';
print convertSecondToTime($total_projectlinesa_tobill, 'allhourmin');
@@ -903,8 +965,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
}
}
// Contacts of task
- if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST))
- {
+ if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) {
print ' ';
}
print ' ';
@@ -945,45 +1006,40 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec
$numlines = count($lines);
// Create a smaller array with sublevels only to be used later. This increase dramatically performances.
- if ($parent == 0) // Always and only if at first level
- {
- for ($i = 0; $i < $numlines; $i++)
- {
- if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i];
+ if ($parent == 0) { // Always and only if at first level
+ for ($i = 0; $i < $numlines; $i++) {
+ if ($lines[$i]->fk_task_parent) {
+ $lineswithoutlevel0[] = $lines[$i];
+ }
}
}
- if (empty($oldprojectforbreak))
- {
+ if (empty($oldprojectforbreak)) {
$oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 to start break , -1 no break
}
//dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0));
- for ($i = 0; $i < $numlines; $i++)
- {
- if ($parent == 0) $level = 0;
+ for ($i = 0; $i < $numlines; $i++) {
+ if ($parent == 0) {
+ $level = 0;
+ }
//if ($lines[$i]->fk_task_parent == $parent)
//{
// If we want all or we have a role on task, we show it
- if (empty($mine) || !empty($tasksrole[$lines[$i]->id]))
- {
+ if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) {
//dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project);
// Break on a new project
- if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
- {
+ if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) {
$lastprojectid = $lines[$i]->fk_project;
- if ($preselectedday)
- {
+ if ($preselectedday) {
$projectstatic->id = $lines[$i]->fk_project;
}
}
- if (empty($workloadforid[$projectstatic->id]))
- {
- if ($preselectedday)
- {
+ if (empty($workloadforid[$projectstatic->id])) {
+ if ($preselectedday) {
$projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week
$workloadforid[$projectstatic->id] = 1;
}
@@ -1005,13 +1061,11 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec
$thirdpartystatic->name = $lines[$i]->thirdparty_name;
$thirdpartystatic->email = $lines[$i]->thirdparty_email;
- if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id))
- {
+ if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) {
print ' '."\n";
print '';
print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
- if ($projectstatic->title)
- {
+ if ($projectstatic->title) {
print ' - ';
print $projectstatic->title;
}
@@ -1019,7 +1073,9 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec
print ' ';
}
- if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id;
+ if ($oldprojectforbreak != -1) {
+ $oldprojectforbreak = $projectstatic->id;
+ }
print ''."\n";
@@ -1032,8 +1088,7 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec
// Project
print "";
- if ($oldprojectforbreak == -1)
- {
+ if ($oldprojectforbreak == -1) {
print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
print ' '.$projectstatic->title;
}
@@ -1041,17 +1096,23 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec
// Thirdparty
print ' ';
- if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10);
+ if ($thirdpartystatic->id > 0) {
+ print $thirdpartystatic->getNomUrl(1, 'project', 10);
+ }
print ' ';
// Ref
print '';
print '';
- for ($k = 0; $k < $level; $k++) print " ";
+ for ($k = 0; $k < $level; $k++) {
+ print " ";
+ }
print $taskstatic->getNomUrl(1, 'withproject', 'time');
// Label task
print ' ';
- for ($k = 0; $k < $level; $k++) print " ";
+ for ($k = 0; $k < $level; $k++) {
+ print " ";
+ }
print $taskstatic->label;
//print " ";
//for ($k = 0 ; $k < $level ; $k++) print " ";
@@ -1068,14 +1129,12 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec
//var_dump($lines[$i]);
//var_dump($projectsrole[$lines[$i]->fk_project]);
// If at least one role for project
- if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
- {
+ if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) {
$disabledproject = 0;
$disabledtask = 0;
}
// If $restricteditformytask is on and I have no role on task, i disable edit
- if ($restricteditformytask && empty($tasksrole[$lines[$i]->id]))
- {
+ if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) {
$disabledtask = 1;
}
@@ -1085,9 +1144,13 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec
print ' ';
$cssonholiday = '';
- if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayallday ';
- elseif (!$isavailable[$preselectedday]['morning']) $cssonholiday .= 'onholidaymorning ';
- elseif (!$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayafternoon ';
+ if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) {
+ $cssonholiday .= 'onholidayallday ';
+ } elseif (!$isavailable[$preselectedday]['morning']) {
+ $cssonholiday .= 'onholidaymorning ';
+ } elseif (!$isavailable[$preselectedday]['afternoon']) {
+ $cssonholiday .= 'onholidayafternoon ';
+ }
// Duration
print '';
@@ -1096,7 +1159,9 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec
$totalforeachline[$preselectedday] += $lines[$i]->timespent_duration;
$alreadyspent = '';
- if ($dayWorkLoad > 0) $alreadyspent = convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin');
+ if ($dayWorkLoad > 0) {
+ $alreadyspent = convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin');
+ }
print convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin');
@@ -1174,54 +1239,47 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
$numlines = count($lines);
// Create a smaller array with sublevels only to be used later. This increase dramatically performances.
- if ($parent == 0) // Always and only if at first level
- {
- for ($i = 0; $i < $numlines; $i++)
- {
- if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i];
+ if ($parent == 0) { // Always and only if at first level
+ for ($i = 0; $i < $numlines; $i++) {
+ if ($lines[$i]->fk_task_parent) {
+ $lineswithoutlevel0[] = $lines[$i];
+ }
}
}
- if (empty($oldprojectforbreak))
- {
+ if (empty($oldprojectforbreak)) {
$oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 to start break , -1 no break
}
//dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0));
- for ($i = 0; $i < $numlines; $i++)
- {
- if ($parent == 0) $level = 0;
+ for ($i = 0; $i < $numlines; $i++) {
+ if ($parent == 0) {
+ $level = 0;
+ }
- if ($lines[$i]->fk_task_parent == $parent)
- {
+ if ($lines[$i]->fk_task_parent == $parent) {
$obj = &$lines[$i]; // To display extrafields
// If we want all or we have a role on task, we show it
- if (empty($mine) || !empty($tasksrole[$lines[$i]->id]))
- {
+ if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) {
//dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project);
- if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) // we have no role on task and we request to hide such cases
- {
+ if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) { // we have no role on task and we request to hide such cases
continue;
}
// Break on a new project
- if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
- {
+ if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) {
$lastprojectid = $lines[$i]->fk_project;
- if ($preselectedday)
- {
+ if ($preselectedday) {
$projectstatic->id = $lines[$i]->fk_project;
}
}
- if (empty($workloadforid[$projectstatic->id]))
- {
- if ($preselectedday)
- {
+ if (empty($workloadforid[$projectstatic->id])) {
+ if ($preselectedday) {
$projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week
- $workloadforid[$projectstatic->id] = 1;
+ $workloadforid[$projectstatic->id] = 1;
}
}
@@ -1241,91 +1299,98 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
$thirdpartystatic->name = $lines[$i]->thirdparty_name;
$thirdpartystatic->email = $lines[$i]->thirdparty_email;
- if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id))
- {
+ if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) {
$addcolspan = 0;
- if (!empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++;
- if (!empty($arrayfields['t.progress']['checked'])) $addcolspan++;
- foreach ($arrayfields as $key => $val)
- {
- if ($val['checked'] && substr($key, 0, 5) == 'efpt.') $addcolspan++;
+ if (!empty($arrayfields['t.planned_workload']['checked'])) {
+ $addcolspan++;
+ }
+ if (!empty($arrayfields['t.progress']['checked'])) {
+ $addcolspan++;
+ }
+ foreach ($arrayfields as $key => $val) {
+ if ($val['checked'] && substr($key, 0, 5) == 'efpt.') {
+ $addcolspan++;
+ }
}
print ' '."\n";
print '';
print $projectstatic->getNomUrl(1, '', 0, ''.$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
- if ($thirdpartystatic->id > 0) print ' - '.$thirdpartystatic->getNomUrl(1);
- if ($projectstatic->title)
- {
+ if ($thirdpartystatic->id > 0) {
+ print ' - '.$thirdpartystatic->getNomUrl(1);
+ }
+ if ($projectstatic->title) {
print ' - ';
print ''.$projectstatic->title.' ';
}
/*
- $colspan=5+(empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:2);
- print '';
+ $colspan=5+(empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:2);
+ print '';
- print '';
+ print ' ';
- // PROJECT fields
- if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center ');
- if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right ');
- if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right ');
- if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right ');
- if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right ');
+ // PROJECT fields
+ if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center ');
+ if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right ');
+ if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right ');
+ if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right ');
+ if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right ');
- $extrafieldsobjectkey='projet';
- $extrafieldsobjectprefix='efp.';
- include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
+ $extrafieldsobjectkey='projet';
+ $extrafieldsobjectprefix='efp.';
+ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
- print ' ';
- print '';
+ print ' ';
+ print '';
- // PROJECT fields
- if (! empty($arrayfields['p.fk_opp_status']['checked']))
- {
- print '';
- $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code');
- if ($code) print $langs->trans("OppStatus".$code);
- print " \n";
- }
- if (! empty($arrayfields['p.opp_amount']['checked']))
- {
- print '';
- print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency);
- print " \n";
- }
- if (! empty($arrayfields['p.opp_percent']['checked']))
- {
- print '';
- print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %';
- print " \n";
- }
- if (! empty($arrayfields['p.budget_amount']['checked']))
- {
- print '';
- print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency);
- print " \n";
- }
- if (! empty($arrayfields['p.usage_bill_time']['checked']))
- {
- print '';
- print yn($lines[$i]->usage_bill_time);
- print " \n";
- }
+ // PROJECT fields
+ if (! empty($arrayfields['p.fk_opp_status']['checked']))
+ {
+ print '';
+ $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code');
+ if ($code) print $langs->trans("OppStatus".$code);
+ print " \n";
+ }
+ if (! empty($arrayfields['p.opp_amount']['checked']))
+ {
+ print '';
+ print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency);
+ print " \n";
+ }
+ if (! empty($arrayfields['p.opp_percent']['checked']))
+ {
+ print '';
+ print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %';
+ print " \n";
+ }
+ if (! empty($arrayfields['p.budget_amount']['checked']))
+ {
+ print '';
+ print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency);
+ print " \n";
+ }
+ if (! empty($arrayfields['p.usage_bill_time']['checked']))
+ {
+ print '';
+ print yn($lines[$i]->usage_bill_time);
+ print " \n";
+ }
- $extrafieldsobjectkey='projet';
- $extrafieldsobjectprefix='efp.';
- include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
+ $extrafieldsobjectkey='projet';
+ $extrafieldsobjectprefix='efp.';
+ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
- print ' ';
- print '
';
+ print '';
+ print '
';
*/
print ' ';
print ' ';
}
- if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id;
+ if ($oldprojectforbreak != -1) {
+ $oldprojectforbreak = $projectstatic->id;
+ }
print ''."\n";
@@ -1337,30 +1402,36 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
*/
// Project
- if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
- {
+ if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
print "";
- if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
+ if ($oldprojectforbreak == -1) {
+ print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
+ }
print " ";
}
// Thirdparty
- if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
- {
+ if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
print '';
- if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10);
+ if ($thirdpartystatic->id > 0) {
+ print $thirdpartystatic->getNomUrl(1, 'project', 10);
+ }
print ' ';
}
// Ref
print '';
print '';
- for ($k = 0; $k < $level; $k++) print '';
+ for ($k = 0; $k < $level; $k++) {
+ print '
';
+ }
print $taskstatic->getNomUrl(1, 'withproject', 'time');
// Label task
print ' ';
print ''.$taskstatic->label.'';
- for ($k = 0; $k < $level; $k++) print "
";
+ for ($k = 0; $k < $level; $k++) {
+ print "
";
+ }
print " \n";
// TASK extrafields
@@ -1369,17 +1440,18 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
// Planned Workload
- if (!empty($arrayfields['t.planned_workload']['checked']))
- {
+ if (!empty($arrayfields['t.planned_workload']['checked'])) {
print '';
- if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin');
- else print '--:--';
+ if ($lines[$i]->planned_workload) {
+ print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin');
+ } else {
+ print '--:--';
+ }
print ' ';
}
// Progress declared %
- if (!empty($arrayfields['t.progress']['checked']))
- {
+ if (!empty($arrayfields['t.progress']['checked'])) {
print '';
print $formother->select_percent($lines[$i]->progress, $lines[$i]->id.'progress');
print ' ';
@@ -1388,19 +1460,23 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
// Time spent by everybody
print '';
// $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user
- if ($lines[$i]->duration)
- {
+ if ($lines[$i]->duration) {
print '';
print convertSecondToTime($lines[$i]->duration, 'allhourmin');
print ' ';
- } else print '--:--';
+ } else {
+ print '--:--';
+ }
print " \n";
// Time spent by user
print '';
$tmptimespent = $taskstatic->getSummaryOfTimeSpent($fuser->id);
- if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin');
- else print '--:--';
+ if ($tmptimespent['total_duration']) {
+ print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin');
+ } else {
+ print '--:--';
+ }
print " \n";
$disabledproject = 1; $disabledtask = 1;
@@ -1408,14 +1484,12 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
//var_dump($lines[$i]);
//var_dump($projectsrole[$lines[$i]->fk_project]);
// If at least one role for project
- if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
- {
+ if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) {
$disabledproject = 0;
$disabledtask = 0;
}
// If $restricteditformytask is on and I have no role on task, i disable edit
- if ($restricteditformytask && empty($tasksrole[$lines[$i]->id]))
- {
+ if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) {
$disabledtask = 1;
}
@@ -1426,9 +1500,13 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
print '';
$cssonholiday = '';
- if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayallday ';
- elseif (!$isavailable[$preselectedday]['morning']) $cssonholiday .= 'onholidaymorning ';
- elseif (!$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayafternoon ';
+ if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) {
+ $cssonholiday .= 'onholidayallday ';
+ } elseif (!$isavailable[$preselectedday]['morning']) {
+ $cssonholiday .= 'onholidaymorning ';
+ } elseif (!$isavailable[$preselectedday]['afternoon']) {
+ $cssonholiday .= 'onholidayafternoon ';
+ }
global $daytoparse;
$tmparray = dol_getdate($daytoparse, true); // detail of current day
@@ -1436,8 +1514,7 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
$idw = ($tmparray['wday'] - (empty($conf->global->MAIN_START_WEEK) ? 0 : 1));
global $numstartworkingday, $numendworkingday;
$cssweekend = '';
- if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css.
- {
+ if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) { // This is a day is not inside the setup of working days, so we use a week-end css.
$cssweekend = 'weekend';
}
@@ -1447,7 +1524,9 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
$totalforeachday[$preselectedday] += $dayWorkLoad;
$alreadyspent = '';
- if ($dayWorkLoad > 0) $alreadyspent = convertSecondToTime($dayWorkLoad, 'allhourmin');
+ if ($dayWorkLoad > 0) {
+ $alreadyspent = convertSecondToTime($dayWorkLoad, 'allhourmin');
+ }
$idw = 0;
@@ -1477,14 +1556,16 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
// Warning
print '';
- if ((!$lines[$i]->public) && $disabledproject) print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject"));
- elseif ($disabledtask)
- {
- $titleassigntask = $langs->trans("AssignTaskToMe");
- if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...');
+ if ((!$lines[$i]->public) && $disabledproject) {
+ print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject"));
+ } elseif ($disabledtask) {
+ $titleassigntask = $langs->trans("AssignTaskToMe");
+ if ($fuser->id != $user->id) {
+ $titleassigntask = $langs->trans("AssignTaskToUser", '...');
+ }
- print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask));
- }
+ print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask));
+ }
print ' ';
print " \n";
@@ -1492,15 +1573,13 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
$inc++;
$level++;
- if ($lines[$i]->id > 0)
- {
+ if ($lines[$i]->id > 0) {
//var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level);
//var_dump($totalforeachday);
$ret = projectLinesPerDay($inc, $lines[$i]->id, $fuser, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable, $oldprojectforbreak, $arrayfields, $extrafields);
//var_dump('ret with parent='.$lines[$i]->id.' level='.$level);
//var_dump($ret);
- foreach ($ret as $key => $val)
- {
+ foreach ($ret as $key => $val) {
$totalforeachday[$key] += $val;
}
//var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks');
@@ -1548,50 +1627,45 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$
$lineswithoutlevel0 = array();
// Create a smaller array with sublevels only to be used later. This increase dramatically performances.
- if ($parent == 0) // Always and only if at first level
- {
- for ($i = 0; $i < $numlines; $i++)
- {
- if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i];
+ if ($parent == 0) { // Always and only if at first level
+ for ($i = 0; $i < $numlines; $i++) {
+ if ($lines[$i]->fk_task_parent) {
+ $lineswithoutlevel0[] = $lines[$i];
+ }
}
}
//dol_syslog('projectLinesPerWeek inc='.$inc.' firstdaytoshow='.$firstdaytoshow.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0));
- if (empty($oldprojectforbreak))
- {
+ if (empty($oldprojectforbreak)) {
$oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 = start break, -1 = never break
}
- for ($i = 0; $i < $numlines; $i++)
- {
- if ($parent == 0) $level = 0;
+ for ($i = 0; $i < $numlines; $i++) {
+ if ($parent == 0) {
+ $level = 0;
+ }
- if ($lines[$i]->fk_task_parent == $parent)
- {
+ if ($lines[$i]->fk_task_parent == $parent) {
$obj = &$lines[$i]; // To display extrafields
// If we want all or we have a role on task, we show it
- if (empty($mine) || !empty($tasksrole[$lines[$i]->id]))
- {
+ if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) {
//dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project);
- if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) // we have no role on task and we request to hide such cases
- {
+ if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) { // we have no role on task and we request to hide such cases
continue;
}
// Break on a new project
- if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
- {
+ if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) {
$lastprojectid = $lines[$i]->fk_project;
$projectstatic->id = $lines[$i]->fk_project;
}
//var_dump('--- '.$level.' '.$firstdaytoshow.' '.$fuser->id.' '.$projectstatic->id.' '.$workloadforid[$projectstatic->id]);
//var_dump($projectstatic->weekWorkLoadPerTask);
- if (empty($workloadforid[$projectstatic->id]))
- {
+ if (empty($workloadforid[$projectstatic->id])) {
$projectstatic->loadTimeSpent($firstdaytoshow, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week
$workloadforid[$projectstatic->id] = 1;
}
@@ -1615,22 +1689,27 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$
$thirdpartystatic->name = $lines[$i]->thirdparty_name;
$thirdpartystatic->email = $lines[$i]->thirdparty_email;
- if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id))
- {
+ if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) {
$addcolspan = 0;
- if (!empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++;
- if (!empty($arrayfields['t.progress']['checked'])) $addcolspan++;
- foreach ($arrayfields as $key => $val)
- {
- if ($val['checked'] && substr($key, 0, 5) == 'efpt.') $addcolspan++;
+ if (!empty($arrayfields['t.planned_workload']['checked'])) {
+ $addcolspan++;
+ }
+ if (!empty($arrayfields['t.progress']['checked'])) {
+ $addcolspan++;
+ }
+ foreach ($arrayfields as $key => $val) {
+ if ($val['checked'] && substr($key, 0, 5) == 'efpt.') {
+ $addcolspan++;
+ }
}
print ''."\n";
print '';
print $projectstatic->getNomUrl(1, '', 0, ''.$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
- if ($thirdpartystatic->id > 0) print ' - '.$thirdpartystatic->getNomUrl(1);
- if ($projectstatic->title)
- {
+ if ($thirdpartystatic->id > 0) {
+ print ' - '.$thirdpartystatic->getNomUrl(1);
+ }
+ if ($projectstatic->title) {
print ' - ';
print ''.$projectstatic->title.' ';
}
@@ -1641,65 +1720,67 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$
print ' ';
// PROJECT fields
- if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center ');
- if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right ');
- if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right ');
- if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right ');
- if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right ');
+ if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center ');
+ if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right ');
+ if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right ');
+ if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right ');
+ if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right ');
- $extrafieldsobjectkey='projet';
- $extrafieldsobjectprefix='efp.';
- include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
+ $extrafieldsobjectkey='projet';
+ $extrafieldsobjectprefix='efp.';
+ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
- print ' ';
- print '';
+ print ' ';
+ print '';
- // PROJECT fields
- if (! empty($arrayfields['p.fk_opp_status']['checked']))
- {
- print '';
- $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code');
- if ($code) print $langs->trans("OppStatus".$code);
- print " \n";
- }
- if (! empty($arrayfields['p.opp_amount']['checked']))
- {
- print '';
- print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency);
- print " \n";
- }
- if (! empty($arrayfields['p.opp_percent']['checked']))
- {
- print '';
- print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %';
- print " \n";
- }
- if (! empty($arrayfields['p.budget_amount']['checked']))
- {
- print '';
- print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency);
- print " \n";
- }
- if (! empty($arrayfields['p.usage_bill_time']['checked']))
- {
- print '';
- print yn($lines[$i]->usage_bill_time);
- print " \n";
- }
+ // PROJECT fields
+ if (! empty($arrayfields['p.fk_opp_status']['checked']))
+ {
+ print '';
+ $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code');
+ if ($code) print $langs->trans("OppStatus".$code);
+ print " \n";
+ }
+ if (! empty($arrayfields['p.opp_amount']['checked']))
+ {
+ print '';
+ print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency);
+ print " \n";
+ }
+ if (! empty($arrayfields['p.opp_percent']['checked']))
+ {
+ print '';
+ print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %';
+ print " \n";
+ }
+ if (! empty($arrayfields['p.budget_amount']['checked']))
+ {
+ print '';
+ print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency);
+ print " \n";
+ }
+ if (! empty($arrayfields['p.usage_bill_time']['checked']))
+ {
+ print '';
+ print yn($lines[$i]->usage_bill_time);
+ print " \n";
+ }
- $extrafieldsobjectkey='projet';
- $extrafieldsobjectprefix='efp.';
- include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
+ $extrafieldsobjectkey='projet';
+ $extrafieldsobjectprefix='efp.';
+ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
- print ' ';
- print '
';
+ print '