--- /tmp/dsg/dolibarr/htdocs/core/lib/github_accounting.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_accounting.lib.php @@ -56,7 +56,7 @@ $head = array(); $head[$h][0] = DOL_URL_ROOT.'/accountancy/admin/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("AccountAccounting"); + $head[$h][1] = $langs->trans("Asset"); $head[$h][2] = 'card'; $h++; @@ -96,7 +96,7 @@ if ($account < 0 || is_empty($account)) return ''; - if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO)) return $account; + if (!is_empty($conf->global->ACCOUNTING_MANAGE_ZERO)) return $account; $g = $conf->global->ACCOUNTING_LENGTH_GACCOUNT; if (!is_empty($g)) { @@ -131,7 +131,7 @@ if ($accounta < 0 || is_empty($accounta)) return ''; - if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO)) return $accounta; + if (!is_empty($conf->global->ACCOUNTING_MANAGE_ZERO)) return $accounta; $a = $conf->global->ACCOUNTING_LENGTH_AACCOUNT; if (!is_empty($a)) { @@ -173,133 +173,73 @@ */ function journalHead($nom, $variante, $period, $periodlink, $description, $builddate, $exportlink = '', $moreparam = array(), $calcmode = '', $varlink = '') { - global $langs; - - print "\n\n\n"; - - if (!is_empty($varlink)) $varlink = '?'.$varlink; - - $head = array(); - $h = 0; - $head[$h][0] = $_SERVER["PHP_SELF"].$varlink; - $head[$h][1] = $langs->trans("Journalization"); - $head[$h][2] = 'journal'; - - print '
'; - print ''; - - print dol_get_fiche_head($head, 'journal'); - - foreach ($moreparam as $key => $value) - { - print ''; - } - print ''; - - // Ligne de titre - print ''; - print ''; - print ''; - print ''; - - // Calculation mode - if ($calcmode) - { - print ''; - print ''; - if (!$variante) print ''; - print ''; - } - - // Ligne de la periode d'analyse du rapport - print ''; - print ''; - if (!$periodlink) print ''; - print ''; - - // Ligne de description - print ''; - print ''; - print ''; - print ''; - - print '
'.$langs->trans("Name").''; - print $nom; - print '
'.$langs->trans("CalculationMode").''; - else print ''; - print $calcmode; - if ($variante) print ''.$variante; - print '
'.$langs->trans("ReportPeriod").''; - else print ''; - if ($period) print $period; - if ($periodlink) print ''.$periodlink; - print '
'.$langs->trans("ReportDescription").''.$description.'
'; - - print dol_get_fiche_end(); - - print '
'; - - print '
'; - - print "\n\n\n"; -} - -/** - * Return Default dates for transfer based on periodicity option in accountancy setup - * - * @return array Dates of periodicity by default - */ -function getDefaultDatesForTransfer() -{ - global $db, $conf; - - // Period by default on transfer (0: previous month | 1: current month | 2: fiscal year) - $periodbydefaultontransfer = $conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER; - isset($periodbydefaultontransfer) ? $periodbydefaultontransfer : 0; - if ($periodbydefaultontransfer == 2) { - $sql = "SELECT date_start, date_end from ".MAIN_DB_PREFIX."accounting_fiscalyear "; - $sql .= " where date_start < '".$db->idate(dol_now())."' and date_end > '".$db->idate(dol_now())."'"; - $sql .= $db->plimit(1); - $res = $db->query($sql); - if ($res->num_rows > 0) { - $fiscalYear = $db->fetch_object($res); - $date_start = strtotime($fiscalYear->date_start); - $date_end = strtotime($fiscalYear->date_end); - } else { - $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); - $year_start = dol_print_date(dol_now(), '%Y'); - $year_end = $year_start + 1; - $month_end = $month_start - 1; - if ($month_end < 1) - { - $month_end = 12; - $year_end--; - } - $date_start = dol_mktime(0, 0, 0, $month_start, 1, $year_start); - $date_end = dol_get_last_day($year_end, $month_end); - } - } elseif ($periodbydefaultontransfer == 1) { - $year_current = strftime("%Y", dol_now()); - $pastmonth = strftime("%m", dol_now()); - $pastmonthyear = $year_current; - if ($pastmonth == 0) { - $pastmonth = 12; - $pastmonthyear--; - } - } else { - $year_current = strftime("%Y", dol_now()); - $pastmonth = strftime("%m", dol_now()) - 1; - $pastmonthyear = $year_current; - if ($pastmonth == 0) { - $pastmonth = 12; - $pastmonthyear--; - } - } - - return array( - 'date_start' => $date_start, - 'date_end' => $date_end, - 'pastmonthyear' => $pastmonthyear, - 'pastmonth' => $pastmonth - ); -} + global $langs; + + print "\n\n\n"; + + if (!is_empty($varlink)) $varlink = '?'.$varlink; + + $head = array(); + $h = 0; + $head[$h][0] = $_SERVER["PHP_SELF"].$varlink; + $head[$h][1] = $langs->trans("Journalization"); + $head[$h][2] = 'journal'; + + print '
'; + print ''; + + dol_fiche_head($head, 'journal'); + + foreach ($moreparam as $key => $value) + { + print ''; + } + print ''; + + // Ligne de titre + print ''; + print ''; + print ''; + print ''; + + // Calculation mode + if ($calcmode) + { + print ''; + print ''; + if (!$variante) print ''; + print ''; + } + + // Ligne de la periode d'analyse du rapport + print ''; + print ''; + if (!$periodlink) print ''; + print ''; + + // Ligne de description + print ''; + print ''; + print ''; + print ''; + + print '
'.$langs->trans("Name").''; + print $nom; + print '
'.$langs->trans("CalculationMode").''; + else print ''; + print $calcmode; + if ($variante) print ''.$variante; + print '
'.$langs->trans("ReportPeriod").''; + else print ''; + if ($period) print $period; + if ($periodlink) print ''.$periodlink; + print '
'.$langs->trans("ReportDescription").''.$description.'
'; + + dol_fiche_end(); + + print '
'; + + print '
'; + + print "\n\n\n"; +} --- /tmp/dsg/dolibarr/htdocs/core/lib/github_admin.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_admin.lib.php @@ -35,23 +35,17 @@ */ function versiontostring($versionarray) { - $string = '?'; - if (isset($versionarray[0])) { - $string = $versionarray[0]; - } - if (isset($versionarray[1])) { - $string .= '.'.$versionarray[1]; - } - if (isset($versionarray[2])) { - $string .= '.'.$versionarray[2]; - } - return $string; + $string = '?'; + if (isset($versionarray[0])) $string = $versionarray[0]; + if (isset($versionarray[1])) $string .= '.'.$versionarray[1]; + if (isset($versionarray[2])) $string .= '.'.$versionarray[2]; + return $string; } /** * Compare 2 versions (stored into 2 arrays). * To check if Dolibarr version is lower than (x,y,z), do "if versioncompare(versiondolibarrarray(), array(x.y.z)) <= 0" - * For example: if (versioncompare(versiondolibarrarray(),array(4,0,-5)) >= 0) is true if version is 4.0 alpha or higher. + * For example: if (versioncompare(versiondolibarrarray(),array(4,0,-4)) >= 0) is true if version is 4.0 alpha or higher. * For example: if (versioncompare(versiondolibarrarray(),array(4,0,0)) >= 0) is true if version is 4.0 final or higher. * For example: if (versioncompare(versiondolibarrarray(),array(4,0,1)) >= 0) is true if version is 4.0.1 or higher. * Alternative way to compare: if ((float) DOL_VERSION >= 4.0) is true if version is 4.0 alpha or higher (works only to compare first and second level) @@ -65,55 +59,32 @@ */ function versioncompare($versionarray1, $versionarray2) { - $ret = 0; - $level = 0; - $count1 = count($versionarray1); - $count2 = count($versionarray2); - $maxcount = max($count1, $count2); - while ($level < $maxcount) { - $operande1 = isset($versionarray1[$level]) ? $versionarray1[$level] : 0; - $operande2 = isset($versionarray2[$level]) ? $versionarray2[$level] : 0; - if (preg_match('/alpha|dev/i', $operande1)) { - $operande1 = -5; - } - if (preg_match('/alpha|dev/i', $operande2)) { - $operande2 = -5; - } - if (preg_match('/beta$/i', $operande1)) { - $operande1 = -4; - } - if (preg_match('/beta$/i', $operande2)) { - $operande2 = -4; - } - if (preg_match('/beta([0-9])+/i', $operande1)) { - $operande1 = -3; - } - if (preg_match('/beta([0-9])+/i', $operande2)) { - $operande2 = -3; - } - if (preg_match('/rc$/i', $operande1)) { - $operande1 = -2; - } - if (preg_match('/rc$/i', $operande2)) { - $operande2 = -2; - } - if (preg_match('/rc([0-9])+/i', $operande1)) { - $operande1 = -1; - } - if (preg_match('/rc([0-9])+/i', $operande2)) { - $operande2 = -1; - } - $level++; - //print 'level '.$level.' '.$operande1.'-'.$operande2.'
'; - if ($operande1 < $operande2) { - $ret = -$level; break; - } - if ($operande1 > $operande2) { - $ret = $level; break; - } - } - //print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'
'."\n"; - return $ret; + $ret = 0; + $level = 0; + $count1 = count($versionarray1); + $count2 = count($versionarray2); + $maxcount = max($count1, $count2); + while ($level < $maxcount) + { + $operande1 = isset($versionarray1[$level]) ? $versionarray1[$level] : 0; + $operande2 = isset($versionarray2[$level]) ? $versionarray2[$level] : 0; + if (preg_match('/alpha|dev/i', $operande1)) $operande1 = -5; + if (preg_match('/alpha|dev/i', $operande2)) $operande2 = -5; + if (preg_match('/beta$/i', $operande1)) $operande1 = -4; + if (preg_match('/beta$/i', $operande2)) $operande2 = -4; + if (preg_match('/beta([0-9])+/i', $operande1)) $operande1 = -3; + if (preg_match('/beta([0-9])+/i', $operande2)) $operande2 = -3; + if (preg_match('/rc$/i', $operande1)) $operande1 = -2; + if (preg_match('/rc$/i', $operande2)) $operande2 = -2; + if (preg_match('/rc([0-9])+/i', $operande1)) $operande1 = -1; + if (preg_match('/rc([0-9])+/i', $operande2)) $operande2 = -1; + $level++; + //print 'level '.$level.' '.$operande1.'-'.$operande2.'
'; + if ($operande1 < $operande2) { $ret = -$level; break; } + if ($operande1 > $operande2) { $ret = $level; break; } + } + //print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'
'."\n"; + return $ret; } @@ -124,7 +95,7 @@ */ function versionphparray() { - return explode('.', PHP_VERSION); + return explode('.', PHP_VERSION); } /** @@ -134,7 +105,7 @@ */ function versiondolibarrarray() { - return explode('.', DOL_VERSION); + return explode('.', DOL_VERSION); } @@ -160,255 +131,252 @@ */ function run_sql($sqlfile, $silent = 1, $entity = '', $usesavepoint = 1, $handler = '', $okerror = 'default', $linelengthlimit = 32768, $nocommentremoval = 0, $offsetforchartofaccount = 0) { - global $db, $conf, $langs, $user; - - dol_syslog("Admin.lib::run_sql run sql file ".$sqlfile." silent=".$silent." entity=".$entity." usesavepoint=".$usesavepoint." handler=".$handler." okerror=".$okerror, LOG_DEBUG); - - if (!is_numeric($linelengthlimit)) { - dol_syslog("Admin.lib::run_sql param linelengthlimit is not a numeric", LOG_ERR); - return -1; - } - - $ok = 0; - $error = 0; - $i = 0; - $buffer = ''; - $arraysql = array(); - - // Get version of database - $versionarray = $db->getVersionArray(); - - $fp = fopen($sqlfile, "r"); - if ($fp) { - while (!feof($fp)) { - // Warning fgets with second parameter that is null or 0 hang. - if ($linelengthlimit > 0) { - $buf = fgets($fp, $linelengthlimit); - } else { - $buf = fgets($fp); - } - - // Test if request must be ran only for particular database or version (if yes, we must remove the -- comment) - $reg = array(); - if (preg_match('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', $buf, $reg)) { - $qualified = 1; - - // restrict on database type - if (!empty($reg[1])) { - if (!preg_match('/'.preg_quote($reg[1]).'/i', $db->type)) { - $qualified = 0; - } - } - - // restrict on version - if ($qualified) { - if (!empty($reg[2])) { - if (is_numeric($reg[2])) { // This is a version - $versionrequest = explode('.', $reg[2]); - //print var_dump($versionrequest); - //print var_dump($versionarray); - if (!count($versionrequest) || !count($versionarray) || versioncompare($versionrequest, $versionarray) > 0) { - $qualified = 0; - } - } else // This is a test on a constant. For example when we have -- VMYSQLUTF8UNICODE, we test constant $conf->global->UTF8UNICODE - { - $dbcollation = strtoupper(preg_replace('/_/', '', $conf->db->dolibarr_main_db_collation)); - //var_dump($reg[2]); - //var_dump($dbcollation); - if (empty($conf->db->dolibarr_main_db_collation) || ($reg[2] != $dbcollation)) { - $qualified = 0; - } - //var_dump($qualified); - } - } - } - - if ($qualified) { - // Version qualified, delete SQL comments - $buf = preg_replace('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', '', $buf); - //print "Ligne $i qualifi?e par version: ".$buf.'
'; - } - } - - // Add line buf to buffer if not a comment - if ($nocommentremoval || !preg_match('/^\s*--/', $buf)) { - if (empty($nocommentremoval)) { - $buf = preg_replace('/([,;ERLT\)])\s*--.*$/i', '\1', $buf); //remove comment from a line that not start with -- before add it to the buffer - } - $buffer .= trim($buf); - } - - //print $buf.'
';exit; - - if (preg_match('/;/', $buffer)) { // If string contains ';', it's end of a request string, we save it in arraysql. - // Found new request - if ($buffer) { - $arraysql[$i] = $buffer; - } - $i++; - $buffer = ''; - } - } - - if ($buffer) { - $arraysql[$i] = $buffer; - } - fclose($fp); - } else { - dol_syslog("Admin.lib::run_sql failed to open file ".$sqlfile, LOG_ERR); - } - - // Loop on each request to see if there is a __+MAX_table__ key - $listofmaxrowid = array(); // This is a cache table - foreach ($arraysql as $i => $sql) { - $newsql = $sql; - - // Replace __+MAX_table__ with max of table - while (preg_match('/__\+MAX_([A-Za-z0-9_]+)__/i', $newsql, $reg)) { - $table = $reg[1]; - if (!isset($listofmaxrowid[$table])) { - //var_dump($db); - $sqlgetrowid = 'SELECT MAX(rowid) as max from '.preg_replace('/^llx_/', MAIN_DB_PREFIX, $table); - $resql = $db->query($sqlgetrowid); - if ($resql) { - $obj = $db->fetch_object($resql); - $listofmaxrowid[$table] = $obj->max; - if (empty($listofmaxrowid[$table])) { - $listofmaxrowid[$table] = 0; - } - } else { - if (!$silent) { - print ''; - } - if (!$silent) { - print '
'.$langs->trans("Failed to get max rowid for ".$table)."
"; - } - if (!$silent) { - print ''; - } - $error++; - break; - } - } - // Replace __+MAX_llx_table__ with +999 - $from = '__+MAX_'.$table.'__'; - $to = '+'.$listofmaxrowid[$table]; - $newsql = str_replace($from, $to, $newsql); - dol_syslog('Admin.lib::run_sql New Request '.($i + 1).' (replacing '.$from.' to '.$to.')', LOG_DEBUG); - - $arraysql[$i] = $newsql; - } - - if ($offsetforchartofaccount > 0) { - // Replace lines - // 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401, 'PCG99-ABREGE', 'CAPIT', '1234', 1400, '...', 1);' - // with - // 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401 + 200100000, 'PCG99-ABREGE','CAPIT', '1234', 1400 + 200100000, '...', 1);' - // Note: string with 1234 instead of '1234' is also supported - $newsql = preg_replace('/VALUES\s*\(__ENTITY__, \s*(\d+)\s*,(\s*\'[^\',]*\'\s*,\s*\'[^\',]*\'\s*,\s*\'?[^\',]*\'?\s*),\s*\'?([^\',]*)\'?/ims', 'VALUES (__ENTITY__, \1 + '.$offsetforchartofaccount.', \2, \3 + '.$offsetforchartofaccount, $newsql); - $newsql = preg_replace('/([,\s])0 \+ '.$offsetforchartofaccount.'/ims', '\1 0', $newsql); - //var_dump($newsql); - $arraysql[$i] = $newsql; - } - } - - // Loop on each request to execute request - $cursorinsert = 0; - $listofinsertedrowid = array(); - foreach ($arraysql as $i => $sql) { - if ($sql) { - // Replace the prefix tables - if (MAIN_DB_PREFIX != 'llx_') { - $sql = preg_replace('/llx_/i', MAIN_DB_PREFIX, $sql); - } - - if (!empty($handler)) { - $sql = preg_replace('/__HANDLER__/i', "'".$db->escape($handler)."'", $sql); - } - - $newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? $entity : $conf->entity), $sql); - - // Add log of request - if (!$silent) { - print ''.$langs->trans("Request").' '.($i + 1)." sql='".dol_htmlentities($newsql, ENT_NOQUOTES)."'\n"; - } - dol_syslog('Admin.lib::run_sql Request '.($i + 1), LOG_DEBUG); + global $db, $conf, $langs, $user; + + dol_syslog("Admin.lib::run_sql run sql file ".$sqlfile." silent=".$silent." entity=".$entity." usesavepoint=".$usesavepoint." handler=".$handler." okerror=".$okerror, LOG_DEBUG); + + if (!is_numeric($linelengthlimit)) + { + dol_syslog("Admin.lib::run_sql param linelengthlimit is not a numeric", LOG_ERR); + return -1; + } + + $ok = 0; + $error = 0; + $i = 0; + $buffer = ''; + $arraysql = array(); + + // Get version of database + $versionarray = $db->getVersionArray(); + + $fp = fopen($sqlfile, "r"); + if ($fp) + { + while (!feof($fp)) + { + // Warning fgets with second parameter that is null or 0 hang. + if ($linelengthlimit > 0) $buf = fgets($fp, $linelengthlimit); + else $buf = fgets($fp); + + // Test if request must be ran only for particular database or version (if yes, we must remove the -- comment) + $reg = array(); + if (preg_match('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', $buf, $reg)) + { + $qualified = 1; + + // restrict on database type + if (!empty($reg[1])) + { + if (!preg_match('/'.preg_quote($reg[1]).'/i', $db->type)) $qualified = 0; + } + + // restrict on version + if ($qualified) + { + if (!empty($reg[2])) + { + if (is_numeric($reg[2])) // This is a version + { + $versionrequest = explode('.', $reg[2]); + //print var_dump($versionrequest); + //print var_dump($versionarray); + if (!count($versionrequest) || !count($versionarray) || versioncompare($versionrequest, $versionarray) > 0) + { + $qualified = 0; + } + } + else // This is a test on a constant. For example when we have -- VMYSQLUTF8UNICODE, we test constant $conf->global->UTF8UNICODE + { + $dbcollation = strtoupper(preg_replace('/_/', '', $conf->db->dolibarr_main_db_collation)); + //var_dump($reg[2]); + //var_dump($dbcollation); + if (empty($conf->db->dolibarr_main_db_collation) || ($reg[2] != $dbcollation)) $qualified = 0; + //var_dump($qualified); + } + } + } + + if ($qualified) + { + // Version qualified, delete SQL comments + $buf = preg_replace('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', '', $buf); + //print "Ligne $i qualifi?e par version: ".$buf.'
'; + } + } + + // Add line buf to buffer if not a comment + if ($nocommentremoval || !preg_match('/^\s*--/', $buf)) + { + if (empty($nocommentremoval)) $buf = preg_replace('/([,;ERLT\)])\s*--.*$/i', '\1', $buf); //remove comment from a line that not start with -- before add it to the buffer + $buffer .= trim($buf); + } + + //print $buf.'
';exit; + + if (preg_match('/;/', $buffer)) // If string contains ';', it's end of a request string, we save it in arraysql. + { + // Found new request + if ($buffer) $arraysql[$i] = $buffer; + $i++; + $buffer = ''; + } + } + + if ($buffer) $arraysql[$i] = $buffer; + fclose($fp); + } + else + { + dol_syslog("Admin.lib::run_sql failed to open file ".$sqlfile, LOG_ERR); + } + + // Loop on each request to see if there is a __+MAX_table__ key + $listofmaxrowid = array(); // This is a cache table + foreach ($arraysql as $i => $sql) + { + $newsql = $sql; + + // Replace __+MAX_table__ with max of table + while (preg_match('/__\+MAX_([A-Za-z0-9_]+)__/i', $newsql, $reg)) + { + $table = $reg[1]; + if (!isset($listofmaxrowid[$table])) + { + //var_dump($db); + $sqlgetrowid = 'SELECT MAX(rowid) as max from '.preg_replace('/^llx_/', MAIN_DB_PREFIX, $table); + $resql = $db->query($sqlgetrowid); + if ($resql) + { + $obj = $db->fetch_object($resql); + $listofmaxrowid[$table] = $obj->max; + if (empty($listofmaxrowid[$table])) $listofmaxrowid[$table] = 0; + } + else + { + if (!$silent) print ''; + if (!$silent) print '
'.$langs->trans("Failed to get max rowid for ".$table)."
"; + if (!$silent) print ''; + $error++; + break; + } + } + // Replace __+MAX_llx_table__ with +999 + $from = '__+MAX_'.$table.'__'; + $to = '+'.$listofmaxrowid[$table]; + $newsql = str_replace($from, $to, $newsql); + dol_syslog('Admin.lib::run_sql New Request '.($i + 1).' (replacing '.$from.' to '.$to.')', LOG_DEBUG); + + $arraysql[$i] = $newsql; + } + + if ($offsetforchartofaccount > 0) + { + // Replace lines + // 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401, 'PCG99-ABREGE','CAPIT', 'XXXXXX', '1', '0', '...', 1);' + // with + // 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401 + 200100000, 'PCG99-ABREGE','CAPIT', 'XXXXXX', '1', '0', '...', 1);' + $newsql = preg_replace('/VALUES\s*\(__ENTITY__, \s*(\d+)\s*,(\s*\'[^\',]*\'\s*,\s*\'[^\',]*\'\s*,\s*\'?[^\',]*\'?\s*),\s*\'?([^\',]*)\'?/ims', 'VALUES (__ENTITY__, \1 + '.$offsetforchartofaccount.', \2, \3 + '.$offsetforchartofaccount, $newsql); + $newsql = preg_replace('/([,\s])0 \+ '.$offsetforchartofaccount.'/ims', '\1 0', $newsql); + //var_dump($newsql); + $arraysql[$i] = $newsql; + } + } + + // Loop on each request to execute request + $cursorinsert = 0; + $listofinsertedrowid = array(); + foreach ($arraysql as $i => $sql) + { + if ($sql) + { + // Replace the prefix tables + if (MAIN_DB_PREFIX != 'llx_') + { + $sql = preg_replace('/llx_/i', MAIN_DB_PREFIX, $sql); + } + + if (!empty($handler)) $sql = preg_replace('/__HANDLER__/i', "'".$handler."'", $sql); + + $newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? $entity : $conf->entity), $sql); + + // Ajout trace sur requete (eventuellement a commenter si beaucoup de requetes) + if (!$silent) print ''.$langs->trans("Request").' '.($i + 1)." sql='".dol_htmlentities($newsql, ENT_NOQUOTES)."'\n"; + dol_syslog('Admin.lib::run_sql Request '.($i + 1), LOG_DEBUG); $sqlmodified = 0; - // Replace for encrypt data - if (preg_match_all('/__ENCRYPT\(\'([^\']+)\'\)__/i', $newsql, $reg)) { - $num = count($reg[0]); - - for ($j = 0; $j < $num; $j++) { - $from = $reg[0][$j]; - $to = $db->encrypt($reg[1][$j], 1); - $newsql = str_replace($from, $to, $newsql); - } - $sqlmodified++; - } - - // Replace for decrypt data - if (preg_match_all('/__DECRYPT\(\'([A-Za-z0-9_]+)\'\)__/i', $newsql, $reg)) { - $num = count($reg[0]); - - for ($j = 0; $j < $num; $j++) { - $from = $reg[0][$j]; - $to = $db->decrypt($reg[1][$j]); - $newsql = str_replace($from, $to, $newsql); - } - $sqlmodified++; - } - - // Replace __x__ with rowid of insert nb x - while (preg_match('/__([0-9]+)__/', $newsql, $reg)) { - $cursor = $reg[1]; - if (empty($listofinsertedrowid[$cursor])) { - if (!$silent) { - print ''; - } - if (!$silent) { - print '
'.$langs->trans("FileIsNotCorrect")."
"; - } - if (!$silent) { - print ''; - } - $error++; - break; - } - $from = '__'.$cursor.'__'; - $to = $listofinsertedrowid[$cursor]; - $newsql = str_replace($from, $to, $newsql); - $sqlmodified++; - } - - if ($sqlmodified) { - dol_syslog('Admin.lib::run_sql New Request '.($i + 1), LOG_DEBUG); - } - - $result = $db->query($newsql, $usesavepoint); - if ($result) { - if (!$silent) { - print ''."\n"; - } - - if (preg_replace('/insert into ([^\s]+)/i', $newsql, $reg)) { - $cursorinsert++; - - // It's an insert - $table = preg_replace('/([^a-zA-Z_]+)/i', '', $reg[1]); - $insertedrowid = $db->last_insert_id($table); - $listofinsertedrowid[$cursorinsert] = $insertedrowid; - dol_syslog('Admin.lib::run_sql Insert nb '.$cursorinsert.', done in table '.$table.', rowid is '.$listofinsertedrowid[$cursorinsert], LOG_DEBUG); - } - // print 'OK'; - } else { - $errno = $db->errno(); - if (!$silent) { - print ''."\n"; - } + // Replace for encrypt data + if (preg_match_all('/__ENCRYPT\(\'([^\']+)\'\)__/i', $newsql, $reg)) + { + $num = count($reg[0]); + + for ($j = 0; $j < $num; $j++) + { + $from = $reg[0][$j]; + $to = $db->encrypt($reg[1][$j], 1); + $newsql = str_replace($from, $to, $newsql); + } + $sqlmodified++; + } + + // Replace for decrypt data + if (preg_match_all('/__DECRYPT\(\'([A-Za-z0-9_]+)\'\)__/i', $newsql, $reg)) + { + $num = count($reg[0]); + + for ($j = 0; $j < $num; $j++) + { + $from = $reg[0][$j]; + $to = $db->decrypt($reg[1][$j]); + $newsql = str_replace($from, $to, $newsql); + } + $sqlmodified++; + } + + // Replace __x__ with rowid of insert nb x + while (preg_match('/__([0-9]+)__/', $newsql, $reg)) + { + $cursor = $reg[1]; + if (empty($listofinsertedrowid[$cursor])) + { + if (!$silent) print ''; + if (!$silent) print '
'.$langs->trans("FileIsNotCorrect")."
"; + if (!$silent) print ''; + $error++; + break; + } + $from = '__'.$cursor.'__'; + $to = $listofinsertedrowid[$cursor]; + $newsql = str_replace($from, $to, $newsql); + $sqlmodified++; + } + + if ($sqlmodified) dol_syslog('Admin.lib::run_sql New Request '.($i + 1), LOG_DEBUG); + + $result = $db->query($newsql, $usesavepoint); + if ($result) + { + if (!$silent) print ''."\n"; + + if (preg_replace('/insert into ([^\s]+)/i', $newsql, $reg)) + { + $cursorinsert++; + + // It's an insert + $table = preg_replace('/([^a-zA-Z_]+)/i', '', $reg[1]); + $insertedrowid = $db->last_insert_id($table); + $listofinsertedrowid[$cursorinsert] = $insertedrowid; + dol_syslog('Admin.lib::run_sql Insert nb '.$cursorinsert.', done in table '.$table.', rowid is '.$listofinsertedrowid[$cursorinsert], LOG_DEBUG); + } + // print 'OK'; + } + else + { + $errno = $db->errno(); + if (!$silent) print ''."\n"; // Define list of errors we accept (array $okerrors) - $okerrors = array( // By default + $okerrors = array( // By default 'DB_ERROR_TABLE_ALREADY_EXISTS', 'DB_ERROR_COLUMN_ALREADY_EXISTS', 'DB_ERROR_KEY_NAME_ALREADY_EXISTS', @@ -421,68 +389,39 @@ 'DB_ERROR_CANNOT_CREATE', // Qd contrainte deja existante 'DB_ERROR_CANT_DROP_PRIMARY_KEY', 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS', - 'DB_ERROR_22P02' + 'DB_ERROR_22P02' ); - if ($okerror == 'none') { - $okerrors = array(); + if ($okerror == 'none') $okerrors = array(); + + // Is it an error we accept + if (!in_array($errno, $okerrors)) + { + if (!$silent) print ''; + if (!$silent) print '
'.$langs->trans("Error")." ".$db->errno().": ".$newsql."
".$db->error()."
"; + if (!$silent) print ''."\n"; + dol_syslog('Admin.lib::run_sql Request '.($i + 1)." Error ".$db->errno()." ".$newsql."
".$db->error(), LOG_ERR); + $error++; } - - // Is it an error we accept - if (!in_array($errno, $okerrors)) { - if (!$silent) { - print ''; - } - if (!$silent) { - print '
'.$langs->trans("Error")." ".$db->errno().": ".$newsql."
".$db->error()."
"; - } - if (!$silent) { - print ''."\n"; - } - dol_syslog('Admin.lib::run_sql Request '.($i + 1)." Error ".$db->errno()." ".$newsql."
".$db->error(), LOG_ERR); - $error++; - } - } - - if (!$silent) { - print ''."\n"; - } - } - } - - if (!$silent) { - print ''.$langs->trans("ProcessMigrateScript").''; - print ''; - if ($error == 0) { - print ''.$langs->trans("OK").''; - } else { - print ''.$langs->trans("Error").''; - } - //if (! empty($conf->use_javascript_ajax)) { - print ''; - print ' - '.$langs->trans("ShowHideDetails").''; - //} - print ''."\n"; - } - - if ($error == 0) { - $ok = 1; - } else { - $ok = 0; - } - - return $ok; + } + + if (!$silent) print ''."\n"; + } + } + + if ($error == 0) + { + if (!$silent) print ''.$langs->trans("ProcessMigrateScript").''; + if (!$silent) print ''.$langs->trans("OK").''."\n"; + $ok = 1; + } + else + { + if (!$silent) print ''.$langs->trans("ProcessMigrateScript").''; + if (!$silent) print ''.$langs->trans("KO").''."\n"; + $ok = 0; + } + + return $ok; } @@ -498,32 +437,32 @@ */ function dolibarr_del_const($db, $name, $entity = 1) { - global $conf; - - if (empty($name)) { - dol_print_error('', 'Error call dolibar_del_const with parameter name empty'); - return -1; - } - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql .= " WHERE (".$db->decrypt('name')." = '".$db->escape($name)."'"; - if (is_numeric($name)) { - $sql .= " OR rowid = '".$db->escape($name)."'"; - } - $sql .= ")"; - if ($entity >= 0) { - $sql .= " AND entity = ".$entity; - } - - dol_syslog("admin.lib::dolibarr_del_const", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) { - $conf->global->$name = ''; - return 1; - } else { - dol_print_error($db); - return -1; - } + global $conf; + + if (empty($name)) + { + dol_print_error('', 'Error call dolibar_del_const with parameter name empty'); + return -1; + } + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; + $sql .= " WHERE (".$db->decrypt('name')." = '".$db->escape($name)."'"; + if (is_numeric($name)) $sql .= " OR rowid = '".$db->escape($name)."'"; + $sql .= ")"; + if ($entity >= 0) $sql .= " AND entity = ".$entity; + + dol_syslog("admin.lib::dolibarr_del_const", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $conf->global->$name = ''; + return 1; + } + else + { + dol_print_error($db); + return -1; + } } /** @@ -538,23 +477,22 @@ */ function dolibarr_get_const($db, $name, $entity = 1) { - global $conf; - $value = ''; - - $sql = "SELECT ".$db->decrypt('value')." as value"; - $sql .= " FROM ".MAIN_DB_PREFIX."const"; - $sql .= " WHERE name = ".$db->encrypt($name, 1); - $sql .= " AND entity = ".$entity; - - dol_syslog("admin.lib::dolibarr_get_const", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) { - $obj = $db->fetch_object($resql); - if ($obj) { - $value = $obj->value; - } - } - return $value; + global $conf; + $value = ''; + + $sql = "SELECT ".$db->decrypt('value')." as value"; + $sql .= " FROM ".MAIN_DB_PREFIX."const"; + $sql .= " WHERE name = ".$db->encrypt($name, 1); + $sql .= " AND entity = ".$entity; + + dol_syslog("admin.lib::dolibarr_get_const", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + if ($obj) $value = $obj->value; + } + return $value; } @@ -574,52 +512,55 @@ */ function dolibarr_set_const($db, $name, $value, $type = 'chaine', $visible = 0, $note = '', $entity = 1) { - global $conf; - - // Clean parameters - $name = trim($name); - - // Check parameters - if (empty($name)) { - dol_print_error($db, "Error: Call to function dolibarr_set_const with wrong parameters", LOG_ERR); - exit; - } - - //dol_syslog("dolibarr_set_const name=$name, value=$value type=$type, visible=$visible, note=$note entity=$entity"); - - $db->begin(); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql .= " WHERE name = ".$db->encrypt($name, 1); - if ($entity >= 0) { - $sql .= " AND entity = ".$entity; - } - - dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG); - $resql = $db->query($sql); - - if (strcmp($value, '')) { // true if different. Must work for $value='0' or $value=0 - $sql = "INSERT INTO ".MAIN_DB_PREFIX."const(name,value,type,visible,note,entity)"; - $sql .= " VALUES ("; - $sql .= $db->encrypt($name, 1); - $sql .= ", ".$db->encrypt($value, 1); - $sql .= ",'".$db->escape($type)."',".$visible.",'".$db->escape($note)."',".$entity.")"; - - //print "sql".$value."-".pg_escape_string($value)."-".$sql;exit; - //print "xx".$db->escape($value); - dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG); - $resql = $db->query($sql); - } - - if ($resql) { - $db->commit(); - $conf->global->$name = $value; - return 1; - } else { - $error = $db->lasterror(); - $db->rollback(); - return -1; - } + global $conf; + + // Clean parameters + $name = trim($name); + + // Check parameters + if (empty($name)) + { + dol_print_error($db, "Error: Call to function dolibarr_set_const with wrong parameters", LOG_ERR); + exit; + } + + //dol_syslog("dolibarr_set_const name=$name, value=$value type=$type, visible=$visible, note=$note entity=$entity"); + + $db->begin(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; + $sql .= " WHERE name = ".$db->encrypt($name, 1); + if ($entity >= 0) $sql .= " AND entity = ".$entity; + + dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG); + $resql = $db->query($sql); + + if (strcmp($value, '')) // true if different. Must work for $value='0' or $value=0 + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."const(name,value,type,visible,note,entity)"; + $sql .= " VALUES ("; + $sql .= $db->encrypt($name, 1); + $sql .= ", ".$db->encrypt($value, 1); + $sql .= ",'".$db->escape($type)."',".$visible.",'".$db->escape($note)."',".$entity.")"; + + //print "sql".$value."-".pg_escape_string($value)."-".$sql;exit; + //print "xx".$db->escape($value); + dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG); + $resql = $db->query($sql); + } + + if ($resql) + { + $db->commit(); + $conf->global->$name = $value; + return 1; + } + else + { + $error = $db->lasterror(); + $db->rollback(); + return -1; + } } @@ -635,10 +576,10 @@ global $langs, $conf, $user; $h = 0; $head = array(); - $mode = empty($conf->global->MAIN_MODULE_SETUP_ON_LIST_BY_DEFAULT) ? 'commonkanban' : 'common'; - $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=".$mode; + + $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=commonkanban"; $head[$h][1] = $langs->trans("AvailableModules"); - $head[$h][2] = 'modules'; + $head[$h][2] = 'commonkanban'; $h++; $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=marketplace"; @@ -667,72 +608,66 @@ */ function security_prepare_head() { - global $db, $langs, $conf, $user; - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT."/admin/security_other.php"; - $head[$h][1] = $langs->trans("Miscellaneous"); - $head[$h][2] = 'misc'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/security.php"; - $head[$h][1] = $langs->trans("Passwords"); - $head[$h][2] = 'passwords'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/security_file.php"; - $head[$h][1] = $langs->trans("Files").' ('.$langs->trans("Upload").')'; - $head[$h][2] = 'file'; - $h++; - - /* - $head[$h][0] = DOL_URL_ROOT."/admin/security_file_download.php"; - $head[$h][1] = $langs->trans("Files").' ('.$langs->trans("Download").')'; - $head[$h][2] = 'filedownload'; - $h++; + global $db, $langs, $conf, $user; + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT."/admin/security_other.php"; + $head[$h][1] = $langs->trans("Miscellaneous"); + $head[$h][2] = 'misc'; + $h++; + + $head[$h][0] = DOL_URL_ROOT."/admin/security.php"; + $head[$h][1] = $langs->trans("Passwords"); + $head[$h][2] = 'passwords'; + $h++; + + $head[$h][0] = DOL_URL_ROOT."/admin/security_file.php"; + $head[$h][1] = $langs->trans("Files").' ('.$langs->trans("Upload").')'; + $head[$h][2] = 'file'; + $h++; + + /* + $head[$h][0] = DOL_URL_ROOT."/admin/security_file_download.php"; + $head[$h][1] = $langs->trans("Files").' ('.$langs->trans("Download").')'; + $head[$h][2] = 'filedownload'; + $h++; */ - $head[$h][0] = DOL_URL_ROOT."/admin/proxy.php"; - $head[$h][1] = $langs->trans("ExternalAccess"); - $head[$h][2] = 'proxy'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/events.php"; - $head[$h][1] = $langs->trans("Audit"); - $head[$h][2] = 'audit'; - $h++; - - - // Show permissions lines - $nbPerms = 0; - $sql = "SELECT COUNT(r.id) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."rights_def as r"; - $sql .= " WHERE r.libelle NOT LIKE 'tou%'"; // On ignore droits "tous" - $sql .= " AND entity = ".$conf->entity; - $sql .= " AND bydefault = 1"; - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { - $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled - } - $resql = $db->query($sql); - if ($resql) { - $obj = $db->fetch_object($resql); - if ($obj) { - $nbPerms = $obj->nb; - } - } else { - dol_print_error($db); - } - - $head[$h][0] = DOL_URL_ROOT."/admin/perms.php"; - $head[$h][1] = $langs->trans("DefaultRights"); - if ($nbPerms > 0) { - $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.$nbPerms.'' : ''); - } - $head[$h][2] = 'default'; - $h++; - - return $head; + $head[$h][0] = DOL_URL_ROOT."/admin/proxy.php"; + $head[$h][1] = $langs->trans("ExternalAccess"); + $head[$h][2] = 'proxy'; + $h++; + + $head[$h][0] = DOL_URL_ROOT."/admin/events.php"; + $head[$h][1] = $langs->trans("Audit"); + $head[$h][2] = 'audit'; + $h++; + + + // Show permissions lines + $nbPerms = 0; + $sql = "SELECT COUNT(r.id) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."rights_def as r"; + $sql .= " WHERE r.libelle NOT LIKE 'tou%'"; // On ignore droits "tous" + $sql .= " AND entity = ".$conf->entity; + $sql .= " AND bydefault = 1"; + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + if ($obj) $nbPerms = $obj->nb; + } + else dol_print_error($db); + + $head[$h][0] = DOL_URL_ROOT."/admin/perms.php"; + $head[$h][1] = $langs->trans("DefaultRights"); + if ($nbPerms > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.$nbPerms.'' : ''); + $head[$h][2] = 'default'; + $h++; + + return $head; } /** @@ -742,12 +677,12 @@ */ function modulehelp_prepare_head($object) { - global $langs, $conf, $user; - $h = 0; - $head = array(); - - // FIX for compatibity habitual tabs - $object->id = $object->numero; + global $langs, $conf, $user; + $h = 0; + $head = array(); + + // FIX for compatibity habitual tabs + $object->id = $object->numero; $head[$h][0] = DOL_URL_ROOT."/admin/modulehelp.php?id=".$object->id.'&mode=desc'; $head[$h][1] = $langs->trans("Description"); @@ -759,19 +694,20 @@ $head[$h][2] = 'feature'; $h++; - if ($object->isCoreOrExternalModule() == 'external') { + if ($object->isCoreOrExternalModule() == 'external') + { $head[$h][0] = DOL_URL_ROOT."/admin/modulehelp.php?id=".$object->id.'&mode=changelog'; $head[$h][1] = $langs->trans("ChangeLog"); $head[$h][2] = 'changelog'; $h++; } - complete_head_from_modules($conf, $langs, $object, $head, $h, 'modulehelp_admin'); - - complete_head_from_modules($conf, $langs, $object, $head, $h, 'modulehelp_admin', 'remove'); - - - return $head; + complete_head_from_modules($conf, $langs, $object, $head, $h, 'modulehelp_admin'); + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'modulehelp_admin', 'remove'); + + + return $head; } /** * Prepare array with list of tabs @@ -780,26 +716,26 @@ */ function translation_prepare_head() { - global $langs, $conf, $user; - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=searchkey"; - $head[$h][1] = $langs->trans("TranslationKeySearch"); - $head[$h][2] = 'searchkey'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=overwrite"; - $head[$h][1] = $langs->trans("TranslationOverwriteKey").''; - $head[$h][2] = 'overwrite'; - $h++; - - complete_head_from_modules($conf, $langs, null, $head, $h, 'translation_admin'); - - complete_head_from_modules($conf, $langs, null, $head, $h, 'translation_admin', 'remove'); - - - return $head; + global $langs, $conf, $user; + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=overwrite"; + $head[$h][1] = $langs->trans("TranslationOverwriteKey").''; + $head[$h][2] = 'overwrite'; + $h++; + + $head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=searchkey"; + $head[$h][1] = $langs->trans("TranslationKeySearch"); + $head[$h][2] = 'searchkey'; + $h++; + + complete_head_from_modules($conf, $langs, null, $head, $h, 'translation_admin'); + + complete_head_from_modules($conf, $langs, null, $head, $h, 'translation_admin', 'remove'); + + + return $head; } @@ -810,48 +746,49 @@ */ function defaultvalues_prepare_head() { - global $langs, $conf, $user; - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=createform"; - $head[$h][1] = $langs->trans("DefaultCreateForm"); - $head[$h][2] = 'createform'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=filters"; - $head[$h][1] = $langs->trans("DefaultSearchFilters"); - $head[$h][2] = 'filters'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=sortorder"; - $head[$h][1] = $langs->trans("DefaultSortOrder"); - $head[$h][2] = 'sortorder'; - $h++; - - if (!empty($conf->use_javascript_ajax)) { - $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=focus"; - $head[$h][1] = $langs->trans("DefaultFocus"); - $head[$h][2] = 'focus'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=mandatory"; - $head[$h][1] = $langs->trans("DefaultMandatory"); - $head[$h][2] = 'mandatory'; - $h++; - } - - /*$head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=searchkey"; - $head[$h][1] = $langs->trans("TranslationKeySearch"); - $head[$h][2] = 'searchkey'; - $h++;*/ - - complete_head_from_modules($conf, $langs, null, $head, $h, 'defaultvalues_admin'); - - complete_head_from_modules($conf, $langs, null, $head, $h, 'defaultvalues_admin', 'remove'); - - - return $head; + global $langs, $conf, $user; + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=createform"; + $head[$h][1] = $langs->trans("DefaultCreateForm"); + $head[$h][2] = 'createform'; + $h++; + + $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=filters"; + $head[$h][1] = $langs->trans("DefaultSearchFilters"); + $head[$h][2] = 'filters'; + $h++; + + $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=sortorder"; + $head[$h][1] = $langs->trans("DefaultSortOrder"); + $head[$h][2] = 'sortorder'; + $h++; + + if (!empty($conf->use_javascript_ajax)) + { + $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=focus"; + $head[$h][1] = $langs->trans("DefaultFocus"); + $head[$h][2] = 'focus'; + $h++; + + $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=mandatory"; + $head[$h][1] = $langs->trans("DefaultMandatory"); + $head[$h][2] = 'mandatory'; + $h++; + } + + /*$head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=searchkey"; + $head[$h][1] = $langs->trans("TranslationKeySearch"); + $head[$h][2] = 'searchkey'; + $h++;*/ + + complete_head_from_modules($conf, $langs, null, $head, $h, 'defaultvalues_admin'); + + complete_head_from_modules($conf, $langs, null, $head, $h, 'defaultvalues_admin', 'remove'); + + + return $head; } @@ -862,52 +799,55 @@ */ function listOfSessions() { - global $conf; - - $arrayofSessions = array(); - // session.save_path can be returned empty so we set a default location and work from there - $sessPath = '/tmp'; - $iniPath = ini_get("session.save_path"); - if ($iniPath) { - $sessPath = $iniPath; - } - $sessPath .= '/'; // We need the trailing slash - dol_syslog('admin.lib:listOfSessions sessPath='.$sessPath); - - $dh = @opendir(dol_osencode($sessPath)); - if ($dh) { - while (($file = @readdir($dh)) !== false) { - if (preg_match('/^sess_/i', $file) && $file != "." && $file != "..") { - $fullpath = $sessPath.$file; - if (!@is_dir($fullpath) && is_readable($fullpath)) { - $sessValues = file_get_contents($fullpath); // get raw session data - // Example of possible value + global $conf; + + $arrayofSessions = array(); + // session.save_path can be returned empty so we set a default location and work from there + $sessPath = '/tmp'; + $iniPath = ini_get("session.save_path"); + if ($iniPath) { + $sessPath = $iniPath; + } + $sessPath .= '/'; // We need the trailing slash + dol_syslog('admin.lib:listOfSessions sessPath='.$sessPath); + + $dh = @opendir(dol_osencode($sessPath)); + if ($dh) + { + while (($file = @readdir($dh)) !== false) + { + if (preg_match('/^sess_/i', $file) && $file != "." && $file != "..") + { + $fullpath = $sessPath.$file; + if (!@is_dir($fullpath) && is_readable($fullpath)) + { + $sessValues = file_get_contents($fullpath); // get raw session data + // Example of possible value //$sessValues = 'newtoken|s:32:"1239f7a0c4b899200fe9ca5ea394f307";dol_loginmesg|s:0:"";newtoken|s:32:"1236457104f7ae0f328c2928973f3cb5";dol_loginmesg|s:0:"";token|s:32:"123615ad8d650c5cc4199b9a1a76783f"; // dol_login|s:5:"admin";dol_authmode|s:8:"dolibarr";dol_tz|s:1:"1";dol_tz_string|s:13:"Europe/Berlin";dol_dst|i:0;dol_dst_observed|s:1:"1";dol_dst_first|s:0:"";dol_dst_second|s:0:"";dol_screenwidth|s:4:"1920"; // dol_screenheight|s:3:"971";dol_company|s:12:"MyBigCompany";dol_entity|i:1;mainmenu|s:4:"home";leftmenuopened|s:10:"admintools";idmenu|s:0:"";leftmenu|s:10:"admintools";'; - if (preg_match('/dol_login/i', $sessValues) && // limit to dolibarr session - (preg_match('/dol_entity\|i:'.$conf->entity.';/i', $sessValues) || preg_match('/dol_entity\|s:([0-9]+):"'.$conf->entity.'"/i', $sessValues)) && // limit to current entity - preg_match('/dol_company\|s:([0-9]+):"('.$conf->global->MAIN_INFO_SOCIETE_NOM.')"/i', $sessValues)) { // limit to company name - $tmp = explode('_', $file); - $idsess = $tmp[1]; - $regs = array(); - $loginfound = preg_match('/dol_login\|s:[0-9]+:"([A-Za-z0-9]+)"/i', $sessValues, $regs); - if ($loginfound) { - $arrayofSessions[$idsess]["login"] = $regs[1]; - } - $arrayofSessions[$idsess]["age"] = time() - filectime($fullpath); - $arrayofSessions[$idsess]["creation"] = filectime($fullpath); - $arrayofSessions[$idsess]["modification"] = filemtime($fullpath); - $arrayofSessions[$idsess]["raw"] = $sessValues; - } - } - } - } - @closedir($dh); - } - - return $arrayofSessions; + if (preg_match('/dol_login/i', $sessValues) && // limit to dolibarr session + (preg_match('/dol_entity\|i:'.$conf->entity.';/i', $sessValues) || preg_match('/dol_entity\|s:([0-9]+):"'.$conf->entity.'"/i', $sessValues)) && // limit to current entity + preg_match('/dol_company\|s:([0-9]+):"('.$conf->global->MAIN_INFO_SOCIETE_NOM.')"/i', $sessValues)) // limit to company name + { + $tmp = explode('_', $file); + $idsess = $tmp[1]; + $regs = array(); + $loginfound = preg_match('/dol_login\|s:[0-9]+:"([A-Za-z0-9]+)"/i', $sessValues, $regs); + if ($loginfound) $arrayofSessions[$idsess]["login"] = $regs[1]; + $arrayofSessions[$idsess]["age"] = time() - filectime($fullpath); + $arrayofSessions[$idsess]["creation"] = filectime($fullpath); + $arrayofSessions[$idsess]["modification"] = filemtime($fullpath); + $arrayofSessions[$idsess]["raw"] = $sessValues; + } + } + } + } + @closedir($dh); + } + + return $arrayofSessions; } /** @@ -918,45 +858,42 @@ */ function purgeSessions($mysessionid) { - global $conf; - - $sessPath = ini_get("session.save_path")."/"; - dol_syslog('admin.lib:purgeSessions mysessionid='.$mysessionid.' sessPath='.$sessPath); - - $error = 0; - - $dh = @opendir(dol_osencode($sessPath)); - if ($dh) { - while (($file = @readdir($dh)) !== false) { - if ($file != "." && $file != "..") { - $fullpath = $sessPath.$file; - if (!@is_dir($fullpath)) { - $sessValues = file_get_contents($fullpath); // get raw session data - - if (preg_match('/dol_login/i', $sessValues) && // limit to dolibarr session - preg_match('/dol_entity\|s:([0-9]+):"('.$conf->entity.')"/i', $sessValues) && // limit to current entity - preg_match('/dol_company\|s:([0-9]+):"('.$conf->global->MAIN_INFO_SOCIETE_NOM.')"/i', $sessValues)) { // limit to company name - $tmp = explode('_', $file); - $idsess = $tmp[1]; - // We remove session if it's not ourself - if ($idsess != $mysessionid) { - $res = @unlink($fullpath); - if (!$res) { - $error++; - } - } - } - } - } - } - @closedir($dh); - } - - if (!$error) { - return 1; - } else { - return -$error; - } + global $conf; + + $sessPath = ini_get("session.save_path")."/"; + dol_syslog('admin.lib:purgeSessions mysessionid='.$mysessionid.' sessPath='.$sessPath); + + $error = 0; + $dh = @opendir(dol_osencode($sessPath)); + while (($file = @readdir($dh)) !== false) + { + if ($file != "." && $file != "..") + { + $fullpath = $sessPath.$file; + if (!@is_dir($fullpath)) + { + $sessValues = file_get_contents($fullpath); // get raw session data + + if (preg_match('/dol_login/i', $sessValues) && // limit to dolibarr session + preg_match('/dol_entity\|s:([0-9]+):"('.$conf->entity.')"/i', $sessValues) && // limit to current entity + preg_match('/dol_company\|s:([0-9]+):"('.$conf->global->MAIN_INFO_SOCIETE_NOM.')"/i', $sessValues)) // limit to company name + { + $tmp = explode('_', $file); + $idsess = $tmp[1]; + // We remove session if it's not ourself + if ($idsess != $mysessionid) + { + $res = @unlink($fullpath); + if (!$res) $error++; + } + } + } + } + } + @closedir($dh); + + if (!$error) return 1; + else return -$error; } @@ -970,9 +907,9 @@ */ function activateModule($value, $withdeps = 1) { - global $db, $langs, $conf, $mysoc; - - $ret = array(); + global $db, $langs, $conf, $mysoc; + + $ret = array(); // Check parameters if (empty($value)) { @@ -980,38 +917,38 @@ return $ret; } - $ret = array('nbmodules'=>0, 'errors'=>array(), 'nbperms'=>0); - $modName = $value; - $modFile = $modName.".class.php"; - - // Loop on each directory to fill $modulesdir - $modulesdir = dolGetModulesDirs(); - - // Loop on each modulesdir directories - $found = false; - foreach ($modulesdir as $dir) { - if (file_exists($dir.$modFile)) { - $found = @include_once $dir.$modFile; - if ($found) { - break; - } - } - } - - $objMod = new $modName($db); - - // Test if PHP version ok - $verphp = versionphparray(); - $vermin = isset($objMod->phpmin) ? $objMod->phpmin : 0; + $ret = array('nbmodules'=>0, 'errors'=>array(), 'nbperms'=>0); + $modName = $value; + $modFile = $modName.".class.php"; + + // Loop on each directory to fill $modulesdir + $modulesdir = dolGetModulesDirs(); + + // Loop on each modulesdir directories + $found = false; + foreach ($modulesdir as $dir) + { + if (file_exists($dir.$modFile)) + { + $found = @include_once $dir.$modFile; + if ($found) break; + } + } + + $objMod = new $modName($db); + + // Test if PHP version ok + $verphp = versionphparray(); + $vermin = isset($objMod->phpmin) ? $objMod->phpmin : 0; if (is_array($vermin) && versioncompare($verphp, $vermin) < 0) { $ret['errors'][] = $langs->trans("ErrorModuleRequirePHPVersion", versiontostring($vermin)); return $ret; } - // Test if Dolibarr version ok - $verdol = versiondolibarrarray(); - $vermin = isset($objMod->need_dolibarr_version) ? $objMod->need_dolibarr_version : 0; - //print 'version: '.versioncompare($verdol,$vermin).' - '.join(',',$verdol).' - '.join(',',$vermin);exit; + // Test if Dolibarr version ok + $verdol = versiondolibarrarray(); + $vermin = isset($objMod->need_dolibarr_version) ? $objMod->need_dolibarr_version : 0; + //print 'version: '.versioncompare($verdol,$vermin).' - '.join(',',$verdol).' - '.join(',',$vermin);exit; if (is_array($vermin) && versioncompare($verdol, $vermin) < 0) { $ret['errors'][] = $langs->trans("ErrorModuleRequireDolibarrVersion", versiontostring($vermin)); return $ret; @@ -1025,68 +962,85 @@ $const_name = $objMod->const_name; if (!empty($conf->global->$const_name)) { - return $ret; - } - - $result = $objMod->init(); // Enable module - - if ($result <= 0) { - $ret['errors'][] = $objMod->error; - } else { - if ($withdeps) { - if (isset($objMod->depends) && is_array($objMod->depends) && !empty($objMod->depends)) { - // Activation of modules this module depends on - // this->depends may be array('modModule1', 'mmodModule2') or array('always1'=>"modModule1", 'FR'=>'modModule2') - foreach ($objMod->depends as $key => $modulestring) { - //var_dump((! is_numeric($key)) && ! preg_match('/^always/', $key) && $mysoc->country_code && ! preg_match('/^'.$mysoc->country_code.'/', $key));exit; - if ((!is_numeric($key)) && !preg_match('/^always/', $key) && $mysoc->country_code && !preg_match('/^'.$mysoc->country_code.'/', $key)) { - dol_syslog("We are not concerned by dependency with key=".$key." because our country is ".$mysoc->country_code); - continue; - } - $activate = false; - foreach ($modulesdir as $dir) { - if (file_exists($dir.$modulestring.".class.php")) { - $resarray = activateModule($modulestring); - if (empty($resarray['errors'])) { - $activate = true; - } else { - foreach ($resarray['errors'] as $errorMessage) { - dol_syslog($errorMessage, LOG_ERR); - } - } - break; - } - } - - if ($activate) { - $ret['nbmodules'] += $resarray['nbmodules']; - $ret['nbperms'] += $resarray['nbperms']; - } else { - $ret['errors'][] = $langs->trans('activateModuleDependNotSatisfied', $objMod->name, $modulestring); - } - } - } - - if (isset($objMod->conflictwith) && is_array($objMod->conflictwith) && !empty($objMod->conflictwith)) { - // Desactivation des modules qui entrent en conflit - $num = count($objMod->conflictwith); - for ($i = 0; $i < $num; $i++) { - foreach ($modulesdir as $dir) { - if (file_exists($dir.$objMod->conflictwith[$i].".class.php")) { - unActivateModule($objMod->conflictwith[$i], 0); - } - } - } - } - } - } - - if (!count($ret['errors'])) { - $ret['nbmodules']++; - $ret['nbperms'] += count($objMod->rights); - } - - return $ret; + return $ret; + } + + $result = $objMod->init(); // Enable module + + if ($result <= 0) + { + $ret['errors'][] = $objMod->error; + } + else + { + if ($withdeps) + { + if (isset($objMod->depends) && is_array($objMod->depends) && !empty($objMod->depends)) + { + // Activation of modules this module depends on + // this->depends may be array('modModule1', 'mmodModule2') or array('always1'=>"modModule1", 'FR'=>'modModule2') + foreach ($objMod->depends as $key => $modulestring) + { + //var_dump((! is_numeric($key)) && ! preg_match('/^always/', $key) && $mysoc->country_code && ! preg_match('/^'.$mysoc->country_code.'/', $key));exit; + if ((!is_numeric($key)) && !preg_match('/^always/', $key) && $mysoc->country_code && !preg_match('/^'.$mysoc->country_code.'/', $key)) + { + dol_syslog("We are not concerned by dependency with key=".$key." because our country is ".$mysoc->country_code); + continue; + } + $activate = false; + foreach ($modulesdir as $dir) + { + if (file_exists($dir.$modulestring.".class.php")) + { + $resarray = activateModule($modulestring); + if (empty($resarray['errors'])) { + $activate = true; + } else { + foreach ($resarray['errors'] as $errorMessage) { + dol_syslog($errorMessage, LOG_ERR); + } + } + break; + } + } + + if ($activate) + { + $ret['nbmodules'] += $resarray['nbmodules']; + $ret['nbperms'] += $resarray['nbperms']; + } + else + { + $ret['errors'][] = $langs->trans('activateModuleDependNotSatisfied', $objMod->name, $modulestring); + } + } + } + + if (isset($objMod->conflictwith) && is_array($objMod->conflictwith) && !empty($objMod->conflictwith)) + { + // Desactivation des modules qui entrent en conflit + $num = count($objMod->conflictwith); + for ($i = 0; $i < $num; $i++) + { + foreach ($modulesdir as $dir) + { + if (file_exists($dir.$objMod->conflictwith[$i].".class.php")) + { + unActivateModule($objMod->conflictwith[$i], 0); + } + } + } + } + } + } + + if (!count($ret['errors'])) + { + $ret['nbmodules']++; + $ret['nbperms'] += count($objMod->rights); + } + + return $ret; } @@ -1099,60 +1053,60 @@ */ function unActivateModule($value, $requiredby = 1) { - global $db, $modules, $conf; - - // Check parameters - if (empty($value)) { - return 'ErrorBadParameter'; - } - - $ret = ''; - $modName = $value; - $modFile = $modName.".class.php"; - - // Loop on each directory to fill $modulesdir - $modulesdir = dolGetModulesDirs(); - - // Loop on each modulesdir directories - $found = false; - foreach ($modulesdir as $dir) { - if (file_exists($dir.$modFile)) { - $found = @include_once $dir.$modFile; - if ($found) { - break; - } - } - } - - if ($found) { - $objMod = new $modName($db); - $result = $objMod->remove(); - if ($result <= 0) { - $ret = $objMod->error; - } - } else // We come here when we try to unactivate a module when module does not exists anymore in sources - { - //print $dir.$modFile;exit; - // TODO Replace this after DolibarrModules is moved as abstract class with a try catch to show module we try to disable has not been found or could not be loaded - include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; - $genericMod = new DolibarrModules($db); - $genericMod->name = preg_replace('/^mod/i', '', $modName); - $genericMod->rights_class = strtolower(preg_replace('/^mod/i', '', $modName)); - $genericMod->const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', $modName)); - dol_syslog("modules::unActivateModule Failed to find module file, we use generic function with name ".$modName); - $genericMod->remove(''); - } - - // Disable modules that depends on module we disable - if (!$ret && $requiredby && is_object($objMod) && is_array($objMod->requiredby)) { - $countrb = count($objMod->requiredby); - for ($i = 0; $i < $countrb; $i++) { - //var_dump($objMod->requiredby[$i]); - unActivateModule($objMod->requiredby[$i]); - } - } - - return $ret; + global $db, $modules, $conf; + + // Check parameters + if (empty($value)) return 'ErrorBadParameter'; + + $ret = ''; + $modName = $value; + $modFile = $modName.".class.php"; + + // Loop on each directory to fill $modulesdir + $modulesdir = dolGetModulesDirs(); + + // Loop on each modulesdir directories + $found = false; + foreach ($modulesdir as $dir) + { + if (file_exists($dir.$modFile)) + { + $found = @include_once $dir.$modFile; + if ($found) break; + } + } + + if ($found) + { + $objMod = new $modName($db); + $result = $objMod->remove(); + if ($result <= 0) $ret = $objMod->error; + } + else // We come here when we try to unactivate a module when module does not exists anymore in sources + { + //print $dir.$modFile;exit; + // TODO Replace this after DolibarrModules is moved as abstract class with a try catch to show module we try to disable has not been found or could not be loaded + include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; + $genericMod = new DolibarrModules($db); + $genericMod->name = preg_replace('/^mod/i', '', $modName); + $genericMod->rights_class = strtolower(preg_replace('/^mod/i', '', $modName)); + $genericMod->const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', $modName)); + dol_syslog("modules::unActivateModule Failed to find module file, we use generic function with name ".$modName); + $genericMod->remove(''); + } + + // Disable modules that depends on module we disable + if (!$ret && $requiredby && is_object($objMod) && is_array($objMod->requiredby)) + { + $countrb = count($objMod->requiredby); + for ($i = 0; $i < $countrb; $i++) + { + //var_dump($objMod->requiredby[$i]); + unActivateModule($objMod->requiredby[$i]); + } + } + + return $ret; } @@ -1176,52 +1130,55 @@ */ function complete_dictionary_with_modules(&$taborder, &$tabname, &$tablib, &$tabsql, &$tabsqlsort, &$tabfield, &$tabfieldvalue, &$tabfieldinsert, &$tabrowid, &$tabcond, &$tabhelp, &$tabfieldcheck) { - global $db, $modules, $conf, $langs; - - dol_syslog("complete_dictionary_with_modules Search external modules to complete the list of dictionnary tables", LOG_DEBUG, 1); - - // Search modules + global $db, $modules, $conf, $langs; + + dol_syslog("complete_dictionary_with_modules Search external modules to complete the list of dictionnary tables", LOG_DEBUG, 1); + + // Search modules $modulesdir = dolGetModulesDirs(); - $i = 0; // is a sequencer of modules found - $j = 0; // j is module number. Automatically affected if module number not defined. - - foreach ($modulesdir as $dir) { - // Load modules attributes in arrays (name, numero, orders) from dir directory - //print $dir."\n
"; - dol_syslog("Scan directory ".$dir." for modules"); - $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) { - while (($file = readdir($handle)) !== false) { - //print "$i ".$file."\n
"; - if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') { - $modName = substr($file, 0, dol_strlen($file) - 10); - - if ($modName) { - include_once $dir.$file; - $objMod = new $modName($db); - - if ($objMod->numero > 0) { - $j = $objMod->numero; - } else { - $j = 1000 + $i; - } - - $modulequalified = 1; - - // We discard modules according to features level (PS: if module is activated we always show it) - $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod))); - if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && !$conf->global->$const_name) { - $modulequalified = 0; - } - if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && !$conf->global->$const_name) { - $modulequalified = 0; - } - //If module is not activated disqualified - if (empty($conf->global->$const_name)) { - $modulequalified = 0; - } - - if ($modulequalified) { + $i = 0; // is a sequencer of modules found + $j = 0; // j is module number. Automatically affected if module number not defined. + + foreach ($modulesdir as $dir) + { + // Load modules attributes in arrays (name, numero, orders) from dir directory + //print $dir."\n
"; + dol_syslog("Scan directory ".$dir." for modules"); + $handle = @opendir(dol_osencode($dir)); + if (is_resource($handle)) + { + while (($file = readdir($handle)) !== false) + { + //print "$i ".$file."\n
"; + if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') + { + $modName = substr($file, 0, dol_strlen($file) - 10); + + if ($modName) + { + include_once $dir.$file; + $objMod = new $modName($db); + + if ($objMod->numero > 0) + { + $j = $objMod->numero; + } + else + { + $j = 1000 + $i; + } + + $modulequalified = 1; + + // We discard modules according to features level (PS: if module is activated we always show it) + $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod))); + if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && !$conf->global->$const_name) $modulequalified = 0; + if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && !$conf->global->$const_name) $modulequalified = 0; + //If module is not activated disqualified + if (empty($conf->global->$const_name)) $modulequalified = 0; + + if ($modulequalified) + { // Load languages files of module if (isset($objMod->langfiles) && is_array($objMod->langfiles)) { foreach ($objMod->langfiles as $langfile) { @@ -1229,138 +1186,117 @@ } } - // Complete the arrays &$tabname,&$tablib,&$tabsql,&$tabsqlsort,&$tabfield,&$tabfieldvalue,&$tabfieldinsert,&$tabrowid,&$tabcond - if (empty($objMod->dictionaries) && !empty($objMod->dictionnaries)) { - $objMod->dictionaries = $objMod->dictionnaries; // For backward compatibility + // Complete the arrays &$tabname,&$tablib,&$tabsql,&$tabsqlsort,&$tabfield,&$tabfieldvalue,&$tabfieldinsert,&$tabrowid,&$tabcond + if (empty($objMod->dictionaries) && !empty($objMod->dictionnaries)) $objMod->dictionaries = $objMod->dictionnaries; // For backward compatibility + + if (!empty($objMod->dictionaries)) + { + //var_dump($objMod->dictionaries['tabname']); + $nbtabname = $nbtablib = $nbtabsql = $nbtabsqlsort = $nbtabfield = $nbtabfieldvalue = $nbtabfieldinsert = $nbtabrowid = $nbtabcond = $nbtabfieldcheck = $nbtabhelp = 0; + foreach ($objMod->dictionaries['tabname'] as $val) { $nbtabname++; $taborder[] = max($taborder) + 1; $tabname[] = $val; } // Position + foreach ($objMod->dictionaries['tablib'] as $val) { $nbtablib++; $tablib[] = $val; } + foreach ($objMod->dictionaries['tabsql'] as $val) { $nbtabsql++; $tabsql[] = $val; } + foreach ($objMod->dictionaries['tabsqlsort'] as $val) { $nbtabsqlsort++; $tabsqlsort[] = $val; } + foreach ($objMod->dictionaries['tabfield'] as $val) { $nbtabfield++; $tabfield[] = $val; } + foreach ($objMod->dictionaries['tabfieldvalue'] as $val) { $nbtabfieldvalue++; $tabfieldvalue[] = $val; } + foreach ($objMod->dictionaries['tabfieldinsert'] as $val) { $nbtabfieldinsert++; $tabfieldinsert[] = $val; } + foreach ($objMod->dictionaries['tabrowid'] as $val) { $nbtabrowid++; $tabrowid[] = $val; } + foreach ($objMod->dictionaries['tabcond'] as $val) { $nbtabcond++; $tabcond[] = $val; } + if (!empty($objMod->dictionaries['tabhelp'])) foreach ($objMod->dictionaries['tabhelp'] as $val) { $nbtabhelp++; $tabhelp[] = $val; } + if (!empty($objMod->dictionaries['tabfieldcheck'])) foreach ($objMod->dictionaries['tabfieldcheck'] as $val) { $nbtabfieldcheck++; $tabfieldcheck[] = $val; } + + if ($nbtabname != $nbtablib || $nbtablib != $nbtabsql || $nbtabsql != $nbtabsqlsort) + { + print 'Error in descriptor of module '.$const_name.'. Array ->dictionaries has not same number of record for key "tabname", "tablib", "tabsql" and "tabsqlsort"'; + //print "$const_name: $nbtabname=$nbtablib=$nbtabsql=$nbtabsqlsort=$nbtabfield=$nbtabfieldvalue=$nbtabfieldinsert=$nbtabrowid=$nbtabcond=$nbtabfieldcheck=$nbtabhelp\n"; + } + else + { + $taborder[] = 0; // Add an empty line + } + } + + $j++; + $i++; + } + else dol_syslog("Module ".get_class($objMod)." not qualified"); + } + } + } + closedir($handle); + } + else + { + dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING); + } + } + + dol_syslog("", LOG_DEBUG, -1); + + return 1; +} + +/** + * Activate external modules mandatory when country is country_code + * + * @param string $country_code CountryCode + * @return int 1 + */ +function activateModulesRequiredByCountry($country_code) +{ + global $db, $conf, $langs; + + $modulesdir = dolGetModulesDirs(); + + foreach ($modulesdir as $dir) + { + // Load modules attributes in arrays (name, numero, orders) from dir directory + dol_syslog("Scan directory ".$dir." for modules"); + $handle = @opendir(dol_osencode($dir)); + if (is_resource($handle)) + { + while (($file = readdir($handle)) !== false) + { + if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') + { + $modName = substr($file, 0, dol_strlen($file) - 10); + + if ($modName) + { + include_once $dir.$file; + $objMod = new $modName($db); + + $modulequalified = 1; + + // We discard modules according to features level (PS: if module is activated we always show it) + $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod))); + + if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; + if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0; + if (!empty($conf->global->$const_name)) $modulequalified = 0; // already activated + + if ($modulequalified) + { + // Load languages files of module + if (isset($objMod->automatic_activation) && is_array($objMod->automatic_activation) && isset($objMod->automatic_activation[$country_code])) + { + activateModule($modName); + + setEventMessages($objMod->automatic_activation[$country_code], null, 'warnings'); } - - if (!empty($objMod->dictionaries)) { - //var_dump($objMod->dictionaries['tabname']); - $nbtabname = $nbtablib = $nbtabsql = $nbtabsqlsort = $nbtabfield = $nbtabfieldvalue = $nbtabfieldinsert = $nbtabrowid = $nbtabcond = $nbtabfieldcheck = $nbtabhelp = 0; - foreach ($objMod->dictionaries['tabname'] as $val) { - $nbtabname++; $taborder[] = max($taborder) + 1; $tabname[] = $val; - } // Position - foreach ($objMod->dictionaries['tablib'] as $val) { - $nbtablib++; $tablib[] = $val; - } - foreach ($objMod->dictionaries['tabsql'] as $val) { - $nbtabsql++; $tabsql[] = $val; - } - foreach ($objMod->dictionaries['tabsqlsort'] as $val) { - $nbtabsqlsort++; $tabsqlsort[] = $val; - } - foreach ($objMod->dictionaries['tabfield'] as $val) { - $nbtabfield++; $tabfield[] = $val; - } - foreach ($objMod->dictionaries['tabfieldvalue'] as $val) { - $nbtabfieldvalue++; $tabfieldvalue[] = $val; - } - foreach ($objMod->dictionaries['tabfieldinsert'] as $val) { - $nbtabfieldinsert++; $tabfieldinsert[] = $val; - } - foreach ($objMod->dictionaries['tabrowid'] as $val) { - $nbtabrowid++; $tabrowid[] = $val; - } - foreach ($objMod->dictionaries['tabcond'] as $val) { - $nbtabcond++; $tabcond[] = $val; - } - if (!empty($objMod->dictionaries['tabhelp'])) { - foreach ($objMod->dictionaries['tabhelp'] as $val) { - $nbtabhelp++; $tabhelp[] = $val; - } - } - if (!empty($objMod->dictionaries['tabfieldcheck'])) { - foreach ($objMod->dictionaries['tabfieldcheck'] as $val) { - $nbtabfieldcheck++; $tabfieldcheck[] = $val; - } - } - - if ($nbtabname != $nbtablib || $nbtablib != $nbtabsql || $nbtabsql != $nbtabsqlsort) { - print 'Error in descriptor of module '.$const_name.'. Array ->dictionaries has not same number of record for key "tabname", "tablib", "tabsql" and "tabsqlsort"'; - //print "$const_name: $nbtabname=$nbtablib=$nbtabsql=$nbtabsqlsort=$nbtabfield=$nbtabfieldvalue=$nbtabfieldinsert=$nbtabrowid=$nbtabcond=$nbtabfieldcheck=$nbtabhelp\n"; - } else { - $taborder[] = 0; // Add an empty line - } - } - - $j++; - $i++; - } else { - dol_syslog("Module ".get_class($objMod)." not qualified"); } + else dol_syslog("Module ".get_class($objMod)." not qualified"); } } } closedir($handle); - } else { + } + else + { dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING); } } - dol_syslog("", LOG_DEBUG, -1); - - return 1; -} - -/** - * Activate external modules mandatory when country is country_code - * - * @param string $country_code CountryCode - * @return int 1 - */ -function activateModulesRequiredByCountry($country_code) -{ - global $db, $conf, $langs; - - $modulesdir = dolGetModulesDirs(); - - foreach ($modulesdir as $dir) { - // Load modules attributes in arrays (name, numero, orders) from dir directory - dol_syslog("Scan directory ".$dir." for modules"); - $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) { - while (($file = readdir($handle)) !== false) { - if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') { - $modName = substr($file, 0, dol_strlen($file) - 10); - - if ($modName) { - include_once $dir.$file; - $objMod = new $modName($db); - - $modulequalified = 1; - - // We discard modules according to features level (PS: if module is activated we always show it) - $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod))); - - if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { - $modulequalified = 0; - } - if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { - $modulequalified = 0; - } - if (!empty($conf->global->$const_name)) { - $modulequalified = 0; // already activated - } - - if ($modulequalified) { - // Load languages files of module - if (isset($objMod->automatic_activation) && is_array($objMod->automatic_activation) && isset($objMod->automatic_activation[$country_code])) { - activateModule($modName); - - setEventMessages($objMod->automatic_activation[$country_code], null, 'warnings'); - } - } else { - dol_syslog("Module ".get_class($objMod)." not qualified"); - } - } - } - } - closedir($handle); - } else { - dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING); - } - } - return 1; } @@ -1372,99 +1308,100 @@ */ function complete_elementList_with_modules(&$elementList) { - global $db, $modules, $conf, $langs; - - // Search modules - $filename = array(); - $modules = array(); - $orders = array(); - $categ = array(); - $dirmod = array(); - - $i = 0; // is a sequencer of modules found - $j = 0; // j is module number. Automatically affected if module number not defined. - - dol_syslog("complete_elementList_with_modules Search external modules to complete the list of contact element", LOG_DEBUG, 1); - - $modulesdir = dolGetModulesDirs(); - - foreach ($modulesdir as $dir) { - // Load modules attributes in arrays (name, numero, orders) from dir directory - //print $dir."\n
"; - dol_syslog("Scan directory ".$dir." for modules"); - $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) { - while (($file = readdir($handle)) !== false) { - //print "$i ".$file."\n
"; - if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') { - $modName = substr($file, 0, dol_strlen($file) - 10); - - if ($modName) { - include_once $dir.$file; - $objMod = new $modName($db); - - if ($objMod->numero > 0) { - $j = $objMod->numero; - } else { - $j = 1000 + $i; - } - - $modulequalified = 1; - - // We discard modules according to features level (PS: if module is activated we always show it) - $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod))); - if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && !$conf->global->$const_name) { - $modulequalified = 0; - } - if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && !$conf->global->$const_name) { - $modulequalified = 0; - } - //If module is not activated disqualified - if (empty($conf->global->$const_name)) { - $modulequalified = 0; - } - - if ($modulequalified) { + global $db, $modules, $conf, $langs; + + // Search modules + $filename = array(); + $modules = array(); + $orders = array(); + $categ = array(); + $dirmod = array(); + + $i = 0; // is a sequencer of modules found + $j = 0; // j is module number. Automatically affected if module number not defined. + + dol_syslog("complete_elementList_with_modules Search external modules to complete the list of contact element", LOG_DEBUG, 1); + + $modulesdir = dolGetModulesDirs(); + + foreach ($modulesdir as $dir) + { + // Load modules attributes in arrays (name, numero, orders) from dir directory + //print $dir."\n
"; + dol_syslog("Scan directory ".$dir." for modules"); + $handle = @opendir(dol_osencode($dir)); + if (is_resource($handle)) + { + while (($file = readdir($handle)) !== false) + { + //print "$i ".$file."\n
"; + if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') + { + $modName = substr($file, 0, dol_strlen($file) - 10); + + if ($modName) + { + include_once $dir.$file; + $objMod = new $modName($db); + + if ($objMod->numero > 0) + { + $j = $objMod->numero; + } + else + { + $j = 1000 + $i; + } + + $modulequalified = 1; + + // We discard modules according to features level (PS: if module is activated we always show it) + $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod))); + if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && !$conf->global->$const_name) $modulequalified = 0; + if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && !$conf->global->$const_name) $modulequalified = 0; + //If module is not activated disqualified + if (empty($conf->global->$const_name)) $modulequalified = 0; + + if ($modulequalified) + { // Load languages files of module - if (isset($objMod->langfiles) && is_array($objMod->langfiles)) { - foreach ($objMod->langfiles as $langfile) { - $langs->load($langfile); - } - } - - $modules[$i] = $objMod; - $filename[$i] = $modName; - $orders[$i] = $objMod->family."_".$j; // Sort on family then module number - $dirmod[$i] = $dir; - //print "x".$modName." ".$orders[$i]."\n
"; - - if (!empty($objMod->module_parts['contactelement'])) { - if (is_array($objMod->module_parts['contactelement'])) { - foreach ($objMod->module_parts['contactelement'] as $elem => $title) { - $elementList[$elem] = $langs->trans($title); - } - } else { - $elementList[$objMod->name] = $langs->trans($objMod->name); - } + if (isset($objMod->langfiles) && is_array($objMod->langfiles)) + { + foreach ($objMod->langfiles as $langfile) + { + $langs->load($langfile); + } + } + + $modules[$i] = $objMod; + $filename[$i] = $modName; + $orders[$i] = $objMod->family."_".$j; // Sort on family then module number + $dirmod[$i] = $dir; + //print "x".$modName." ".$orders[$i]."\n
"; + + if (!empty($objMod->module_parts['contactelement'])) + { + $elementList[$objMod->name] = $langs->trans($objMod->name); } - $j++; - $i++; - } else { - dol_syslog("Module ".get_class($objMod)." not qualified"); - } - } - } - } - closedir($handle); - } else { - dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING); - } - } - - dol_syslog("", LOG_DEBUG, -1); - - return 1; + $j++; + $i++; + } + else dol_syslog("Module ".get_class($objMod)." not qualified"); + } + } + } + closedir($handle); + } + else + { + dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING); + } + } + + dol_syslog("", LOG_DEBUG, -1); + + return 1; } /** @@ -1478,192 +1415,211 @@ */ function form_constantes($tableau, $strictw3c = 0, $helptext = '') { - global $db, $langs, $conf, $user; - global $_Avery_Labels; - - $form = new Form($db); - - if (empty($strictw3c)) { - dol_syslog("Warning: Function form_constantes is calle with parameter strictw3c = 0, this is deprecated. Value must be 2 now.", LOG_DEBUG); - } - if (!empty($strictw3c) && $strictw3c == 1) { - print "\n".'
'; - print ''; - print ''; - } - - print ''; - print ''; - print ''; - print ''; - if (empty($strictw3c)) { - print ''; - } - print "\n"; - - $label = ''; - foreach ($tableau as $key => $const) { // Loop on each param - $label = ''; - // $const is a const key like 'MYMODULE_ABC' - if (is_numeric($key)) { // Very old behaviour - $type = 'string'; - } else { - if (is_array($const)) { - $type = $const['type']; + global $db, $langs, $conf, $user; + global $_Avery_Labels; + + $form = new Form($db); + + if (empty($strictw3c)) { + dol_syslog("Warning: Function form_constantes is calle with parameter strictw3c = 0, this is deprecated. Value must be 2 now.", LOG_DEBUG); + } + if (!empty($strictw3c) && $strictw3c == 1) + { + print "\n".''; + print ''; + print ''; + } + + print '
'.$langs->trans("Description").''; - $text = $langs->trans("Value"); - print $form->textwithpicto($text, $helptext, 1, 'help', '', 0, 2, 'idhelptext'); - print ''.$langs->trans("Action").'
'; + print ''; + print ''; + print ''; + if (empty($strictw3c)) print ''; + print "\n"; + + $label = ''; + foreach ($tableau as $key => $const) // Loop on each param + { + $label = ''; + // $const is a const key like 'MYMODULE_ABC' + if (is_numeric($key)) { // Very old behaviour + $type = 'string'; + } + else + { + if (is_array($const)) + { + $type = $const['type']; $label = $const['label']; - $const = $key; - } else { - $type = $const; - $const = $key; - } - } - - $sql = "SELECT "; - $sql .= "rowid"; - $sql .= ", ".$db->decrypt('name')." as name"; - $sql .= ", ".$db->decrypt('value')." as value"; - $sql .= ", type"; - $sql .= ", note"; - $sql .= " FROM ".MAIN_DB_PREFIX."const"; - $sql .= " WHERE ".$db->decrypt('name')." = '".$db->escape($const)."'"; - $sql .= " AND entity IN (0, ".$conf->entity.")"; - $sql .= " ORDER BY name ASC, entity DESC"; - $result = $db->query($sql); - - dol_syslog("List params", LOG_DEBUG); - if ($result) { - $obj = $db->fetch_object($result); // Take first result of select - - if (empty($obj)) { // If not yet into table - $obj = (object) array('rowid'=>'', 'name'=>$const, 'value'=>'', 'type'=>$type, 'note'=>''); - } - - if (empty($strictw3c)) { - print "\n".''; - print ''; - } - - print ''; - - // Show constant - print '\n"; - - // Value - if ($const == 'ADHERENT_CARD_TYPE' || $const == 'ADHERENT_ETIQUETTE_TYPE') { - print ''; - } else { - print ''; - } - // Submit - if (empty($strictw3c)) { - print '"; - } - print "\n"; - - if (empty($strictw3c)) { - print "\n"; - } - } - } - print '
'.$langs->trans("Description").''; + $text = $langs->trans("Value"); + print $form->textwithpicto($text, $helptext, 1, 'help', '', 0, 2, 'idhelptext'); + print ''.$langs->trans("Action").'
'; - if (empty($strictw3c)) { - print ''; - } - print ''; - print ''; - print ''; - print ''; - - print ($label ? $label : $langs->trans('Desc'.$const)); - - if ($const == 'ADHERENT_MAILMAN_URL') { - print '. '.$langs->trans("Example").': '.img_down().'
'; - //print 'http://lists.exampe.com/cgi-bin/mailman/admin/%LISTE%/members?adminpw=%MAILMAN_ADMINPW%&subscribees=%EMAIL%&send_welcome_msg_to_this_batch=1'; - print ''; - } - if ($const == 'ADHERENT_MAILMAN_UNSUB_URL') { - print '. '.$langs->trans("Example").': '.img_down().'
'; - print ''; - //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?adminpw=%MAILMAN_ADMINPW%&unsubscribees=%EMAIL%'; - } - if ($const == 'ADHERENT_MAILMAN_LISTS') { - print '. '.$langs->trans("Example").': '.img_down().'
'; - print ''; - //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?adminpw=%MAILMAN_ADMINPW%&unsubscribees=%EMAIL%'; - } - - print "
'; - // List of possible labels (defined into $_Avery_Labels variable set into format_cards.lib.php) - require_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php'; - $arrayoflabels = array(); - foreach (array_keys($_Avery_Labels) as $codecards) { - $arrayoflabels[$codecards] = $_Avery_Labels[$codecards]['name']; - } - print $form->selectarray('constvalue'.(empty($strictw3c) ? '' : '[]'), $arrayoflabels, ($obj->value ? $obj->value : 'CARD'), 1, 0, 0); - print ''; - print ''; - print ''; - print ''; - print ''; - if ($obj->type == 'textarea' || in_array($const, array('ADHERENT_CARD_TEXT', 'ADHERENT_CARD_TEXT_RIGHT', 'ADHERENT_ETIQUETTE_TEXT'))) { - print '\n"; - } elseif ($obj->type == 'html') { - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('constvalue_'.$const.(empty($strictw3c) ? '' : '[]'), $obj->value, '', 160, 'dolibarr_notes', '', false, false, $conf->fckeditor->enabled, ROWS_5, '90%'); - $doleditor->Create(); - } elseif ($obj->type == 'yesno') { - print $form->selectyesno('constvalue'.(empty($strictw3c) ? '' : '[]'), $obj->value, 1); - } elseif (preg_match('/emailtemplate/', $obj->type)) { - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - - $tmp = explode(':', $obj->type); - - $nboftemplates = $formmail->fetchAllEMailTemplate($tmp[1], $user, null, -1); // We set lang=null to get in priority record with no lang - //$arraydefaultmessage = $formmail->getEMailTemplate($db, $tmp[1], $user, null, 0, 1, ''); - $arrayofmessagename = array(); - if (is_array($formmail->lines_model)) { - foreach ($formmail->lines_model as $modelmail) { - //var_dump($modelmail); - $moreonlabel = ''; - if (!empty($arrayofmessagename[$modelmail->label])) { - $moreonlabel = ' ('.$langs->trans("SeveralLangugeVariatFound").')'; - } - // The 'label' is the key that is unique if we exclude the language - $arrayofmessagename[$modelmail->label.':'.$tmp[1]] = $langs->trans(preg_replace('/\(|\)/', '', $modelmail->label)).$moreonlabel; - } - } - //var_dump($arraydefaultmessage); - //var_dump($arrayofmessagename); - print $form->selectarray('constvalue_'.$obj->name, $arrayofmessagename, $obj->value.':'.$tmp[1], 'None', 0, 0, '', 0, 0, 0, '', '', 1); - } else // type = 'string' ou 'chaine' - { - print ''; - } - print ''; - print ''; - print "
'; - - if (!empty($strictw3c) && $strictw3c == 1) { - print '
'; - print "\n"; - } + $const = $key; + } + else + { + $type = $const; + $const = $key; + } + } + + $sql = "SELECT "; + $sql .= "rowid"; + $sql .= ", ".$db->decrypt('name')." as name"; + $sql .= ", ".$db->decrypt('value')." as value"; + $sql .= ", type"; + $sql .= ", note"; + $sql .= " FROM ".MAIN_DB_PREFIX."const"; + $sql .= " WHERE ".$db->decrypt('name')." = '".$db->escape($const)."'"; + $sql .= " AND entity IN (0, ".$conf->entity.")"; + $sql .= " ORDER BY name ASC, entity DESC"; + $result = $db->query($sql); + + dol_syslog("List params", LOG_DEBUG); + if ($result) + { + $obj = $db->fetch_object($result); // Take first result of select + + if (empty($obj)) // If not yet into table + { + $obj = (object) array('rowid'=>'', 'name'=>$const, 'value'=>'', 'type'=>$type, 'note'=>''); + } + + if (empty($strictw3c)) + { + print "\n".'
'; + print ''; + } + + print ''; + + // Show constant + print ''; + if (empty($strictw3c)) print ''; + print ''; + print ''; + print ''; + print ''; + + print ($label ? $label : $langs->trans('Desc'.$const)); + + if ($const == 'ADHERENT_MAILMAN_URL') + { + print '. '.$langs->trans("Example").': '.img_down().'
'; + //print 'http://lists.exampe.com/cgi-bin/mailman/admin/%LISTE%/members?adminpw=%MAILMAN_ADMINPW%&subscribees=%EMAIL%&send_welcome_msg_to_this_batch=1'; + print ''; + } + if ($const == 'ADHERENT_MAILMAN_UNSUB_URL') + { + print '. '.$langs->trans("Example").': '.img_down().'
'; + print ''; + //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?adminpw=%MAILMAN_ADMINPW%&unsubscribees=%EMAIL%'; + } + if ($const == 'ADHERENT_MAILMAN_LISTS') + { + print '. '.$langs->trans("Example").': '.img_down().'
'; + print ''; + //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?adminpw=%MAILMAN_ADMINPW%&unsubscribees=%EMAIL%'; + } + + print "\n"; + + // Value + if ($const == 'ADHERENT_CARD_TYPE' || $const == 'ADHERENT_ETIQUETTE_TYPE') + { + print ''; + // List of possible labels (defined into $_Avery_Labels variable set into format_cards.lib.php) + require_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php'; + $arrayoflabels = array(); + foreach (array_keys($_Avery_Labels) as $codecards) + { + $arrayoflabels[$codecards] = $_Avery_Labels[$codecards]['name']; + } + print $form->selectarray('constvalue'.(empty($strictw3c) ? '' : '[]'), $arrayoflabels, ($obj->value ? $obj->value : 'CARD'), 1, 0, 0); + print ''; + print ''; + print ''; + } + else + { + print ''; + print ''; + print ''; + if ($obj->type == 'textarea' || in_array($const, array('ADHERENT_CARD_TEXT', 'ADHERENT_CARD_TEXT_RIGHT', 'ADHERENT_ETIQUETTE_TEXT'))) + { + print '\n"; + } + elseif ($obj->type == 'html') + { + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor = new DolEditor('constvalue_'.$const.(empty($strictw3c) ? '' : '[]'), $obj->value, '', 160, 'dolibarr_notes', '', false, false, $conf->fckeditor->enabled, ROWS_5, '90%'); + $doleditor->Create(); + } + elseif ($obj->type == 'yesno') + { + print $form->selectyesno('constvalue'.(empty($strictw3c) ? '' : '[]'), $obj->value, 1); + } + elseif (preg_match('/emailtemplate/', $obj->type)) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + + $tmp = explode(':', $obj->type); + + $nboftemplates = $formmail->fetchAllEMailTemplate($tmp[1], $user, null, -1); // We set lang=null to get in priority record with no lang + //$arraydefaultmessage = $formmail->getEMailTemplate($db, $tmp[1], $user, null, 0, 1, ''); + $arrayofmessagename = array(); + if (is_array($formmail->lines_model)) + { + foreach ($formmail->lines_model as $modelmail) + { + //var_dump($modelmail); + $moreonlabel = ''; + if (!empty($arrayofmessagename[$modelmail->label])) $moreonlabel = ' ('.$langs->trans("SeveralLangugeVariatFound").')'; + // The 'label' is the key that is unique if we exclude the language + $arrayofmessagename[$modelmail->label.':'.$tmp[1]] = $langs->trans(preg_replace('/\(|\)/', '', $modelmail->label)).$moreonlabel; + } + } + //var_dump($arraydefaultmessage); + //var_dump($arrayofmessagename); + print $form->selectarray('constvalue_'.$obj->name, $arrayofmessagename, $obj->value.':'.$tmp[1], 'None', 0, 0, '', 0, 0, 0, '', '', 1); + } + else // type = 'string' ou 'chaine' + { + print ''; + } + print ''; + } + // Submit + if (empty($strictw3c)) + { + print ''; + print ''; + print ""; + } + print "\n"; + + if (empty($strictw3c)) print "
\n"; + } + } + print ''; + + if (!empty($strictw3c) && $strictw3c == 1) + { + print '
'; + print "\n"; + } } @@ -1681,22 +1637,18 @@ $listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); $i = 0; if (!empty($modules)) { - foreach ($modules as $module) { + foreach ($modules as $module) + { $moduleconst = $module->const_name; $modulename = strtolower($module->name); //print 'modulename='.$modulename; //if (empty($conf->global->$moduleconst)) continue; - if (!in_array($modulename, $listofmodules)) { - continue; - } + if (!in_array($modulename, $listofmodules)) continue; //var_dump($modulename.' - '.$langs->trans('Module'.$module->numero.'Name')); - if ($i > 0) { - $text .= ', '; - } else { - $text .= ' '; - } + if ($i > 0) $text .= ', '; + else $text .= ' '; $i++; $text .= $langs->trans('Module'.$module->numero.'Name'); } @@ -1720,18 +1672,21 @@ $db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity, libelle, description)"; - $sql .= " VALUES ('".$db->escape($name)."','".$db->escape($type)."',".$conf->entity.", "; - $sql .= ($label ? "'".$db->escape($label)."'" : 'null').", "; - $sql .= (!empty($description) ? "'".$db->escape($description)."'" : "null"); - $sql .= ")"; - - dol_syslog("admin.lib::addDocumentModel", LOG_DEBUG); + $sql = "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity, libelle, description)"; + $sql .= " VALUES ('".$db->escape($name)."','".$type."',".$conf->entity.", "; + $sql .= ($label ? "'".$db->escape($label)."'" : 'null').", "; + $sql .= (!empty($description) ? "'".$db->escape($description)."'" : "null"); + $sql .= ")"; + + dol_syslog("admin.lib::addDocumentModel", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) { + if ($resql) + { $db->commit(); return 1; - } else { + } + else + { dol_print_error($db); $db->rollback(); return -1; @@ -1753,15 +1708,18 @@ $sql = "DELETE FROM ".MAIN_DB_PREFIX."document_model"; $sql .= " WHERE nom = '".$db->escape($name)."'"; - $sql .= " AND type = '".$db->escape($type)."'"; + $sql .= " AND type = '".$type."'"; $sql .= " AND entity = ".$conf->entity; dol_syslog("admin.lib::delDocumentModel", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) { + if ($resql) + { $db->commit(); return 1; - } else { + } + else + { dol_print_error($db); $db->rollback(); return -1; @@ -1778,20 +1736,21 @@ { ob_start(); phpinfo(); - $phpinfostring = ob_get_contents(); - ob_end_clean(); - $info_arr = array(); - $info_lines = explode("\n", strip_tags($phpinfostring, "

")); + $info_lines = explode("\n", strip_tags(ob_get_clean(), "

")); // end of ob_start() $cat = "General"; - foreach ($info_lines as $line) { + foreach ($info_lines as $line) + { // new cat? $title = array(); preg_match("~

(.*)

~", $line, $title) ? $cat = $title[1] : null; $val = array(); - if (preg_match("~]+>([^<]*)]+>([^<]*)~", $line, $val)) { + if (preg_match("~]+>([^<]*)]+>([^<]*)~", $line, $val)) + { $info_arr[trim($cat)][trim($val[1])] = $val[2]; - } elseif (preg_match("~]+>([^<]*)]+>([^<]*)]+>([^<]*)~", $line, $val)) { + } + elseif (preg_match("~]+>([^<]*)]+>([^<]*)]+>([^<]*)~", $line, $val)) + { $info_arr[trim($cat)][trim($val[1])] = array("local" => $val[2], "master" => $val[3]); } } @@ -1815,21 +1774,16 @@ $head[$h][2] = 'company'; $h++; - $head[$h][0] = DOL_URL_ROOT."/admin/openinghours.php"; - $head[$h][1] = $langs->trans("OpeningHours"); - $head[$h][2] = 'openinghours'; - $h++; + $head[$h][0] = DOL_URL_ROOT."/admin/openinghours.php"; + $head[$h][1] = $langs->trans("OpeningHours"); + $head[$h][2] = 'openinghours'; + $h++; $head[$h][0] = DOL_URL_ROOT."/admin/accountant.php"; $head[$h][1] = $langs->trans("Accountant"); $head[$h][2] = 'accountant'; $h++; - $head[$h][0] = DOL_URL_ROOT."/admin/company_socialnetworks.php"; - $head[$h][1] = $langs->trans("SocialNetworksInformation"); - $head[$h][2] = 'socialnetworks'; - $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'mycompany_admin', 'add'); complete_head_from_modules($conf, $langs, null, $head, $h, 'mycompany_admin', 'remove'); @@ -1849,39 +1803,35 @@ $h = 0; $head = array(); - if (!empty($user->admin) && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) { + if (!empty($user->admin) && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) + { $head[$h][0] = DOL_URL_ROOT."/admin/mails.php"; $head[$h][1] = $langs->trans("OutGoingEmailSetup"); $head[$h][2] = 'common'; $h++; - if ($conf->mailing->enabled) { + if ($conf->mailing->enabled) + { $head[$h][0] = DOL_URL_ROOT."/admin/mails_emailing.php"; $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing", $langs->transnoentitiesnoconv("EMailing")); $head[$h][2] = 'common_emailing'; $h++; } - - if ($conf->ticket->enabled) { - $head[$h][0] = DOL_URL_ROOT."/admin/mails_ticket.php"; - $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing", $langs->transnoentitiesnoconv("Ticket")); - $head[$h][2] = 'common_ticket'; - $h++; - } } - if (!empty($user->admin) && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) { + $head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php"; + $head[$h][1] = $langs->trans("EMailTemplates"); + $head[$h][2] = 'templates'; + $h++; + + if (!empty($user->admin) && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) + { $head[$h][0] = DOL_URL_ROOT."/admin/mails_senderprofile_list.php"; $head[$h][1] = $langs->trans("EmailSenderProfiles"); $head[$h][2] = 'senderprofiles'; $h++; } - $head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php"; - $head[$h][1] = $langs->trans("EMailTemplates"); - $head[$h][2] = 'templates'; - $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'email_admin', 'remove'); return $head; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_agenda.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_agenda.lib.php @@ -51,7 +51,6 @@ { global $conf, $user, $langs, $db, $hookmanager; global $begin_h, $end_h, $begin_d, $end_d; - global $massaction; $langs->load("companies"); @@ -64,58 +63,70 @@ print ''; print ''; print ''; - if ($massaction != 'predelete') { // When $massaction == 'predelete', action may be already output to 'delete' by the mass action system. - print ''; - } + print ''; print ''; + print '
'; + + if ($conf->browser->layout == 'phone') print '
'; + else print ''; + + if ($conf->browser->layout == 'phone') print '
'; + else print '
'; + + print ''; + if ($canedit) { - print '
'; // Type - print ''; - print ''.$langs->trans("Type").''; + print '
'; + print ''; // Assigned to - print '
'; + print '
'; + print ''; if ($conf->resource->enabled) { - include_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php'; - $formresource = new FormResource($db); - - // Resource - print '
'; - print img_picto('', 'object_resource', 'class="fawidth30 inline-block"'); - print ''.$langs->trans("Resource").''; - print $formresource->select_resource_list($resourceid, "search_resourceid", '', 1, 0, 0, null, '', 2, 0, 'maxwidth500'); - print '
'; + include_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php'; + $formresource = new FormResource($db); + + // Resource + print ''; + print ''; } } if (!empty($conf->societe->enabled) && $user->rights->societe->lire) { - print '
'; + print '
'; + print ''; } if (!empty($conf->projet->enabled) && $user->rights->projet->lire) @@ -123,29 +134,80 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; $formproject = new FormProjets($db); - print '
'; + print '
'; + print ''; } if ($canedit && !preg_match('/list/', $_SERVER["PHP_SELF"])) { // Status - print '
'; - print img_picto('', 'setup', 'class="fawidth30 inline-block"'); - print ''.$langs->trans("Status").''; + print '
'; + print ''; + } + + if ($canedit && $action == 'show_peruser') + { + // Filter on hours + print ''; + print ''; + print "'; + + // Filter on days + print ''; + print ''; + print "'; } // Hooks $parameters = array('canedit'=>$canedit, 'pid'=>$pid, 'socid'=>$socid); - $object = null; $reshook = $hookmanager->executeHooks('searchAgendaFrom', $parameters, $object, $action); // Note that $action and $object may have been + print '
'; + print $langs->trans("Type"); + print ''; $multiselect = 0; if (!empty($conf->global->MAIN_ENABLE_MULTISELECT_TYPE)) // We use an option here because it adds bugs when used on agenda page "peruser" and "list" { $multiselect = (!empty($conf->global->AGENDA_USE_EVENT_TYPE)); } + print ''; print $formactions->select_type_actions($actioncode, "search_actioncode", $excludetype, (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1), 0, $multiselect, 0, 'maxwidth500'); - print ''; + print '
'; + print $langs->trans("ActionsToDoBy").'   '; + print ''; print img_picto('', 'user', 'class="fawidth30 inline-block"'); - print ''.$langs->trans("ActionsToDoBy").''; - print $form->select_dolusers($filtert, 'search_filtert', 1, '', !$canedit, '', '', 0, 0, 0, '', 0, '', 'maxwidth500 widthcentpercentminusxx'); - print ''; - print '
'; + print $form->select_dolusers($filtert, 'search_filtert', 1, '', !$canedit, '', '', 0, 0, 0, '', 0, '', 'maxwidth500'); + if (empty($conf->dol_optimize_smallscreen)) print '   '.$langs->trans("or").' '.$langs->trans("ToUserOfGroup").'   '; + else print '
'; print img_picto('', 'object_group', 'class="fawidth30 inline-block"'); - print ''.$langs->trans("ToUserOfGroup").''; print $form->select_dolgroups($usergroupid, 'usergroup', 1, '', !$canedit, '', '', '0', false, 'maxwidth500'); - print '
'; + print '
'; + print $langs->trans("Resource"); + print ''; + print img_picto('', 'object_resource', 'class="fawidth30 inline-block"'); + print $formresource->select_resource_list($resourceid, "search_resourceid", '', 1, 0, 0, null, '', 2, 0, 'maxwidth500'); + print '
'; + print $langs->trans("ThirdParty").'   '; + print ''; print img_picto('', 'company', 'class="fawidth30 inline-block"'); - print ''.$langs->trans("ThirdParty").''; print $form->select_company($socid, 'search_socid', '', ' ', 0, 0, null, 0, 'minwidth100 maxwidth500'); - print ''; + print '
'; + print $langs->trans("Project").'   '; + print ''; print img_picto('', 'project', 'class="fawidth30 inline-block"'); - print ''.$langs->trans("Project").''; print $formproject->select_projects($socid ? $socid : -1, $pid, 'search_projectid', 0, 0, 1, 0, 0, 0, 0, '', 1, 0, 'maxwidth500'); - print ''; + print '
'; + print $langs->trans("Status"); + print '  '; $formactions->form_select_status_action('formaction', $status, 1, 'search_status', 1, 2, 'minwidth100'); - print ''; + print '
'.$langs->trans("VisibleTimeRange").'"; + print '
'; + print ''; + if (empty($conf->dol_use_jmobile)) print ' - '; + else print '
'; + print ''; + if (empty($conf->dol_use_jmobile)) print ' '.$langs->trans("H"); + print '
'; + print '
'.$langs->trans("VisibleDaysRange").'"; + print '
'; + print ''; + if (empty($conf->dol_use_jmobile)) print ' - '; + else print '
'; + print ''; + print '
'; + print '
'; + + if ($conf->browser->layout == 'phone') print ''; + else print '
'; + + print ''; + print '
'; + print '
'; + print ''; + print '
'; + print '
'; + + if ($conf->browser->layout == 'phone') print ''; + else print '
'; + + print '
'; // Close fichecenter print '
'; + + //print ''; } @@ -157,24 +219,22 @@ */ function show_array_actions_to_do($max = 5) { - global $langs, $conf, $user, $db, $socid; + global $langs, $conf, $user, $db, $bc, $socid; $now = dol_now(); include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; include_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; - $sql = "SELECT a.id, a.label, a.datep as dp, a.datep2 as dp2, a.fk_user_author, a.percent"; - $sql .= ", c.code, c.libelle as type_label"; - $sql .= ", s.rowid as socid, s.nom as name, s.name_alias"; - $sql .= ", s.code_client, s.code_compta, s.client"; - $sql .= ", s.logo, s.email, s.entity"; + $sql = "SELECT a.id, a.label, a.datep as dp, a.datep2 as dp2, a.fk_user_author, a.percent,"; + $sql .= " c.code, c.libelle as type_label,"; + $sql .= " s.nom as sname, s.rowid, s.client"; $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a LEFT JOIN "; $sql .= " ".MAIN_DB_PREFIX."c_actioncomm as c ON c.id = a.fk_action"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; - $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep2 > '".$db->idate($now)."'))"; + $sql .= " WHERE a.entity = ".$conf->entity; + $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep2 > '".$db->idate($now)."'))"; if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($socid) $sql .= " AND s.rowid = ".$socid; $sql .= " ORDER BY a.datep DESC, a.id DESC"; @@ -183,54 +243,49 @@ $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($resql); + $num = $db->num_rows($resql); print '
'; - print ''; - print ''; - print ''; + print '
'.$langs->trans("LastActionsToDo", $max).''.$langs->trans("FullList").'
'; + print ''; + print ''; print ''; - $i = 0; + $var = true; + $i = 0; $staticaction = new ActionComm($db); - $customerstatic = new Client($db); - - while ($i < $num) - { - $obj = $db->fetch_object($resql); - - - print ''; - - $staticaction->type_code = $obj->code; - $staticaction->label = ($obj->label ? $obj->label : $obj->type_label); - $staticaction->id = $obj->id; - print ''; - - // print ''; - - print ''; - - $datep = $db->jdate($obj->dp); - $datep2 = $db->jdate($obj->dp2); - - // Date - print ''; + + $staticaction->type_code = $obj->code; + $staticaction->label = ($obj->label ? $obj->label : $obj->type_label); + $staticaction->id = $obj->id; + print ''; + + // print ''; + + print ''; + + $datep = $db->jdate($obj->dp); + $datep2 = $db->jdate($obj->dp2); + + // Date + print '\n"; - $i++; - } - print "
'.$langs->trans("LastActionsToDo", $max).''.$langs->trans("FullList").'
'.$staticaction->getNomUrl(1, 34).''.dol_trunc($obj->label,22).''; - if ($obj->socid > 0) - { - $customerstatic->id = $obj->socid; - $customerstatic->name = $obj->name; - //$customerstatic->name_alias = $obj->name_alias; - $customerstatic->code_client = $obj->code_client; - $customerstatic->code_compta = $obj->code_compta; - $customerstatic->client = $obj->client; - $customerstatic->logo = $obj->logo; - $customerstatic->email = $obj->email; - $customerstatic->entity = $obj->entity; - print $customerstatic->getNomUrl(1, '', 40); - } - print ''.dol_print_date($datep, 'day').' '; + $customerstatic = new Client($db); + + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + + print '
'.$staticaction->getNomUrl(1, 34).''.dol_trunc($obj->label,22).''; + if ($obj->rowid > 0) + { + $customerstatic->id = $obj->rowid; + $customerstatic->name = $obj->sname; + $customerstatic->client = $obj->client; + print $customerstatic->getNomUrl(1, '', 16); + } + print ''.dol_print_date($datep, 'day').' '; $late = 0; if ($obj->percent == 0 && $datep && $datep < time()) $late = 1; if ($obj->percent == 0 && !$datep && $datep2 && $datep2 < time()) $late = 1; @@ -244,13 +299,15 @@ print "

"; - - $db->free($resql); - } else { - dol_print_error($db); + $i++; + } + print "

"; + + $db->free($resql); + } + else + { + dol_print_error($db); } } @@ -263,23 +320,21 @@ */ function show_array_last_actions_done($max = 5) { - global $langs, $conf, $user, $db, $socid; + global $langs, $conf, $user, $db, $bc, $socid; $now = dol_now(); - $sql = "SELECT a.id, a.percent, a.datep as da, a.datep2 as da2, a.fk_user_author, a.label"; - $sql .= ", c.code, c.libelle"; - $sql .= ", s.rowid as socid, s.nom as name, s.name_alias"; - $sql .= ", s.code_client, s.code_compta, s.client"; - $sql .= ", s.logo, s.email, s.entity"; + $sql = "SELECT a.id, a.percent, a.datep as da, a.datep2 as da2, a.fk_user_author, a.label,"; + $sql .= " c.code, c.libelle,"; + $sql .= " s.rowid, s.nom as sname, s.client"; $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a LEFT JOIN "; $sql .= " ".MAIN_DB_PREFIX."c_actioncomm as c ON c.id = a.fk_action "; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; - $sql .= " AND (a.percent >= 100 OR (a.percent = -1 AND a.datep2 <= '".$db->idate($now)."'))"; + $sql .= " WHERE a.entity = ".$conf->entity; + $sql .= " AND (a.percent >= 100 OR (a.percent = -1 AND a.datep2 <= '".$db->idate($now)."'))"; if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($socid) $sql .= " AND s.rowid = ".$socid; $sql .= " ORDER BY a.datep2 DESC"; $sql .= $db->plimit($max, 0); @@ -291,13 +346,13 @@ print '
'; print ''; print ''; - print ''; + print ''; print ''; - + $var = true; $i = 0; - $staticaction = new ActionComm($db); - $customerstatic = new Societe($db); + $staticaction = new ActionComm($db); + $customerstatic = new Societe($db); while ($i < $num) { @@ -311,30 +366,24 @@ $staticaction->id = $obj->id; print ''; - //print ''; + //print ''; print ''; // Date - print '"; - // Status - print '\n"; + // Statut + print "\n"; print "\n"; $i++; @@ -344,7 +393,9 @@ print "
'.$langs->trans("LastDoneTasks", $max).''.$langs->trans("FullList").''.$langs->trans("FullList").'
'.$staticaction->getNomUrl(1, 34).''.dol_trunc($obj->label,24).''.dol_trunc($obj->label,24).''; - if ($obj->socid > 0) + if ($obj->rowid > 0) { - $customerstatic->id = $obj->socid; - $customerstatic->name = $obj->name; - //$customerstatic->name_alias = $obj->name_alias; - $customerstatic->code_client = $obj->code_client; - $customerstatic->code_compta = $obj->code_compta; - $customerstatic->client = $obj->client; - $customerstatic->logo = $obj->logo; - $customerstatic->email = $obj->email; - $customerstatic->entity = $obj->entity; - print $customerstatic->getNomUrl(1, '', 30); + $customerstatic->id = $obj->rowid; + $customerstatic->name = $obj->sname; + $customerstatic->client = $obj->client; + print $customerstatic->getNomUrl(1, '', 24); } print ''.dol_print_date($db->jdate($obj->da2), 'day'); + print ''.dol_print_date($db->jdate($obj->da2), 'day'); print "'.$staticaction->LibStatut($obj->percent, 3)."".$staticaction->LibStatut($obj->percent, 3)."

"; $db->free($resql); - } else { + } + else + { dol_print_error($db); } } @@ -371,10 +422,13 @@ $head[$h][2] = 'autoactions'; $h++; - $head[$h][0] = DOL_URL_ROOT."/admin/agenda_reminder.php"; - $head[$h][1] = $langs->trans("Reminders"); - $head[$h][2] = 'reminders'; - $h++; + if ($conf->global->MAIN_FEATURES_LEVEL > 0) + { + $head[$h][0] = DOL_URL_ROOT."/admin/agenda_reminder.php"; + $head[$h][1] = $langs->trans("Reminders"); + $head[$h][2] = 'reminders'; + $h++; + } $head[$h][0] = DOL_URL_ROOT."/admin/agenda_xcal.php"; $head[$h][1] = $langs->trans("ExportCal"); @@ -417,32 +471,32 @@ $head[$h][2] = 'card'; $h++; - // Tab to link resources + // Tab to link resources if ($conf->resource->enabled) { - include_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php'; - $resource = new DolResource($db); + include_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php'; + $resource = new DolResource($db); $head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=action&element_id='.$object->id; - $listofresourcelinked = $resource->getElementResources($object->element, $object->id); - $nbResources = (is_array($listofresourcelinked) ?count($listofresourcelinked) : 0); + $listofresourcelinked = $resource->getElementResources($object->element, $object->id); + $nbResources = (is_array($listofresourcelinked) ?count($listofresourcelinked) : 0); $head[$h][1] = $langs->trans("Resources"); if ($nbResources > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbResources).'' : ''); $head[$h][2] = 'resources'; $h++; } - // Attached files - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->agenda->dir_output."/".$object->id; - $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.'/comm/action/document.php?id='.$object->id; - $head[$h][1] = $langs->trans("Documents"); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbFiles + $nbLinks).'' : ''); - $head[$h][2] = 'documents'; - $h++; + // Attached files + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->agenda->dir_output."/".$object->id; + $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.'/comm/action/document.php?id='.$object->id; + $head[$h][1] = $langs->trans("Documents"); + if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbFiles + $nbLinks).'' : ''); + $head[$h][2] = 'documents'; + $h++; $head[$h][0] = DOL_URL_ROOT.'/comm/action/info.php?id='.$object->id; $head[$h][1] = $langs->trans('Info'); @@ -465,55 +519,55 @@ */ function calendars_prepare_head($param) { - global $langs, $conf, $user; - - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/comm/action/list.php?action=show_list'.($param ? '&'.$param : ''); - $head[$h][1] = $langs->trans("ViewList"); - $head[$h][2] = 'cardlist'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/comm/action/index.php?action=show_month'.($param ? '&'.$param : ''); - $head[$h][1] = $langs->trans("ViewCal"); - $head[$h][2] = 'cardmonth'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/comm/action/index.php?action=show_week'.($param ? '&'.$param : ''); - $head[$h][1] = $langs->trans("ViewWeek"); - $head[$h][2] = 'cardweek'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/comm/action/index.php?action=show_day'.($param ? '&'.$param : ''); - $head[$h][1] = $langs->trans("ViewDay"); - $head[$h][2] = 'cardday'; - $h++; - - //if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) - if (!empty($conf->global->AGENDA_SHOW_PERTYPE)) - { - $head[$h][0] = DOL_URL_ROOT.'/comm/action/pertype.php'.($param ? '?'.$param : ''); - $head[$h][1] = $langs->trans("ViewPerType"); - $head[$h][2] = 'cardpertype'; - $h++; - } - - $newparam = $param; - $newparam = preg_replace('/&?search_filtert=\d+/', '', $newparam); - $head[$h][0] = DOL_URL_ROOT.'/comm/action/peruser.php'.($newparam ? '?'.$newparam : ''); - $head[$h][1] = $langs->trans("ViewPerUser"); - $head[$h][2] = 'cardperuser'; - $h++; - - - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, null, $head, $h, 'agenda'); - - complete_head_from_modules($conf, $langs, null, $head, $h, 'agenda', 'remove'); - - return $head; + global $langs, $conf, $user; + + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/comm/action/list.php'.($param ? '?'.$param : ''); + $head[$h][1] = $langs->trans("ViewList"); + $head[$h][2] = 'cardlist'; + $h++; + + $head[$h][0] = DOL_URL_ROOT.'/comm/action/index.php?action=show_month'.($param ? '&'.$param : ''); + $head[$h][1] = $langs->trans("ViewCal"); + $head[$h][2] = 'cardmonth'; + $h++; + + $head[$h][0] = DOL_URL_ROOT.'/comm/action/index.php?action=show_week'.($param ? '&'.$param : ''); + $head[$h][1] = $langs->trans("ViewWeek"); + $head[$h][2] = 'cardweek'; + $h++; + + $head[$h][0] = DOL_URL_ROOT.'/comm/action/index.php?action=show_day'.($param ? '&'.$param : ''); + $head[$h][1] = $langs->trans("ViewDay"); + $head[$h][2] = 'cardday'; + $h++; + + //if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) + if (!empty($conf->global->AGENDA_SHOW_PERTYPE)) + { + $head[$h][0] = DOL_URL_ROOT.'/comm/action/pertype.php'.($param ? '?'.$param : ''); + $head[$h][1] = $langs->trans("ViewPerType"); + $head[$h][2] = 'cardpertype'; + $h++; + } + + $newparam = $param; + $newparam = preg_replace('/&?search_filtert=\d+/', '', $newparam); + $head[$h][0] = DOL_URL_ROOT.'/comm/action/peruser.php'.($newparam ? '?'.$newparam : ''); + $head[$h][1] = $langs->trans("ViewPerUser"); + $head[$h][2] = 'cardperuser'; + $h++; + + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'agenda'); + + complete_head_from_modules($conf, $langs, null, $head, $h, 'agenda', 'remove'); + + return $head; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_ajax.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_ajax.lib.php @@ -25,38 +25,37 @@ /** - * Generic function that return javascript to add to a page to transform a common input field into an autocomplete field by calling an Ajax page (ex: /societe/ajaxcompanies.php). - * The HTML field must be an input text with id=search_$htmlname. - * This use the jQuery "autocomplete" function. If we want to use the select2, we must also convert the input into select on funcntions that call this method. - * - * @param string $selected Preselected value - * @param string $htmlname HTML name of input field - * @param string $url Ajax Url to call for request: /path/page.php. Must return a json array ('key'=>id, 'value'=>String shown into input field once selected, 'label'=>String shown into combo list) - * @param string $urloption More parameters on URL request - * @param int $minLength Minimum number of chars to trigger that Ajax search - * @param int $autoselect Automatic selection if just one value (trigger("change") on field is done is search return only 1 result) - * @param array $ajaxoptions Multiple options array + * Generic function that return javascript to add to a page to transform a common input field into an autocomplete field by calling an Ajax page (ex: /societe/ajaxcompanies.php). + * The HTML field must be an input text with id=search_$htmlname. + * This use the jQuery "autocomplete" function. If we want to use the select2, we must also convert the input into select on funcntions that call this method. + * + * @param string $selected Preselected value + * @param string $htmlname HTML name of input field + * @param string $url Ajax Url to call for request: /path/page.php. Must return a json array ('key'=>id, 'value'=>String shown into input field once selected, 'label'=>String shown into combo list) + * @param string $urloption More parameters on URL request + * @param int $minLength Minimum number of chars to trigger that Ajax search + * @param int $autoselect Automatic selection if just one value + * @param array $ajaxoptions Multiple options array * - Ex: array('update'=>array('field1','field2'...)) will reset field1 and field2 once select done * - Ex: array('disabled'=> ) * - Ex: array('show'=> ) * - Ex: array('update_textarea'=> ) * - Ex: array('option_disabled'=> id to disable and warning to show if we select a disabled value (this is possible when using autocomplete ajax) - * @param string $moreparams More params provided to ajax call - * @return string Script - */ -function ajax_autocompleter($selected, $htmlname, $url, $urloption = '', $minLength = 2, $autoselect = 0, $ajaxoptions = array(), $moreparams = '') + * @return string Script + */ +function ajax_autocompleter($selected, $htmlname, $url, $urloption = '', $minLength = 2, $autoselect = 0, $ajaxoptions = array()) { - if (empty($minLength)) $minLength = 1; - - $dataforrenderITem = 'ui-autocomplete'; - $dataforitem = 'ui-autocomplete-item'; - // Allow two constant to use other values for backward compatibility - if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) $dataforrenderITem = constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM'); - if (defined('JS_QUERY_AUTOCOMPLETE_ITEM')) $dataforitem = constant('JS_QUERY_AUTOCOMPLETE_ITEM'); - - // Input search_htmlname is original field - // Input htmlname is a second input field used when using ajax autocomplete. - $script = ''; + if (empty($minLength)) $minLength = 1; + + $dataforrenderITem = 'ui-autocomplete'; + $dataforitem = 'ui-autocomplete-item'; + // Allow two constant to use other values for backward compatibility + if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) $dataforrenderITem = constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM'); + if (defined('JS_QUERY_AUTOCOMPLETE_ITEM')) $dataforitem = constant('JS_QUERY_AUTOCOMPLETE_ITEM'); + + // Input search_htmlname is original field + // Input htmlname is a second input field used when using ajax autocomplete. + $script = ''; $script .= ''."\n"; $script .= ''; - $msg .= "\n"; - - return $msg; + $msg .= "\n"; + + return $msg; } @@ -402,8 +396,8 @@ if (empty($minLengthToAutocomplete)) $minLengthToAutocomplete = 0; - $tmpplugin = 'select2'; - $msg = "\n".' + $tmpplugin = 'select2'; + $msg = "\n".' \n"; - - return $msg; + $msg .= "\n"; + + return $msg; } /** * On/off button for constant * * @param string $code Name of constant - * @param array $input Array of complementary actions to do if success ("disabled"|"enabled'|'set'|'del') => CSS element to switch, 'alert' => message to show, ... Example: array('disabled'=>array(0=>'cssid')) - * @param int $entity Entity. Current entity is used if null. + * @param array $input Array of options. ("disabled"|"enabled'|'set'|'del') => CSS element to switch, 'alert' => message to show, ... Example: array('disabled'=>array(0=>'cssid')) + * @param int $entity Entity to set. Use current entity if null. * @param int $revertonoff Revert on/off * @param int $strict Use only "disabled" with delConstant and "enabled" with setConstant * @param int $forcereload Force to reload page if we click/change value (this is supported only when there is no 'alert' option in input) - * @param string $marginleftonlyshort 1 = Add a short left margin on picto, 2 = Add a larger left margin on picto, 0 = No left margin. Works for fontawesome picto only. - * @param int $forcenoajax 1 = Force to use a ahref link instead of ajax code. + * @param string $marginleftonlyshort 1 = Add a short left margin on picto, 2 = Add a larger left margin on picto, 0 = No margin left. Works for fontawesome picto only. * @return string */ -function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2, $forcenoajax = 0) +function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2) { global $conf, $langs, $user; $entity = ((isset($entity) && is_numeric($entity) && $entity >= 0) ? $entity : $conf->entity); - if (!isset($input)) $input = array(); - - if (empty($conf->use_javascript_ajax) || $forcenoajax) + if (! isset($input)) $input = array(); + + if (empty($conf->use_javascript_ajax)) { - if (empty($conf->global->$code)) print ''.img_picto($langs->trans("Disabled"), 'off').''; - else print ''.img_picto($langs->trans("Enabled"), 'on').''; - } else { + if (empty($conf->global->$code)) print ''.img_picto($langs->trans("Disabled"), 'off').''; + else print ''.img_picto($langs->trans("Enabled"), 'on').''; + } + else + { $out = "\n".' '; - $out .= ''.img_picto($langs->trans($text_off), 'switch_off').''; - $out .= ''.img_picto($langs->trans($text_on), 'switch_on').''; - - return $out; + $out .= ''.img_picto($langs->trans($text_off), 'switch_off').''; + $out .= ''.img_picto($langs->trans($text_on), 'switch_on').''; + + return $out; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_asset.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_asset.lib.php @@ -80,7 +80,7 @@ $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/asset/card.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/asset/card.php'; $head[$h][1] = $langs->trans("Card"); $head[$h][2] = 'card'; $h++; @@ -88,10 +88,10 @@ // Show more tabs from modules // Entries must be declared in modules descriptor with line //$this->tabs = array( - // 'entity:+tabname:Title:@assets:/asset/mypage.php?id=__ID__' + // 'entity:+tabname:Title:@assets:/assets/mypage.php?id=__ID__' //); // to add new tab //$this->tabs = array( - // 'entity:-tabname:Title:@assets:/asset/mypage.php?id=__ID__' + // 'entity:-tabname:Title:@assets:/assets/mypage.php?id=__ID__' //); // to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'assets'); --- /tmp/dsg/dolibarr/htdocs/core/lib/github_bank.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_bank.lib.php @@ -34,88 +34,88 @@ */ function bank_prepare_head(Account $object) { - global $db, $langs, $conf, $user; - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/compta/bank/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("BankAccount"); - $head[$h][2] = 'bankname'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/compta/bank/bankentries_list.php?id=".$object->id; - $head[$h][1] = $langs->trans("BankTransactions"); - $head[$h][2] = 'journal'; - $h++; - - // if ($conf->global->MAIN_FEATURES_LEVEL >= 1) - // { - $head[$h][0] = DOL_URL_ROOT."/compta/bank/treso.php?account=".$object->id; - $head[$h][1] = $langs->trans("PlannedTransactions"); - $head[$h][2] = 'cash'; - $h++; - // } - - $head[$h][0] = DOL_URL_ROOT."/compta/bank/annuel.php?account=".$object->id; - $head[$h][1] = $langs->trans("IOMonthlyReporting"); - $head[$h][2] = 'annual'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/compta/bank/graph.php?account=".$object->id; - $head[$h][1] = $langs->trans("Graph"); - $head[$h][2] = 'graph'; - $h++; - - if ($object->courant != Account::TYPE_CASH) - { - $nbReceipts = 0; - - // List of all standing receipts - $sql = "SELECT COUNT(DISTINCT(b.num_releve)) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql .= " WHERE b.fk_account = ".$object->id; - - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - if ($obj) $nbReceipts = $obj->nb; - $db->free($resql); - } - - $head[$h][0] = DOL_URL_ROOT."/compta/bank/releve.php?account=".$object->id; - $head[$h][1] = $langs->trans("AccountStatements"); - if (($nbReceipts) > 0) $head[$h][1] .= ''.($nbReceipts).''; - $head[$h][2] = 'statement'; - $h++; + global $db, $langs, $conf, $user; + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/compta/bank/card.php?id='.$object->id; + $head[$h][1] = $langs->trans("BankAccount"); + $head[$h][2] = 'bankname'; + $h++; + + $head[$h][0] = DOL_URL_ROOT."/compta/bank/bankentries_list.php?id=".$object->id; + $head[$h][1] = $langs->trans("BankTransactions"); + $head[$h][2] = 'journal'; + $h++; + + // if ($conf->global->MAIN_FEATURES_LEVEL >= 1) + // { + $head[$h][0] = DOL_URL_ROOT."/compta/bank/treso.php?account=".$object->id; + $head[$h][1] = $langs->trans("PlannedTransactions"); + $head[$h][2] = 'cash'; + $h++; + // } + + $head[$h][0] = DOL_URL_ROOT."/compta/bank/annuel.php?account=".$object->id; + $head[$h][1] = $langs->trans("IOMonthlyReporting"); + $head[$h][2] = 'annual'; + $h++; + + $head[$h][0] = DOL_URL_ROOT."/compta/bank/graph.php?account=".$object->id; + $head[$h][1] = $langs->trans("Graph"); + $head[$h][2] = 'graph'; + $h++; + + if ($object->courant != Account::TYPE_CASH) + { + $nbReceipts = 0; + + // List of all standing receipts + $sql = "SELECT COUNT(DISTINCT(b.num_releve)) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= " WHERE b.fk_account = ".$object->id; + + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + if ($obj) $nbReceipts = $obj->nb; + $db->free($resql); + } + + $head[$h][0] = DOL_URL_ROOT."/compta/bank/releve.php?account=".$object->id; + $head[$h][1] = $langs->trans("AccountStatements"); + if (($nbReceipts) > 0) $head[$h][1] .= ''.($nbReceipts).''; + $head[$h][2] = 'statement'; + $h++; } - // Attached files - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->bank->dir_output."/".dol_sanitizeFileName($object->ref); - $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."/compta/bank/document.php?account=".$object->id; - $head[$h][1] = $langs->trans("Documents"); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; - $head[$h][2] = 'document'; - $h++; + // Attached files + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->bank->dir_output."/".dol_sanitizeFileName($object->ref); + $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."/compta/bank/document.php?account=".$object->id; + $head[$h][1] = $langs->trans("Documents"); + if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + $head[$h][2] = 'document'; + $h++; // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'bank'); - - /*$head[$h][0] = DOL_URL_ROOT . "/compta/bank/info.php?id=" . $object->id; + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'bank'); + + /*$head[$h][0] = DOL_URL_ROOT . "/compta/bank/info.php?id=" . $object->id; $head[$h][1] = $langs->trans("Info"); $head[$h][2] = 'info'; $h++;*/ complete_head_from_modules($conf, $langs, $object, $head, $h, 'bank', 'remove'); - return $head; + return $head; } /** * Prepare array with list of tabs @@ -134,10 +134,10 @@ $head[$h][2] = 'general'; $h++; - $head[$h][0] = DOL_URL_ROOT.'/admin/chequereceipts.php'; - $head[$h][1] = $langs->trans("CheckReceiptShort"); - $head[$h][2] = 'checkreceipts'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/chequereceipts.php'; + $head[$h][1] = $langs->trans("CheckReceiptShort"); + $head[$h][2] = 'checkreceipts'; + $h++; // Show more tabs from modules @@ -215,17 +215,17 @@ $head[$h][2] = 'card'; $h++; - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'various_payment'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'various_payment'); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $upload_dir = $conf->bank->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/compta/bank/various_payment/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; @@ -250,12 +250,12 @@ */ function checkSwiftForAccount($account) { - $swift = $account->bic; - if (preg_match("/^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/", $swift)) { - return true; - } else { - return false; - } + $swift = $account->bic; + if (preg_match("/^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/", $swift)) { + return true; + } else { + return false; + } } /** @@ -266,13 +266,13 @@ */ function checkIbanForAccount($account) { - require_once DOL_DOCUMENT_ROOT.'/includes/php-iban/oophp-iban.php'; - - $iban = new IBAN($account->iban); - $check = $iban->Verify(); - - if ($check) return true; - else return false; + require_once DOL_DOCUMENT_ROOT.'/includes/php-iban/oophp-iban.php'; + + $iban = new IBAN($account->iban); + $check = $iban->Verify(); + + if ($check) return true; + else return false; } /** @@ -283,68 +283,69 @@ */ function checkBanForAccount($account) { - $country_code = $account->getCountryCode(); - - // For compatibility between - // account of type CompanyBankAccount class (we use number, cle_rib) - // account of type Account class (we use num_compte, cle) - if (empty($account->number)) - $account->number = $account->num_compte; - if (empty($account->cle)) - $account->cle = $account->cle_rib; - - dol_syslog("bank.lib::checkBanForAccount account->code_banque=".$account->code_banque." account->code_guichet=".$account->code_guichet." account->number=".$account->number." account->cle=".$account->cle." account->iban=".$account->iban." country_code=".$country_code, LOG_DEBUG); - - if ($country_code == 'FR') { // France rules - $coef = array(62, 34, 3); - // Concatenation des differents codes. - $rib = strtolower(trim($account->code_banque).trim($account->code_guichet).trim($account->number).trim($account->cle)); - // On remplace les eventuelles lettres par des chiffres. - //$rib = strtr($rib, "abcdefghijklmnopqrstuvwxyz","12345678912345678912345678"); //Ne marche pas - $rib = strtr($rib, "abcdefghijklmnopqrstuvwxyz", "12345678912345678923456789"); - // Separation du rib en 3 groupes de 7 + 1 groupe de 2. - // Multiplication de chaque groupe par les coef du tableau - - for ($i = 0, $s = 0; $i < 3; $i++) { - $code = substr($rib, 7 * $i, 7); - $s += (0 + (int) $code) * $coef[$i]; - } - // Soustraction du modulo 97 de $s a 97 pour obtenir la cle - $cle_rib = 97 - ($s % 97); - if ($cle_rib == $account->cle) { - return true; - } - return false; - } - - if ($country_code == 'BE') { // Belgium rules - } - - if ($country_code == 'ES') { // Spanish rules - $CCC = strtolower(trim($account->number)); - $rib = strtolower(trim($account->code_banque).trim($account->code_guichet)); - $cle_rib = strtolower(checkES($rib, $CCC)); - if ($cle_rib == strtolower($account->cle)) { - return true; - } - return false; - } - if ($country_code == 'AU') { // Australian - if (strlen($account->code_banque) > 7) - return false; // Sould be 6 but can be 123-456 - elseif (strlen($account->code_banque) < 6) - return false; // Sould be 6 - else return true; - } - - // No particular rule - // If account is CompanyBankAccount class, we use number - // If account is Account class, we use num_compte - if (empty($account->number)) { - return false; - } - - return true; + $country_code = $account->getCountryCode(); + + // For compatibility between + // account of type CompanyBankAccount class (we use number, cle_rib) + // account of type Account class (we use num_compte, cle) + if (empty($account->number)) + $account->number = $account->num_compte; + if (empty($account->cle)) + $account->cle = $account->cle_rib; + + dol_syslog("bank.lib::checkBanForAccount account->code_banque=".$account->code_banque." account->code_guichet=".$account->code_guichet." account->number=".$account->number." account->cle=".$account->cle." account->iban=".$account->iban." country_code=".$country_code, LOG_DEBUG); + + if ($country_code == 'FR') { // France rules + $coef = array(62, 34, 3); + // Concatenation des differents codes. + $rib = strtolower(trim($account->code_banque).trim($account->code_guichet).trim($account->number).trim($account->cle)); + // On remplace les eventuelles lettres par des chiffres. + //$rib = strtr($rib, "abcdefghijklmnopqrstuvwxyz","12345678912345678912345678"); //Ne marche pas + $rib = strtr($rib, "abcdefghijklmnopqrstuvwxyz", "12345678912345678923456789"); + // Separation du rib en 3 groupes de 7 + 1 groupe de 2. + // Multiplication de chaque groupe par les coef du tableau + + for ($i = 0, $s = 0; $i < 3; $i++) { + $code = substr($rib, 7 * $i, 7); + $s += (0 + (int) $code) * $coef[$i]; + } + // Soustraction du modulo 97 de $s a 97 pour obtenir la cle + $cle_rib = 97 - ($s % 97); + if ($cle_rib == $account->cle) { + return true; + } + return false; + } + + if ($country_code == 'BE') { // Belgium rules + } + + if ($country_code == 'ES') { // Spanish rules + $CCC = strtolower(trim($account->number)); + $rib = strtolower(trim($account->code_banque).trim($account->code_guichet)); + $cle_rib = strtolower(checkES($rib, $CCC)); + if ($cle_rib == strtolower($account->cle)) { + return true; + } + return false; + } + if ($country_code == 'AU') { // Australian + if (strlen($account->code_banque) > 7) + return false; // Sould be 6 but can be 123-456 + elseif (strlen($account->code_banque) < 6) + return false; // Sould be 6 + else + return true; + } + + // No particular rule + // If account is CompanyBankAccount class, we use number + // If account is Account class, we use num_compte + if (empty($account->number)) { + return false; + } + + return true; } @@ -358,53 +359,53 @@ */ function checkES($IentOfi, $InumCta) { - if (empty($IentOfi) || empty($InumCta) || strlen($IentOfi) != 8 || strlen($InumCta) != 10) { - $keycontrol = ""; - return $keycontrol; - } - - $ccc = $IentOfi.$InumCta; - $numbers = "1234567890"; - - $i = 0; - - while ($i <= strlen($ccc) - 1) { - if (strpos($numbers, substr($ccc, $i, 1)) === false) { - $keycontrol = ""; - return $keycontrol; - } - $i++; - } - - $values = array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6); - $sum = 0; - - for ($i = 2; $i < 10; $i++) { - $sum += $values[$i] * substr($IentOfi, $i - 2, 1); - } - - $key = 11 - $sum % 11; - - if ($key == 10) - $key = 1; - if ($key == 11) - $key = 0; - - $keycontrol = $key; - - $sum = 0; - - for ($i = 0; $i < 11; $i++) { - $sum += $values[$i] * (int) substr($InumCta, $i, 1); //int to cast result of substr to a number - } - - $key = 11 - $sum % 11; - - if ($key == 10) - $key = 1; - if ($key == 11) - $key = 0; - - $keycontrol .= $key; - return $keycontrol; -} + if (empty($IentOfi) || empty($InumCta) || strlen($IentOfi) != 8 || strlen($InumCta) != 10) { + $keycontrol = ""; + return $keycontrol; + } + + $ccc = $IentOfi.$InumCta; + $numbers = "1234567890"; + + $i = 0; + + while ($i <= strlen($ccc) - 1) { + if (strpos($numbers, substr($ccc, $i, 1)) === false) { + $keycontrol = ""; + return $keycontrol; + } + $i++; + } + + $values = array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6); + $sum = 0; + + for ($i = 2; $i < 10; $i++) { + $sum += $values[$i] * substr($IentOfi, $i - 2, 1); + } + + $key = 11 - $sum % 11; + + if ($key == 10) + $key = 1; + if ($key == 11) + $key = 0; + + $keycontrol = $key; + + $sum = 0; + + for ($i = 0; $i < 11; $i++) { + $sum += $values[$i] * (int) substr($InumCta, $i, 1); //int to cast result of substr to a number + } + + $key = 11 - $sum % 11; + + if ($key == 10) + $key = 1; + if ($key == 11) + $key = 0; + + $keycontrol .= $key; + return $keycontrol; +} --- /tmp/dsg/dolibarr/htdocs/core/lib/github_barcode.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_barcode.lib.php @@ -67,23 +67,23 @@ */ function barcode_print($code, $encoding = "ANY", $scale = 2, $mode = "png") { - dol_syslog("barcode.lib.php::barcode_print $code $encoding $scale $mode"); - - $bars = barcode_encode($code, $encoding); - if (!$bars || !empty($bars['error'])) - { - // Return error message instead of array - if (empty($bars['error'])) $error = 'Bad Value '.$code.' for encoding '.$encoding; - else $error = $bars['error']; - dol_syslog('barcode.lib.php::barcode_print '.$error, LOG_ERR); - return $error; - } - if (!$mode) $mode = "png"; - //if (preg_match("/^(text|txt|plain)$/i",$mode)) print barcode_outtext($bars['text'],$bars['bars']); - //elseif (preg_match("/^(html|htm)$/i",$mode)) print barcode_outhtml($bars['text'],$bars['bars'], $scale,0, 0); - //else - barcode_outimage($bars['text'], $bars['bars'], $scale, $mode); - return $bars; + dol_syslog("barcode.lib.php::barcode_print $code $encoding $scale $mode"); + + $bars = barcode_encode($code, $encoding); + if (!$bars || !empty($bars['error'])) + { + // Return error message instead of array + if (empty($bars['error'])) $error = 'Bad Value '.$code.' for encoding '.$encoding; + else $error = $bars['error']; + dol_syslog('barcode.lib.php::barcode_print '.$error, LOG_ERR); + return $error; + } + if (!$mode) $mode = "png"; + //if (preg_match("/^(text|txt|plain)$/i",$mode)) print barcode_outtext($bars['text'],$bars['bars']); + //elseif (preg_match("/^(html|htm)$/i",$mode)) print barcode_outhtml($bars['text'],$bars['bars'], $scale,0, 0); + //else + barcode_outimage($bars['text'], $bars['bars'], $scale, $mode); + return $bars; } /** @@ -110,42 +110,45 @@ */ function barcode_encode($code, $encoding) { - global $genbarcode_loc; - - if ( - (preg_match("/^ean$/i", $encoding)) - - || (($encoding) && (preg_match("/^isbn$/i", $encoding)) - && ((strlen($code) == 9 || strlen($code) == 10) || - (((preg_match("/^978/", $code) && strlen($code) == 12) || - (strlen($code) == 13))))) - - || ((!isset($encoding) || !$encoding || (preg_match("/^ANY$/i", $encoding))) - && (preg_match("/^[0-9]{12,13}$/", $code))) - ) - { - /* use built-in EAN-Encoder */ - dol_syslog("barcode.lib.php::barcode_encode Use barcode_encode_ean"); - $bars = barcode_encode_ean($code, $encoding); - } elseif (file_exists($genbarcode_loc)) // For example C39 - { - /* use genbarcode */ - dol_syslog("barcode.lib.php::barcode_encode Use genbarcode ".$genbarcode_loc." code=".$code." encoding=".$encoding); - $bars = barcode_encode_genbarcode($code, $encoding); - } else { - print "barcode_encode needs an external programm for encodings other then EAN/ISBN (code=".$code.", encoding=".$encoding.")
\n"; - print "
    \n"; - print "
  • download gnu-barcode from www.gnu.org/software/barcode/\n"; - print "
  • compile and install them\n"; - print "
  • download genbarcode from www.ashberg.de/bar/\n"; - print "
  • compile and install them\n"; - print "
  • specify path the genbarcode in barcode module setup\n"; - print "
\n"; - print "
\n"; - return false; - } - - return $bars; + global $genbarcode_loc; + + if ( + (preg_match("/^ean$/i", $encoding)) + + || (($encoding) && (preg_match("/^isbn$/i", $encoding)) + && ((strlen($code) == 9 || strlen($code) == 10) || + (((preg_match("/^978/", $code) && strlen($code) == 12) || + (strlen($code) == 13))))) + + || ((!isset($encoding) || !$encoding || (preg_match("/^ANY$/i", $encoding))) + && (preg_match("/^[0-9]{12,13}$/", $code))) + ) + { + /* use built-in EAN-Encoder */ + dol_syslog("barcode.lib.php::barcode_encode Use barcode_encode_ean"); + $bars = barcode_encode_ean($code, $encoding); + } + elseif (file_exists($genbarcode_loc)) // For example C39 + { + /* use genbarcode */ + dol_syslog("barcode.lib.php::barcode_encode Use genbarcode ".$genbarcode_loc." code=".$code." encoding=".$encoding); + $bars = barcode_encode_genbarcode($code, $encoding); + } + else + { + print "barcode_encode needs an external programm for encodings other then EAN/ISBN (code=".$code.", encoding=".$encoding.")
\n"; + print "
    \n"; + print "
  • download gnu-barcode from www.gnu.org/software/barcode/\n"; + print "
  • compile and install them\n"; + print "
  • download genbarcode from www.ashberg.de/bar/\n"; + print "
  • compile and install them\n"; + print "
  • specify path the genbarcode in barcode module setup\n"; + print "
\n"; + print "
\n"; + return false; + } + + return $bars; } @@ -157,14 +160,14 @@ */ function barcode_gen_ean_sum($ean) { - $even = true; $esum = 0; $osum = 0; - $ln = strlen($ean) - 1; - for ($i = $ln; $i >= 0; $i--) - { - if ($even) $esum += $ean[$i]; else $osum += $ean[$i]; - $even = !$even; - } - return (10 - ((3 * $esum + $osum) % 10)) % 10; + $even = true; $esum = 0; $osum = 0; + $ln = strlen($ean) - 1; + for ($i = $ln; $i >= 0; $i--) + { + if ($even) $esum += $ean[$i]; else $osum += $ean[$i]; + $even = !$even; + } + return (10 - ((3 * $esum + $osum) % 10)) % 10; } /** @@ -176,56 +179,56 @@ */ function barcode_encode_ean($ean, $encoding = "EAN-13") { - $digits = array(3211, 2221, 2122, 1411, 1132, 1231, 1114, 1312, 1213, 3112); - $mirror = array("000000", "001011", "001101", "001110", "010011", "011001", "011100", "010101", "010110", "011010"); - $guards = array("9a1a", "1a1a1", "a1a"); - - $ean = trim($ean); - if (preg_match("/[^0-9]/i", $ean)) - { - return array("error"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (not a numeric)", "text"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (not a numeric)"); - } - $encoding = strtoupper($encoding); - if ($encoding == "ISBN") - { - if (!preg_match("/^978/", $ean)) $ean = "978".$ean; - } - if (preg_match("/^978/", $ean)) $encoding = "ISBN"; - if (strlen($ean) < 12 || strlen($ean) > 13) - { - return array("error"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (must have 12/13 numbers)", "text"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (must have 12/13 numbers)"); - } - - $ean = substr($ean, 0, 12); - $eansum = barcode_gen_ean_sum($ean); - $ean .= $eansum; - $line = $guards[0]; - for ($i = 1; $i < 13; $i++) - { - $str = $digits[$ean[$i]]; - if ($i < 7 && $mirror[$ean[0]][$i - 1] == 1) $line .= strrev($str); else $line .= $str; - if ($i == 6) $line .= $guards[1]; - } - $line .= $guards[2]; - - /* create text */ - $pos = 0; - $text = ""; - for ($a = 0; $a < 13; $a++) - { - if ($a > 0) $text .= " "; - $text .= "$pos:12:{$ean[$a]}"; - if ($a == 0) $pos += 12; - elseif ($a == 6) $pos += 12; - else $pos += 7; - } - - return array( - "error" => '', - "encoding" => $encoding, + $digits = array(3211, 2221, 2122, 1411, 1132, 1231, 1114, 1312, 1213, 3112); + $mirror = array("000000", "001011", "001101", "001110", "010011", "011001", "011100", "010101", "010110", "011010"); + $guards = array("9a1a", "1a1a1", "a1a"); + + $ean = trim($ean); + if (preg_match("/[^0-9]/i", $ean)) + { + return array("error"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (not a numeric)", "text"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (not a numeric)"); + } + $encoding = strtoupper($encoding); + if ($encoding == "ISBN") + { + if (!preg_match("/^978/", $ean)) $ean = "978".$ean; + } + if (preg_match("/^978/", $ean)) $encoding = "ISBN"; + if (strlen($ean) < 12 || strlen($ean) > 13) + { + return array("error"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (must have 12/13 numbers)", "text"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (must have 12/13 numbers)"); + } + + $ean = substr($ean, 0, 12); + $eansum = barcode_gen_ean_sum($ean); + $ean .= $eansum; + $line = $guards[0]; + for ($i = 1; $i < 13; $i++) + { + $str = $digits[$ean[$i]]; + if ($i < 7 && $mirror[$ean[0]][$i - 1] == 1) $line .= strrev($str); else $line .= $str; + if ($i == 6) $line .= $guards[1]; + } + $line .= $guards[2]; + + /* create text */ + $pos = 0; + $text = ""; + for ($a = 0; $a < 13; $a++) + { + if ($a > 0) $text .= " "; + $text .= "$pos:12:{$ean[$a]}"; + if ($a == 0) $pos += 12; + elseif ($a == 6) $pos += 12; + else $pos += 7; + } + + return array( + "error" => '', + "encoding" => $encoding, "bars" => $line, "text" => $text - ); + ); } /** @@ -237,50 +240,52 @@ */ function barcode_encode_genbarcode($code, $encoding) { - global $genbarcode_loc; - - // Clean parameters - if (preg_match("/^ean$/i", $encoding) && strlen($code) == 13) $code = substr($code, 0, 12); - if (!$encoding) $encoding = "ANY"; - $encoding = preg_replace("/[\\\|]/", "_", $encoding); - $code = preg_replace("/[\\\|]/", "_", $code); - - $command = escapeshellarg($genbarcode_loc); - //$paramclear=" \"".str_replace("\"", "\\\"",$code)."\" \"".str_replace("\"", "\\\"",strtoupper($encoding))."\""; - $paramclear = " ".escapeshellarg($code)." ".escapeshellarg(strtoupper($encoding)); - - $fullcommandclear = $command." ".$paramclear." 2>&1"; - //print $fullcommandclear."
\n";exit; - - dol_syslog("Run command ".$fullcommandclear); - $fp = popen($fullcommandclear, "r"); - if ($fp) - { - $bars = fgets($fp, 1024); - $text = fgets($fp, 1024); - $encoding = fgets($fp, 1024); - pclose($fp); - } else { - dol_syslog("barcode.lib.php::barcode_encode_genbarcode failed to run popen ".$fullcommandclear, LOG_ERR); - return false; - } - //var_dump($bars); - $ret = array( + global $genbarcode_loc; + + // Clean parameters + if (preg_match("/^ean$/i", $encoding) && strlen($code) == 13) $code = substr($code, 0, 12); + if (!$encoding) $encoding = "ANY"; + $encoding = preg_replace("/[\\\|]/", "_", $encoding); + $code = preg_replace("/[\\\|]/", "_", $code); + + $command = escapeshellarg($genbarcode_loc); + //$paramclear=" \"".str_replace("\"", "\\\"",$code)."\" \"".str_replace("\"", "\\\"",strtoupper($encoding))."\""; + $paramclear = " ".escapeshellarg($code)." ".escapeshellarg(strtoupper($encoding)); + + $fullcommandclear = $command." ".$paramclear." 2>&1"; + //print $fullcommandclear."
\n";exit; + + dol_syslog("Run command ".$fullcommandclear); + $fp = popen($fullcommandclear, "r"); + if ($fp) + { + $bars = fgets($fp, 1024); + $text = fgets($fp, 1024); + $encoding = fgets($fp, 1024); + pclose($fp); + } + else + { + dol_syslog("barcode.lib.php::barcode_encode_genbarcode failed to run popen ".$fullcommandclear, LOG_ERR); + return false; + } + //var_dump($bars); + $ret = array( "bars" => trim($bars), "text" => trim($text), "encoding" => trim($encoding), - "error" => "" - ); - //var_dump($ret); - if (preg_match('/permission denied/i', $ret['bars'])) - { - $ret['error'] = $ret['bars']; $ret['bars'] = ''; - return $ret; - } - if (!$ret['bars']) return false; - if (!$ret['text']) return false; - if (!$ret['encoding']) return false; - return $ret; + "error" => "" + ); + //var_dump($ret); + if (preg_match('/permission denied/i', $ret['bars'])) + { + $ret['error'] = $ret['bars']; $ret['bars'] = ''; + return $ret; + } + if (!$ret['bars']) return false; + if (!$ret['text']) return false; + if (!$ret['encoding']) return false; + return $ret; } /** @@ -296,105 +301,114 @@ */ function barcode_outimage($text, $bars, $scale = 1, $mode = "png", $total_y = 0, $space = '') { - global $bar_color, $bg_color, $text_color; - global $font_loc, $filebarcode; - - //print "$text, $bars, $scale, $mode, $total_y, $space, $font_loc, $filebarcode
"; - //var_dump($text); - //var_dump($bars); - //var_dump($font_loc); - - /* set defaults */ - if ($scale < 1) $scale = 2; - $total_y = (int) $total_y; - if ($total_y < 1) $total_y = (int) $scale * 60; - if (!$space) - $space = array('top'=>2 * $scale, 'bottom'=>2 * $scale, 'left'=>2 * $scale, 'right'=>2 * $scale); - - /* count total width */ - $xpos = 0; - $width = true; - $ln = strlen($bars); - for ($i = 0; $i < $ln; $i++) - { - $val = strtolower($bars[$i]); - if ($width) - { - $xpos += $val * $scale; - $width = false; - continue; - } - if (preg_match("/[a-z]/", $val)) - { - /* tall bar */ - $val = ord($val) - ord('a') + 1; - } - $xpos += $val * $scale; - $width = true; - } - - /* allocate the image */ - $total_x = ($xpos) + $space['right'] + $space['right']; - $xpos = $space['left']; - if (!function_exists("imagecreate")) - { - print "You don't have the gd2 extension enabled
\n"; - return ""; - } - $im = imagecreate($total_x, $total_y); - /* create two images */ - $col_bg = ImageColorAllocate($im, $bg_color[0], $bg_color[1], $bg_color[2]); - $col_bar = ImageColorAllocate($im, $bar_color[0], $bar_color[1], $bar_color[2]); - $col_text = ImageColorAllocate($im, $text_color[0], $text_color[1], $text_color[2]); - $height = round($total_y - ($scale * 10)); - $height2 = round($total_y - $space['bottom']); - - /* paint the bars */ - $width = true; - $ln = strlen($bars); - for ($i = 0; $i < $ln; $i++) - { - $val = strtolower($bars[$i]); - if ($width) - { - $xpos += $val * $scale; - $width = false; - continue; - } - if (preg_match("/[a-z]/", $val)) - { - /* tall bar */ - $val = ord($val) - ord('a') + 1; - $h = $height2; - } else $h = $height; - imagefilledrectangle($im, $xpos, $space['top'], $xpos + ($val * $scale) - 1, $h, $col_bar); - $xpos += $val * $scale; - $width = true; - } - - $chars = explode(" ", $text); - foreach ($chars as $v) { - if (trim($v)) { - $inf = explode(":", $v); - $fontsize = $scale * ($inf[1] / 1.8); - $fontheight = $total_y - ($fontsize / 2.7) + 2; - imagettftext($im, $fontsize, 0, $space['left'] + ($scale * $inf[0]) + 2, $fontheight, $col_text, $font_loc, $inf[2]); - } - } - - /* output the image */ - $mode = strtolower($mode); - if ($mode == 'jpg' || $mode == 'jpeg') { - header("Content-Type: image/jpeg; name=\"barcode.jpg\""); - imagejpeg($im); - } elseif ($mode == 'gif') { - header("Content-Type: image/gif; name=\"barcode.gif\""); - imagegif($im); - } elseif (!empty($filebarcode)) { - // To wxrite into afile onto disk - imagepng($im, $filebarcode); - } else { - header("Content-Type: image/png; name=\"barcode.png\""); - imagepng($im); - } -} + global $bar_color, $bg_color, $text_color; + global $font_loc, $filebarcode; + + //print "$text, $bars, $scale, $mode, $total_y, $space, $font_loc, $filebarcode
"; + //var_dump($text); + //var_dump($bars); + //var_dump($font_loc); + + /* set defaults */ + if ($scale < 1) $scale = 2; + $total_y = (int) $total_y; + if ($total_y < 1) $total_y = (int) $scale * 60; + if (!$space) + $space = array('top'=>2 * $scale, 'bottom'=>2 * $scale, 'left'=>2 * $scale, 'right'=>2 * $scale); + + /* count total width */ + $xpos = 0; + $width = true; + $ln = strlen($bars); + for ($i = 0; $i < $ln; $i++) + { + $val = strtolower($bars[$i]); + if ($width) + { + $xpos += $val * $scale; + $width = false; + continue; + } + if (preg_match("/[a-z]/", $val)) + { + /* tall bar */ + $val = ord($val) - ord('a') + 1; + } + $xpos += $val * $scale; + $width = true; + } + + /* allocate the image */ + $total_x = ($xpos) + $space['right'] + $space['right']; + $xpos = $space['left']; + if (!function_exists("imagecreate")) + { + print "You don't have the gd2 extension enabled
\n"; + return ""; + } + $im = imagecreate($total_x, $total_y); + /* create two images */ + $col_bg = ImageColorAllocate($im, $bg_color[0], $bg_color[1], $bg_color[2]); + $col_bar = ImageColorAllocate($im, $bar_color[0], $bar_color[1], $bar_color[2]); + $col_text = ImageColorAllocate($im, $text_color[0], $text_color[1], $text_color[2]); + $height = round($total_y - ($scale * 10)); + $height2 = round($total_y - $space['bottom']); + + /* paint the bars */ + $width = true; + $ln = strlen($bars); + for ($i = 0; $i < $ln; $i++) + { + $val = strtolower($bars[$i]); + if ($width) + { + $xpos += $val * $scale; + $width = false; + continue; + } + if (preg_match("/[a-z]/", $val)) + { + /* tall bar */ + $val = ord($val) - ord('a') + 1; + $h = $height2; + } else $h = $height; + imagefilledrectangle($im, $xpos, $space['top'], $xpos + ($val * $scale) - 1, $h, $col_bar); + $xpos += $val * $scale; + $width = true; + } + + $chars = explode(" ", $text); + reset($chars); + while (list($n, $v) = each($chars)) + { + if (trim($v)) + { + $inf = explode(":", $v); + $fontsize = $scale * ($inf[1] / 1.8); + $fontheight = $total_y - ($fontsize / 2.7) + 2; + imagettftext($im, $fontsize, 0, $space['left'] + ($scale * $inf[0]) + 2, $fontheight, $col_text, $font_loc, $inf[2]); + } + } + + /* output the image */ + $mode = strtolower($mode); + if ($mode == 'jpg' || $mode == 'jpeg') + { + header("Content-Type: image/jpeg; name=\"barcode.jpg\""); + imagejpeg($im); + } + elseif ($mode == 'gif') + { + header("Content-Type: image/gif; name=\"barcode.gif\""); + imagegif($im); + } + elseif (!empty($filebarcode)) // To wxrite into afile onto disk + { + imagepng($im, $filebarcode); + } + else + { + header("Content-Type: image/png; name=\"barcode.png\""); + imagepng($im); + } +} --- /tmp/dsg/dolibarr/htdocs/core/lib/github_company.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_company.lib.php @@ -41,36 +41,41 @@ */ function societe_prepare_head(Societe $object) { - global $db, $langs, $conf, $user; - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/societe/card.php?socid='.$object->id; - $head[$h][1] = $langs->trans("ThirdParty"); - $head[$h][2] = 'card'; - $h++; - - if (empty($conf->global->MAIN_SUPPORT_SHARED_CONTACT_BETWEEN_THIRDPARTIES)) { - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->societe->contact->lire) { - //$nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external')); + global $db, $langs, $conf, $user; + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/societe/card.php?socid='.$object->id; + $head[$h][1] = $langs->trans("ThirdParty"); + $head[$h][2] = 'card'; + $h++; + + if (empty($conf->global->MAIN_SUPPORT_SHARED_CONTACT_BETWEEN_THIRDPARTIES)) + { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->societe->contact->lire) + { + //$nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external')); $nbContact = 0; // TODO $sql = "SELECT COUNT(p.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p"; $sql .= " WHERE p.fk_soc = ".$object->id; $resql = $db->query($sql); - if ($resql) { + if ($resql) + { $obj = $db->fetch_object($resql); if ($obj) $nbContact = $obj->nb; } - $head[$h][0] = DOL_URL_ROOT.'/societe/contact.php?socid='.$object->id; - $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; - $head[$h][2] = 'contact'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/societe/contact.php?socid='.$object->id; + $head[$h][1] = $langs->trans('ContactsAddresses'); + if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + $head[$h][2] = 'contact'; + $h++; } - } else { + } + else + { $head[$h][0] = DOL_URL_ROOT.'/societe/societecontact.php?socid='.$object->id; $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][1] = $langs->trans("ContactsAddresses"); @@ -79,69 +84,79 @@ $h++; } - if ($object->client == 1 || $object->client == 2 || $object->client == 3) { - $head[$h][0] = DOL_URL_ROOT.'/comm/card.php?socid='.$object->id; - $head[$h][1] = ''; - if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && ($object->client == 2 || $object->client == 3)) $head[$h][1] .= $langs->trans("Prospect"); - if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && $object->client == 3) $head[$h][1] .= ' | '; - if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && ($object->client == 1 || $object->client == 3)) $head[$h][1] .= $langs->trans("Customer"); - $head[$h][2] = 'customer'; - $h++; - - if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { - $langs->load("products"); - // price - $head[$h][0] = DOL_URL_ROOT.'/societe/price.php?socid='.$object->id; - $head[$h][1] = $langs->trans("CustomerPrices"); - $head[$h][2] = 'price'; - $h++; - } - } - $supplier_module_enabled = 0; - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_proposal->enabled) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) $supplier_module_enabled = 1; - if ($supplier_module_enabled == 1 && $object->fournisseur && !empty($user->rights->fournisseur->lire)) { - $head[$h][0] = DOL_URL_ROOT.'/fourn/card.php?socid='.$object->id; - $head[$h][1] = $langs->trans("Supplier"); - $head[$h][2] = 'supplier'; - $h++; - } - - if (!empty($conf->projet->enabled) && (!empty($user->rights->projet->lire))) { - $head[$h][0] = DOL_URL_ROOT.'/societe/project.php?socid='.$object->id; - $head[$h][1] = $langs->trans("Projects"); - $nbNote = 0; - $sql = "SELECT COUNT(n.rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."projet as n"; - $sql .= " WHERE fk_soc = ".$object->id; - $sql .= " AND entity IN (".getEntity('project').")"; - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) { - $obj = $db->fetch_object($resql); - $nbNote = $obj->nb; - $i++; - } - } else { - dol_print_error($db); - } + if ($object->client == 1 || $object->client == 2 || $object->client == 3) + { + $head[$h][0] = DOL_URL_ROOT.'/comm/card.php?socid='.$object->id; + $head[$h][1] = ''; + if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && ($object->client == 2 || $object->client == 3)) $head[$h][1] .= $langs->trans("Prospect"); + if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && $object->client == 3) $head[$h][1] .= ' | '; + if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && ($object->client == 1 || $object->client == 3)) $head[$h][1] .= $langs->trans("Customer"); + $head[$h][2] = 'customer'; + $h++; + + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) + { + $langs->load("products"); + // price + $head[$h][0] = DOL_URL_ROOT.'/societe/price.php?socid='.$object->id; + $head[$h][1] = $langs->trans("CustomerPrices"); + $head[$h][2] = 'price'; + $h++; + } + } + $supplier_module_enabled = 0; + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_proposal->enabled) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) $supplier_module_enabled = 1; + if ($supplier_module_enabled == 1 && $object->fournisseur && !empty($user->rights->fournisseur->lire)) + { + $head[$h][0] = DOL_URL_ROOT.'/fourn/card.php?socid='.$object->id; + $head[$h][1] = $langs->trans("Supplier"); + $head[$h][2] = 'supplier'; + $h++; + } + + if (!empty($conf->projet->enabled) && (!empty($user->rights->projet->lire))) + { + $head[$h][0] = DOL_URL_ROOT.'/societe/project.php?socid='.$object->id; + $head[$h][1] = $langs->trans("Projects"); + $nbNote = 0; + $sql = "SELECT COUNT(n.rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet as n"; + $sql .= " WHERE fk_soc = ".$object->id; + $sql .= " AND entity IN (".getEntity('project').")"; + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $nbNote = $obj->nb; + $i++; + } + } + else { + dol_print_error($db); + } if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; - $head[$h][2] = 'project'; - $h++; - } - - // Tab to link resources - if (!empty($conf->resource->enabled) && !empty($conf->global->RESOURCE_ON_THIRDPARTIES)) { + $head[$h][2] = 'project'; + $h++; + } + + // Tab to link resources + if (!empty($conf->resource->enabled) && !empty($conf->global->RESOURCE_ON_THIRDPARTIES)) + { $head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=societe&element_id='.$object->id; $head[$h][1] = $langs->trans("Resources"); $head[$h][2] = 'resources'; $h++; } - if (!empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) { + if (!empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) + { // Tab to accountancy - if (!empty($conf->accounting->enabled) && $object->client > 0) { + if (!empty($conf->accounting->enabled) && $object->client > 0) + { $head[$h][0] = DOL_URL_ROOT.'/accountancy/bookkeeping/thirdparty_lettering_customer.php?socid='.$object->id; $head[$h][1] = $langs->trans("TabLetteringCustomer"); $head[$h][2] = 'lettering_customer'; @@ -149,7 +164,8 @@ } // Tab to accountancy - if (!empty($conf->accounting->enabled) && $object->fournisseur > 0) { + if (!empty($conf->accounting->enabled) && $object->fournisseur > 0) + { $head[$h][0] = DOL_URL_ROOT.'/accountancy/bookkeeping/thirdparty_lettering_supplier.php?socid='.$object->id; $head[$h][1] = $langs->trans("TabLetteringSupplier"); $head[$h][2] = 'lettering_supplier'; @@ -158,24 +174,27 @@ } // Related items - if ((!empty($conf->commande->enabled) || !empty($conf->propal->enabled) || !empty($conf->facture->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) - && empty($conf->global->THIRPARTIES_DISABLE_RELATED_OBJECT_TAB)) { - $head[$h][0] = DOL_URL_ROOT.'/societe/consumption.php?socid='.$object->id; - $head[$h][1] = $langs->trans("Referers"); - $head[$h][2] = 'consumption'; - $h++; - } - - // Bank accounts - if (empty($conf->global->SOCIETE_DISABLE_BANKACCOUNT)) { - $nbBankAccount = 0; + if ((!empty($conf->commande->enabled) || !empty($conf->propal->enabled) || !empty($conf->facture->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) + && empty($conf->global->THIRPARTIES_DISABLE_RELATED_OBJECT_TAB)) + { + $head[$h][0] = DOL_URL_ROOT.'/societe/consumption.php?socid='.$object->id; + $head[$h][1] = $langs->trans("Referers"); + $head[$h][2] = 'consumption'; + $h++; + } + + // Bank accounts + if (empty($conf->global->SOCIETE_DISABLE_BANKACCOUNT)) + { + $nbBankAccount = 0; $foundonexternalonlinesystem = 0; - $langs->load("banks"); - - //$title = $langs->trans("BankAccounts"); - $title = $langs->trans("PaymentInformation"); - - if (!empty($conf->stripe->enabled)) { + $langs->load("banks"); + + //$title = $langs->trans("BankAccounts"); + $title = $langs->trans("PaymentInformation"); + + if (!empty($conf->stripe->enabled)) + { //$langs->load("stripe"); //$title = $langs->trans("BankAccountsAndGateways"); @@ -188,137 +207,150 @@ if ($stripecu) $foundonexternalonlinesystem++; } - $sql = "SELECT COUNT(n.rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib as n"; - $sql .= " WHERE n.fk_soc = ".$object->id; - if (empty($conf->stripe->enabled)) { + $sql = "SELECT COUNT(n.rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib as n"; + $sql .= " WHERE n.fk_soc = ".$object->id; + if (empty($conf->stripe->enabled)) { $sql .= " AND n.stripe_card_ref IS NULL"; } else { $sql .= " AND (n.stripe_card_ref IS NULL OR (n.stripe_card_ref IS NOT NULL AND n.status = ".$servicestatus."))"; } - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) { - $obj = $db->fetch_object($resql); - $nbBankAccount = $obj->nb; - $i++; - } - } else { - dol_print_error($db); - } - - //if (! empty($conf->stripe->enabled) && $nbBankAccount > 0) $nbBankAccount = '...'; // No way to know exact number - - $head[$h][0] = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; - $head[$h][1] = $title; - if ($foundonexternalonlinesystem) $head[$h][1] .= '...'; - elseif ($nbBankAccount > 0) $head[$h][1] .= ''.$nbBankAccount.''; - $head[$h][2] = 'rib'; - $h++; - } - - if (!empty($conf->website->enabled) && (!empty($conf->global->WEBSITE_USE_WEBSITE_ACCOUNTS)) && (!empty($user->rights->societe->lire))) { - $head[$h][0] = DOL_URL_ROOT.'/societe/website.php?id='.$object->id; - $head[$h][1] = $langs->trans("WebSiteAccounts"); - $nbNote = 0; - $sql = "SELECT COUNT(n.rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe_account as n"; - $sql .= " WHERE fk_soc = ".$object->id.' AND fk_website > 0'; - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) { - $obj = $db->fetch_object($resql); - $nbNote = $obj->nb; - $i++; - } - } else { - dol_print_error($db); - } + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $nbBankAccount = $obj->nb; + $i++; + } + } + else { + dol_print_error($db); + } + + //if (! empty($conf->stripe->enabled) && $nbBankAccount > 0) $nbBankAccount = '...'; // No way to know exact number + + $head[$h][0] = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; + $head[$h][1] = $title; + if ($foundonexternalonlinesystem) $head[$h][1] .= '...'; + elseif ($nbBankAccount > 0) $head[$h][1] .= ''.$nbBankAccount.''; + $head[$h][2] = 'rib'; + $h++; + } + + if (!empty($conf->website->enabled) && (!empty($conf->global->WEBSITE_USE_WEBSITE_ACCOUNTS)) && (!empty($user->rights->societe->lire))) + { + $head[$h][0] = DOL_URL_ROOT.'/societe/website.php?id='.$object->id; + $head[$h][1] = $langs->trans("WebSiteAccounts"); + $nbNote = 0; + $sql = "SELECT COUNT(n.rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_account as n"; + $sql .= " WHERE fk_soc = ".$object->id.' AND fk_website > 0'; + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $nbNote = $obj->nb; + $i++; + } + } + else { + dol_print_error($db); + } + if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + $head[$h][2] = 'website'; + $h++; + } + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'thirdparty'); + + if ($user->socid == 0) + { + // Notifications + if (!empty($conf->notification->enabled)) + { + $nbNote = 0; + $sql = "SELECT COUNT(n.rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."notify_def as n"; + $sql .= " WHERE fk_soc = ".$object->id; + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $nbNote = $obj->nb; + $i++; + } + } + else { + dol_print_error($db); + } + + $head[$h][0] = DOL_URL_ROOT.'/societe/notify/card.php?socid='.$object->id; + $head[$h][1] = $langs->trans("Notifications"); + if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + $head[$h][2] = 'notify'; + $h++; + } + + // Notes + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; + if (!empty($object->note_public)) $nbNote++; + $head[$h][0] = DOL_URL_ROOT.'/societe/note.php?id='.$object->id; + $head[$h][1] = $langs->trans("Notes"); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; - $head[$h][2] = 'website'; - $h++; - } - - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'thirdparty'); - - if ($user->socid == 0) { - // Notifications - if (!empty($conf->notification->enabled)) { - $nbNote = 0; - $sql = "SELECT COUNT(n.rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."notify_def as n"; - $sql .= " WHERE fk_soc = ".$object->id; - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) { - $obj = $db->fetch_object($resql); - $nbNote = $obj->nb; - $i++; - } - } else { - dol_print_error($db); - } - - $head[$h][0] = DOL_URL_ROOT.'/societe/notify/card.php?socid='.$object->id; - $head[$h][1] = $langs->trans("Notifications"); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; - $head[$h][2] = 'notify'; - $h++; - } - - // Notes - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/societe/note.php?id='.$object->id; - $head[$h][1] = $langs->trans("Notes"); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; - $head[$h][2] = 'note'; - $h++; - - // Attached files - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id; - $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.'/societe/document.php?socid='.$object->id; - $head[$h][1] = $langs->trans("Documents"); + $head[$h][2] = 'note'; + $h++; + + // Attached files + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id; + $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.'/societe/document.php?socid='.$object->id; + $head[$h][1] = $langs->trans("Documents"); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; - $head[$h][2] = 'document'; - $h++; - } - - $head[$h][0] = DOL_URL_ROOT.'/societe/agenda.php?socid='.$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))) { - $head[$h][1] .= '/'; - $head[$h][1] .= $langs->trans("Agenda"); - } - $head[$h][2] = 'agenda'; - $h++; - - // Log - /*$head[$h][0] = DOL_URL_ROOT.'/societe/info.php?socid='.$object->id; + $head[$h][2] = 'document'; + $h++; + } + + $head[$h][0] = DOL_URL_ROOT.'/societe/agenda.php?socid='.$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))) + { + $head[$h][1] .= '/'; + $head[$h][1] .= $langs->trans("Agenda"); + } + $head[$h][2] = 'agenda'; + $h++; + + // Log + /*$head[$h][0] = DOL_URL_ROOT.'/societe/info.php?socid='.$object->id; $head[$h][1] = $langs->trans("Info"); $head[$h][2] = 'info'; $h++;*/ - complete_head_from_modules($conf, $langs, $object, $head, $h, 'thirdparty', 'remove'); - - return $head; + complete_head_from_modules($conf, $langs, $object, $head, $h, 'thirdparty', 'remove'); + + return $head; } @@ -330,21 +362,21 @@ */ function societe_prepare_head2($object) { - global $langs, $conf, $user; - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/societe/card.php?socid='.$object->id; - $head[$h][1] = $langs->trans("ThirdParty"); - $head[$h][2] = 'company'; - $h++; - - $head[$h][0] = 'commerciaux.php?socid='.$object->id; - $head[$h][1] = $langs->trans("SalesRepresentative"); - $head[$h][2] = 'salesrepresentative'; - $h++; - - return $head; + global $langs, $conf, $user; + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/societe/card.php?socid='.$object->id; + $head[$h][1] = $langs->trans("ThirdParty"); + $head[$h][2] = 'company'; + $h++; + + $head[$h][0] = 'commerciaux.php?socid='.$object->id; + $head[$h][1] = $langs->trans("SalesRepresentative"); + $head[$h][2] = 'salesrepresentative'; + $h++; + + return $head; } @@ -356,35 +388,35 @@ */ function societe_admin_prepare_head() { - global $langs, $conf, $user; - - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/societe/admin/societe.php'; - $head[$h][1] = $langs->trans("Miscellaneous"); - $head[$h][2] = 'general'; - $h++; - - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab - complete_head_from_modules($conf, $langs, null, $head, $h, 'company_admin'); - - $head[$h][0] = DOL_URL_ROOT.'/societe/admin/societe_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsThirdParties"); - $head[$h][2] = 'attributes'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/societe/admin/contact_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsContacts"); - $head[$h][2] = 'attributes_contacts'; - $h++; - - complete_head_from_modules($conf, $langs, null, $head, $h, 'company_admin', 'remove'); - - return $head; + global $langs, $conf, $user; + + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/societe/admin/societe.php'; + $head[$h][1] = $langs->trans("Miscellaneous"); + $head[$h][2] = 'general'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'company_admin'); + + $head[$h][0] = DOL_URL_ROOT.'/societe/admin/societe_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsThirdParties"); + $head[$h][2] = 'attributes'; + $h++; + + $head[$h][0] = DOL_URL_ROOT.'/societe/admin/contact_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsContacts"); + $head[$h][2] = 'attributes_contacts'; + $h++; + + complete_head_from_modules($conf, $langs, null, $head, $h, 'company_admin', 'remove'); + + return $head; } @@ -406,45 +438,52 @@ */ function getCountry($searchkey, $withcode = '', $dbtouse = 0, $outputlangs = '', $entconv = 1, $searchlabel = '') { - global $db, $langs; - - $result = ''; - - // Check parameters - if (empty($searchkey) && empty($searchlabel)) { - if ($withcode === 'all') return array('id'=>'', 'code'=>'', 'label'=>''); - else return ''; - } - if (!is_object($dbtouse)) $dbtouse = $db; - if (!is_object($outputlangs)) $outputlangs = $langs; - - $sql = "SELECT rowid, code, label FROM ".MAIN_DB_PREFIX."c_country"; - if (is_numeric($searchkey)) $sql .= " WHERE rowid=".$searchkey; - elseif (!empty($searchkey)) $sql .= " WHERE code='".$db->escape($searchkey)."'"; - else $sql .= " WHERE label='".$db->escape($searchlabel)."'"; - - $resql = $dbtouse->query($sql); - if ($resql) { - $obj = $dbtouse->fetch_object($resql); - if ($obj) { - $label = ((!empty($obj->label) && $obj->label != '-') ? $obj->label : ''); - if (is_object($outputlangs)) { - $outputlangs->load("dict"); - if ($entconv) $label = ($obj->code && ($outputlangs->trans("Country".$obj->code) != "Country".$obj->code)) ? $outputlangs->trans("Country".$obj->code) : $label; - else $label = ($obj->code && ($outputlangs->transnoentitiesnoconv("Country".$obj->code) != "Country".$obj->code)) ? $outputlangs->transnoentitiesnoconv("Country".$obj->code) : $label; - } - if ($withcode == 1) $result = $label ? "$obj->code - $label" : "$obj->code"; - elseif ($withcode == 2) $result = $obj->code; - elseif ($withcode == 3) $result = $obj->rowid; - elseif ($withcode === 'all') $result = array('id'=>$obj->rowid, 'code'=>$obj->code, 'label'=>$label); - else $result = $label; - } else { - $result = 'NotDefined'; - } - $dbtouse->free($resql); - return $result; - } else dol_print_error($dbtouse, ''); - return 'Error'; + global $db, $langs; + + $result = ''; + + // Check parameters + if (empty($searchkey) && empty($searchlabel)) + { + if ($withcode === 'all') return array('id'=>'', 'code'=>'', 'label'=>''); + else return ''; + } + if (!is_object($dbtouse)) $dbtouse = $db; + if (!is_object($outputlangs)) $outputlangs = $langs; + + $sql = "SELECT rowid, code, label FROM ".MAIN_DB_PREFIX."c_country"; + if (is_numeric($searchkey)) $sql .= " WHERE rowid=".$searchkey; + elseif (!empty($searchkey)) $sql .= " WHERE code='".$db->escape($searchkey)."'"; + else $sql .= " WHERE label='".$db->escape($searchlabel)."'"; + + $resql = $dbtouse->query($sql); + if ($resql) + { + $obj = $dbtouse->fetch_object($resql); + if ($obj) + { + $label = ((!empty($obj->label) && $obj->label != '-') ? $obj->label : ''); + if (is_object($outputlangs)) + { + $outputlangs->load("dict"); + if ($entconv) $label = ($obj->code && ($outputlangs->trans("Country".$obj->code) != "Country".$obj->code)) ? $outputlangs->trans("Country".$obj->code) : $label; + else $label = ($obj->code && ($outputlangs->transnoentitiesnoconv("Country".$obj->code) != "Country".$obj->code)) ? $outputlangs->transnoentitiesnoconv("Country".$obj->code) : $label; + } + if ($withcode == 1) $result = $label ? "$obj->code - $label" : "$obj->code"; + elseif ($withcode == 2) $result = $obj->code; + elseif ($withcode == 3) $result = $obj->rowid; + elseif ($withcode === 'all') $result = array('id'=>$obj->rowid, 'code'=>$obj->code, 'label'=>$label); + else $result = $label; + } + else + { + $result = 'NotDefined'; + } + $dbtouse->free($resql); + return $result; + } + else dol_print_error($dbtouse, ''); + return 'Error'; } /** @@ -464,57 +503,70 @@ */ function getState($id, $withcode = '', $dbtouse = 0, $withregion = 0, $outputlangs = '', $entconv = 1) { - global $db, $langs; - - if (!is_object($dbtouse)) $dbtouse = $db; - - $sql = "SELECT d.rowid as id, d.code_departement as code, d.nom as name, d.active, c.label as country, c.code as country_code, r.code_region as region_code, r.nom as region_name FROM"; - $sql .= " ".MAIN_DB_PREFIX."c_departements as d, ".MAIN_DB_PREFIX."c_regions as r,".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE d.fk_region=r.code_region and r.fk_pays=c.rowid and d.rowid=".$id; - $sql .= " AND d.active = 1 AND r.active = 1 AND c.active = 1"; - $sql .= " ORDER BY c.code, d.code_departement"; - - dol_syslog("Company.lib::getState", LOG_DEBUG); - $resql = $dbtouse->query($sql); - if ($resql) { - $obj = $dbtouse->fetch_object($resql); - if ($obj) { - $label = ((!empty($obj->name) && $obj->name != '-') ? $obj->name : ''); - if (is_object($outputlangs)) { - $outputlangs->load("dict"); - if ($entconv) $label = ($obj->code && ($outputlangs->trans("State".$obj->code) != "State".$obj->code)) ? $outputlangs->trans("State".$obj->code) : $label; - else $label = ($obj->code && ($outputlangs->transnoentitiesnoconv("State".$obj->code) != "State".$obj->code)) ? $outputlangs->transnoentitiesnoconv("State".$obj->code) : $label; - } - - if ($withcode == 1) { - if ($withregion == 1) { - return $label = $obj->region_name.' - '.$obj->code.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); - } else { - return $label = $obj->code.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); - } - } elseif ($withcode == 2) { - if ($withregion == 1) { - return $label = $obj->region_name.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); - } else { - return $label = ($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); - } - } elseif ($withcode === 'all') { - if ($withregion == 1) { - return array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$label, 'region_code'=>$obj->region_code, 'region'=>$obj->region_name); - } else { - return array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$label); - } - } else { - if ($withregion == 1) { - return $label = $obj->region_name.' - '.$label; - } else { - return $label; - } - } - } else { - return $langs->transnoentitiesnoconv("NotDefined"); - } - } else dol_print_error($dbtouse, ''); + global $db, $langs; + + if (!is_object($dbtouse)) $dbtouse = $db; + + $sql = "SELECT d.rowid as id, d.code_departement as code, d.nom as name, d.active, c.label as country, c.code as country_code, r.code_region as region_code, r.nom as region_name FROM"; + $sql .= " ".MAIN_DB_PREFIX."c_departements as d, ".MAIN_DB_PREFIX."c_regions as r,".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE d.fk_region=r.code_region and r.fk_pays=c.rowid and d.rowid=".$id; + $sql .= " AND d.active = 1 AND r.active = 1 AND c.active = 1"; + $sql .= " ORDER BY c.code, d.code_departement"; + + dol_syslog("Company.lib::getState", LOG_DEBUG); + $resql = $dbtouse->query($sql); + if ($resql) + { + $obj = $dbtouse->fetch_object($resql); + if ($obj) + { + $label = ((!empty($obj->name) && $obj->name != '-') ? $obj->name : ''); + if (is_object($outputlangs)) + { + $outputlangs->load("dict"); + if ($entconv) $label = ($obj->code && ($outputlangs->trans("State".$obj->code) != "State".$obj->code)) ? $outputlangs->trans("State".$obj->code) : $label; + else $label = ($obj->code && ($outputlangs->transnoentitiesnoconv("State".$obj->code) != "State".$obj->code)) ? $outputlangs->transnoentitiesnoconv("State".$obj->code) : $label; + } + + if ($withcode == 1) { + if ($withregion == 1) { + return $label = $obj->region_name.' - '.$obj->code.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); + } + else { + return $label = $obj->code.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); + } + } + elseif ($withcode == 2) { + if ($withregion == 1) { + return $label = $obj->region_name.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); + } + else { + return $label = ($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); + } + } + elseif ($withcode === 'all') { + if ($withregion == 1) { + return array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$label, 'region_code'=>$obj->region_code, 'region'=>$obj->region_name); + } + else { + return array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$label); + } + } + else { + if ($withregion == 1) { + return $label = $obj->region_name.' - '.$label; + } + else { + return $label; + } + } + } + else + { + return $langs->transnoentitiesnoconv("NotDefined"); + } + } + else dol_print_error($dbtouse, ''); } /** @@ -527,35 +579,40 @@ */ function currency_name($code_iso, $withcode = '', $outputlangs = null) { - global $langs, $db; - - if (empty($outputlangs)) $outputlangs = $langs; - - $outputlangs->load("dict"); - - // If there is a translation, we can send immediatly the label - if ($outputlangs->trans("Currency".$code_iso) != "Currency".$code_iso) { - return ($withcode ? $code_iso.' - ' : '').$outputlangs->trans("Currency".$code_iso); - } - - // If no translation, we read table to get label by default - $sql = "SELECT label FROM ".MAIN_DB_PREFIX."c_currencies"; - $sql .= " WHERE code_iso='".$db->escape($code_iso)."'"; - - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - - if ($num) { - $obj = $db->fetch_object($resql); - $label = ($obj->label != '-' ? $obj->label : ''); - if ($withcode) return ($label == $code_iso) ? "$code_iso" : "$code_iso - $label"; - else return $label; - } else { - return $code_iso; - } - } - return 'ErrorWhenReadingCurrencyLabel'; + global $langs, $db; + + if (empty($outputlangs)) $outputlangs = $langs; + + $outputlangs->load("dict"); + + // If there is a translation, we can send immediatly the label + if ($outputlangs->trans("Currency".$code_iso) != "Currency".$code_iso) + { + return ($withcode ? $code_iso.' - ' : '').$outputlangs->trans("Currency".$code_iso); + } + + // If no translation, we read table to get label by default + $sql = "SELECT label FROM ".MAIN_DB_PREFIX."c_currencies"; + $sql .= " WHERE code_iso='".$code_iso."'"; + + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + + if ($num) + { + $obj = $db->fetch_object($resql); + $label = ($obj->label != '-' ? $obj->label : ''); + if ($withcode) return ($label == $code_iso) ? "$code_iso" : "$code_iso - $label"; + else return $label; + } + else + { + return $code_iso; + } + } + return 'ErrorWhenReadingCurrencyLabel'; } /** @@ -566,26 +623,30 @@ */ function getFormeJuridiqueLabel($code) { - global $db, $langs; - - if (!$code) return ''; - - $sql = "SELECT libelle FROM ".MAIN_DB_PREFIX."c_forme_juridique"; - $sql .= " WHERE code='".$db->escape($code)."'"; - - dol_syslog("Company.lib::getFormeJuridiqueLabel", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - - if ($num) { - $obj = $db->fetch_object($resql); - $label = ($obj->libelle != '-' ? $obj->libelle : ''); - return $label; - } else { - return $langs->trans("NotDefined"); - } - } + global $db, $langs; + + if (!$code) return ''; + + $sql = "SELECT libelle FROM ".MAIN_DB_PREFIX."c_forme_juridique"; + $sql .= " WHERE code='$code'"; + + dol_syslog("Company.lib::getFormeJuridiqueLabel", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + + if ($num) + { + $obj = $db->fetch_object($resql); + $label = ($obj->libelle != '-' ? $obj->libelle : ''); + return $label; + } + else + { + return $langs->trans("NotDefined"); + } + } } @@ -637,7 +698,8 @@ //'CH', // Switzerland - No. Swizerland in not in EEC ); - if (!empty($conf->global->MAIN_COUNTRIES_IN_EEC)) { + if (!empty($conf->global->MAIN_COUNTRIES_IN_EEC)) + { // For example MAIN_COUNTRIES_IN_EEC = 'AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,NL,HU,IE,IM,IT,LT,LU,LV,MC,MT,PL,PT,RO,SE,SK,SI,UK' $country_code_in_EEC = explode(',', $conf->global->MAIN_COUNTRIES_IN_EEC); } @@ -657,8 +719,8 @@ $country_code_in_EEC = getCountriesInEEC(); - //print "dd".$this->country_code; - return in_array($object->country_code, $country_code_in_EEC); + //print "dd".$this->country_code; + return in_array($object->country_code, $country_code_in_EEC); } @@ -676,109 +738,120 @@ */ function show_projects($conf, $langs, $db, $object, $backtopage = '', $nocreatelink = 0, $morehtmlright = '') { - global $user; - - $i = -1; - - if (!empty($conf->projet->enabled) && $user->rights->projet->lire) { - $langs->load("projects"); - - $newcardbutton = ''; - if (!empty($conf->projet->enabled) && $user->rights->projet->creer && empty($nocreatelink)) { - $newcardbutton .= dolGetButtonTitle($langs->trans('AddProject'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/projet/card.php?socid='.$object->id.'&action=create&backtopage='.urlencode($backtopage)); - } - - print "\n"; - print load_fiche_titre($langs->trans("ProjectsDedicatedToThisThirdParty"), $newcardbutton.$morehtmlright, ''); - print '
'; - print "\n".''; - - $sql = "SELECT p.rowid as id, p.entity, p.title, p.ref, p.public, p.dateo as do, p.datee as de, p.fk_statut as status, p.fk_opp_status, p.opp_amount, p.opp_percent, p.tms as date_update, p.budget_amount"; - $sql .= ", cls.code as opp_status_code"; - $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_lead_status as cls on p.fk_opp_status = cls.rowid"; - $sql .= " WHERE p.fk_soc = ".$object->id; - $sql .= " AND p.entity IN (".getEntity('project').")"; - $sql .= " ORDER BY p.dateo DESC"; - - $result = $db->query($sql); - if ($result) { - $num = $db->num_rows($result); - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - if ($num > 0) { - require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - - $projecttmp = new Project($db); - - $i = 0; - - while ($i < $num) { - $obj = $db->fetch_object($result); - $projecttmp->fetch($obj->id); - - // To verify role of users - $userAccess = $projecttmp->restrictedProjectArea($user); - - if ($user->rights->projet->lire && $userAccess > 0) { - print ''; - - // Ref - print ''; - - // Label - print ''; - // Date start - print ''; - // Date end - print ''; - // Opp amount - print ''; - // Opp status - print ''; - // Opp percent - print ''; - // Status - print ''; - - print ''; - } - $i++; - } - } else { - print ''; - } - $db->free($result); - } else { - dol_print_error($db); - } - print "
'.$langs->trans("Ref").''.$langs->trans("Name").''.$langs->trans("DateStart").''.$langs->trans("DateEnd").''.$langs->trans("OpportunityAmountShort").''.$langs->trans("OpportunityStatusShort").''.$langs->trans("OpportunityProbabilityShort").''.$langs->trans("Status").'
'; - print $projecttmp->getNomUrl(1); - print ''.$obj->title.''.dol_print_date($db->jdate($obj->do), "day").''.dol_print_date($db->jdate($obj->de), "day").''; - if ($obj->opp_status_code) { - print price($obj->opp_amount, 1, '', 1, -1, -1, ''); - } - print ''; - if ($obj->opp_status_code) print $langs->trans("OppStatus".$obj->opp_status_code); - print ''; - if ($obj->opp_percent) print price($obj->opp_percent, 1, '', 1, 0).'%'; - print ''.$projecttmp->getLibStatut(5).'
'.$langs->trans("None").'
"; - print '
'; - - print "
\n"; - } - - return $i; + global $user; + + $i = -1; + + if (!empty($conf->projet->enabled) && $user->rights->projet->lire) + { + $langs->load("projects"); + + $newcardbutton = ''; + if (!empty($conf->projet->enabled) && $user->rights->projet->creer && empty($nocreatelink)) + { + $newcardbutton .= dolGetButtonTitle($langs->trans('AddProject'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/projet/card.php?socid='.$object->id.'&action=create&backtopage='.urlencode($backtopage)); + } + + print "\n"; + print load_fiche_titre($langs->trans("ProjectsDedicatedToThisThirdParty"), $newcardbutton.$morehtmlright, ''); + print '
'; + print "\n".''; + + $sql = "SELECT p.rowid as id, p.entity, p.title, p.ref, p.public, p.dateo as do, p.datee as de, p.fk_statut as status, p.fk_opp_status, p.opp_amount, p.opp_percent, p.tms as date_update, p.budget_amount"; + $sql .= ", cls.code as opp_status_code"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_lead_status as cls on p.fk_opp_status = cls.rowid"; + $sql .= " WHERE p.fk_soc = ".$object->id; + $sql .= " AND p.entity IN (".getEntity('project').")"; + $sql .= " ORDER BY p.dateo DESC"; + + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + if ($num > 0) + { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + + $projecttmp = new Project($db); + + $i = 0; + + while ($i < $num) + { + $obj = $db->fetch_object($result); + $projecttmp->fetch($obj->id); + + // To verify role of users + $userAccess = $projecttmp->restrictedProjectArea($user); + + if ($user->rights->projet->lire && $userAccess > 0) + { + print ''; + + // Ref + print ''; + + // Label + print ''; + // Date start + print ''; + // Date end + print ''; + // Opp amount + print ''; + // Opp status + print ''; + // Opp percent + print ''; + // Status + print ''; + + print ''; + } + $i++; + } + } + else + { + print ''; + } + $db->free($result); + } + else + { + dol_print_error($db); + } + print "
'.$langs->trans("Ref").''.$langs->trans("Name").''.$langs->trans("DateStart").''.$langs->trans("DateEnd").''.$langs->trans("OpportunityAmountShort").''.$langs->trans("OpportunityStatusShort").''.$langs->trans("OpportunityProbabilityShort").''.$langs->trans("Status").'
'; + print $projecttmp->getNomUrl(1); + print ''.$obj->title.''.dol_print_date($db->jdate($obj->do), "day").''.dol_print_date($db->jdate($obj->de), "day").''; + if ($obj->opp_status_code) + { + print price($obj->opp_amount, 1, '', 1, -1, -1, ''); + } + print ''; + if ($obj->opp_status_code) print $langs->trans("OppStatus".$obj->opp_status_code); + print ''; + if ($obj->opp_percent) print price($obj->opp_percent, 1, '', 1, 0).'%'; + print ''.$projecttmp->getLibStatut(5).'
'.$langs->trans("None").'
"; + print '
'; + + print "
\n"; + } + + return $i; } @@ -799,364 +872,388 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; $formcompany = new FormCompany($db); - $form = new Form($db); - - $optioncss = GETPOST('optioncss', 'alpha'); - $sortfield = GETPOST("sortfield", 'alpha'); - $sortorder = GETPOST("sortorder", 'alpha'); - $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); - - $search_status = GETPOST("search_status", 'int'); - if ($search_status == '') $search_status = 1; // always display active customer first - - $search_name = GETPOST("search_name", 'alpha'); - $search_address = GETPOST("search_address", 'alpha'); - $search_poste = GETPOST("search_poste", 'alpha'); + $form = new Form($db); + + $optioncss = GETPOST('optioncss', 'alpha'); + $sortfield = GETPOST("sortfield", 'alpha'); + $sortorder = GETPOST("sortorder", 'alpha'); + $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); + + $search_status = GETPOST("search_status", 'int'); + if ($search_status == '') $search_status = 1; // always display active customer first + + $search_name = GETPOST("search_name", 'alpha'); + $search_address = GETPOST("search_address", 'alpha'); + $search_poste = GETPOST("search_poste", 'alpha'); $search_roles = GETPOST("search_roles", 'array'); - $socialnetworks = getArrayOfSocialNetworks(); - - $searchAddressPhoneDBFields = array( - //Address - 't.address', - 't.zip', - 't.town', - - //Phone - 't.phone', - 't.phone_perso', - 't.phone_mobile', - - //Fax - 't.fax', - - //E-mail - 't.email', - ); - //Social media - foreach ($socialnetworks as $key => $value) { - if ($value['active']) { - $searchAddressPhoneDBFields['t.'.$key] = "t.socialnetworks->'$.".$key."'"; - } - } - - if (!$sortorder) $sortorder = "ASC"; - if (!$sortfield) $sortfield = "t.lastname"; - - if (!empty($conf->clicktodial->enabled)) { - $user->fetch_clicktodial(); // lecture des infos de clicktodial du user - } - - - $contactstatic = new Contact($db); - - $extrafields->fetch_name_optionals_label($contactstatic->table_element); - - $contactstatic->fields = array( - 'name' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1), - 'poste' =>array('type'=>'varchar(128)', 'label'=>'PostOrFunction', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>20), - 'address' =>array('type'=>'varchar(128)', 'label'=>'Address', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>30), - 'role' =>array('type'=>'checkbox', 'label'=>'Role', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>40), - 'statut' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>50, 'arrayofkeyval'=>array(0=>$contactstatic->LibStatut(0, 1), 1=>$contactstatic->LibStatut(1, 1))), - ); - - // Definition of fields for list - $arrayfields = array( - 't.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID ? 1 : 0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID ? 1 : 0), 'position'=>1), - 't.name'=>array('label'=>"Name", 'checked'=>1, 'position'=>10), - 't.poste'=>array('label'=>"PostOrFunction", 'checked'=>1, 'position'=>20), - 't.address'=>array('label'=>(empty($conf->dol_optimize_smallscreen) ? $langs->trans("Address").' / '.$langs->trans("Phone").' / '.$langs->trans("Email") : $langs->trans("Address")), 'checked'=>1, 'position'=>30), - 'sc.role'=>array('label'=>"ContactByDefaultFor", 'checked'=>1, 'position'=>40), - 't.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>50, 'class'=>'center'), - ); - // Extra fields - if (is_array($extrafields->attributes[$contactstatic->table_element]['label']) && count($extrafields->attributes[$contactstatic->table_element]['label'])) { - foreach ($extrafields->attributes[$contactstatic->table_element]['label'] as $key => $val) { - if (!empty($extrafields->attributes[$contactstatic->table_element]['list'][$key])) { + $socialnetworks = getArrayOfSocialNetworks(); + + $searchAddressPhoneDBFields = array( + //Address + 't.address', + 't.zip', + 't.town', + + //Phone + 't.phone', + 't.phone_perso', + 't.phone_mobile', + + //Fax + 't.fax', + + //E-mail + 't.email', + ); + //Social media + foreach ($socialnetworks as $key => $value) { + if ($value['active']) { + $searchAddressPhoneDBFields['t.'.$key] = "t.socialnetworks->'$.".$key."'"; + } + } + + if (!$sortorder) $sortorder = "ASC"; + if (!$sortfield) $sortfield = "t.lastname"; + + if (!empty($conf->clicktodial->enabled)) + { + $user->fetch_clicktodial(); // lecture des infos de clicktodial du user + } + + + $contactstatic = new Contact($db); + + $extrafields->fetch_name_optionals_label($contactstatic->table_element); + + $contactstatic->fields = array( + 'name' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1), + 'poste' =>array('type'=>'varchar(128)', 'label'=>'PostOrFunction', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>20), + 'address' =>array('type'=>'varchar(128)', 'label'=>'Address', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>30), + 'role' =>array('type'=>'checkbox', 'label'=>'Role', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>40), + 'statut' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>50, 'arrayofkeyval'=>array(0=>$contactstatic->LibStatut(0, 1), 1=>$contactstatic->LibStatut(1, 1))), + ); + + // Definition of fields for list + $arrayfields = array( + 't.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID ? 1 : 0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID ? 1 : 0), 'position'=>1), + 't.name'=>array('label'=>"Name", 'checked'=>1, 'position'=>10), + 't.poste'=>array('label'=>"PostOrFunction", 'checked'=>1, 'position'=>20), + 't.address'=>array('label'=>(empty($conf->dol_optimize_smallscreen) ? $langs->trans("Address").' / '.$langs->trans("Phone").' / '.$langs->trans("Email") : $langs->trans("Address")), 'checked'=>1, 'position'=>30), + 'sc.role'=>array('label'=>"ContactByDefaultFor", 'checked'=>1, 'position'=>40), + 't.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>50, 'class'=>'center'), + ); + // Extra fields + if (is_array($extrafields->attributes[$contactstatic->table_element]['label']) && count($extrafields->attributes[$contactstatic->table_element]['label'])) + { + foreach ($extrafields->attributes[$contactstatic->table_element]['label'] as $key => $val) + { + if (!empty($extrafields->attributes[$contactstatic->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$contactstatic->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$contactstatic->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>1000 + $extrafields->attributes[$contactstatic->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$contactstatic->table_element]['list'][$key]) != 3 && $extrafields->attributes[$contactstatic->table_element]['perms'][$key])); } - } - } - - // Initialize array of search criterias - $search = array(); - foreach ($arrayfields as $key => $val) { - $queryName = 'search_'.substr($key, 2); - if (GETPOST($queryName, 'alpha')) { - $search[substr($key, 2)] = GETPOST($queryName, 'alpha'); - } - } - $search_array_options = $extrafields->getOptionalsFromPost($contactstatic->table_element, '', 'search_'); - - // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers - $search_status = ''; - $search_name = ''; - $search_roles = array(); - $search_address = ''; - $search_poste = ''; - $search = array(); - $search_array_options = array(); - - foreach ($contactstatic->fields as $key => $val) { + } + } + + // Initialize array of search criterias + $search = array(); + foreach ($arrayfields as $key => $val) + { + $queryName = 'search_'.substr($key, 2); + if (GETPOST($queryName, 'alpha')) { + $search[substr($key, 2)] = GETPOST($queryName, 'alpha'); + } + } + $search_array_options = $extrafields->getOptionalsFromPost($contactstatic->table_element, '', 'search_'); + + // Purge search criteria + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers + { + $search_status = ''; + $search_name = ''; + $search_roles = array(); + $search_address = ''; + $search_poste = ''; + $search = array(); + $search_array_options = array(); + + foreach ($contactstatic->fields as $key => $val) + { $search[$key] = ''; } - } - - $contactstatic->fields = dol_sort_array($contactstatic->fields, 'position'); - $arrayfields = dol_sort_array($arrayfields, 'position'); - - $newcardbutton = ''; - if ($user->rights->societe->contact->creer) { - $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); - $newcardbutton .= dolGetButtonTitle($addcontact, '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contact/card.php?socid='.$object->id.'&action=create&backtopage='.urlencode($backtopage)); - } - - print "\n"; - - $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ContactsForCompany") : $langs->trans("ContactsAddressesForCompany")); - print load_fiche_titre($title, $newcardbutton, ''); - - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - //if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + } + + $contactstatic->fields = dol_sort_array($contactstatic->fields, 'position'); + $arrayfields = dol_sort_array($arrayfields, 'position'); + + $newcardbutton = ''; + if ($user->rights->societe->contact->creer) + { + $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); + $newcardbutton .= dolGetButtonTitle($addcontact, '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contact/card.php?socid='.$object->id.'&action=create&backtopage='.urlencode($backtopage)); + } + + print "\n"; + + $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ContactsForCompany") : $langs->trans("ContactsAddressesForCompany")); + print load_fiche_titre($title, $newcardbutton, ''); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + //if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print "\n".''."\n"; - - $param = "socid=".urlencode($object->id); - if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if (count($search_roles) > 0) $param .= implode('&search_roles[]=', $search_roles); - if ($search_name != '') $param .= '&search_name='.urlencode($search_name); - if ($search_poste != '') $param .= '&search_poste='.urlencode($search_poste); - if ($search_address != '') $param .= '&search_address='.urlencode($search_address); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - - // Add $param from extra fields - $extrafieldsobjectkey = $contactstatic->table_element; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - - $sql = "SELECT t.rowid, t.lastname, t.firstname, t.fk_pays as country_id, t.civility, t.poste, t.phone as phone_pro, t.phone_mobile, t.phone_perso, t.fax, t.email, t.socialnetworks, t.statut, t.photo,"; - $sql .= " t.civility as civility_id, t.address, t.zip, t.town"; - $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as ef on (t.rowid = ef.fk_object)"; - $sql .= " WHERE t.fk_soc = ".$object->id; - if ($search_status != '' && $search_status != '-1') $sql .= " AND t.statut = ".$db->escape($search_status); - if ($search_name) $sql .= natural_search(array('t.lastname', 't.firstname'), $search_name); - if ($search_poste) $sql .= natural_search('t.poste', $search_poste); - if ($search_address) { + print "\n".'
'."\n"; + + $param = "socid=".urlencode($object->id); + if ($search_status != '') $param .= '&search_status='.urlencode($search_status); + if (count($search_roles) > 0) $param .= implode('&search_roles[]=', $search_roles); + if ($search_name != '') $param .= '&search_name='.urlencode($search_name); + if ($search_poste != '') $param .= '&search_poste='.urlencode($search_poste); + if ($search_address != '') $param .= '&search_address='.urlencode($search_address); + if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + + // Add $param from extra fields + $extrafieldsobjectkey = $contactstatic->table_element; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + + $sql = "SELECT t.rowid, t.lastname, t.firstname, t.fk_pays as country_id, t.civility, t.poste, t.phone as phone_pro, t.phone_mobile, t.phone_perso, t.fax, t.email, t.socialnetworks, t.statut, t.photo,"; + $sql .= " t.civility as civility_id, t.address, t.zip, t.town"; + $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as ef on (t.rowid = ef.fk_object)"; + $sql .= " WHERE t.fk_soc = ".$object->id; + if ($search_status != '' && $search_status != '-1') $sql .= " AND t.statut = ".$db->escape($search_status); + if ($search_name) $sql .= natural_search(array('t.lastname', 't.firstname'), $search_name); + if ($search_poste) $sql .= natural_search('t.poste', $search_poste); + if ($search_address) { $sql .= natural_search($searchAddressPhoneDBFields, $search_address); } if (count($search_roles) > 0) { $sql .= " AND t.rowid IN (SELECT sc.fk_socpeople FROM ".MAIN_DB_PREFIX."societe_contacts as sc WHERE sc.fk_c_type_contact IN (".implode(',', $search_roles)."))"; } - // Add where from extra fields - $extrafieldsobjectkey = $contactstatic->table_element; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; - if ($sortfield == "t.name") $sql .= " ORDER BY t.lastname $sortorder, t.firstname $sortorder"; - else $sql .= " ORDER BY $sortfield $sortorder"; - - dol_syslog('core/lib/company.lib.php :: show_contacts', LOG_DEBUG); - $result = $db->query($sql); - if (!$result) dol_print_error($db); - - $num = $db->num_rows($result); - - // Fields title search - // -------------------------------------------------------------------- - print ''; - foreach ($contactstatic->fields as $key => $val) { - $align = ''; - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $align .= ($align ? ' ' : '').'center'; - if (in_array($val['type'], array('timestamp'))) $align .= ($align ? ' ' : '').'nowrap'; - if ($key == 'status' || $key == 'statut') $align .= ($align ? ' ' : '').'center'; - if (!empty($arrayfields['t.'.$key]['checked']) || !empty($arrayfields['sc.'.$key]['checked'])) { - print ''; - } - } - // Extra fields - $extrafieldsobjectkey = $contactstatic->table_element; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; - - // Fields from hook - $parameters = array('arrayfields'=>$arrayfields); - $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $contactstatic); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Action column - print ''; - print ''."\n"; - - - // Fields title label - // -------------------------------------------------------------------- - print ''; - foreach ($contactstatic->fields as $key => $val) { - $align = ''; - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $align .= ($align ? ' ' : '').'center'; - if (in_array($val['type'], array('timestamp'))) $align .= ($align ? ' ' : '').'nowrap'; - if ($key == 'status' || $key == 'statut') $align .= ($align ? ' ' : '').'center'; - if (!empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($val['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align ? 'class="'.$align.'"' : ''), $sortfield, $sortorder, $align.' ')."\n"; - if ($key == 'role') $align .= ($align ? ' ' : '').'left'; - if (!empty($arrayfields['sc.'.$key]['checked'])) { - print getTitleFieldOfList($arrayfields['sc.'.$key]['label'], 0, $_SERVER['PHP_SELF'], '', '', $param, ($align ? 'class="'.$align.'"' : ''), $sortfield, $sortorder, $align.' ')."\n"; - } - } - // Extra fields - $extrafieldsobjectkey = $contactstatic->table_element; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; - // Hook fields + // Add where from extra fields + $extrafieldsobjectkey = $contactstatic->table_element; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; + if ($sortfield == "t.name") $sql .= " ORDER BY t.lastname $sortorder, t.firstname $sortorder"; + else $sql .= " ORDER BY $sortfield $sortorder"; + + dol_syslog('core/lib/company.lib.php :: show_contacts', LOG_DEBUG); + $result = $db->query($sql); + if (!$result) dol_print_error($db); + + $num = $db->num_rows($result); + + // Fields title search + // -------------------------------------------------------------------- + print ''; + foreach ($contactstatic->fields as $key => $val) + { + $align = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $align .= ($align ? ' ' : '').'center'; + if (in_array($val['type'], array('timestamp'))) $align .= ($align ? ' ' : '').'nowrap'; + if ($key == 'status' || $key == 'statut') $align .= ($align ? ' ' : '').'center'; + if (!empty($arrayfields['t.'.$key]['checked']) || !empty($arrayfields['sc.'.$key]['checked'])) + { + print ''; + } + } + // Extra fields + $extrafieldsobjectkey = $contactstatic->table_element; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + + // Fields from hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $contactstatic); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Action column + print ''; + print ''."\n"; + + + // Fields title label + // -------------------------------------------------------------------- + print ''; + foreach ($contactstatic->fields as $key => $val) + { + $align = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $align .= ($align ? ' ' : '').'center'; + if (in_array($val['type'], array('timestamp'))) $align .= ($align ? ' ' : '').'nowrap'; + if ($key == 'status' || $key == 'statut') $align .= ($align ? ' ' : '').'center'; + if (!empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($val['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align ? 'class="'.$align.'"' : ''), $sortfield, $sortorder, $align.' ')."\n"; + if ($key == 'role') $align .= ($align ? ' ' : '').'left'; + if (!empty($arrayfields['sc.'.$key]['checked'])) { + print getTitleFieldOfList($arrayfields['sc.'.$key]['label'], 0, $_SERVER['PHP_SELF'], '', '', $param, ($align ? 'class="'.$align.'"' : ''), $sortfield, $sortorder, $align.' ')."\n"; + } + } + // Extra fields + $extrafieldsobjectkey = $contactstatic->table_element; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; + // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); - $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ')."\n"; - print ''."\n"; - - $i = -1; - - if ($num || (GETPOST('button_search') || GETPOST('button_search.x') || GETPOST('button_search_x'))) { - $i = 0; - - while ($i < $num) { - $obj = $db->fetch_object($result); - - $contactstatic->id = $obj->rowid; - $contactstatic->ref = $obj->ref; - $contactstatic->statut = $obj->statut; - $contactstatic->lastname = $obj->lastname; - $contactstatic->firstname = $obj->firstname; - $contactstatic->civility_id = $obj->civility_id; - $contactstatic->civility_code = $obj->civility_id; - $contactstatic->poste = $obj->poste; - $contactstatic->address = $obj->address; - $contactstatic->zip = $obj->zip; - $contactstatic->town = $obj->town; - $contactstatic->phone_pro = $obj->phone_pro; - $contactstatic->phone_mobile = $obj->phone_mobile; - $contactstatic->phone_perso = $obj->phone_perso; - $contactstatic->email = $obj->email; - $contactstatic->web = $obj->web; - $contactstatic->socialnetworks = $obj->socialnetworks; - $contactstatic->photo = $obj->photo; - - $country_code = getCountry($obj->country_id, 2); - $contactstatic->country_code = $country_code; - - $contactstatic->setGenderFromCivility(); - $contactstatic->fetch_optionals(); - - $resultRole = $contactstatic->fetchRoles(); - if ($resultRole < 0) { - setEventMessages(null, $contactstatic->errors, 'errors'); - } - - if (is_array($contactstatic->array_options)) { - foreach ($contactstatic->array_options as $key => $val) { - $obj->$key = $val; - } - } - - print ''; - - // ID - if (!empty($arrayfields['t.rowid']['checked'])) { - print ''; - } + $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ')."\n"; + print ''."\n"; + + $i = -1; + + if ($num || (GETPOST('button_search') || GETPOST('button_search.x') || GETPOST('button_search_x'))) + { + $i = 0; + + while ($i < $num) + { + $obj = $db->fetch_object($result); + + $contactstatic->id = $obj->rowid; + $contactstatic->ref = $obj->ref; + $contactstatic->statut = $obj->statut; + $contactstatic->lastname = $obj->lastname; + $contactstatic->firstname = $obj->firstname; + $contactstatic->civility_id = $obj->civility_id; + $contactstatic->civility_code = $obj->civility_id; + $contactstatic->poste = $obj->poste; + $contactstatic->address = $obj->address; + $contactstatic->zip = $obj->zip; + $contactstatic->town = $obj->town; + $contactstatic->phone_pro = $obj->phone_pro; + $contactstatic->phone_mobile = $obj->phone_mobile; + $contactstatic->phone_perso = $obj->phone_perso; + $contactstatic->email = $obj->email; + $contactstatic->web = $obj->web; + $contactstatic->socialnetworks = $obj->socialnetworks; + $contactstatic->photo = $obj->photo; + + $country_code = getCountry($obj->country_id, 2); + $contactstatic->country_code = $country_code; + + $contactstatic->setGenderFromCivility(); + $contactstatic->fetch_optionals(); + + $resultRole = $contactstatic->fetchRoles(); + if ($resultRole < 0) { + setEventMessages(null, $contactstatic->errors, 'errors'); + } + + if (is_array($contactstatic->array_options)) + { + foreach ($contactstatic->array_options as $key => $val) + { + $obj->$key = $val; + } + } + + print ''; + + // ID + if (!empty($arrayfields['t.rowid']['checked'])) + { + print ''; + } // Photo - Name - if (!empty($arrayfields['t.name']['checked'])) { - print ''; - } + } // Job position - if (!empty($arrayfields['t.poste']['checked'])) { - print ''; - } - - // Address - Phone - Email - if (!empty($arrayfields['t.address']['checked'])) { - print ''; - } - - // Role - if (!empty($arrayfields['sc.role']['checked'])) { - print ''; - } - - // Status - if (!empty($arrayfields['t.statut']['checked'])) { - print ''; - } - - // Extra fields - $extrafieldsobjectkey = $contactstatic->table_element; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - - // Actions + if (!empty($arrayfields['t.poste']['checked'])) + { + print ''; + } + + // Address - Phone - Email + if (!empty($arrayfields['t.address']['checked'])) + { + print ''; + } + + // Role + if (!empty($arrayfields['sc.role']['checked'])) + { + print ''; + } + + // Status + if (!empty($arrayfields['t.statut']['checked'])) + { + print ''; + } + + // Extra fields + $extrafieldsobjectkey = $contactstatic->table_element; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + + // Actions print ''; - - print "\n"; - $i++; - } - } else { + if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) + { + print ''; + print img_object($langs->trans("Event"), "action"); + print '   '; + } + + // Edit + if ($user->rights->societe->contact->creer) + { + print ''; + print img_edit(); + print ''; + } + + print ''; + + print "\n"; + $i++; + } + } + else + { $colspan = 1; foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; - } - print "\n
'; - if (in_array($key, array('statut'))) { - print $form->selectarray('search_status', array('-1'=>'', '0'=>$contactstatic->LibStatut(0, 1), '1'=>$contactstatic->LibStatut(1, 1)), $search_status); - } elseif (in_array($key, array('role'))) { - print $formcompany->showRoles("search_roles", $contactstatic, 'edit', $search_roles); - } else { - print ''; - } - print ''; - print $form->showFilterButtons(); - print '
'; + if (in_array($key, array('statut'))) { + print $form->selectarray('search_status', array('-1'=>'', '0'=>$contactstatic->LibStatut(0, 1), '1'=>$contactstatic->LibStatut(1, 1)), $search_status); + } elseif (in_array($key, array('role'))) { + print $formcompany->showRoles("search_roles", $contactstatic, 'edit', $search_roles); + } else { + print ''; + } + print ''; + print $form->showFilterButtons(); + print '
'; - print $contactstatic->id; - print '
'; + print $contactstatic->id; + print ''; - print $form->showphoto('contact', $contactstatic, 0, 0, 0, 'photorefnoborder valignmiddle marginrightonly', 'small', 1, 0, 1); + if (!empty($arrayfields['t.name']['checked'])) + { + print ''; + print $form->showphoto('contact', $contactstatic, 0, 0, 0, 'photorefnoborder valignmiddle marginrightonly', 'small', 1, 0, 1); print $contactstatic->getNomUrl(0, '', 0, '&backtopage='.urlencode($backtopage)); print ''; - if ($obj->poste) print $obj->poste; - print ''; - print $contactstatic->getBannerAddress('contact', $object); - print ''; - print $formcompany->showRoles("roles", $contactstatic, 'view'); - print ''.$contactstatic->getLibStatut(5).''; + if ($obj->poste) print $obj->poste; + print ''; + print $contactstatic->getBannerAddress('contact', $object); + print ''; + print $formcompany->showRoles("roles", $contactstatic, 'view'); + print ''.$contactstatic->getLibStatut(5).''; // Add to agenda - if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) { - print ''; - print img_object($langs->trans("Event"), "action"); - print '   '; - } - - // Edit - if ($user->rights->societe->contact->creer) { - print ''; - print img_edit(); - print ''; - } - - print '
'.$langs->trans("None").'
\n"; + } + print "\n\n"; print '
'; - print '
'."\n"; - - return $i; + print ''."\n"; + + return $i; } @@ -1174,12 +1271,12 @@ */ function show_actions_todo($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '') { - global $user, $conf; - - $out = show_actions_done($conf, $langs, $db, $filterobj, $objcon, 1, $actioncode, 'todo'); - - if ($noprint) return $out; - else print $out; + global $user, $conf; + + $out = show_actions_done($conf, $langs, $db, $filterobj, $objcon, 1, $actioncode, 'todo'); + + if ($noprint) return $out; + else print $out; } /** @@ -1189,7 +1286,7 @@ * @param Conf $conf Object conf * @param Translate $langs Object langs * @param DoliDB $db Object db - * @param mixed $filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket... to list events linked to an object + * @param mixed $filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket|... to list events linked to an object * @param Contact $objcon Filter on object contact to filter events on a contact * @param int $noprint Return string but does not output it * @param string $actioncode Filter on actioncode @@ -1197,326 +1294,343 @@ * @param array $filters Filter on other fields * @param string $sortfield Sort field * @param string $sortorder Sort order - * @param string $module You can add module name here if elementtype in table llx_actioncomm is objectkey@module * @return string|void Return html part or void if noprint is 1 */ -function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC', $module = '') +function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC') { - global $user, $conf; - global $form; - - global $param, $massactionbutton; - $start_year = GETPOST('dateevent_startyear', 'int'); - $start_month = GETPOST('dateevent_startmonth', 'int'); - $start_day = GETPOST('dateevent_startday', 'int'); - $end_year = GETPOST('dateevent_endyear', 'int'); - $end_month = GETPOST('dateevent_endmonth', 'int'); - $end_day = GETPOST('dateevent_endday', 'int'); - $tms_start = ''; - $tms_end = ''; - - if (!empty($start_year) && !empty($start_month) && !empty($start_day)) { - $tms_start = dol_mktime(0, 0, 0, $start_month, $start_day, $start_year, 'tzuserrel'); - } - if (!empty($end_year) && !empty($end_month) && !empty($end_day)) { - $tms_end = dol_mktime(23, 59, 59, $end_month, $end_day, $end_year, 'tzuserrel'); - } - 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 - $tms_start = ''; - $tms_end = ''; - } - dol_include_once('/comm/action/class/actioncomm.class.php'); - - // Check parameters - if (!is_object($filterobj) && !is_object($objcon)) dol_print_error('', 'BadParameter'); - - $out = ''; - $histo = array(); - $numaction = 0; - $now = dol_now('tzuser'); - - // Open DSI -- Fix order by -- Begin - $sortfield_list = explode(',', $sortfield); - $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent'); - $sortfield_new_list = array(); - foreach ($sortfield_list as $sortfield_value) { - $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)]; - } - $sortfield_new = implode(',', $sortfield_new_list); - - $sql = ''; - - if (!empty($conf->agenda->enabled)) { - // Recherche histo sur actioncomm - if (is_object($objcon) && $objcon->id > 0) { - $sql = "SELECT DISTINCT a.id, a.label as label,"; - } else { - $sql = "SELECT a.id, a.label as label,"; - } - $sql .= " a.datep as dp,"; - $sql .= " a.datep2 as dp2,"; - $sql .= " a.percent as percent, 'action' as type,"; - $sql .= " a.fk_element, a.elementtype,"; - $sql .= " a.fk_contact,"; - $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,"; - $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; - if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur'))) $sql .= ", sp.lastname, sp.firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { /* Nothing */ } elseif (is_object($filterobj) && get_class($filterobj) == 'Project') { /* Nothing */ } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", m.lastname, m.firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", o.ref"; - elseif (is_object($filterobj) && is_array($filterobj->fields) && is_array($filterobj->fields['rowid']) && is_array($filterobj->fields['ref']) && $filterobj->table_element && $filterobj->element) $sql .= ", o.ref"; - - $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id"; - - $force_filter_contact = false; - if (is_object($objcon) && $objcon->id > 0) { - $force_filter_contact = true; - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm"; - $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".$objcon->id; - } - - if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur'))) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er"; - $sql .= " ON er.resource_type = 'dolresource'"; - $sql .= " AND er.element_id = a.id"; - $sql .= " AND er.resource_id = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Project') { /* Nothing */ } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", ".MAIN_DB_PREFIX."adherent as m"; - elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", ".MAIN_DB_PREFIX."product as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", ".MAIN_DB_PREFIX."ticket as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", ".MAIN_DB_PREFIX."contrat as o"; - elseif (is_object($filterobj) && is_array($filterobj->fields) && is_array($filterobj->fields['rowid']) && is_array($filterobj->fields['ref']) && $filterobj->table_element && $filterobj->element) $sql .= ", ".MAIN_DB_PREFIX.$filterobj->table_element." as o"; - - $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; - if ($force_filter_contact === false) { - if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) $sql .= " AND a.fk_soc = ".$filterobj->id; - elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { /* Nothing */ } - elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) $sql .= " AND a.fk_project = ".$filterobj->id; - elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { - $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') { - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') { - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && is_array($filterobj->fields) && is_array($filterobj->fields['rowid']) && is_array($filterobj->fields['ref']) && $filterobj->table_element && $filterobj->element) { - // Generic case - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = '".$db->escape($filterobj->element).($module ? '@'.$module : '')."'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } - } - - if (!empty($tms_start) && !empty($tms_end)) { - $sql .= " AND ((a.datep BETWEEN '".$db->idate($tms_start)."' AND '".$db->idate($tms_end)."') OR (a.datep2 BETWEEN '".$db->idate($tms_start)."' AND '".$db->idate($tms_end)."'))"; - } - elseif (empty($tms_start) && !empty($tms_end)) { - $sql .= " AND ((a.datep <= '".$db->idate($tms_end)."') OR (a.datep2 <= '".$db->idate($tms_end)."'))"; - } - elseif (!empty($tms_start) && empty($tms_end)) { - $sql .= " AND ((a.datep >= '".$db->idate($tms_start)."') OR (a.datep2 >= '".$db->idate($tms_start)."'))"; - } - - if (is_array($actioncode) && !empty($actioncode)) { - $sql .= ' AND ('; - foreach ($actioncode as $key => $code) { - if ($key != 0) $sql .= "OR ("; - if (!empty($code)) addEventTypeSQL($sql, $code, $donetodo, $now, $filters, ""); - if ($key != 0) $sql .= ")"; - } - $sql .= ')'; - } - elseif (!empty($actioncode)) addEventTypeSQL($sql, $actioncode, $donetodo, $now, $filters); - - if (is_array($actioncode)) { - foreach ($actioncode as $code) { - $sql2 = addMailingEventTypeSQL($code, $objcon, $filterobj); - if (!empty($sql2)) { - if (!empty($sql)) $sql = $sql." UNION ".$sql2; - elseif (empty($sql)) $sql = $sql2; - break; - } - } - } - else { - $sql2 = addMailingEventTypeSQL($actioncode, $objcon, $filterobj); - if (!empty($sql) && !empty($sql2)) { - $sql = $sql." UNION ".$sql2; - } - elseif (empty($sql) && !empty($sql2)) { - $sql = $sql2; - } - } - } - - //TODO Add limit in nb of results - if ($sql) { - $sql .= $db->order($sortfield_new, $sortorder); - dol_syslog("company.lib::show_actions_done", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) { - $i = 0; - $num = $db->num_rows($resql); - - while ($i < $num) { - $obj = $db->fetch_object($resql); - - if ($obj->type == 'action') { - $contactaction = new ActionComm($db); - $contactaction->id = $obj->id; - $result = $contactaction->fetchResources(); - if ($result < 0) { - dol_print_error($db); - setEventMessage("company.lib::show_actions_done Error fetch ressource", 'errors'); - } - - //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; - //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; - $tododone = ''; - if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) $tododone = 'todo'; - - $histo[$numaction] = array( - 'type'=>$obj->type, - 'tododone'=>$tododone, - 'id'=>$obj->id, - 'datestart'=>$db->jdate($obj->dp), - 'dateend'=>$db->jdate($obj->dp2), - 'note'=>$obj->label, - 'percent'=>$obj->percent, - - 'userid'=>$obj->user_id, - 'login'=>$obj->user_login, - 'userfirstname'=>$obj->user_firstname, - 'userlastname'=>$obj->user_lastname, - 'userphoto'=>$obj->user_photo, - - 'contact_id'=>$obj->fk_contact, - 'socpeopleassigned' => $contactaction->socpeopleassigned, - 'lastname'=>$obj->lastname, - 'firstname'=>$obj->firstname, - 'fk_element'=>$obj->fk_element, - 'elementtype'=>$obj->elementtype, - // Type of event - 'acode'=>$obj->acode, - 'alabel'=>$obj->alabel, - 'libelle'=>$obj->alabel, // deprecated - 'apicto'=>$obj->apicto - ); - } else { - $histo[$numaction] = array( - 'type'=>$obj->type, - 'tododone'=>'done', - 'id'=>$obj->id, - 'datestart'=>$db->jdate($obj->dp), - 'dateend'=>$db->jdate($obj->dp2), - 'note'=>$obj->label, - 'percent'=>$obj->percent, - 'acode'=>$obj->acode, - - 'userid'=>$obj->user_id, - 'login'=>$obj->user_login, - 'userfirstname'=>$obj->user_firstname, - 'userlastname'=>$obj->user_lastname, - 'userphoto'=>$obj->user_photo - ); - } - - $numaction++; - $i++; - } - } else { - dol_print_error($db); - } - } - - if (!empty($conf->agenda->enabled) || (!empty($conf->mailing->enabled) && !empty($objcon->email))) { - $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60; - - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - - $formactions = new FormActions($db); - - $actionstatic = new ActionComm($db); - $userstatic = new User($db); - $userlinkcache = array(); - $contactstatic = new Contact($db); - $elementlinkcache = array(); - - $out .= '
'; - $out .= ''; - if ($objcon && get_class($objcon) == 'Contact' && - (is_null($filterobj) || get_class($filterobj) == 'Societe')) { - $out .= ''; - } else { - $out .= ''; - } - if ($filterobj && get_class($filterobj) == 'Societe') $out .= ''; - - $out .= "\n"; - - $out .= '
'; - $out .= ''; - - $out .= ''; - if ($donetodo) { - $out .= ''; - } - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - // Action column - $out .= ''; - $out .= ''; - - $out .= ''; - if ($donetodo) { - $tmp = ''; - if (get_class($filterobj) == 'Societe') $tmp .= ''; - $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : ''); - $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : ''); - $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : ''); - //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort"); - if (get_class($filterobj) == 'Societe') $tmp .= ''; - $out .= getTitleFieldOfList($tmp); + global $user, $conf; + global $form; + + global $param, $massactionbutton; + + dol_include_once('/comm/action/class/actioncomm.class.php'); + + // Check parameters + if (!is_object($filterobj) && !is_object($objcon)) dol_print_error('', 'BadParameter'); + + $out = ''; + $histo = array(); + $numaction = 0; + $now = dol_now('tzuser'); + + // Open DSI -- Fix order by -- Begin + $sortfield_list = explode(',', $sortfield); + $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent'); + $sortfield_new_list = array(); + foreach ($sortfield_list as $sortfield_value) { + $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)]; + } + $sortfield_new = implode(',', $sortfield_new_list); + + $sql = ''; + + if (!empty($conf->agenda->enabled)) + { + // Recherche histo sur actioncomm + if (is_object($objcon) && $objcon->id > 0) { + $sql = "SELECT DISTINCT a.id, a.label as label,"; + } + else + { + $sql = "SELECT a.id, a.label as label,"; + } + $sql .= " a.datep as dp,"; + $sql .= " a.datep2 as dp2,"; + $sql .= " a.percent as percent, 'action' as type,"; + $sql .= " a.fk_element, a.elementtype,"; + $sql .= " a.fk_contact,"; + $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,"; + $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; + if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur'))) $sql .= ", sp.lastname, sp.firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { /* Nothing */ } + elseif (is_object($filterobj) && get_class($filterobj) == 'Project') { /* Nothing */ } + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", m.lastname, m.firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", o.ref"; + elseif (is_object($filterobj) && is_array($filterobj->fields) && is_array($filterobj->fields['rowid']) && is_array($filterobj->fields['ref']) && $filterobj->table_element && $filterobj->element) $sql .= ", o.ref"; + + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id"; + + $force_filter_contact = false; + if (is_object($objcon) && $objcon->id > 0) { + $force_filter_contact = true; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm"; + $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".$objcon->id; + } + + if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur'))) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er"; + $sql .= " ON er.resource_type = 'dolresource'"; + $sql .= " AND er.element_id = a.id"; + $sql .= " AND er.resource_id = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'Project') { /* Nothing */ } + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", ".MAIN_DB_PREFIX."adherent as m"; + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", ".MAIN_DB_PREFIX."product as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", ".MAIN_DB_PREFIX."ticket as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", ".MAIN_DB_PREFIX."contrat as o"; + elseif (is_object($filterobj) && is_array($filterobj->fields) && is_array($filterobj->fields['rowid']) && is_array($filterobj->fields['ref']) && $filterobj->table_element && $filterobj->element) $sql .= ", ".MAIN_DB_PREFIX.$filterobj->table_element." as o"; + + $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; + if ($force_filter_contact === false) { + if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) $sql .= " AND a.fk_soc = ".$filterobj->id; + elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { /* Nothing */ } + elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) $sql .= " AND a.fk_project = ".$filterobj->id; + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') + { + $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && is_array($filterobj->fields) && is_array($filterobj->fields['rowid']) && is_array($filterobj->fields['ref']) && $filterobj->table_element && $filterobj->element) + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = '".$db->escape($filterobj->element)."'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + } + + // Condition on actioncode + if (!empty($actioncode)) + { + if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) + { + if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; + elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; + else + { + if ($actioncode == 'AC_OTH') $sql .= " AND c.type != 'systemauto'"; + elseif ($actioncode == 'AC_OTH_AUTO') $sql .= " AND c.type = 'systemauto'"; + } + } + else + { + if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; + elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; + else $sql .= " AND c.code = '".$db->escape($actioncode)."'"; + } + } + if ($donetodo == 'todo') $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; + elseif ($donetodo == 'done') $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; + if (is_array($filters) && $filters['search_agenda_label']) $sql .= natural_search('a.label', $filters['search_agenda_label']); + } + + // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing. + if (!empty($conf->mailing->enabled) && !empty($objcon->email) + && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) + { + $langs->load("mails"); + + $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type"; + $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id"; + $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto"; + $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action + if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql2 .= ", '' as lastname, '' as firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql2 .= ", '' as lastname, '' as firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql2 .= ", '' as ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql2 .= ", '' as ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql2 .= ", '' as ref"; + $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u"; + $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email. + $sql2 .= " AND mc.statut = 1"; + $sql2 .= " AND u.rowid = m.fk_user_valid"; + $sql2 .= " AND mc.fk_mailing = m.rowid"; + } + + if (!empty($sql) && !empty($sql2)) { + $sql = $sql." UNION ".$sql2; + } elseif (empty($sql) && !empty($sql2)) { + $sql = $sql2; + } + + //TODO Add limit in nb of results + if ($sql) + { + $sql .= $db->order($sortfield_new, $sortorder); + dol_syslog("company.lib::show_actions_done", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $i = 0; + $num = $db->num_rows($resql); + + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + if ($obj->type == 'action') { + $contactaction = new ActionComm($db); + $contactaction->id = $obj->id; + $result = $contactaction->fetchResources(); + if ($result < 0) { + dol_print_error($db); + setEventMessage("company.lib::show_actions_done Error fetch ressource", 'errors'); + } + + //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; + //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; + $tododone = ''; + if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) $tododone = 'todo'; + + $histo[$numaction] = array( + 'type'=>$obj->type, + 'tododone'=>$tododone, + 'id'=>$obj->id, + 'datestart'=>$db->jdate($obj->dp), + 'dateend'=>$db->jdate($obj->dp2), + 'note'=>$obj->label, + 'percent'=>$obj->percent, + + 'userid'=>$obj->user_id, + 'login'=>$obj->user_login, + 'userfirstname'=>$obj->user_firstname, + 'userlastname'=>$obj->user_lastname, + 'userphoto'=>$obj->user_photo, + + 'contact_id'=>$obj->fk_contact, + 'socpeopleassigned' => $contactaction->socpeopleassigned, + 'lastname'=>$obj->lastname, + 'firstname'=>$obj->firstname, + 'fk_element'=>$obj->fk_element, + 'elementtype'=>$obj->elementtype, + // Type of event + 'acode'=>$obj->acode, + 'alabel'=>$obj->alabel, + 'libelle'=>$obj->alabel, // deprecated + 'apicto'=>$obj->apicto + ); + } else { + $histo[$numaction] = array( + 'type'=>$obj->type, + 'tododone'=>'done', + 'id'=>$obj->id, + 'datestart'=>$db->jdate($obj->dp), + 'dateend'=>$db->jdate($obj->dp2), + 'note'=>$obj->label, + 'percent'=>$obj->percent, + 'acode'=>$obj->acode, + + 'userid'=>$obj->user_id, + 'login'=>$obj->user_login, + 'userfirstname'=>$obj->user_firstname, + 'userlastname'=>$obj->user_lastname, + 'userphoto'=>$obj->user_photo + ); + } + + $numaction++; + $i++; + } + } + else + { + dol_print_error($db); + } + } + + if (!empty($conf->agenda->enabled) || (!empty($conf->mailing->enabled) && !empty($objcon->email))) + { + $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60; + + require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; + + $formactions = new FormActions($db); + + $actionstatic = new ActionComm($db); + $userstatic = new User($db); + $contactstatic = new Contact($db); + + $out .= ''; + if ($objcon && get_class($objcon) == 'Contact' && + (is_null($filterobj) || get_class($filterobj) == 'Societe')) + { + $out .= ''; + } + else + { + $out .= ''; + } + if ($filterobj && get_class($filterobj) == 'Societe') $out .= ''; + + $out .= "\n"; + + $out .= '
'; + $out .= '
'; - $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, (empty($conf->global->AGENDA_USE_MULTISELECT_TYPE) ? 0 : 1), 1); - $out .= ''; - $out .= $form->selectDateToDate($tms_start, $tms_end, 'dateevent', 1); - $out .= ''; - $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); - $out .= $searchpicto; - $out .= '
'; + + $out .= ''; + if ($donetodo) + { + $out .= ''; + } + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + // Action column + $out .= ''; + $out .= ''; + + $out .= ''; + if ($donetodo) + { + $tmp = ''; + if (get_class($filterobj) == 'Societe') $tmp .= ''; + $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : ''); + $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : ''); + $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : ''); + //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort"); + if (get_class($filterobj) == 'Societe') $tmp .= ''; + $out .= getTitleFieldOfList($tmp); } $out .= getTitleFieldOfList($langs->trans("Ref"), 0, $_SERVER["PHP_SELF"], 'a.id', '', $param, '', $sortfield, $sortorder); $out .= getTitleFieldOfList($langs->trans("Owner")); - $out .= getTitleFieldOfList($langs->trans("Type")); + $out .= getTitleFieldOfList($langs->trans("Type")); $out .= getTitleFieldOfList($langs->trans("Label"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); - $out .= getTitleFieldOfList($langs->trans("Date"), 0, $_SERVER["PHP_SELF"], 'a.datep,a.id', '', $param, 'align="center"', $sortfield, $sortorder); - $out .= getTitleFieldOfList($langs->trans("RelatedObjects"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); + $out .= getTitleFieldOfList($langs->trans("Date"), 0, $_SERVER["PHP_SELF"], 'a.datep,a.id', '', $param, 'align="center"', $sortfield, $sortorder); + $out .= getTitleFieldOfList($langs->trans("RelatedObjects"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); $out .= getTitleFieldOfList($langs->trans("ActionOnContact"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); $out .= getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], 'a.percent', '', $param, 'align="center"', $sortfield, $sortorder); $out .= getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'maxwidthsearch '); @@ -1526,141 +1640,123 @@ $caction = new CActionComm($db); $arraylist = $caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : 0), '', 1); - foreach ($histo as $key => $value) { + foreach ($histo as $key => $value) + { $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo $actionstatic->type_picto = $histo[$key]['apicto']; $actionstatic->type_code = $histo[$key]['acode']; - $out .= ''; - - // Done or todo - if ($donetodo) { - $out .= ''; - } - - // Ref - $out .= ''; - - // Author of event - $out .= ''; - - // Type - $out .= ''; - - // Title - $out .= ''; - - // Date - $out .= '\n"; - - // Title of event - //$out.=''; - - // Linked object - $out .= ''; - - // Contact(s) for action - if (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) { - $contactstatic->lastname = $histo[$key]['lastname']; - $contactstatic->firstname = $histo[$key]['firstname']; - $contactstatic->id = $histo[$key]['contact_id']; - $out .= ''; - } elseif (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) { + $out .= ''; + + // Done or todo + if ($donetodo) + { + $out .= ''; + } + + // Ref + $out .= ''; + + // Author of event + $out .= ''; + + // Type + $out .= ''; + + // Title + $out .= ''; + + // Date + $out .= '\n"; + + // Title of event + //$out.=''; + + // Linked object + $out .= ''; + + // Contact(s) for action + if (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) + { + $contactstatic->lastname = $histo[$key]['lastname']; + $contactstatic->firstname = $histo[$key]['firstname']; + $contactstatic->id = $histo[$key]['contact_id']; + $out .= ''; + } elseif (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) { $out .= ''; - } else { - $out .= ''; } - - // Status - $out .= ''; - - // Actions - $out .= ''; - - $out .= "\n"; - $i++; - } - $out .= "
'; + $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1); + $out .= ''; + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); + $out .= $searchpicto; + $out .= '
'; - $out .= ''; - if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') { - $out .= ''.img_object($langs->trans("ShowEMailing"), "email").' '; - $out .= $histo[$key]['id']; - $out .= ''; - } else { - $out .= $actionstatic->getNomUrl(1, -1); - } - $out .= ''; - //$userstatic->id=$histo[$key]['userid']; - //$userstatic->login=$histo[$key]['login']; - //$out.=$userstatic->getLoginUrl(1); - if ($histo[$key]['userid'] > 0) { - if (isset($userlinkcache[$histo[$key]['userid']])) { - $link = $userlinkcache[$histo[$key]['userid']]; - } else { - $userstatic->fetch($histo[$key]['userid']); - $link = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', ''); - $userlinkcache[$histo[$key]['userid']] = $link; - } - $out .= $link; - } - $out .= ''; - // TODO Code common with code into showactions - $imgpicto = ''; - if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { - if ($actionstatic->type_picto) { - $imgpicto .= img_picto('', $actionstatic->type_picto); - } - else { - if ($actionstatic->type_code == 'AC_RDV') $imgpicto .= img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actionstatic->type_code == 'AC_TEL') $imgpicto .= img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actionstatic->type_code == 'AC_FAX') $imgpicto .= img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actionstatic->type_code == 'AC_EMAIL' || $actionstatic->type_code == 'AC_EMAIL_IN') $imgpicto .= img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actionstatic->type_code == 'AC_INT') $imgpicto .= img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actionstatic->type_code == 'AC_OTH' && $actionstatic->code == 'TICKET_MSG') $imgpicto = img_picto('', 'object_conversation', '', false, 0, 0, '', 'paddingright').' '; - elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) $imgpicto .= img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' '; - } - } - $out .= $imgpicto; - $labeltype = $actionstatic->type_code; - if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype = 'AC_OTH'; - if ($actionstatic->type_code == 'AC_OTH' && $actionstatic->code == 'TICKET_MSG') { - $labeltype = $langs->trans("Message"); - } else { - if (!empty($arraylist[$labeltype])) $labeltype = $arraylist[$labeltype]; - if ($actionstatic->type_code == 'AC_OTH_AUTO' && ($actionstatic->type_code != $actionstatic->code) && $labeltype && !empty($arraylist[$actionstatic->code])) $labeltype .= ' - '.$arraylist[$actionstatic->code]; // Use code in priority on type_code - } - $out .= dol_trunc($labeltype, 28); - $out .= ''; - if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'action') { - $transcode = $langs->trans("Action".$histo[$key]['acode']); - $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']); - //$actionstatic->libelle=$libelle; - $libelle = $histo[$key]['note']; - $actionstatic->id = $histo[$key]['id']; - $out .= dol_trunc($libelle, 120); - } - if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') { - $out .= ''.img_object($langs->trans("ShowEMailing"), "email").' '; - $transcode = $langs->trans("Action".$histo[$key]['acode']); - $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing'); - $out .= dol_trunc($libelle, 120); - } - $out .= ''; - $out .= dol_print_date($histo[$key]['datestart'], 'dayhour', 'tzuserrel'); - if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) { - $tmpa = dol_getdate($histo[$key]['datestart'], true); - $tmpb = dol_getdate($histo[$key]['dateend'], true); - if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel'); - else $out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour', 'tzuserrel'); - } - $late = 0; - if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; - if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; - if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) $late = 1; - if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; - if ($late) $out .= img_warning($langs->trans("Late")).' '; - $out .= "'.dol_trunc($histo[$key]['note'], 40).''; - if (isset($histo[$key]['elementtype']) && !empty($histo[$key]['fk_element'])) { - if (isset($elementlinkcache[$histo[$key]['elementtype']]) && isset($elementlinkcache[$histo[$key]['elementtype']][$histo[$key]['fk_element']])) { - $link = $elementlinkcache[$histo[$key]['elementtype']][$histo[$key]['fk_element']]; - } else { - if (!isset($elementlinkcache[$histo[$key]['elementtype']])) { - $elementlinkcache[$histo[$key]['elementtype']] = array(); - } - $link = dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1); - $elementlinkcache[$histo[$key]['elementtype']][$histo[$key]['fk_element']] = $link; - } - $out .= $link; - } else { - $out .= ' '; - } - $out .= ''.$contactstatic->getNomUrl(1, '', 10).'
'; + $out .= ''; + if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') { + $out .= ''.img_object($langs->trans("ShowEMailing"), "email").' '; + $out .= $histo[$key]['id']; + $out .= ''; + } else { + $out .= $actionstatic->getNomUrl(1, -1); + } + $out .= ''; + //$userstatic->id=$histo[$key]['userid']; + //$userstatic->login=$histo[$key]['login']; + //$out.=$userstatic->getLoginUrl(1); + if ($histo[$key]['userid'] > 0) + { + $userstatic->fetch($histo[$key]['userid']); // TODO Introduce a cache on users fetched + $out .= $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', ''); + } + $out .= ''; + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) + { + if ($actionstatic->type_picto) print img_picto('', $actionstatic->type_picto); + else { + if ($actionstatic->type_code == 'AC_RDV') $out .= img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actionstatic->type_code == 'AC_TEL') $out .= img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actionstatic->type_code == 'AC_FAX') $out .= img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actionstatic->type_code == 'AC_EMAIL') $out .= img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actionstatic->type_code == 'AC_INT') $out .= img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' '; + elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) $out .= img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' '; + } + } + $labeltype = $actionstatic->type_code; + if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype = 'AC_OTH'; + if (!empty($arraylist[$labeltype])) $labeltype = $arraylist[$labeltype]; + $out .= dol_trunc($labeltype, 28); + $out .= ''; + if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'action') + { + $transcode = $langs->trans("Action".$histo[$key]['acode']); + $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']); + //$actionstatic->libelle=$libelle; + $libelle = $histo[$key]['note']; + $actionstatic->id = $histo[$key]['id']; + $out .= dol_trunc($libelle, 120); + } + if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') + { + $out .= ''.img_object($langs->trans("ShowEMailing"), "email").' '; + $transcode = $langs->trans("Action".$histo[$key]['acode']); + $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing'); + $out .= dol_trunc($libelle, 120); + } + $out .= ''; + $out .= dol_print_date($histo[$key]['datestart'], 'dayhour', 'tzuserrel'); + if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) + { + $tmpa = dol_getdate($histo[$key]['datestart'], true); + $tmpb = dol_getdate($histo[$key]['dateend'], true); + if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel'); + else $out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour', 'tzuserrel'); + } + $late = 0; + if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; + if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; + if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) $late = 1; + if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; + if ($late) $out .= img_warning($langs->trans("Late")).' '; + $out .= "'.dol_trunc($histo[$key]['note'], 40).''; + if (isset($histo[$key]['elementtype']) && !empty($histo[$key]['fk_element'])) + { + $out .= dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1); + } + else $out .= ' '; + $out .= ''.$contactstatic->getNomUrl(1, '', 10).''; $contact = new Contact($db); foreach ($histo[$key]['socpeopleassigned'] as $cid => $value) { @@ -1679,27 +1775,28 @@ } } $out .= ' '.$actionstatic->LibStatut($histo[$key]['percent'], 3, 0, $histo[$key]['datestart']).'
\n"; - $out .= "
\n"; - - $out .= '
'; - } - - if ($noprint) return $out; - else print $out; + else { + $out .= ' '; + } + + // Status + $out .= ''.$actionstatic->LibStatut($histo[$key]['percent'], 3, 0, $histo[$key]['datestart']).''; + + // Actions + $out .= ''; + + $out .= "\n"; + $i++; + } + $out .= "\n"; + $out .= "\n"; + + $out .= ''; + } + + if ($noprint) return $out; + else print $out; } /** @@ -1726,7 +1823,8 @@ $result = $db->query($sql); $num = $db->num_rows($result); - if ($num) { + if ($num) + { $socstatic = new Societe($db); print load_fiche_titre($langs->trans("Subsidiaries"), '', ''); @@ -1740,7 +1838,8 @@ $i = 0; - while ($i < $num) { + while ($i < $num) + { $obj = $db->fetch_object($result); $socstatic->id = $obj->rowid; @@ -1782,73 +1881,3 @@ return $i; } -/** - * Add Event Type SQL - * - * @param string $sql $sql modified - * @param string $actioncode Action code - * @param string $donetodo donetodo - * @param string $now now - * @param string $filters array - * @param string $sqlANDOR "AND", "OR" or "" sql condition - * @return string sql request - */ -function addEventTypeSQL(&$sql, $actioncode, $donetodo, $now, $filters, $sqlANDOR = "AND") -{ - global $conf, $db; - // Condition on actioncode - - if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { - if ($actioncode == 'AC_NON_AUTO') $sql .= " $sqlANDOR c.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " $sqlANDOR c.type = 'systemauto'"; - else { - if ($actioncode == 'AC_OTH') $sql .= " $sqlANDOR c.type != 'systemauto'"; - elseif ($actioncode == 'AC_OTH_AUTO') $sql .= " $sqlANDOR c.type = 'systemauto'"; - } - } - else { - if ($actioncode == 'AC_NON_AUTO') $sql .= " $sqlANDOR c.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " $sqlANDOR c.type = 'systemauto'"; - else $sql .= " $sqlANDOR c.code = '".$db->escape($actioncode)."'"; - } - - if ($donetodo == 'todo') $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; - elseif ($donetodo == 'done') $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; - if (is_array($filters) && $filters['search_agenda_label']) $sql .= natural_search('a.label', $filters['search_agenda_label']); - - return $sql; -} - -/** - * Add Mailing Event Type SQL - * - * @param string $actioncode Action code - * @param Object $objcon objcon - * @param Object $filterobj filterobj - * @return string - */ -function addMailingEventTypeSQL($actioncode, $objcon, $filterobj) -{ - global $conf, $langs, $db; - // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing. - if (!empty($conf->mailing->enabled) && !empty($objcon->email) - && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) { - $langs->load("mails"); - - $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type"; - $sql2 .= ", '' as fk_element, '' as elementtype, '' as contact_id"; - $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto"; - $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action - if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql2 .= ", '' as lastname, '' as firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql2 .= ", '' as lastname, '' as firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql2 .= ", '' as ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql2 .= ", '' as ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql2 .= ", '' as ref"; - $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u"; - $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email. - $sql2 .= " AND mc.statut = 1"; - $sql2 .= " AND u.rowid = m.fk_user_valid"; - $sql2 .= " AND mc.fk_mailing=m.rowid"; - return $sql2; - } -} --- /tmp/dsg/dolibarr/htdocs/core/lib/github_contact.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_contact.lib.php @@ -59,54 +59,54 @@ $tab++; // Related items - if (!empty($conf->commande->enabled) || !empty($conf->propal->enabled) || !empty($conf->facture->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) - { - $head[$tab][0] = DOL_URL_ROOT.'/contact/consumption.php?id='.$object->id; - $head[$tab][1] = $langs->trans("Referers"); - $head[$tab][2] = 'consumption'; - $tab++; - } + if (! empty($conf->commande->enabled) || ! empty($conf->propal->enabled) || ! empty($conf->facture->enabled) || ! empty($conf->ficheinter->enabled) || !empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) + { + $head[$tab][0] = DOL_URL_ROOT.'/contact/consumption.php?id='.$object->id; + $head[$tab][1] = $langs->trans("Referers"); + $head[$tab][2] = 'consumption'; + $tab++; + } - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $tab, 'contact'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $tab, 'contact'); - // Notes - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { - $nbNote = (empty($object->note_private) ? 0 : 1) + (empty($object->note_public) ? 0 : 1); - $head[$tab][0] = DOL_URL_ROOT.'/contact/note.php?id='.$object->id; - $head[$tab][1] = $langs->trans("Note"); - if ($nbNote > 0) $head[$tab][1] .= ''.$nbNote.''; - $head[$tab][2] = 'note'; - $tab++; - } + // Notes + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { + $nbNote = (empty($object->note_private) ? 0 : 1) + (empty($object->note_public) ? 0 : 1); + $head[$tab][0] = DOL_URL_ROOT.'/contact/note.php?id='.$object->id; + $head[$tab][1] = $langs->trans("Note"); + if ($nbNote > 0) $head[$tab][1] .= ''.$nbNote.''; + $head[$tab][2] = 'note'; + $tab++; + } - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->societe->dir_output."/contact/".dol_sanitizeFileName($object->ref); - $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); - $head[$tab][0] = DOL_URL_ROOT.'/contact/document.php?id='.$object->id; - $head[$tab][1] = $langs->trans("Documents"); - if (($nbFiles + $nbLinks) > 0) $head[$tab][1] .= ''.($nbFiles + $nbLinks).''; - $head[$tab][2] = 'documents'; - $tab++; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->societe->dir_output."/contact/".dol_sanitizeFileName($object->ref); + $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); + $nbLinks = Link::count($db, $object->element, $object->id); + $head[$tab][0] = DOL_URL_ROOT.'/contact/document.php?id='.$object->id; + $head[$tab][1] = $langs->trans("Documents"); + if (($nbFiles + $nbLinks) > 0) $head[$tab][1] .= ''.($nbFiles + $nbLinks).''; + $head[$tab][2] = 'documents'; + $tab++; - // Agenda / Events - $head[$tab][0] = DOL_URL_ROOT.'/contact/agenda.php?id='.$object->id; - $head[$tab][1] .= $langs->trans("Events"); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { - $head[$tab][1] .= '/'; - $head[$tab][1] .= $langs->trans("Agenda"); - } - $head[$tab][2] = 'agenda'; - $tab++; + // Agenda / Events + $head[$tab][0] = DOL_URL_ROOT.'/contact/agenda.php?id='.$object->id; + $head[$tab][1] .= $langs->trans("Events"); + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) + { + $head[$tab][1] .= '/'; + $head[$tab][1] .= $langs->trans("Agenda"); + } + $head[$tab][2] = 'agenda'; + $tab++; - // Log - /* + // Log + /* $head[$tab][0] = DOL_URL_ROOT.'/contact/info.php?id='.$object->id; $head[$tab][1] = $langs->trans("Info"); $head[$tab][2] = 'info'; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_contract.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_contract.lib.php @@ -42,37 +42,37 @@ 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.'/contrat/contact.php?id='.$object->id; + $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT.'/contrat/contact.php?id='.$object->id; $head[$h][1] = $langs->trans("ContactsAddresses"); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; $head[$h][2] = 'contact'; $h++; } - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'contract'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'contract'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; if (!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/contrat/note.php?id='.$object->id; - $head[$h][1] = $langs->trans("Notes"); + $head[$h][0] = DOL_URL_ROOT.'/contrat/note.php?id='.$object->id; + $head[$h][1] = $langs->trans("Notes"); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; - $head[$h][2] = 'note'; - $h++; - } + $head[$h][2] = 'note'; + $h++; + } require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->contrat->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref); + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->contrat->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/contrat/document.php?id='.$object->id; $head[$h][1] = $langs->trans("Documents"); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; @@ -89,7 +89,7 @@ $head[$h][2] = 'agenda'; $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'contract', 'remove'); + complete_head_from_modules($conf, $langs, $object, $head, $h, 'contract', 'remove'); return $head; } @@ -119,13 +119,13 @@ $head[$h][0] = DOL_URL_ROOT.'/contrat/admin/contract_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes'; - $h++; + $head[$h][2] = 'attributes'; + $h++; - $head[$h][0] = DOL_URL_ROOT.'/contrat/admin/contractdet_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsLines"); - $head[$h][2] = 'attributeslines'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/contrat/admin/contractdet_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsLines"); + $head[$h][2] = 'attributeslines'; + $h++; complete_head_from_modules($conf, $langs, null, $head, $h, 'contract_admin', 'remove'); --- /tmp/dsg/dolibarr/htdocs/core/lib/github_cron.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_cron.lib.php @@ -30,26 +30,21 @@ */ function cronadmin_prepare_head() { - global $langs, $conf, $user; - $h = 0; - $head = array(); + global $langs, $conf, $user; + $h = 0; + $head = array(); - $head[$h][0] = dol_buildpath('/cron/admin/cron.php', 1); - $head[$h][1] = $langs->trans("Miscellaneous"); - $head[$h][2] = 'setup'; - $h++; + $head[$h][0] = dol_buildpath('/cron/admin/cron.php', 1); + $head[$h][1] = $langs->trans("Miscellaneous"); + $head[$h][2] = 'setup'; + $h++; - $head[$h][0] = dol_buildpath('/cron/list.php?mode=modulesetup', 1); - $head[$h][1] = $langs->trans("Module2300Name"); - $head[$h][2] = 'jobs'; - $h++; + complete_head_from_modules($conf, $langs, null, $head, $h, 'cronadmin'); - complete_head_from_modules($conf, $langs, null, $head, $h, 'cronadmin'); - - complete_head_from_modules($conf, $langs, null, $head, $h, 'cronadmin', 'remove'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'cronadmin', 'remove'); - return $head; + return $head; } /** @@ -104,8 +99,8 @@ print ' '.$langs->trans("OrToLaunchASpecificJob").'
'; $url = $urlwithroot.'/public/cron/cron_run_jobs.php?'.(empty($conf->global->CRON_KEY) ? '' : 'securitykey='.$conf->global->CRON_KEY.'&').'userlogin='.$user->login.'&id=cronjobid'; print img_picto('', 'globe').' '.$url."
\n"; - print ''; - print '
'; + print ''; + print '
'; $logintouse = 'firstadmin'; if ($user->admin) $logintouse = $user->login; @@ -119,18 +114,20 @@ // Add note if (empty($conf->global->CRON_DISABLE_TUTORIAL_CRON)) { - $linuxlike = 1; - if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0; - if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0; - print $langs->trans("Note").': '; - if ($linuxlike) - { - print $langs->trans("CronExplainHowToRunUnix"); - print '
'; - print '
'; - } else { - print $langs->trans("CronExplainHowToRunWin"); - } + $linuxlike = 1; + if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0; + if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0; + print $langs->trans("Note").': '; + if ($linuxlike) + { + print $langs->trans("CronExplainHowToRunUnix"); + print '
'; + print '
'; + } + else + { + print $langs->trans("CronExplainHowToRunWin"); + } } return 0; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_date.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_date.lib.php @@ -33,34 +33,34 @@ */ function get_tz_array() { - $tzarray = array( - -11=>"Pacific/Midway", - -10=>"Pacific/Fakaofo", - -9=>"America/Anchorage", - -8=>"America/Los_Angeles", - -7=>"America/Dawson_Creek", - -6=>"America/Chicago", - -5=>"America/Bogota", - -4=>"America/Anguilla", - -3=>"America/Araguaina", - -2=>"America/Noronha", - -1=>"Atlantic/Azores", - 0=>"Africa/Abidjan", - 1=>"Europe/Paris", - 2=>"Europe/Helsinki", - 3=>"Europe/Moscow", - 4=>"Asia/Dubai", - 5=>"Asia/Karachi", - 6=>"Indian/Chagos", - 7=>"Asia/Jakarta", - 8=>"Asia/Hong_Kong", - 9=>"Asia/Tokyo", - 10=>"Australia/Sydney", - 11=>"Pacific/Noumea", - 12=>"Pacific/Auckland", - 13=>"Pacific/Enderbury" - ); - return $tzarray; + $tzarray = array( + -11=>"Pacific/Midway", + -10=>"Pacific/Fakaofo", + -9=>"America/Anchorage", + -8=>"America/Los_Angeles", + -7=>"America/Dawson_Creek", + -6=>"America/Chicago", + -5=>"America/Bogota", + -4=>"America/Anguilla", + -3=>"America/Araguaina", + -2=>"America/Noronha", + -1=>"Atlantic/Azores", + 0=>"Africa/Abidjan", + 1=>"Europe/Paris", + 2=>"Europe/Helsinki", + 3=>"Europe/Moscow", + 4=>"Asia/Dubai", + 5=>"Asia/Karachi", + 6=>"Indian/Chagos", + 7=>"Asia/Jakarta", + 8=>"Asia/Hong_Kong", + 9=>"Asia/Tokyo", + 10=>"Australia/Sydney", + 11=>"Pacific/Noumea", + 12=>"Pacific/Auckland", + 13=>"Pacific/Enderbury" + ); + return $tzarray; } @@ -71,35 +71,37 @@ */ function getServerTimeZoneString() { - return @date_default_timezone_get(); + return @date_default_timezone_get(); } /** * Return server timezone int. * * @param string $refgmtdate Reference period for timezone (timezone differs on winter and summer. May be 'now', 'winter' or 'summer') - * @return float An offset in hour (+1 for Europe/Paris on winter and +2 for Europe/Paris on summer). Note some countries use half and even quarter hours. + * @return int An offset in hour (+1 for Europe/Paris on winter and +2 for Europe/Paris on summer) */ function getServerTimeZoneInt($refgmtdate = 'now') { - if (method_exists('DateTimeZone', 'getOffset')) - { - // Method 1 (include daylight) - $gmtnow = dol_now('gmt'); $yearref = dol_print_date($gmtnow, '%Y'); $monthref = dol_print_date($gmtnow, '%m'); $dayref = dol_print_date($gmtnow, '%d'); - if ($refgmtdate == 'now') $newrefgmtdate = $yearref.'-'.$monthref.'-'.$dayref; - elseif ($refgmtdate == 'summer') $newrefgmtdate = $yearref.'-08-01'; - else $newrefgmtdate = $yearref.'-01-01'; - $newrefgmtdate .= 'T00:00:00+00:00'; - $localtz = new DateTimeZone(getServerTimeZoneString()); - $localdt = new DateTime($newrefgmtdate, $localtz); - $tmp = -1 * $localtz->getOffset($localdt); - //print $refgmtdate.'='.$tmp; - } else { - $tmp = 0; - dol_print_error('', 'PHP version must be 5.3+'); - } - $tz = round(($tmp < 0 ? 1 : -1) * abs($tmp / 3600)); - return $tz; + if (method_exists('DateTimeZone', 'getOffset')) + { + // Method 1 (include daylight) + $gmtnow = dol_now('gmt'); $yearref = dol_print_date($gmtnow, '%Y'); $monthref = dol_print_date($gmtnow, '%m'); $dayref = dol_print_date($gmtnow, '%d'); + if ($refgmtdate == 'now') $newrefgmtdate = $yearref.'-'.$monthref.'-'.$dayref; + elseif ($refgmtdate == 'summer') $newrefgmtdate = $yearref.'-08-01'; + else $newrefgmtdate = $yearref.'-01-01'; + $newrefgmtdate .= 'T00:00:00+00:00'; + $localtz = new DateTimeZone(getServerTimeZoneString()); + $localdt = new DateTime($newrefgmtdate, $localtz); + $tmp = -1 * $localtz->getOffset($localdt); + //print $refgmtdate.'='.$tmp; + } + else + { + $tmp = 0; + dol_print_error('', 'PHP version must be 5.3+'); + } + $tz = round(($tmp < 0 ? 1 : -1) * abs($tmp / 3600)); + return $tz; } @@ -108,7 +110,7 @@ * * @param int $time Date timestamp (or string with format YYYY-MM-DD) * @param int $duration_value Value of delay to add - * @param int $duration_unit Unit of added delay (d, m, y, w, h, i) + * @param int $duration_unit Unit of added delay (d, m, y, w, h) * @return int New timestamp */ function dol_time_plus_duree($time, $duration_value, $duration_unit) @@ -116,7 +118,6 @@ global $conf; if ($duration_value == 0) return $time; - if ($duration_unit == 'i') return $time + (60 * $duration_value); if ($duration_unit == 'h') return $time + (3600 * $duration_value); if ($duration_unit == 'w') return $time + (3600 * 24 * 7 * $duration_value); @@ -182,15 +183,15 @@ global $langs; if (empty($lengthOfDay)) $lengthOfDay = 86400; // 1 day = 24 hours - if (empty($lengthOfWeek)) $lengthOfWeek = 7; // 1 week = 7 days - - if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') + if (empty($lengthOfWeek)) $lengthOfWeek = 7; // 1 week = 7 days + + if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') { if ((int) $iSecond === 0) return '0'; // This is to avoid having 0 return a 12:00 AM for en_US - $sTime = ''; - $sDay = 0; - $sWeek = 0; + $sTime = ''; + $sDay = 0; + $sWeek = 0; if ($iSecond >= $lengthOfDay) { @@ -205,17 +206,17 @@ if ($lengthOfWeek < 7) { - if ($sDay) - { - if ($sDay >= $lengthOfWeek) - { - $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek); - $sDay = $sDay % $lengthOfWeek; - $weekTranslate = $langs->trans("DurationWeek"); - if ($sWeek >= 2) $weekTranslate = $langs->trans("DurationWeeks"); - $sTime .= $sWeek.' '.$weekTranslate.' '; - } - } + if ($sDay) + { + if ($sDay >= $lengthOfWeek) + { + $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek); + $sDay = $sDay % $lengthOfWeek; + $weekTranslate = $langs->trans("DurationWeek"); + if ($sWeek >= 2) $weekTranslate = $langs->trans("DurationWeeks"); + $sTime .= $sWeek.' '.$weekTranslate.' '; + } + } } if ($sDay > 0) { @@ -230,41 +231,51 @@ { $sTime .= dol_print_date($iSecond, 'hourduration', true); } - } elseif ($format == 'allhourminsec') - { - return sprintf("%02d", ($sWeek * $lengthOfWeek * 24 + $sDay * 24 + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60))); - } elseif ($format == 'allhourmin') - { - return sprintf("%02d", ($sWeek * $lengthOfWeek * 24 + $sDay * 24 + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))); - } elseif ($format == 'allhour') + } + elseif ($format == 'allhourminsec') + { + return sprintf("%02d", ($sWeek * $lengthOfWeek * 24 + $sDay * 24 + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60))); + } + elseif ($format == 'allhourmin') + { + return sprintf("%02d", ($sWeek * $lengthOfWeek * 24 + $sDay * 24 + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))); + } + elseif ($format == 'allhour') { return sprintf("%02d", ($sWeek * $lengthOfWeek * 24 + $sDay * 24 + (int) floor($iSecond / 3600))); } - } elseif ($format == 'hour') // only hour part + } + elseif ($format == 'hour') // only hour part { $sTime = dol_print_date($iSecond, '%H', true); - } elseif ($format == 'fullhour') + } + elseif ($format == 'fullhour') { if (!empty($iSecond)) { $iSecond = $iSecond / 3600; - } else { + } + else { $iSecond = 0; } $sTime = $iSecond; - } elseif ($format == 'min') // only min part + } + elseif ($format == 'min') // only min part { $sTime = dol_print_date($iSecond, '%M', true); - } elseif ($format == 'sec') // only sec part - { - $sTime = dol_print_date($iSecond, '%S', true); - } elseif ($format == 'month') // only month part - { - $sTime = dol_print_date($iSecond, '%m', true); - } elseif ($format == 'year') // only year part - { - $sTime = dol_print_date($iSecond, '%Y', true); - } - return trim($sTime); + } + elseif ($format == 'sec') // only sec part + { + $sTime = dol_print_date($iSecond, '%S', true); + } + elseif ($format == 'month') // only month part + { + $sTime = dol_print_date($iSecond, '%m', true); + } + elseif ($format == 'year') // only year part + { + $sTime = dol_print_date($iSecond, '%Y', true); + } + return trim($sTime); } @@ -289,7 +300,8 @@ } elseif ($year_date > 0 && !empty($day_date)) { $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date)); $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date))."'"; - } else $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'"; + } else + $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'"; } elseif ($year_date > 0) { $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, false)); $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, false))."'"; @@ -319,45 +331,45 @@ function dol_stringtotime($string, $gm = 1) { $reg = array(); - // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used. - if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) - { - dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING); - // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS' - // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS' - $sday = $reg[1]; - $smonth = $reg[2]; - $syear = $reg[3]; - $shour = $reg[4]; - $smin = $reg[5]; - $ssec = $reg[6]; - if ($syear < 50) $syear += 1900; - if ($syear >= 50 && $syear < 100) $syear += 2000; - $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec); - } elseif ( - preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/i', $string, $reg) // Convert date with format YYYY-MM-DDTHH:MM:SSZ (RFC3339) - || preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/i', $string, $reg) // Convert date with format YYYY-MM-DD HH:MM:SS + // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used. + if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) + { + dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING); + // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS' + // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS' + $sday = $reg[1]; + $smonth = $reg[2]; + $syear = $reg[3]; + $shour = $reg[4]; + $smin = $reg[5]; + $ssec = $reg[6]; + if ($syear < 50) $syear += 1900; + if ($syear >= 50 && $syear < 100) $syear += 2000; + $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec); + } + elseif ( + preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/i', $string, $reg) // Convert date with format YYYY-MM-DDTHH:MM:SSZ (RFC3339) + || preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/i', $string, $reg) // Convert date with format YYYY-MM-DD HH:MM:SS || preg_match('/^([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2})([0-9]{2})([0-9]{2})Z$/i', $string, $reg) // Convert date with format YYYYMMDDTHHMMSSZ - ) - { - $syear = $reg[1]; - $smonth = $reg[2]; - $sday = $reg[3]; - $shour = $reg[4]; - $smin = $reg[5]; - $ssec = $reg[6]; - $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec); - } - - $string = preg_replace('/([^0-9])/i', '', $string); - $tmp = $string.'000000'; - $date = dol_mktime(substr($tmp, 8, 2), substr($tmp, 10, 2), substr($tmp, 12, 2), substr($tmp, 4, 2), substr($tmp, 6, 2), substr($tmp, 0, 4), ($gm ? 1 : 0)); - return $date; -} - - -/** - * Return previous day + ) + { + $syear = $reg[1]; + $smonth = $reg[2]; + $sday = $reg[3]; + $shour = $reg[4]; + $smin = $reg[5]; + $ssec = $reg[6]; + $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec); + } + + $string = preg_replace('/([^0-9])/i', '', $string); + $tmp = $string.'000000'; + $date = dol_mktime(substr($tmp, 8, 2), substr($tmp, 10, 2), substr($tmp, 12, 2), substr($tmp, 4, 2), substr($tmp, 6, 2), substr($tmp, 0, 4), ($gm ? 1 : 0)); + return $date; +} + + +/** Return previous day * * @param int $day Day * @param int $month Month @@ -372,8 +384,7 @@ return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']); } -/** - * Return next day +/** Return next day * * @param int $day Day * @param int $month Month @@ -388,8 +399,7 @@ return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']); } -/** - * Return previous month +/** Return previous month * * @param int $month Month * @param int $year Year @@ -401,15 +411,16 @@ { $prev_month = 12; $prev_year = $year - 1; - } else { + } + else + { $prev_month = $month - 1; $prev_year = $year; } return array('year' => $prev_year, 'month' => $prev_month); } -/** - * Return next month +/** Return next month * * @param int $month Month * @param int $year Year @@ -421,15 +432,16 @@ { $next_month = 1; $next_year = $year + 1; - } else { + } + else + { $next_month = $month + 1; $next_year = $year; } return array('year' => $next_year, 'month' => $next_month); } -/** - * Return previous week +/** Return previous week * * @param int $day Day * @param int $week Week @@ -447,8 +459,7 @@ return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']); } -/** - * Return next week +/** Return next week * * @param int $day Day * @param int $week Week @@ -467,15 +478,13 @@ return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']); } -/** - * Return GMT time for first day of a month or year +/** Return GMT time for first day of a month or year * * @param int $year Year * @param int $month Month - * @param mixed $gm False or 0 or 'tzserver' = Return date to compare with server TZ, - * True or 1 or 'gmt' to compare with GMT date. - * Example: dol_get_first_day(1970,1,false) will return -3600 with TZ+1, a dol_print_date on it will return 1970-01-01 00:00:00 - * Example: dol_get_first_day(1970,1,true) will return 0 whatever is TZ, a dol_print_date on it will return 1970-01-01 00:00:00 + * @param mixed $gm False or 0 or 'server' = Return date to compare with server TZ, True or 1 to compare with GM date. + * Exemple: dol_get_first_day(1970,1,false) will return -3600 with TZ+1, after a dol_print_date will return 1970-01-01 00:00:00 + * Exemple: dol_get_first_day(1970,1,true) will return 0 whatever is TZ, after a dol_print_date will return 1970-01-01 00:00:00 * @return int Date for first day, '' if error */ function dol_get_first_day($year, $month = 1, $gm = false) @@ -485,14 +494,11 @@ } -/** - * Return GMT time for last day of a month or year. - * Note: The timestamp contains last day and last hours (23:59:59) +/** Return GMT time for last day of a month or year * * @param int $year Year * @param int $month Month - * @param mixed $gm False or 0 or 'tzserver' = Return date to compare with server TZ, - * True or 1 or 'gmt' to compare with GMT date. + * @param boolean $gm False or 0 or 'server' = Return date to compare with server TZ, True or 1 to compare with GM date. * @return int Date for first day, '' if error */ function dol_get_last_day($year, $month = 12, $gm = false) @@ -502,7 +508,9 @@ { $month = 1; $year += 1; - } else { + } + else + { $month += 1; } @@ -513,41 +521,12 @@ return $datelim; } -/** - * Return GMT time for last hour of a given GMT date (it removes hours, min and second part) - * - * @param int $date Date - * @param mixed $gm False or 0 or 'tzserver' = Return date to compare with server TZ, - * True or 1 or 'gmt' to compare with GMT date. - * @return int Date for last hour of a given date - */ -function dol_get_last_hour($date, $gm = 'tzserver') -{ - $tmparray = dol_getdate($date); - return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm); -} - -/** - * Return GMT time for first hour of a given GMT date (it removes hours, min and second part) - * - * @param int $date Date - * @param mixed $gm False or 0 or 'tzserver' = Return date to compare with server TZ, - * True or 1 or 'gmt' to compare with GMT date. - * @return int Date for last hour of a given date - */ -function dol_get_first_hour($date, $gm = 'tzserver') -{ - $tmparray = dol_getdate($date); - return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm); -} - /** Return first day of week for a date. First day of week may be monday if option MAIN_START_WEEK is 1. * * @param int $day Day * @param int $month Month * @param int $year Year - * @param mixed $gm False or 0 or 'tzserver' = Return date to compare with server TZ, - * True or 1 or 'gmt' to compare with GMT date. + * @param int $gm False or 0 or 'server' = Return date to compare with server TZ, True or 1 to compare with GM date. * @return array year,month,week,first_day,first_month,first_year,prev_day,prev_month,prev_year */ function dol_get_first_day_week($day, $month, $year, $gm = false) @@ -566,28 +545,30 @@ $days = $start_week - $tmparray['wday']; if ($days >= 1) $days = 7 - $days; $days = abs($days); - $seconds = $days * 24 * 60 * 60; + $seconds = $days * 24 * 60 * 60; //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'
'; - //Get first day of week - $tmpdaytms = date($tmparray[0]) - $seconds; // $tmparray[0] is day of parameters + //Get first day of week + $tmpdaytms = date($tmparray[0]) - $seconds; // $tmparray[0] is day of parameters $tmpday = date("d", $tmpdaytms); //Check first day of week is in same month than current day or not if ($tmpday > $day) - { - $prev_month = $month - 1; + { + $prev_month = $month - 1; $prev_year = $year; - if ($prev_month == 0) - { - $prev_month = 12; - $prev_year = $year - 1; - } - } else { - $prev_month = $month; + if ($prev_month == 0) + { + $prev_month = 12; + $prev_year = $year - 1; + } + } + else + { + $prev_month = $month; $prev_year = $year; - } + } $tmpmonth = $prev_month; $tmpyear = $prev_year; @@ -595,48 +576,33 @@ $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0); $tmptime -= 24 * 60 * 60 * 7; $tmparray = dol_getdate($tmptime, true); - $prev_day = $tmparray['mday']; - - //Check prev day of week is in same month than first day or not + $prev_day = $tmparray['mday']; + + //Check prev day of week is in same month than first day or not if ($prev_day > $tmpday) - { - $prev_month = $month - 1; + { + $prev_month = $month - 1; $prev_year = $year; - if ($prev_month == 0) - { - $prev_month = 12; - $prev_year = $year - 1; - } - } - - $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm)); + if ($prev_month == 0) + { + $prev_month = 12; + $prev_year = $year - 1; + } + } + + $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm)); return array('year' => $year, 'month' => $month, 'week' => $week, 'first_day' => $tmpday, 'first_month' => $tmpmonth, 'first_year' => $tmpyear, 'prev_year' => $prev_year, 'prev_month' => $prev_month, 'prev_day' => $prev_day); } /** - * Return the easter day in GMT time. - * This function replaces easter_date() that returns a date in local TZ. - * - * @param int $year Year - * @return int GMT Date of easter day - */ -function getGMTEasterDatetime($year) -{ - $base = new DateTime("$year-03-21", new DateTimeZone("UTC")); - $days = easter_days($year); // Return number of days between 21 march and easter day. - $tmp = $base->add(new DateInterval("P{$days}D")); - return $tmp->getTimestamp(); -} - -/** * Return the number of non working days including saturday and sunday (or not) between 2 dates in timestamp. - * Dates must be UTC with hour, min, sec to 0. - * Called by function num_open_day() - * - * @param int $timestampStart Timestamp start (UTC with hour, min, sec = 0) - * @param int $timestampEnd Timestamp end (UTC with hour, min, sec = 0) + * Dates must be UTC with hour, day, min to 0. + * Called by function num_open_day + * + * @param int $timestampStart Timestamp de debut + * @param int $timestampEnd Timestamp de fin * @param string $country_code Country code * @param int $lastday Last day is included, 0: no, 1:yes * @param int $includesaturday Include saturday as non working day (-1=use setup, 0=no, 1=yes) @@ -649,32 +615,49 @@ global $db, $conf, $mysoc; $nbFerie = 0; + $specialdayrule = array(); // Check to ensure we use correct parameters - if ((($timestampEnd - $timestampStart) % 86400) != 0) return 'Error Dates must use same hours and must be GMT dates'; + if ((($timestampEnd - $timestampStart) % 86400) != 0) return 'ErrorDates must use same hours and must be GMT dates'; if (empty($country_code)) $country_code = $mysoc->country_code; if ($includesaturday < 0) $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1); if ($includesunday < 0) $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1); - $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid'); $i = 0; while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd)) - && ($i < 50000)) // Loop end when equals (Test on i is a security loop to avoid infinite loop) + && ($i < 50000)) // Loop end when equals (Test on i is a security loop to avoid infinite loop) { $ferie = false; - $specialdayrule = array(); - - $jour = gmdate("d", $timestampStart); - $mois = gmdate("m", $timestampStart); - $annee = gmdate("Y", $timestampStart); - - //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n"; - - // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed - // TODO Execute this request first and store results into an array, then reuse this array. + + $jour = date("d", $timestampStart); + $mois = date("m", $timestampStart); + $annee = date("Y", $timestampStart); + + // Check into var $conf->global->HOLIDAY_MORE_DAYS MM-DD,YYYY-MM-DD, ... + // Do not use this anymore, use instead the dictionary of public holidays. + if (!empty($conf->global->HOLIDAY_MORE_PUBLIC_HOLIDAYS)) + { + $arrayofdaystring = explode(',', $conf->global->HOLIDAY_MORE_PUBLIC_HOLIDAYS); + foreach ($arrayofdaystring as $daystring) + { + $tmp = explode('-', $daystring); + if ($tmp[2]) + { + if ($tmp[0] == $annee && $tmp[1] == $mois && $tmp[2] == $jour) $ferie = true; + } + else + { + if ($tmp[0] == $mois && $tmp[1] == $jour) $ferie = true; + } + } + } + + $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid'); + + // Loop on public holiday defined into hrm_public_holiday $sql = "SELECT code, entity, fk_country, dayrule, year, month, day, active"; $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday"; $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")"; @@ -691,7 +674,9 @@ if (!empty($obj->dayrule) && $obj->dayrule != 'date') // For example 'easter', '...' { $specialdayrule[$obj->dayrule] = $obj->dayrule; - } else { + } + else + { $match = 1; if (!empty($obj->year) && $obj->year != $annee) $match = 0; if ($obj->month != $mois) $match = 0; @@ -702,111 +687,145 @@ $i++; } - } else { + } + else + { dol_syslog($db->lasterror(), LOG_ERR); return 'Error sql '.$db->lasterror(); } - //var_dump($specialdayrule)."\n"; - //print "ferie=".$ferie."\n"; - - if (!$ferie) { - // Special dayrules - if (in_array('easter', $specialdayrule)) + + // Special dayrules + if (in_array('easter', $specialdayrule)) + { + // Calculation for easter date + $date_paques = easter_date($annee); + $jour_paques = date("d", $date_paques); + $mois_paques = date("m", $date_paques); + if ($jour_paques == $jour && $mois_paques == $mois) $ferie = true; + // Easter (sunday) + } + + if (in_array('eastermonday', $specialdayrule)) + { + // Calculation for the monday of easter date + $date_paques = easter_date($annee); + $date_lundi_paques = mktime( + date("H", $date_paques), + date("i", $date_paques), + date("s", $date_paques), + date("m", $date_paques), + date("d", $date_paques) + 1, + date("Y", $date_paques) + ); + $jour_lundi_ascension = date("d", $date_lundi_paques); + $mois_lundi_ascension = date("m", $date_lundi_paques); + if ($jour_lundi_ascension == $jour && $mois_lundi_ascension == $mois) $ferie = true; + // Easter (monday) + } + + if (in_array('ascension', $specialdayrule)) + { + // Calcul du jour de l'ascension (39 days after easter day) + $date_paques = easter_date($annee); + $date_ascension = mktime( + date("H", $date_paques), + date("i", $date_paques), + date("s", $date_paques), + date("m", $date_paques), + date("d", $date_paques) + 39, + date("Y", $date_paques) + ); + $jour_ascension = date("d", $date_ascension); + $mois_ascension = date("m", $date_ascension); + if ($jour_ascension == $jour && $mois_ascension == $mois) $ferie = true; + // Ascension (thursday) + } + + if (in_array('pentecote', $specialdayrule)) + { + // Calculation of "Pentecote" (49 days after easter day) + $date_paques = easter_date($annee); + $date_pentecote = mktime( + date("H", $date_paques), + date("i", $date_paques), + date("s", $date_paques), + date("m", $date_paques), + date("d", $date_paques) + 49, + date("Y", $date_paques) + ); + $jour_pentecote = date("d", $date_pentecote); + $mois_pentecote = date("m", $date_pentecote); + if ($jour_pentecote == $jour && $mois_pentecote == $mois) $ferie = true; + // "Pentecote" (sunday) + } + if (in_array('pentecotemonday', $specialdayrule)) + { + // Calculation of "Pentecote" (49 days after easter day) + $date_paques = easter_date($annee); + $date_pentecote = mktime( + date("H", $date_paques), + date("i", $date_paques), + date("s", $date_paques), + date("m", $date_paques), + date("d", $date_paques) + 50, + date("Y", $date_paques) + ); + $jour_pentecote = date("d", $date_pentecote); + $mois_pentecote = date("m", $date_pentecote); + if ($jour_pentecote == $jour && $mois_pentecote == $mois) $ferie = true; + // "Pentecote" (monday) + } + + if (in_array('viernessanto', $specialdayrule)) + { + // Viernes Santo + $date_paques = easter_date($annee); + $date_viernes = mktime( + date("H", $date_paques), + date("i", $date_paques), + date("s", $date_paques), + date("m", $date_paques), + date("d", $date_paques) - 2, + date("Y", $date_paques) + ); + $jour_viernes = date("d", $date_viernes); + $mois_viernes = date("m", $date_viernes); + if ($jour_viernes == $jour && $mois_viernes == $mois) $ferie = true; + //Viernes Santo + } + + if (in_array('fronleichnam', $specialdayrule)) + { + // Fronleichnam (60 days after easter sunday) + $date_paques = easter_date($annee); + $date_fronleichnam = mktime( + date("H", $date_paques), + date("i", $date_paques), + date("s", $date_paques), + date("m", $date_paques), + date("d", $date_paques) + 60, + date("Y", $date_paques) + ); + $jour_fronleichnam = date("d", $date_fronleichnam); + $mois_fronleichnam = date("m", $date_fronleichnam); + if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) $ferie = true; + // Fronleichnam + } + + // If we have to include saturday and sunday + if ($includesaturday || $includesunday) + { + $jour_julien = unixtojd($timestampStart); + $jour_semaine = jddayofweek($jour_julien, 0); + if ($includesaturday) //Saturday (6) and Sunday (0) { - // Calculation for easter date - $date_paques = getGMTEasterDatetime($annee); - $jour_paques = gmdate("d", $date_paques); - $mois_paques = gmdate("m", $date_paques); - if ($jour_paques == $jour && $mois_paques == $mois) $ferie = true; - // Easter (sunday) + if ($jour_semaine == 6) $ferie = true; } - - if (in_array('eastermonday', $specialdayrule)) + if ($includesunday) //Saturday (6) and Sunday (0) { - // Calculation for the monday of easter date - $date_paques = getGMTEasterDatetime($annee); - //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." "; - $date_lundi_paques = $date_paques + (3600 * 24); - $jour_lundi_paques = gmdate("d", $date_lundi_paques); - $mois_lundi_paques = gmdate("m", $date_lundi_paques); - if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) $ferie = true; - // Easter (monday) - //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n"; + if ($jour_semaine == 0) $ferie = true; } - - if (in_array('ascension', $specialdayrule)) - { - // Calcul du jour de l'ascension (39 days after easter day) - $date_paques = getGMTEasterDatetime($annee); - $date_ascension = $date_paques + (3600 * 24 * 39); - $jour_ascension = gmdate("d", $date_ascension); - $mois_ascension = gmdate("m", $date_ascension); - if ($jour_ascension == $jour && $mois_ascension == $mois) $ferie = true; - // Ascension (thursday) - } - - if (in_array('pentecote', $specialdayrule)) - { - // Calculation of "Pentecote" (49 days after easter day) - $date_paques = getGMTEasterDatetime($annee); - $date_pentecote = $date_paques + (3600 * 24 * 49); - $jour_pentecote = gmdate("d", $date_pentecote); - $mois_pentecote = gmdate("m", $date_pentecote); - if ($jour_pentecote == $jour && $mois_pentecote == $mois) $ferie = true; - // "Pentecote" (sunday) - } - if (in_array('pentecotemonday', $specialdayrule)) - { - // Calculation of "Pentecote" (49 days after easter day) - $date_paques = getGMTEasterDatetime($annee); - $date_pentecote = $date_paques + (3600 * 24 * 50); - $jour_pentecote = gmdate("d", $date_pentecote); - $mois_pentecote = gmdate("m", $date_pentecote); - if ($jour_pentecote == $jour && $mois_pentecote == $mois) $ferie = true; - // "Pentecote" (monday) - } - - if (in_array('viernessanto', $specialdayrule)) - { - // Viernes Santo - $date_paques = getGMTEasterDatetime($annee); - $date_viernes = $date_paques - (3600 * 24 * 2); - $jour_viernes = gmdate("d", $date_viernes); - $mois_viernes = gmdate("m", $date_viernes); - if ($jour_viernes == $jour && $mois_viernes == $mois) $ferie = true; - //Viernes Santo - } - - if (in_array('fronleichnam', $specialdayrule)) - { - // Fronleichnam (60 days after easter sunday) - $date_paques = getGMTEasterDatetime($annee); - $date_fronleichnam = $date_paques + (3600 * 24 * 60); - $jour_fronleichnam = gmdate("d", $date_fronleichnam); - $mois_fronleichnam = gmdate("m", $date_fronleichnam); - if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) $ferie = true; - // Fronleichnam - } - } - //print "ferie=".$ferie."\n"; - - // If we have to include saturday and sunday - if (!$ferie) { - if ($includesaturday || $includesunday) - { - $jour_julien = unixtojd($timestampStart); - $jour_semaine = jddayofweek($jour_julien, 0); - if ($includesaturday) //Saturday (6) and Sunday (0) - { - if ($jour_semaine == 6) $ferie = true; - } - if ($includesunday) //Saturday (6) and Sunday (0) - { - if ($jour_semaine == 0) $ferie = true; - } - } - } - //print "ferie=".$ferie."\n"; + } // We increase the counter of non working day if ($ferie) $nbFerie++; @@ -818,7 +837,6 @@ $i++; } - //print "nbFerie=".$nbFerie."\n"; return $nbFerie; } @@ -839,7 +857,9 @@ if ($lastday == 1) { $bit = 0; - } else { + } + else + { $bit = 1; } $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit; @@ -881,7 +901,8 @@ $nbOpenDay = ($numdays - $numholidays); if ($inhour == 1 && $nbOpenDay <= 3) $nbOpenDay = ($nbOpenDay * 24); return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday)); - } elseif ($timestampStart == $timestampEnd) + } + elseif ($timestampStart == $timestampEnd) { $numholidays = 0; if ($lastday) { @@ -889,11 +910,13 @@ if ($numholidays == 1) return 0; } - $nbOpenDay = $lastday; + $nbOpenDay=$lastday; if ($inhour == 1) $nbOpenDay = ($nbOpenDay * 24); return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday)); - } else { + } + else + { return $langs->trans("Error"); } } @@ -911,35 +934,35 @@ function monthArray($outputlangs, $short = 0) { $montharray = array( - 1 => $outputlangs->trans("Month01"), - 2 => $outputlangs->trans("Month02"), - 3 => $outputlangs->trans("Month03"), - 4 => $outputlangs->trans("Month04"), - 5 => $outputlangs->trans("Month05"), - 6 => $outputlangs->trans("Month06"), - 7 => $outputlangs->trans("Month07"), - 8 => $outputlangs->trans("Month08"), - 9 => $outputlangs->trans("Month09"), - 10 => $outputlangs->trans("Month10"), - 11 => $outputlangs->trans("Month11"), - 12 => $outputlangs->trans("Month12") - ); + 1 => $outputlangs->trans("Month01"), + 2 => $outputlangs->trans("Month02"), + 3 => $outputlangs->trans("Month03"), + 4 => $outputlangs->trans("Month04"), + 5 => $outputlangs->trans("Month05"), + 6 => $outputlangs->trans("Month06"), + 7 => $outputlangs->trans("Month07"), + 8 => $outputlangs->trans("Month08"), + 9 => $outputlangs->trans("Month09"), + 10 => $outputlangs->trans("Month10"), + 11 => $outputlangs->trans("Month11"), + 12 => $outputlangs->trans("Month12") + ); if (!empty($short)) { $montharray = array( - 1 => $outputlangs->trans("MonthShort01"), - 2 => $outputlangs->trans("MonthShort02"), - 3 => $outputlangs->trans("MonthShort03"), - 4 => $outputlangs->trans("MonthShort04"), - 5 => $outputlangs->trans("MonthShort05"), - 6 => $outputlangs->trans("MonthShort06"), - 7 => $outputlangs->trans("MonthShort07"), - 8 => $outputlangs->trans("MonthShort08"), - 9 => $outputlangs->trans("MonthShort09"), - 10 => $outputlangs->trans("MonthShort10"), - 11 => $outputlangs->trans("MonthShort11"), - 12 => $outputlangs->trans("MonthShort12") + 1 => $outputlangs->trans("MonthShort01"), + 2 => $outputlangs->trans("MonthShort02"), + 3 => $outputlangs->trans("MonthShort03"), + 4 => $outputlangs->trans("MonthShort04"), + 5 => $outputlangs->trans("MonthShort05"), + 6 => $outputlangs->trans("MonthShort06"), + 7 => $outputlangs->trans("MonthShort07"), + 8 => $outputlangs->trans("MonthShort08"), + 9 => $outputlangs->trans("MonthShort09"), + 10 => $outputlangs->trans("MonthShort10"), + 11 => $outputlangs->trans("MonthShort11"), + 12 => $outputlangs->trans("MonthShort12") ); } @@ -947,6 +970,7 @@ } /** * Return array of week numbers. + * * @param int $month Month number * @param int $year Year number @@ -964,6 +988,7 @@ } /** * Return array of first day of weeks. + * * @param array $TWeek array of week numbers * @param int $year Year number @@ -980,6 +1005,7 @@ } /** * Return array of last day of weeks. + * * @param array $TWeek array of week numbers * @param int $year Year number @@ -995,6 +1021,7 @@ } /** * Return week number. + * * @param int $day Day number * @param int $month Month number --- /tmp/dsg/dolibarr/htdocs/core/lib/github_doc.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_doc.lib.php @@ -75,7 +75,8 @@ $discount->fetch($line->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)' && $line->fk_remise_except) + } + elseif ($desc == '(DEPOSIT)' && $line->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); @@ -83,21 +84,27 @@ $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)' && $line->fk_remise_except) + } + elseif ($desc == '(EXCESS RECEIVED)' && $line->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived", $discount->ref_facture_source); - } elseif ($desc == '(EXCESS PAID)' && $line->fk_remise_except) + } + elseif ($desc == '(EXCESS PAID)' && $line->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid", $discount->ref_invoice_supplier_source); - } else { + } + else + { if ($idprod) { if (empty($hidedesc)) $libelleproduitservice = dol_concatdesc($libelleproduitservice, $desc); - } else { + } + else + { $libelleproduitservice = dol_concatdesc($libelleproduitservice, $desc); } } @@ -116,7 +123,9 @@ if ($prodser->isService()) { $prefix_prodserv = $outputlangs->transnoentitiesnoconv("Service")." "; - } else { + } + else + { $prefix_prodserv = $outputlangs->transnoentitiesnoconv("Product")." "; } } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_doleditor.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_doleditor.lib.php @@ -33,36 +33,36 @@ */ function show_skin($fuser, $edit = 0) { - global $conf, $langs, $db; - global $bc; + global $conf, $langs, $db; + global $bc; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; - $formother = new FormOther($db); + $formother = new FormOther($db); - $dirskins = array('/includes/ckeditor/ckeditor/skins'); - if (!empty($conf->modules_parts['theme'])) // Using this feature slow down application - { - foreach ($conf->modules_parts['theme'] as $reldir) - { - $dirskins = array_merge($dirskins, (array) ($reldir.'theme')); - } - } - $dirskins = array_unique($dirskins); + $dirskins = array('/includes/ckeditor/ckeditor/skins'); + if (!empty($conf->modules_parts['theme'])) // Using this feature slow down application + { + foreach ($conf->modules_parts['theme'] as $reldir) + { + $dirskins = array_merge($dirskins, (array) ($reldir.'theme')); + } + } + $dirskins = array_unique($dirskins); // Now dir_themes=array('/themes') or dir_themes=array('/theme','/mymodule/theme') - $selected_theme = ''; - if (empty($conf->global->FCKEDITOR_SKIN)) $selected_theme = 'moono-lisa'; - else $selected_theme = $conf->global->FCKEDITOR_SKIN; + $selected_theme = ''; + if (empty($conf->global->FCKEDITOR_SKIN)) $selected_theme = 'moono-lisa'; + else $selected_theme = $conf->global->FCKEDITOR_SKIN; - $colspan = 2; + $colspan = 2; - $thumbsbyrow = 6; - print ''; + $thumbsbyrow = 6; + print '
'; - $var = false; + $var = false; - // Title + // Title print ''; print ''; - // - print ''; + print ''; - print '
'.$langs->trans("DefaultSkin").''; $url = 'http://ckeditor.com/addons/skins/all'; @@ -81,51 +81,53 @@ print ''; print '
'; + // + print '
'; - print '
'; + print '
'; - $i = 0; - foreach ($dirskins as $dir) - { - //print $dirroot.$dir;exit; - $dirskin = dol_buildpath($dir, 0); // This include loop on $conf->file->dol_document_root - $urltheme = dol_buildpath($dir, 1); + $i = 0; + foreach ($dirskins as $dir) + { + //print $dirroot.$dir;exit; + $dirskin = dol_buildpath($dir, 0); // This include loop on $conf->file->dol_document_root + $urltheme = dol_buildpath($dir, 1); - if (is_dir($dirskin)) - { - $handle = opendir($dirskin); - if (is_resource($handle)) - { - while (($subdir = readdir($handle)) !== false) - { - if (is_dir($dirskin."/".$subdir) && substr($subdir, 0, 1) <> '.' - && substr($subdir, 0, 3) <> 'CVS' && !preg_match('/common|phones/i', $subdir)) - { - // Disable not stable themes (dir ends with _exp or _dev) - if ($conf->global->MAIN_FEATURES_LEVEL < 2 && preg_match('/_dev$/i', $subdir)) continue; - if ($conf->global->MAIN_FEATURES_LEVEL < 1 && preg_match('/_exp$/i', $subdir)) continue; + if (is_dir($dirskin)) + { + $handle = opendir($dirskin); + if (is_resource($handle)) + { + while (($subdir = readdir($handle)) !== false) + { + if (is_dir($dirskin."/".$subdir) && substr($subdir, 0, 1) <> '.' + && substr($subdir, 0, 3) <> 'CVS' && !preg_match('/common|phones/i', $subdir)) + { + // Disable not stable themes (dir ends with _exp or _dev) + if ($conf->global->MAIN_FEATURES_LEVEL < 2 && preg_match('/_dev$/i', $subdir)) continue; + if ($conf->global->MAIN_FEATURES_LEVEL < 1 && preg_match('/_exp$/i', $subdir)) continue; - print '
'; - if ($subdir == $selected_theme) - { - print ' '.$subdir.''; - } else { - print ' '.$subdir; - } + print '
'; + if ($subdir == $selected_theme) + { + print ' '.$subdir.''; + } + else + { + print ' '.$subdir; + } print '
'; - $i++; - } - } - } - } - } + $i++; + } + } + } + } + } - print '
'; + print '
'; - print '
'; + print ''; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_donation.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_donation.lib.php @@ -46,7 +46,7 @@ $head[$h][0] = DOL_URL_ROOT.'/don/admin/donation_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes'; + $head[$h][2] = 'attributes'; $h++; complete_head_from_modules($conf, $langs, null, $head, $h, 'donation_admin', 'remove'); @@ -79,10 +79,10 @@ complete_head_from_modules($conf, $langs, $object, $head, $h, 'donation'); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $upload_dir = $conf->don->dir_output.'/'.dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/don/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_ecm.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_ecm.lib.php @@ -84,7 +84,9 @@ $head[$h][1] = $langs->trans("Directory"); $head[$h][2] = 'card'; $h++; - } else { + } + else + { $head[$h][0] = DOL_URL_ROOT.'/ecm/dir_card.php?section='.$section.'&module='.$module; $head[$h][1] = $langs->trans("Directory"); $head[$h][2] = 'card'; @@ -138,38 +140,3 @@ return $head; } - -/** - * Return array head with list of tabs to view object informations. - * - * @return array head array with tabs - */ -function ecm_admin_prepare_head() -{ - global $langs, $conf; - $langs->load("ecm"); - - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT."/admin/ecm.php"; - $head[$h][1] = $langs->trans("Setup"); - $head[$h][2] = 'ecm'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_files_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsEcmFiles"); - $head[$h][2] = 'attributes_ecm_files'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_directories_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsEcmDirectories"); - $head[$h][2] = 'attributes_ecm_directories'; - $h++; - - complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin'); - - complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin', 'remove'); - - return $head; -} --- /tmp/dsg/dolibarr/htdocs/core/lib/github_emailing.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_emailing.lib.php @@ -41,11 +41,11 @@ if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->mailing->mailing_advance->recipient)) { - $head[$h][0] = DOL_URL_ROOT."/comm/mailing/cibles.php?id=".$object->id; - $head[$h][1] = $langs->trans("MailRecipients"); + $head[$h][0] = DOL_URL_ROOT."/comm/mailing/cibles.php?id=".$object->id; + $head[$h][1] = $langs->trans("MailRecipients"); if ($object->nbemail > 0) $head[$h][1] .= ''.$object->nbemail.''; - $head[$h][2] = 'targets'; - $h++; + $head[$h][2] = 'targets'; + $h++; } if (!empty($conf->global->EMAILING_USE_ADVANCED_SELECTOR)) --- /tmp/dsg/dolibarr/htdocs/core/lib/github_expedition.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_expedition.lib.php @@ -51,18 +51,17 @@ $hselected = $h; $h++; - if (!empty($conf->global->MAIN_SUBMODULE_DELIVERY)) + if (!empty($conf->global->MAIN_SUBMODULE_LIVRAISON)) { - $head[$h][0] = DOL_URL_ROOT."/admin/delivery.php"; + $head[$h][0] = DOL_URL_ROOT."/admin/livraison.php"; $head[$h][1] = $langs->trans("Receivings"); $h++; } - complete_head_from_modules($conf, $langs, $object, $head, $h, 'order'); - complete_head_from_modules($conf, $langs, $object, $head, $h, 'order', 'remove'); + complete_head_from_modules($conf, $langs, $object, $head, $h, 'order', 'remove'); - return $head; + return $head; } /** @@ -95,45 +94,45 @@ if (!empty($conf->global->MAIN_SUBMODULE_EXPEDITION)) { - $head[$h][0] = DOL_URL_ROOT.'/admin/expedition_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes_shipment'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/expedition_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFields"); + $head[$h][2] = 'attributes_shipment'; + $h++; } if (!empty($conf->global->MAIN_SUBMODULE_EXPEDITION)) { - $head[$h][0] = DOL_URL_ROOT.'/admin/expeditiondet_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsLines"); - $head[$h][2] = 'attributeslines_shipment'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/expeditiondet_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsLines"); + $head[$h][2] = 'attributeslines_shipment'; + $h++; } - if (!empty($conf->global->MAIN_SUBMODULE_DELIVERY)) + if (!empty($conf->global->MAIN_SUBMODULE_LIVRAISON)) { - $head[$h][0] = DOL_URL_ROOT."/admin/delivery.php"; + $head[$h][0] = DOL_URL_ROOT."/admin/livraison.php"; $head[$h][1] = $langs->trans("Receivings"); $head[$h][2] = 'receivings'; $h++; } - if (!empty($conf->global->MAIN_SUBMODULE_DELIVERY)) + if (!empty($conf->global->MAIN_SUBMODULE_LIVRAISON)) { - $head[$h][0] = DOL_URL_ROOT.'/admin/delivery_extrafields.php'; + $head[$h][0] = DOL_URL_ROOT.'/admin/livraison_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFields"); $head[$h][2] = 'attributes_receivings'; $h++; } - if (!empty($conf->global->MAIN_SUBMODULE_DELIVERY)) + if (!empty($conf->global->MAIN_SUBMODULE_LIVRAISON)) { - $head[$h][0] = DOL_URL_ROOT.'/admin/deliverydet_extrafields.php'; + $head[$h][0] = DOL_URL_ROOT.'/admin/livraisondet_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFieldsLines"); $head[$h][2] = 'attributeslines_receivings'; $h++; } - complete_head_from_modules($conf, $langs, null, $head, $h, 'expedition_admin'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'expedition_admin', 'remove'); --- /tmp/dsg/dolibarr/htdocs/core/lib/github_expensereport.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_expensereport.lib.php @@ -41,15 +41,15 @@ // Show more tabs from modules // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'expensereport'); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/expensereport/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; @@ -58,14 +58,14 @@ if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/expensereport/note.php?id='.$object->id; - $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; - $head[$h][2] = 'note'; - $h++; + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; + if (!empty($object->note_public)) $nbNote++; + $head[$h][0] = DOL_URL_ROOT.'/expensereport/note.php?id='.$object->id; + $head[$h][1] = $langs->trans('Notes'); + if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + $head[$h][2] = 'note'; + $h++; } $head[$h][0] = DOL_URL_ROOT.'/expensereport/info.php?id='.$object->id; @@ -94,15 +94,15 @@ $head = array(); $head[$h][0] = DOL_URL_ROOT.'/expensereport/payment/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("ExpenseReportPayment"); + $head[$h][1] = $langs->trans("ExpenseReport"); $head[$h][2] = 'payment'; $h++; - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment_expensereport'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment_expensereport'); $head[$h][0] = DOL_URL_ROOT.'/expensereport/payment/info.php?id='.$object->id; $head[$h][1] = $langs->trans("Info"); @@ -133,19 +133,19 @@ $head[$h][2] = 'expensereport'; $h++; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) + { + $head[$h][0] = DOL_URL_ROOT."/admin/expensereport_ik.php"; + $head[$h][1] = $langs->trans("ExpenseReportsIk"); + $head[$h][2] = 'expenseik'; + $h++; + } + if (!empty($conf->global->MAIN_USE_EXPENSE_RULE)) { $head[$h][0] = DOL_URL_ROOT."/admin/expensereport_rules.php"; $head[$h][1] = $langs->trans("ExpenseReportsRules"); $head[$h][2] = 'expenserules'; - $h++; - } - - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) - { - $head[$h][0] = DOL_URL_ROOT."/admin/expensereport_ik.php"; - $head[$h][1] = $langs->trans("ExpenseReportsIk"); - $head[$h][2] = 'expenseik'; $h++; } @@ -157,10 +157,10 @@ $head[$h][0] = DOL_URL_ROOT.'/admin/expensereport_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes'; - $h++; + $head[$h][2] = 'attributes'; + $h++; - /* + /* $head[$h][0] = DOL_URL_ROOT.'/fichinter/admin/fichinterdet_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFieldsLines"); $head[$h][2] = 'attributesdet'; @@ -169,5 +169,5 @@ complete_head_from_modules($conf, $langs, null, $head, $h, 'expensereport_admin', 'remove'); - return $head; + return $head; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_fichinter.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_fichinter.lib.php @@ -48,19 +48,19 @@ 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.'/fichinter/contact.php?id='.$object->id; + $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT.'/fichinter/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('InterventionContact'); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; $head[$h][2] = 'contact'; $h++; } - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'intervention'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'intervention'); // Tab to link resources if ($conf->resource->enabled) @@ -88,37 +88,37 @@ $h++; } - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; if (!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/fichinter/note.php?id='.$object->id; - $head[$h][1] = $langs->trans('Notes'); + $head[$h][0] = DOL_URL_ROOT.'/fichinter/note.php?id='.$object->id; + $head[$h][1] = $langs->trans('Notes'); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; - $head[$h][2] = 'note'; - $h++; - } + $head[$h][2] = 'note'; + $h++; + } require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $upload_dir = $conf->ficheinter->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/fichinter/document.php?id='.$object->id; $head[$h][1] = $langs->trans("Documents"); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; $head[$h][2] = 'documents'; $h++; - $head[$h][0] = DOL_URL_ROOT.'/fichinter/info.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/fichinter/info.php?id='.$object->id; $head[$h][1] = $langs->trans('Info'); $head[$h][2] = 'info'; $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'intervention', 'remove'); + complete_head_from_modules($conf, $langs, $object, $head, $h, 'intervention', 'remove'); - return $head; + return $head; } /** @@ -148,13 +148,13 @@ $head[$h][0] = DOL_URL_ROOT.'/fichinter/admin/fichinter_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes'; - $h++; + $head[$h][2] = 'attributes'; + $h++; $head[$h][0] = DOL_URL_ROOT.'/fichinter/admin/fichinterdet_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFieldsLines"); - $head[$h][2] = 'attributesdet'; - $h++; + $head[$h][2] = 'attributesdet'; + $h++; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_files.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_files.lib.php @@ -118,7 +118,8 @@ if (is_array($excludefilter)) { $excludefilterarray = array_merge($excludefilterarray, $excludefilter); - } elseif ($excludefilter) $excludefilterarray[] = $excludefilter; + } + elseif ($excludefilter) $excludefilterarray[] = $excludefilter; // Check if file is qualified foreach ($excludefilterarray as $filt) { @@ -142,7 +143,6 @@ if (!$filter || preg_match('/'.$filter.'/i', $file)) // We do not search key $filter into all $path, only into $file part { - $reg = array(); preg_match('/([^\/]+)\/[^\/]+$/', $path.'/'.$file, $reg); $level1name = (isset($reg[1]) ? $reg[1] : ''); $file_list[] = array( @@ -167,7 +167,8 @@ $file_list = array_merge($file_list, dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename != '' ? $relativename.'/' : '').$file, $donotfollowsymlinks)); } } - } elseif (!$isdir && (($types == "files") || ($types == "all"))) + } + elseif (!$isdir && (($types == "files") || ($types == "all"))) { // Add file into file_list array if ($loaddate || $sortcriteria == 'date') $filedate = dol_filemtime($path."/".$file); @@ -224,16 +225,12 @@ { global $conf, $db; - $sql = " SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams,"; - $sql .= " date_c, tms as date_m, fk_user_c, fk_user_m, acl, position, share"; + $sql = " SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m,"; + $sql .= " acl, position, share"; if ($mode) $sql .= ", description"; $sql .= " FROM ".MAIN_DB_PREFIX."ecm_files"; - $sql .= " WHERE entity = ".$conf->entity; - if (preg_match('/%$/', $path)) { - $sql .= " AND filepath LIKE '".$db->escape($path)."'"; - } else { - $sql .= " AND filepath = '".$db->escape($path)."'"; - } + $sql .= " WHERE filepath = '".$db->escape($path)."'"; + $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); if ($resql) @@ -246,7 +243,6 @@ $obj = $db->fetch_object($resql); if ($obj) { - $reg = array(); preg_match('/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename, $reg); $level1name = (isset($reg[1]) ? $reg[1] : ''); $file_list[] = array( @@ -283,7 +279,9 @@ } return $file_list; - } else { + } + else + { dol_print_error($db); return array(); } @@ -294,7 +292,7 @@ * Complete $filearray with data from database. * This will call doldir_list_indatabase to complate filearray. * - * @param array $filearray Array of files obtained using dol_dir_list + * @param array $filearray Array of files get using dol_dir_list * @param string $relativedir Relative dir from DOL_DATA_ROOT * @return void */ @@ -320,19 +318,19 @@ } } - /*var_dump($relativedir); - var_dump($filearray); - var_dump($filearrayindatabase);*/ + //var_dump($filearray); + //var_dump($filearrayindatabase); // Complete filearray with properties found into $filearrayindatabase foreach ($filearray as $key => $val) { $tmpfilename = preg_replace('/\.noexe$/', '', $filearray[$key]['name']); + $found = 0; // Search if it exists into $filearrayindatabase foreach ($filearrayindatabase as $key2 => $val2) { - if (($filearrayindatabase[$key2]['path'] == $filearray[$key]['path']) && ($filearrayindatabase[$key2]['name'] == $tmpfilename)) + if ($filearrayindatabase[$key2]['name'] == $tmpfilename) { $filearray[$key]['position_name'] = ($filearrayindatabase[$key2]['position'] ? $filearrayindatabase[$key2]['position'] : '0').'_'.$filearrayindatabase[$key2]['name']; $filearray[$key]['position'] = $filearrayindatabase[$key2]['position']; @@ -353,7 +351,6 @@ $filearray[$key]['acl'] = ''; $rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filearray[$key]['fullname']); - if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filename)) // If not a tmp file { dol_syslog("list_of_documents We found a file called '".$filearray[$key]['name']."' not indexed into database. We add it"); @@ -377,15 +374,20 @@ if ($result < 0) { setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } else { + } + else + { $filearray[$key]['rowid'] = $result; } - } else { + } + else + { $filearray[$key]['rowid'] = 0; // Should not happened } } } - //var_dump($filearray); var_dump($relativedir.' - tmpfilename='.$tmpfilename.' - found='.$found); + + /*var_dump($filearray);*/ } @@ -403,7 +405,8 @@ $sortorder = strtoupper($sortorder); - if ($sortorder == 'ASC') { $retup = -1; $retdown = 1; } else { $retup = 1; $retdown = -1; } + if ($sortorder == 'ASC') { $retup = -1; $retdown = 1; } + else { $retup = 1; $retdown = -1; } if ($sortfield == 'name') { @@ -511,7 +514,9 @@ if ($folder_content == "...") return true; else return false; - } else return true; // Dir does not exists + } + else + return true; // Dir does not exists } /** @@ -537,7 +542,9 @@ if (!$line === false) $nb++; } fclose($fp); - } else { + } + else + { $nb = -1; } @@ -620,7 +627,9 @@ if (empty($arrayreplacementisregex)) { $content = make_substitutions($content, $arrayreplacement, null); - } else { + } + else + { foreach ($arrayreplacement as $key => $value) { $content = preg_replace($key, $value, $content); @@ -766,7 +775,9 @@ //var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists"); $tmpresult = dolCopyDir($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists, $arrayreplacement, $excludesubdir); } - } else { + } + else + { $newfile = $file; // Replace destination filename with a new one if (is_array($arrayreplacement)) @@ -782,14 +793,18 @@ if ($result > 0 && $tmpresult >= 0) { // Do nothing, so we don't set result to 0 if tmpresult is 0 and result was success in a previous pass - } else { + } + else + { $result = $tmpresult; } if ($result < 0) break; } } closedir($dir_handle); - } else { + } + else + { // Source directory does not exists $result = -2; } @@ -855,7 +870,8 @@ // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions. dol_delete_file($destfile); $result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ - } else dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING); + } + else dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING); } // Move ok @@ -893,7 +909,8 @@ $ecmfile->filename = $filename; $resultecm = $ecmfile->update($user); - } elseif ($resultecm == 0) // If no entry were found for src files, create/update target file + } + elseif ($resultecm == 0) // If no entry were found for src files, create/update target file { $filename = basename($rel_filetorenameafter); $rel_dir = dirname($rel_filetorenameafter); @@ -912,7 +929,8 @@ { setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); } - } elseif ($resultecm < 0) + } + elseif ($resultecm < 0) { setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); } @@ -964,11 +982,11 @@ if (!class_exists('AntiVir')) { require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php'; } - $antivir = new AntiVir($db); + $antivir=new AntiVir($db); $result = $antivir->dol_avscan_file($src_file); if ($result < 0) // If virus or error, we stop here { - $reterrors = $antivir->errors; + $reterrors=$antivir->errors; return $reterrors; } } @@ -1055,7 +1073,7 @@ { // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too. $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity]; - if (!preg_match('/\/$/', $publicmediasdirwithslash)) $publicmediasdirwithslash .= '/'; + if (! preg_match('/\/$/', $publicmediasdirwithslash)) $publicmediasdirwithslash.='/'; if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory $file_name .= '.noexe'; @@ -1080,11 +1098,14 @@ } } - if ($reshook < 0) { // At least one blocking error returned by one hook + if ($reshook < 0) // At least one blocking error returned by one hook + { $errmsg = join(',', $hookmanager->errors); if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks'; // Should not occurs. Added if hook is bugged and does not set ->errors when there is error. return $errmsg; - } elseif (empty($reshook)) { + } + elseif (empty($reshook)) + { // The file functions must be in OS filesystem encoding. $src_file_osencoded = dol_osencode($src_file); $file_name_osencoded = dol_osencode($file_name); @@ -1104,11 +1125,6 @@ dol_syslog("Files.lib::dol_move_uploaded_file File ".$file_name." already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING); return 'ErrorFileAlreadyExists'; } - } else { // We are allowed to erase - if (is_dir($file_name_osencoded)) { // If there is a directory with name of file to create - dol_syslog("Files.lib::dol_move_uploaded_file A directory with name ".$file_name." already exists. Return 'ErrorDirWithFileNameAlreadyExists'", LOG_WARNING); - return 'ErrorDirWithFileNameAlreadyExists'; - } } // Move file @@ -1118,7 +1134,9 @@ if (!empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK)); dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG); return $successcode; // Success - } else { + } + else + { dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR); return -3; // Unknown error } @@ -1159,7 +1177,6 @@ return false; } - $reshook = 0; if (empty($nohook)) { $hookmanager->initHooks(array('fileslib')); @@ -1173,12 +1190,14 @@ $reshook = $hookmanager->executeHooks('deleteFile', $parameters, $object); } - if (empty($nohook) && $reshook != 0) // reshook = 0 to do standard actions, 1 = ok and replace, -1 = ko - { - dol_syslog("reshook=".$reshook); + if (empty($nohook) && $reshook != 0) // reshook = 0 to do standard actions, 1 = ok, -1 = ko + { if ($reshook < 0) return false; return true; - } else { + } + else + { + //print "x".$file." ".$disableglob;exit; $file_osencoded = dol_osencode($file); // New filename encoded in OS filesystem encoding charset if (empty($disableglob) && !empty($file_osencoded)) { @@ -1192,16 +1211,6 @@ { if ($nophperrors) $ok = @unlink($filename); else $ok = unlink($filename); - - // If it fails and it is because of the missing write permission on parent dir - if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) { - dol_syslog("Error in deletion, but parent directory exists with no permission to write, we try to change permission on parent directory and retry...", LOG_DEBUG); - @chmod(dirname($filename), fileperms(dirname($filename)) | 0200); - // Now we retry deletion - if ($nophperrors) $ok = @unlink($filename); - else $ok = unlink($filename); - } - if ($ok) { dol_syslog("Removed file ".$filename, LOG_DEBUG); @@ -1229,16 +1238,19 @@ } } } - } else { + } + else + { dol_syslog("Failed to remove file ".$filename, LOG_WARNING); // TODO Failure to remove can be because file was already removed or because of permission // If error because it does not exists, we should return true, and we should return false if this is a permission problem } } - } else { - dol_syslog("No files to delete found", LOG_DEBUG); - } - } else { + } + else dol_syslog("No files to delete found", LOG_DEBUG); + } + else + { $ok = false; if ($nophperrors) $ok = @unlink($file_osencoded); else $ok = unlink($file_osencoded); @@ -1300,7 +1312,9 @@ if (is_dir(dol_osencode("$dir/$item")) && !is_link(dol_osencode("$dir/$item"))) { $count = dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted); - } else { + } + else + { $result = dol_delete_file("$dir/$item", 1, $nophperrors); $count++; if ($result) $countdeleted++; @@ -1380,7 +1394,9 @@ $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewold); return 0; } - } else { + } + else + { $multiple = $filepreviewold."."; for ($i = 0; $i < 20; $i++) { @@ -1468,7 +1484,9 @@ @chmod($file, octdec($conf->global->MAIN_UMASK)); return 1; - } else { + } + else + { dol_syslog('FailedToDetectDirInDolMetaCreateFor'.$object->element, LOG_WARNING); } @@ -1521,11 +1539,9 @@ * @param string $link Link to add (to add a link instead of a file) * @param string $trackid Track id (used to prefix name of session vars to avoid conflict) * @param int $generatethumbs 1=Generate also thumbs for uploaded image files - * @param Object $object Object used to set 'src_object_*' fields * @return int <=0 if KO, >0 if OK - * @see dol_remove_file_process() - */ -function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles = 'addedfile', $savingdocmask = '', $link = null, $trackid = '', $generatethumbs = 1, $object = null) + */ +function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles = 'addedfile', $savingdocmask = '', $link = null, $trackid = '', $generatethumbs = 1) { global $db, $user, $conf, $langs; @@ -1550,8 +1566,6 @@ $nbok = 0; for ($i = 0; $i < $nbfile; $i++) { - if (empty($TFile['name'][$i])) continue; // For example, when submitting a form with no file name - // Define $destfull (path to file including filename) and $destfile (only filename) $destfull = $upload_dir."/".$TFile['name'][$i]; $destfile = $TFile['name'][$i]; @@ -1578,7 +1592,7 @@ $destfile = dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : '')); // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because - // this function is also applied when we rename and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call). + // this function is also applied when we make try to download file (by the GETPOST(filename, 'alphanohtml') call). $destfile = dol_string_nohtmltag($destfile); $destfull = dol_string_nohtmltag($destfull); @@ -1619,27 +1633,32 @@ // Update index table of files (llx_ecm_files) if ($donotupdatesession == 1) { - $result = addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ? '.noexe' : ''), $TFile['name'][$i], 'uploaded', 0, $object); + $result = addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ? '.noexe' : ''), $TFile['name'][$i], 'uploaded', 0); if ($result < 0) { if ($allowoverwrite) { // Do not show error message. We can have an error due to DB_ERROR_RECORD_ALREADY_EXISTS - } else { + } + else { setEventMessages('WarningFailedToAddFileIntoDatabaseIndex', '', 'warnings'); } } } $nbok++; - } else { + } + else + { $langs->load("errors"); if ($resupload < 0) // Unknown error { setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors'); - } elseif (preg_match('/ErrorFileIsInfectedWithAVirus/', $resupload)) // Files infected by a virus + } + elseif (preg_match('/ErrorFileIsInfectedWithAVirus/', $resupload)) // Files infected by a virus { setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors'); - } else // Known error + } + else // Known error { setEventMessages($langs->trans($resupload), null, 'errors'); } @@ -1666,7 +1685,9 @@ } else { setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors'); } - } else { + } + else + { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors'); } @@ -1684,7 +1705,6 @@ * @param int $donotdeletefile 1=Do not delete physically file * @param string $trackid Track id (used to prefix name of session vars to avoid conflict) * @return void - * @see dol_add_file_process() */ function dol_remove_file_process($filenb, $donotupdatesession = 0, $donotdeletefile = 1, $trackid = '') { @@ -1736,10 +1756,9 @@ * @param string $fullpathorig Full path of origin for file (can be '') * @param string $mode How file was created ('uploaded', 'generated', ...) * @param int $setsharekey Set also the share key - * @param Object $object Object used to set 'src_object_*' fields * @return int <0 if KO, 0 if nothing done, >0 if OK */ -function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uploaded', $setsharekey = 0, $object = null) +function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uploaded', $setsharekey = 0) { global $db, $user; @@ -1762,12 +1781,6 @@ $ecmfile->gen_or_uploaded = $mode; $ecmfile->description = ''; // indexed content $ecmfile->keyword = ''; // keyword content - - if (is_object($object) && $object->id > 0) { - $ecmfile->src_object_id = $object->id; - $ecmfile->src_object_type = $object->table_element; - } - if ($setsharekey) { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; @@ -1877,22 +1890,31 @@ { try { $ret = $image->writeImages($fileoutput, true); - } catch (Exception $e) + } + catch (Exception $e) { dol_syslog($e->getMessage(), LOG_WARNING); } - } else { + } + else + { dol_syslog("Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR); } if ($ret) return $count; else return -3; - } else { + } + else + { return -2; } - } else { + } + else + { return -1; } - } else { + } + else + { return 0; } } @@ -1914,11 +1936,14 @@ $foundhandler = 0; - try { + try + { dol_syslog("dol_compress_file mode=".$mode." inputfile=".$inputfile." outputfile=".$outputfile); $data = implode("", file(dol_osencode($inputfile))); - if ($mode == 'gz') { $foundhandler = 1; $compressdata = gzencode($data, 9); } elseif ($mode == 'bz') { $foundhandler = 1; $compressdata = bzcompress($data, 9); } elseif ($mode == 'zip') + if ($mode == 'gz') { $foundhandler = 1; $compressdata = gzencode($data, 9); } + elseif ($mode == 'bz') { $foundhandler = 1; $compressdata = bzcompress($data, 9); } + elseif ($mode == 'zip') { if (class_exists('ZipArchive') && !empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS)) { @@ -1990,7 +2015,9 @@ $errorstring = "dol_compress_file error archive->errorCode = ".$archive->errorCode()." errormsg=".$errormsg; dol_syslog("dol_compress_file failure - ".$errormsg, LOG_ERR); return -3; - } else { + } + else + { dol_syslog("dol_compress_file success - ".count($result)." files"); return 1; } @@ -2003,7 +2030,9 @@ fwrite($fp, $compressdata); fclose($fp); return 1; - } else { + } + else + { $errorstring = "Try to zip with format ".$mode." with no handler for this format"; dol_syslog($errorstring, LOG_ERR); @@ -2011,7 +2040,8 @@ $errormsg = $errorstring; return -2; } - } catch (Exception $e) + } + catch (Exception $e) { global $langs, $errormsg; $langs->load("errors"); @@ -2039,12 +2069,11 @@ dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir); include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php'; $archive = new PclZip($inputfile); - - // Extract into outputdir, but only files that match the regex '/^((?!\.\.).)*$/' that means "does not include .." - $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir, PCLZIP_OPT_BY_PREG, '/^((?!\.\.).)*$/'); - + $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir); + //var_dump($result); if (!is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true)); - else { + else + { $ok = 1; $errmsg = ''; // Loop on each file to check result for unzipping file foreach ($result as $key => $val) @@ -2063,29 +2092,19 @@ } } - if (class_exists('ZipArchive')) // Must install php-zip to have it + if (class_exists('ZipArchive')) { dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir); $zip = new ZipArchive; $res = $zip->open($inputfile); if ($res === true) { - //$zip->extractTo($outputdir.'/'); - // We must extract one file at time so we can check that file name does not contains '..' to avoid transversal path of zip built for example using - // python3 path_traversal_archiver.py test.zip -l 10 -p tmp/ - // with -l is the range of dot to go back in path. - // and path_traversal_archiver.py found at https://github.com/Alamot/code-snippets/blob/master/path_traversal/path_traversal_archiver.py - for ($i = 0; $i < $zip->numFiles; $i++) { - if (preg_match('/\.\./', $zip->getNameIndex($i))) { - dol_syslog("Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING); - continue; // Discard the file - } - $zip->extractTo($outputdir.'/', array($zip->getNameIndex($i))); - } - + $zip->extractTo($outputdir.'/'); $zip->close(); return array(); - } else { + } + else + { return array('error'=>'ErrUnzipFails'); } } @@ -2118,8 +2137,11 @@ return -3; } - try { - if ($mode == 'gz') { $foundhandler = 0; } elseif ($mode == 'bz') { $foundhandler = 0; } elseif ($mode == 'zip') + try + { + if ($mode == 'gz') { $foundhandler = 0; } + elseif ($mode == 'bz') { $foundhandler = 0; } + elseif ($mode == 'zip') { /*if (defined('ODTPHP_PATHTOPCLZIP')) { @@ -2183,10 +2205,13 @@ { dol_syslog("Try to zip with format ".$mode." with no handler for this format", LOG_ERR); return -2; - } else { + } + else + { return 0; } - } catch (Exception $e) + } + catch (Exception $e) { global $langs, $errormsg; $langs->load("errors"); @@ -2243,7 +2268,7 @@ // Fix modulepart if ($modulepart == 'users') $modulepart = 'user'; - dol_syslog('dol_check_secure_access_document modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity); + dol_syslog('modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity); // We define $accessallowed and $sqlprotectagainstexternals $accessallowed = 0; @@ -2266,22 +2291,20 @@ if (empty($entity) || empty($conf->medias->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); $accessallowed = 1; $original_file = $conf->medias->multidir_output[$entity].'/'.$original_file; - } // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log + } + // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root)) { $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file))); $original_file = $dolibarr_main_data_root.'/'.$original_file; - } // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log - elseif ($modulepart == 'doctemplates' && !empty($dolibarr_main_data_root)) - { - $accessallowed = $user->admin; - $original_file = $dolibarr_main_data_root.'/doctemplates/'.$original_file; - } // Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip + } + // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log elseif ($modulepart == 'doctemplateswebsite' && !empty($dolibarr_main_data_root)) { $accessallowed = ($fuser->rights->website->write && preg_match('/\.jpg$/i', basename($original_file))); $original_file = $dolibarr_main_data_root.'/doctemplates/websites/'.$original_file; - } // Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip + } + // Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root)) { // Dir for custom dirs @@ -2290,169 +2313,203 @@ $accessallowed = ($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file))); $original_file = $dirins.'/'.$original_file; - } // Wrapping for some images + } + // Wrapping for some images elseif ($modulepart == 'mycompany' && !empty($conf->mycompany->dir_output)) { $accessallowed = 1; $original_file = $conf->mycompany->dir_output.'/'.$original_file; - } // Wrapping for users photos + } + // Wrapping for users photos elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output)) { $accessallowed = 1; $original_file = $conf->user->dir_output.'/'.$original_file; - } // Wrapping for members photos + } + // Wrapping for members photos elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output)) { $accessallowed = 1; $original_file = $conf->adherent->dir_output.'/'.$original_file; - } // Wrapping pour les apercu factures + } + // Wrapping pour les apercu factures elseif ($modulepart == 'apercufacture' && !empty($conf->facture->multidir_output[$entity])) { if ($fuser->rights->facture->{$lire}) $accessallowed = 1; $original_file = $conf->facture->multidir_output[$entity].'/'.$original_file; - } // Wrapping pour les apercu propal + } + // Wrapping pour les apercu propal elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity])) { if ($fuser->rights->propale->{$lire}) $accessallowed = 1; $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file; - } // Wrapping pour les apercu commande + } + // Wrapping pour les apercu commande elseif ($modulepart == 'apercucommande' && !empty($conf->commande->multidir_output[$entity])) { if ($fuser->rights->commande->{$lire}) $accessallowed = 1; $original_file = $conf->commande->multidir_output[$entity].'/'.$original_file; - } // Wrapping pour les apercu intervention + } + // Wrapping pour les apercu intervention elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output)) { if ($fuser->rights->ficheinter->{$lire}) $accessallowed = 1; $original_file = $conf->ficheinter->dir_output.'/'.$original_file; - } // Wrapping pour les apercu conat - elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->multidir_output[$entity])) + } + // Wrapping pour les apercu conat + elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->dir_output)) { if ($fuser->rights->contrat->{$lire}) $accessallowed = 1; - $original_file = $conf->contrat->multidir_output[$entity].'/'.$original_file; - } // Wrapping pour les apercu supplier proposal + $original_file = $conf->contrat->dir_output.'/'.$original_file; + } + // Wrapping pour les apercu supplier proposal elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output)) { if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed = 1; $original_file = $conf->supplier_proposal->dir_output.'/'.$original_file; - } // Wrapping pour les apercu supplier order + } + // Wrapping pour les apercu supplier order elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output)) { if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed = 1; $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file; - } // Wrapping pour les apercu supplier invoice + } + // Wrapping pour les apercu supplier invoice elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output)) { if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed = 1; $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file; - } // Wrapping pour les apercu supplier invoice + } + // Wrapping pour les apercu supplier invoice elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output)) { if ($fuser->rights->expensereport->{$lire}) $accessallowed = 1; $original_file = $conf->expensereport->dir_output.'/'.$original_file; - } // Wrapping pour les images des stats propales + } + // Wrapping pour les images des stats propales elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity])) { if ($fuser->rights->propale->{$lire}) $accessallowed = 1; $original_file = $conf->propal->multidir_temp[$entity].'/'.$original_file; - } // Wrapping pour les images des stats commandes + } + // Wrapping pour les images des stats commandes elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp)) { if ($fuser->rights->commande->{$lire}) $accessallowed = 1; $original_file = $conf->commande->dir_temp.'/'.$original_file; - } elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output)) + } + elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output)) { if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed = 1; $original_file = $conf->fournisseur->commande->dir_temp.'/'.$original_file; - } // Wrapping pour les images des stats factures + } + // Wrapping pour les images des stats factures elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp)) { if ($fuser->rights->facture->{$lire}) $accessallowed = 1; $original_file = $conf->facture->dir_temp.'/'.$original_file; - } elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output)) + } + elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output)) { if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed = 1; $original_file = $conf->fournisseur->facture->dir_temp.'/'.$original_file; - } // Wrapping pour les images des stats expeditions + } + // Wrapping pour les images des stats expeditions elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp)) { if ($fuser->rights->expedition->{$lire}) $accessallowed = 1; $original_file = $conf->expedition->dir_temp.'/'.$original_file; - } // Wrapping pour les images des stats expeditions + } + // Wrapping pour les images des stats expeditions elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp)) { if ($fuser->rights->deplacement->{$lire}) $accessallowed = 1; $original_file = $conf->deplacement->dir_temp.'/'.$original_file; - } // Wrapping pour les images des stats expeditions + } + // Wrapping pour les images des stats expeditions elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp)) { if ($fuser->rights->adherent->{$lire}) $accessallowed = 1; $original_file = $conf->adherent->dir_temp.'/'.$original_file; - } // Wrapping pour les images des stats produits + } + // Wrapping pour les images des stats produits elseif (preg_match('/^productstats_/i', $modulepart) && !empty($conf->product->dir_temp)) { if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed = 1; $original_file = (!empty($conf->product->multidir_temp[$entity]) ? $conf->product->multidir_temp[$entity] : $conf->service->multidir_temp[$entity]).'/'.$original_file; - } // Wrapping for taxes + } + // Wrapping for taxes elseif (in_array($modulepart, array('tax', 'tax-vat')) && !empty($conf->tax->dir_output)) { if ($fuser->rights->tax->charges->{$lire}) $accessallowed = 1; $modulepartsuffix = str_replace('tax-', '', $modulepart); $original_file = $conf->tax->dir_output.'/'.($modulepartsuffix != 'tax' ? $modulepartsuffix.'/' : '').$original_file; - } // Wrapping for events + } + // Wrapping for events elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output)) { if ($fuser->rights->agenda->myactions->{$read}) $accessallowed = 1; $original_file = $conf->agenda->dir_output.'/'.$original_file; - } // Wrapping for categories + } + // Wrapping for categories elseif ($modulepart == 'category' && !empty($conf->categorie->multidir_output[$entity])) { if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); if ($fuser->rights->categorie->{$lire}) $accessallowed = 1; $original_file = $conf->categorie->multidir_output[$entity].'/'.$original_file; - } // Wrapping pour les prelevements + } + // Wrapping pour les prelevements elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output)) { if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i', $original_file)) $accessallowed = 1; $original_file = $conf->prelevement->dir_output.'/'.$original_file; - } // Wrapping pour les graph energie + } + // Wrapping pour les graph energie elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp)) { $accessallowed = 1; $original_file = $conf->stock->dir_temp.'/'.$original_file; - } // Wrapping pour les graph fournisseurs + } + // Wrapping pour les graph fournisseurs elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp)) { $accessallowed = 1; $original_file = $conf->fournisseur->dir_temp.'/'.$original_file; - } // Wrapping pour les graph des produits + } + // Wrapping pour les graph des produits elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp)) { $accessallowed = 1; $original_file = $conf->product->multidir_temp[$entity].'/'.$original_file; - } // Wrapping pour les code barre + } + // Wrapping pour les code barre elseif ($modulepart == 'barcode') { $accessallowed = 1; // If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk. //$original_file=$conf->barcode->dir_temp.'/'.$original_file; $original_file = ''; - } // Wrapping pour les icones de background des mailings + } + // Wrapping pour les icones de background des mailings elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp)) { $accessallowed = 1; $original_file = $conf->mailing->dir_temp.'/'.$original_file; - } // Wrapping pour le scanner + } + // Wrapping pour le scanner elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) { $accessallowed = 1; $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file; - } // Wrapping pour les images fckeditor + } + // Wrapping pour les images fckeditor elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output)) { $accessallowed = 1; $original_file = $conf->fckeditor->dir_output.'/'.$original_file; - } // Wrapping for users + } + + // Wrapping for users elseif ($modulepart == 'user' && !empty($conf->user->dir_output)) { $canreaduser = (!empty($fuser->admin) || $fuser->rights->user->user->{$lire}); @@ -2462,7 +2519,9 @@ $accessallowed = 1; } $original_file = $conf->user->dir_output.'/'.$original_file; - } // Wrapping for third parties + } + + // Wrapping for third parties elseif (($modulepart == 'company' || $modulepart == 'societe' || $modulepart == 'thirdparty') && !empty($conf->societe->multidir_output[$entity])) { if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); @@ -2472,7 +2531,9 @@ } $original_file = $conf->societe->multidir_output[$entity].'/'.$original_file; $sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe').")"; - } // Wrapping for contact + } + + // Wrapping for contact elseif ($modulepart == 'contact' && !empty($conf->societe->multidir_output[$entity])) { if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); @@ -2481,7 +2542,9 @@ $accessallowed = 1; } $original_file = $conf->societe->multidir_output[$entity].'/contact/'.$original_file; - } // Wrapping for invoices + } + + // Wrapping for invoices elseif (($modulepart == 'facture' || $modulepart == 'invoice') && !empty($conf->facture->multidir_output[$entity])) { if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2490,7 +2553,8 @@ } $original_file = $conf->facture->multidir_output[$entity].'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('invoice').")"; - } // Wrapping for mass actions + } + // Wrapping for mass actions elseif ($modulepart == 'massfilesarea_proposals' && !empty($conf->propal->multidir_output[$entity])) { if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2498,70 +2562,81 @@ $accessallowed = 1; } $original_file = $conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file; - } elseif ($modulepart == 'massfilesarea_orders') + } + elseif ($modulepart == 'massfilesarea_orders') { if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->commande->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file; - } elseif ($modulepart == 'massfilesarea_sendings') + } + elseif ($modulepart == 'massfilesarea_sendings') { if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->expedition->dir_output.'/sending/temp/massgeneration/'.$user->id.'/'.$original_file; - } elseif ($modulepart == 'massfilesarea_invoices') + } + elseif ($modulepart == 'massfilesarea_invoices') { if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->facture->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file; - } elseif ($modulepart == 'massfilesarea_expensereport') + } + elseif ($modulepart == 'massfilesarea_expensereport') { if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; - } elseif ($modulepart == 'massfilesarea_interventions') + } + elseif ($modulepart == 'massfilesarea_interventions') { if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; - } elseif ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output)) + } + elseif ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output)) { if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; - } elseif ($modulepart == 'massfilesarea_supplier_order') + } + elseif ($modulepart == 'massfilesarea_supplier_order') { if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; - } elseif ($modulepart == 'massfilesarea_supplier_invoice') + } + elseif ($modulepart == 'massfilesarea_supplier_invoice') { if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; - } elseif ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output)) + } + elseif ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output)) { if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; - } // Wrapping for interventions + } + + // Wrapping for interventions elseif (($modulepart == 'fichinter' || $modulepart == 'ficheinter') && !empty($conf->ficheinter->dir_output)) { if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2570,7 +2645,9 @@ } $original_file = $conf->ficheinter->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; - } // Wrapping pour les deplacements et notes de frais + } + + // Wrapping pour les deplacements et notes de frais elseif ($modulepart == 'deplacement' && !empty($conf->deplacement->dir_output)) { if ($fuser->rights->deplacement->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2579,7 +2656,8 @@ } $original_file = $conf->deplacement->dir_output.'/'.$original_file; //$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; - } // Wrapping pour les propales + } + // Wrapping pour les propales elseif (($modulepart == 'propal' || $modulepart == 'propale') && !empty($conf->propal->multidir_output[$entity])) { if ($fuser->rights->propale->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2588,7 +2666,9 @@ } $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('propal').")"; - } // Wrapping pour les commandes + } + + // Wrapping pour les commandes elseif (($modulepart == 'commande' || $modulepart == 'order') && !empty($conf->commande->multidir_output[$entity])) { if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2597,7 +2677,9 @@ } $original_file = $conf->commande->multidir_output[$entity].'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('order').")"; - } // Wrapping pour les projets + } + + // Wrapping pour les projets elseif ($modulepart == 'project' && !empty($conf->projet->dir_output)) { if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2606,7 +2688,8 @@ } $original_file = $conf->projet->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")"; - } elseif ($modulepart == 'project_task' && !empty($conf->projet->dir_output)) + } + elseif ($modulepart == 'project_task' && !empty($conf->projet->dir_output)) { if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i', $original_file)) { @@ -2614,7 +2697,9 @@ } $original_file = $conf->projet->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")"; - } // Wrapping pour les commandes fournisseurs + } + + // Wrapping pour les commandes fournisseurs elseif (($modulepart == 'commande_fournisseur' || $modulepart == 'order_supplier') && !empty($conf->fournisseur->commande->dir_output)) { if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2623,7 +2708,9 @@ } $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; - } // Wrapping pour les factures fournisseurs + } + + // Wrapping pour les factures fournisseurs elseif (($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output)) { if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2632,7 +2719,8 @@ } $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; - } // Wrapping pour les rapport de paiements + } + // Wrapping pour les rapport de paiements elseif ($modulepart == 'supplier_payment') { if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2641,7 +2729,9 @@ } $original_file = $conf->fournisseur->payment->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."paiementfournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; - } // Wrapping pour les rapport de paiements + } + + // Wrapping pour les rapport de paiements elseif ($modulepart == 'facture_paiement' && !empty($conf->facture->dir_output)) { if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2650,7 +2740,9 @@ } if ($fuser->societe_id > 0) $original_file = $conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file; else $original_file = $conf->facture->dir_output.'/payments/'.$original_file; - } // Wrapping for accounting exports + } + + // Wrapping for accounting exports elseif ($modulepart == 'export_compta' && !empty($conf->accounting->dir_output)) { if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i', $original_file)) @@ -2658,23 +2750,28 @@ $accessallowed = 1; } $original_file = $conf->accounting->dir_output.'/'.$original_file; - } // Wrapping pour les expedition - elseif (($modulepart == 'expedition' || $modulepart == 'shipment') && !empty($conf->expedition->dir_output)) + } + + // Wrapping pour les expedition + elseif ($modulepart == 'expedition' && !empty($conf->expedition->dir_output)) { if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->expedition->dir_output."/sending/".$original_file; - } // Delivery Note Wrapping - elseif (($modulepart == 'livraison' || $modulepart == 'delivery') && !empty($conf->expedition->dir_output)) - { - if ($fuser->rights->expedition->delivery->{$lire} || preg_match('/^specimen/i', $original_file)) + } + // Wrapping pour les bons de livraison + elseif ($modulepart == 'livraison' && !empty($conf->expedition->dir_output)) + { + if ($fuser->rights->expedition->livraison->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } $original_file = $conf->expedition->dir_output."/receipt/".$original_file; - } // Wrapping pour les actions + } + + // Wrapping pour les actions elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output)) { if ($fuser->rights->agenda->myactions->{$read} || preg_match('/^specimen/i', $original_file)) @@ -2682,7 +2779,9 @@ $accessallowed = 1; } $original_file = $conf->agenda->dir_output.'/'.$original_file; - } // Wrapping pour les actions + } + + // Wrapping pour les actions elseif ($modulepart == 'actionsreport' && !empty($conf->agenda->dir_temp)) { if ($fuser->rights->agenda->allactions->{$read} || preg_match('/^specimen/i', $original_file)) @@ -2690,7 +2789,9 @@ $accessallowed = 1; } $original_file = $conf->agenda->dir_temp."/".$original_file; - } // Wrapping pour les produits et services + } + + // Wrapping pour les produits et services elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') { if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); @@ -2700,7 +2801,9 @@ } if (!empty($conf->product->enabled)) $original_file = $conf->product->multidir_output[$entity].'/'.$original_file; elseif (!empty($conf->service->enabled)) $original_file = $conf->service->multidir_output[$entity].'/'.$original_file; - } // Wrapping pour les lots produits + } + + // Wrapping pour les lots produits elseif ($modulepart == 'product_batch' || $modulepart == 'produitlot') { if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); @@ -2709,7 +2812,9 @@ $accessallowed = 1; } if (!empty($conf->productbatch->enabled)) $original_file = $conf->productbatch->multidir_output[$entity].'/'.$original_file; - } // Wrapping for stock movements + } + + // Wrapping for stock movements elseif ($modulepart == 'movement' || $modulepart == 'mouvement') { if (empty($entity) || empty($conf->stock->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); @@ -2718,16 +2823,20 @@ $accessallowed = 1; } if (!empty($conf->stock->enabled)) $original_file = $conf->stock->multidir_output[$entity].'/movement/'.$original_file; - } // Wrapping pour les contrats - elseif ($modulepart == 'contract' && !empty($conf->contrat->multidir_output[$entity])) + } + + // Wrapping pour les contrats + elseif ($modulepart == 'contract' && !empty($conf->contrat->dir_output)) { if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file)) { $accessallowed = 1; } - $original_file = $conf->contrat->multidir_output[$entity].'/'.$original_file; + $original_file = $conf->contrat->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."contrat WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('contract').")"; - } // Wrapping pour les dons + } + + // Wrapping pour les dons elseif ($modulepart == 'donation' && !empty($conf->don->dir_output)) { if ($fuser->rights->don->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2735,7 +2844,9 @@ $accessallowed = 1; } $original_file = $conf->don->dir_output.'/'.$original_file; - } // Wrapping pour les dons + } + + // Wrapping pour les dons elseif ($modulepart == 'dolresource' && !empty($conf->resource->dir_output)) { if ($fuser->rights->resource->{$read} || preg_match('/^specimen/i', $original_file)) @@ -2743,7 +2854,9 @@ $accessallowed = 1; } $original_file = $conf->resource->dir_output.'/'.$original_file; - } // Wrapping pour les remises de cheques + } + + // Wrapping pour les remises de cheques elseif ($modulepart == 'remisecheque' && !empty($conf->bank->dir_output)) { if ($fuser->rights->banque->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2752,7 +2865,9 @@ } $original_file = $conf->bank->dir_output.'/checkdeposits/'.$original_file; // original_file should contains relative path so include the get_exdir result - } // Wrapping for bank + } + + // Wrapping for bank elseif (($modulepart == 'banque' || $modulepart == 'bank') && !empty($conf->bank->dir_output)) { if ($fuser->rights->banque->{$lire}) @@ -2760,41 +2875,55 @@ $accessallowed = 1; } $original_file = $conf->bank->dir_output.'/'.$original_file; - } // Wrapping for export module + } + + // Wrapping for export module elseif ($modulepart == 'export' && !empty($conf->export->dir_temp)) { // Aucun test necessaire car on force le rep de download sur // le rep export qui est propre a l'utilisateur $accessallowed = 1; $original_file = $conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file; - } // Wrapping for import module + } + + // Wrapping for import module elseif ($modulepart == 'import' && !empty($conf->import->dir_temp)) { $accessallowed = 1; $original_file = $conf->import->dir_temp.'/'.$original_file; - } // Wrapping pour l'editeur wysiwyg + } + + // Wrapping pour l'editeur wysiwyg elseif ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output)) { $accessallowed = 1; $original_file = $conf->fckeditor->dir_output.'/'.$original_file; - } // Wrapping for backups + } + + // Wrapping for backups elseif ($modulepart == 'systemtools' && !empty($conf->admin->dir_output)) { if ($fuser->admin) $accessallowed = 1; $original_file = $conf->admin->dir_output.'/'.$original_file; - } // Wrapping for upload file test + } + + // Wrapping for upload file test elseif ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp)) { if ($fuser->admin) $accessallowed = 1; $original_file = $conf->admin->dir_temp.'/'.$original_file; - } // Wrapping pour BitTorrent + } + + // Wrapping pour BitTorrent elseif ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output)) { $accessallowed = 1; $dir = 'files'; if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir = 'torrents'; $original_file = $conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file; - } // Wrapping pour Foundation module + } + + // Wrapping pour Foundation module elseif ($modulepart == 'member' && !empty($conf->adherent->dir_output)) { if ($fuser->rights->adherent->{$lire} || preg_match('/^specimen/i', $original_file)) @@ -2802,27 +2931,24 @@ $accessallowed = 1; } $original_file = $conf->adherent->dir_output.'/'.$original_file; - } // Wrapping for Scanner + } + + // Wrapping for Scanner elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) { $accessallowed = 1; $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file; - } // GENERIC Wrapping + } + + // GENERIC Wrapping // If modulepart=module_user_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser // If modulepart=module_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp // If modulepart=module_user Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart - // If modulepart=module-abc Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart - else { - //var_dump($modulepart); - //var_dump($original_file); + else + { if (preg_match('/^specimen/i', $original_file)) $accessallowed = 1; // If link to a file called specimen. Test must be done before changing $original_file int full path. if ($fuser->admin) $accessallowed = 1; // If user is admin - $tmpmodulepart = explode('-', $modulepart); - if (!empty($tmpmodulepart[1])) { - $modulepart = $tmpmodulepart[0]; - $original_file = $tmpmodulepart[1].'/'.$original_file; - } // Define $accessallowed $reg = array(); @@ -2835,7 +2961,8 @@ } if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1; $original_file = $conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file; - } elseif (preg_match('/^([a-z]+)_temp$/i', $modulepart, $reg)) + } + elseif (preg_match('/^([a-z]+)_temp$/i', $modulepart, $reg)) { if (empty($conf->{$reg[1]}->dir_temp)) // modulepart not supported { @@ -2844,7 +2971,8 @@ } if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1; $original_file = $conf->{$reg[1]}->dir_temp.'/'.$original_file; - } elseif (preg_match('/^([a-z]+)_user$/i', $modulepart, $reg)) + } + elseif (preg_match('/^([a-z]+)_user$/i', $modulepart, $reg)) { if (empty($conf->{$reg[1]}->dir_output)) // modulepart not supported { @@ -2853,7 +2981,8 @@ } if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1; $original_file = $conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file; - } elseif (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) + } + elseif (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) { if (empty($conf->{$reg[1]}->dir_output)) // modulepart not supported { @@ -2865,7 +2994,9 @@ $accessallowed = 1; } $original_file = $conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; - } else { + } + else + { if (empty($conf->$modulepart->dir_output)) // modulepart not supported { dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.'). The module for this modulepart value may not be activated.'); @@ -2874,17 +3005,10 @@ // Check fuser->rights->modulepart->myobject->read and fuser->rights->modulepart->read $partsofdirinoriginalfile = explode('/', $original_file); - if (!empty($partsofdirinoriginalfile[1])) { // If original_file is xxx/filename (xxx is a part we will use) - $partofdirinoriginalfile = $partsofdirinoriginalfile[0]; - if ($partofdirinoriginalfile && !empty($fuser->rights->$modulepart->$partofdirinoriginalfile) && ($fuser->rights->$modulepart->$partofdirinoriginalfile->{$lire} || $fuser->rights->$modulepart->$partofdirinoriginalfile->{$read})) $accessallowed = 1; - } - if (!empty($fuser->rights->$modulepart->{$lire}) || !empty($fuser->rights->$modulepart->{$read})) $accessallowed = 1; - - if (is_array($conf->$modulepart->multidir_output) && !empty($conf->$modulepart->multidir_output[$entity])) { - $original_file = $conf->$modulepart->multidir_output[$entity].'/'.$original_file; - } else { - $original_file = $conf->$modulepart->dir_output.'/'.$original_file; - } + $partofdirinoriginalfile = $partsofdirinoriginalfile[0]; + if ($partofdirinoriginalfile && ($fuser->rights->$modulepart->$partofdirinoriginalfile->{$lire} || $fuser->rights->$modulepart->$partofdirinoriginalfile->{$read})) $accessallowed = 1; + if ($fuser->rights->$modulepart->{$lire} || $fuser->rights->$modulepart->{$read}) $accessallowed = 1; + $original_file = $conf->$modulepart->dir_output.'/'.$original_file; } // For modules who wants to manage different levels of permissions for documents @@ -2992,13 +3116,17 @@ if (!file_exists($pathref.'/'.$filename)) { $file_list['missing'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'expectedsize'=>$expectedsize); - } else { + } + else + { $md5_local = md5_file($pathref.'/'.$filename); if ($conffile == '/etc/dolibarr/conf.php' && $filename == '/filefunc.inc.php') // For install with deb or rpm, we ignore test on filefunc.inc.php that was modified by package { $checksumconcat[] = $expectedmd5; - } else { + } + else + { if ($md5_local != $expectedmd5) $file_list['updated'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'expectedsize'=>$expectedsize, 'md5'=>(string) $md5_local); $checksumconcat[] = $md5_local; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_fiscalyear.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_fiscalyear.lib.php @@ -41,8 +41,8 @@ // Show more tabs from modules // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'fiscalyear'); $head[$h][0] = DOL_URL_ROOT.'/accountancy/admin/fiscalyear_info.php?id='.$object->id; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_format_cards.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_format_cards.lib.php @@ -36,27 +36,29 @@ $resql = $db->query($sql); if ($resql) { - while ($row = $db->fetch_array($resql)) - { - $_Avery_Labels[$row['code']]['name'] = $row['name']; - $_Avery_Labels[$row['code']]['paper-size'] = $row['paper_size']; - $_Avery_Labels[$row['code']]['orientation'] = $row['orientation']; - $_Avery_Labels[$row['code']]['metric'] = $row['metric']; - $_Avery_Labels[$row['code']]['marginLeft'] = $row['leftmargin']; - $_Avery_Labels[$row['code']]['marginTop'] = $row['topmargin']; - $_Avery_Labels[$row['code']]['marginTop'] = $row['topmargin']; - $_Avery_Labels[$row['code']]['NX'] = $row['nx']; - $_Avery_Labels[$row['code']]['NY'] = $row['ny']; - $_Avery_Labels[$row['code']]['SpaceX'] = $row['spacex']; - $_Avery_Labels[$row['code']]['SpaceY'] = $row['spacey']; - $_Avery_Labels[$row['code']]['width'] = $row['width']; - $_Avery_Labels[$row['code']]['height'] = $row['height']; - $_Avery_Labels[$row['code']]['font-size'] = $row['font_size']; - $_Avery_Labels[$row['code']]['custom_x'] = $row['custom_x']; - $_Avery_Labels[$row['code']]['custom_y'] = $row['custom_y']; - } -} else { - dol_print_error($db); + while ($row = $db->fetch_array($resql)) + { + $_Avery_Labels[$row['code']]['name'] = $row['name']; + $_Avery_Labels[$row['code']]['paper-size'] = $row['paper_size']; + $_Avery_Labels[$row['code']]['orientation'] = $row['orientation']; + $_Avery_Labels[$row['code']]['metric'] = $row['metric']; + $_Avery_Labels[$row['code']]['marginLeft'] = $row['leftmargin']; + $_Avery_Labels[$row['code']]['marginTop'] = $row['topmargin']; + $_Avery_Labels[$row['code']]['marginTop'] = $row['topmargin']; + $_Avery_Labels[$row['code']]['NX'] = $row['nx']; + $_Avery_Labels[$row['code']]['NY'] = $row['ny']; + $_Avery_Labels[$row['code']]['SpaceX'] = $row['spacex']; + $_Avery_Labels[$row['code']]['SpaceY'] = $row['spacey']; + $_Avery_Labels[$row['code']]['width'] = $row['width']; + $_Avery_Labels[$row['code']]['height'] = $row['height']; + $_Avery_Labels[$row['code']]['font-size'] = $row['font_size']; + $_Avery_Labels[$row['code']]['custom_x'] = $row['custom_x']; + $_Avery_Labels[$row['code']]['custom_y'] = $row['custom_y']; + } +} +else +{ + dol_print_error($db); } // We add characteristics to the name --- /tmp/dsg/dolibarr/htdocs/core/lib/github_fourn.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_fourn.lib.php @@ -39,14 +39,14 @@ $head = array(); $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id; - $head[$h][1] = $langs->trans('SupplierInvoice'); + $head[$h][1] = $langs->trans('Card'); $head[$h][2] = 'card'; $h++; 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.'/fourn/facture/contact.php?facid='.$object->id; + $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/contact.php?facid='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; $head[$h][2] = 'contact'; @@ -75,29 +75,29 @@ $h++; } - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice'); - - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice'); + + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; if (!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/note.php?facid='.$object->id; - $head[$h][1] = $langs->trans('Notes'); + $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/note.php?facid='.$object->id; + $head[$h][1] = $langs->trans('Notes'); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; - $head[$h][2] = 'note'; - $h++; - } + $head[$h][2] = 'note'; + $h++; + } require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object->ref; $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$object->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; @@ -109,9 +109,9 @@ $head[$h][2] = 'info'; $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice', 'remove'); - - return $head; + complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice', 'remove'); + + return $head; } @@ -129,14 +129,14 @@ $head = array(); $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("SupplierOrder"); + $head[$h][1] = $langs->trans("OrderCard"); $head[$h][2] = 'card'; $h++; 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.'/fourn/commande/contact.php?id='.$object->id; + $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; $head[$h][2] = 'contact'; @@ -153,28 +153,28 @@ } // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_order'); - - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_order'); + + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; if (!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/note.php?id='.$object->id; - $head[$h][1] = $langs->trans("Notes"); + $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/note.php?id='.$object->id; + $head[$h][1] = $langs->trans("Notes"); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; - $head[$h][2] = 'note'; - $h++; - } + $head[$h][2] = 'note'; + $h++; + } require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $upload_dir = $conf->fournisseur->dir_output."/commande/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; @@ -185,8 +185,8 @@ $head[$h][1] .= $langs->trans("Events"); 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"); + $head[$h][1] .= '/'; + $head[$h][1] .= $langs->trans("Agenda"); } $head[$h][2] = 'info'; $h++; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_functions.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_functions.lib.php @@ -15,7 +15,6 @@ * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2018-2020 Frédéric France * Copyright (C) 2019 Thibault Foucart - * Copyright (C) 2020 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -82,20 +81,16 @@ { global $conf, $mc; - // fix different element names (France to English) - switch ($element) { - case 'contrat': $element = 'contract'; break; // "/contrat/class/contrat.class.php" - case 'order_supplier': $element = 'supplier_order'; break; // "/fourn/class/fournisseur.commande.class.php" - } - if (is_object($mc)) { return $mc->getEntity($element, $shared, $currentobject); - } else { + } + else + { $out = ''; $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values'); if (in_array($element, $addzero)) $out .= '0,'; - $out .= ((int) $conf->entity); + $out .= $conf->entity; return $out; } } @@ -113,20 +108,11 @@ if (is_object($mc) && method_exists($mc, 'setEntity')) { return $mc->setEntity($currentobject); - } else { + } + else + { return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity); } -} - -/** - * Return if string has a name dedicated to store a secret - * - * @param string $keyname Name of key to test - * @return boolean True if key is used to store a secret - */ -function isASecretKey($keyname) -{ - return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname); } /** @@ -153,8 +139,6 @@ $version = ''; $os = 'unknown'; $phone = ''; - - $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent $detectmobile = new Mobile_Detect(null, $user_agent); $tablet = $detectmobile->isTablet(); @@ -184,14 +168,21 @@ } // OS - if (preg_match('/linux/i', $user_agent)) { $os = 'linux'; } elseif (preg_match('/macintosh/i', $user_agent)) { $os = 'macintosh'; } elseif (preg_match('/windows/i', $user_agent)) { $os = 'windows'; } + if (preg_match('/linux/i', $user_agent)) { $os = 'linux'; } + elseif (preg_match('/macintosh/i', $user_agent)) { $os = 'macintosh'; } + elseif (preg_match('/windows/i', $user_agent)) { $os = 'windows'; } // Name - $reg = array(); - if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'firefox'; $version = $reg[2]; } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'edge'; $version = $reg[2]; } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) { $name = 'chrome'; $version = $reg[2]; } // we can have 'chrome (Mozilla...) chrome x.y' in one string - elseif (preg_match('/chrome/i', $user_agent, $reg)) { $name = 'chrome'; } elseif (preg_match('/iceweasel/i', $user_agent)) { $name = 'iceweasel'; } elseif (preg_match('/epiphany/i', $user_agent)) { $name = 'epiphany'; } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'safari'; $version = $reg[2]; } // Safari is often present in string for mobile but its not. - elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'opera'; $version = $reg[2]; } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end - elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end + if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'firefox'; $version = $reg[2]; } + elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'edge'; $version = $reg[2]; } + elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) { $name = 'chrome'; $version = $reg[2]; } // we can have 'chrome (Mozilla...) chrome x.y' in one string + elseif (preg_match('/chrome/i', $user_agent, $reg)) { $name = 'chrome'; } + elseif (preg_match('/iceweasel/i', $user_agent)) { $name = 'iceweasel'; } + elseif (preg_match('/epiphany/i', $user_agent)) { $name = 'epiphany'; } + elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'safari'; $version = $reg[2]; } // Safari is often present in string for mobile but its not. + elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'opera'; $version = $reg[2]; } + elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end + elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { $name = 'lynxlinks'; $version = $reg[4]; } if ($tablet) { @@ -226,14 +217,14 @@ } /** - * Return true if we are in a context of submitting the parameter $paramname + * Return true if we are in a context of submitting a parameter * * @param string $paramname Name or parameter to test * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty) */ function GETPOSTISSET($paramname) { - $isset = false; + $isset = 0; $relativepathstring = $_SERVER["PHP_SELF"]; // Clean $relativepathstring @@ -256,7 +247,7 @@ { if ($key == $paramname) // We are on the requested parameter { - $isset = true; + $isset = 1; break; } } @@ -265,16 +256,19 @@ // If there is saved contextpage, page or limit if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) { - $isset = true; - } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) - { - $isset = true; - } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) - { - $isset = true; - } - } else { - $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here + $isset = 1; + } + elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) + { + $isset = 1; + } + elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) + { + $isset = 1; + } + } + else { + $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); } return $isset; @@ -289,15 +283,14 @@ * @param string $check Type of check * ''=no check (deprecated) * 'none'=no check (only for param that should have very rich content) - * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array * 'int'=check it's numeric (integer or float) * 'intcomma'=check it's integer+comma ('1,2,3,4...') - * 'alpha'=Same than alphanohtml since v13 - * 'alphanohtml'=check there is no html content and no " and no ../ + * 'alpha'=check it's text and sign * 'aZ'=check it's a-z only * 'aZ09'=check it's simple alpha string (recommended for keys) + * 'array'=check it's array * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string) - * 'nohtml'=check there is no html content and no " and no ../ + * 'nohtml', 'alphanohtml'=check there is no html content * 'restricthtml'=check html content is restricted to some tags only * 'custom'= custom filter specify $filter and $options) * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get) @@ -357,14 +350,17 @@ if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) { $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring]; - } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) + } + elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) { $out = $_SESSION['lastsearch_page_'.$relativepathstring]; - } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) + } + elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) { $out = $_SESSION['lastsearch_limit_'.$relativepathstring]; } - } // Else, retrieve default values if we are not doing a sort + } + // Else, retreive default values if we are not doing a sort elseif (!isset($_GET['sortfield'])) // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set { if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) @@ -378,7 +374,7 @@ } if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) { - if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) + if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) { // Now search in setup to overwrite default values if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' @@ -399,10 +395,12 @@ } if (!$foundintru) $qualified = 1; //var_dump($defkey.'-'.$qualified); - } else $qualified = 1; + } + else $qualified = 1; if ($qualified) { + //var_dump($user->default_values[$relativepathstring][$defkey]['createform']); if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) { $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname]; @@ -412,7 +410,9 @@ } } } - } // Management of default search_filters and sort order + } + // Management of default search_filters and sort order + //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) { if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' @@ -436,7 +436,8 @@ } if (!$foundintru) $qualified = 1; //var_dump($defkey.'-'.$qualified); - } else $qualified = 1; + } + else $qualified = 1; if ($qualified) { @@ -457,7 +458,8 @@ } } } - } elseif (isset($user->default_values[$relativepathstring]['filters'])) + } + elseif (isset($user->default_values[$relativepathstring]['filters'])) { foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) // $defkey is a querystring like 'a=b&c=d', $defval is key of user { @@ -473,11 +475,11 @@ } if (!$foundintru) $qualified = 1; //var_dump($defkey.'-'.$qualified); - } else $qualified = 1; + } + else $qualified = 1; if ($qualified) { - // We must keep $_POST and $_GET here if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) { // We made a search from quick search menu, do we still use default filter ? @@ -486,7 +488,9 @@ $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and , $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace); } - } else { + } + else + { $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and , $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace); } @@ -511,129 +515,37 @@ { $loopnb++; $newout = ''; - if ($reg[1] == 'DAY') { - $tmp = dol_getdate(dol_now(), true); - $newout = $tmp['mday']; - } elseif ($reg[1] == 'MONTH') { - $tmp = dol_getdate(dol_now(), true); - $newout = $tmp['mon']; - } elseif ($reg[1] == 'YEAR') { - $tmp = dol_getdate(dol_now(), true); - $newout = $tmp['year']; - } elseif ($reg[1] == 'PREVIOUS_DAY') { - $tmp = dol_getdate(dol_now(), true); - $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); - $newout = $tmp2['day']; - } elseif ($reg[1] == 'PREVIOUS_MONTH') { - $tmp = dol_getdate(dol_now(), true); - $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']); - $newout = $tmp2['month']; - } elseif ($reg[1] == 'PREVIOUS_YEAR') { - $tmp = dol_getdate(dol_now(), true); - $newout = ($tmp['year'] - 1); - } elseif ($reg[1] == 'NEXT_DAY') { - $tmp = dol_getdate(dol_now(), true); - $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); - $newout = $tmp2['day']; - } elseif ($reg[1] == 'NEXT_MONTH') { - $tmp = dol_getdate(dol_now(), true); - $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']); - $newout = $tmp2['month']; - } elseif ($reg[1] == 'NEXT_YEAR') { - $tmp = dol_getdate(dol_now(), true); - $newout = ($tmp['year'] + 1); - } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') { + if ($reg[1] == 'DAY') { $tmp = dol_getdate(dol_now(), true); $newout = $tmp['mday']; } + elseif ($reg[1] == 'MONTH') { $tmp = dol_getdate(dol_now(), true); $newout = $tmp['mon']; } + elseif ($reg[1] == 'YEAR') { $tmp = dol_getdate(dol_now(), true); $newout = $tmp['year']; } + elseif ($reg[1] == 'PREVIOUS_DAY') { $tmp = dol_getdate(dol_now(), true); $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } + elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp = dol_getdate(dol_now(), true); $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } + elseif ($reg[1] == 'PREVIOUS_YEAR') { $tmp = dol_getdate(dol_now(), true); $newout = ($tmp['year'] - 1); } + elseif ($reg[1] == 'NEXT_DAY') { $tmp = dol_getdate(dol_now(), true); $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } + elseif ($reg[1] == 'NEXT_MONTH') { $tmp = dol_getdate(dol_now(), true); $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } + elseif ($reg[1] == 'NEXT_YEAR') { $tmp = dol_getdate(dol_now(), true); $newout = ($tmp['year'] + 1); } + elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') + { $newout = $mysoc->country_id; - } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') { + } + elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') + { $newout = $user->id; - } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') { + } + elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') + { $newout = $user->fk_user; - } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') { + } + elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') + { $newout = $conf->entity; - } else { - $newout = ''; // Key not found, we replace with empty string - } + } + else $newout = ''; // Key not found, we replace with empty string //var_dump('__'.$reg[1].'__ -> '.$newout); $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out); } } - // Check rule - if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' - if (!is_array($out) || empty($out)) { - $out = array(); - } else { - $tmparray = explode(':', $check); - if (!empty($tmparray[1])) { - $tmpcheck = $tmparray[1]; - } else { - $tmpcheck = 'alphanohtml'; - } - foreach ($out as $outkey => $outval) { - $out[$outkey] = checkVal($outval, $tmpcheck, $filter, $options); - } - } - } - else { - $out = checkVal($out, $check, $filter, $options); - } - - // Sanitizing for special parameters. There is no reason to allow the backtopage parameter to contains an external URL. - if ($paramname == 'backtopage') { - $out = str_replace('\\', '/', $out); - $out = preg_replace(array('/^\/\/+/', '/^[a-z]*:/i'), '', $out); - } - - // Code for search criteria persistence. - // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year' - if (empty($method) || $method == 3 || $method == 4) - { - if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) - { - //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]); - - // We save search key only if $out not empty that means: - // - posted value not empty, or - // - if posted value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not). - - if ($out != '') // $out = '0' or 'abc', it is a search criteria to keep - { - $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out; - } - } - } - - return $out; -} - -/** - * Return value of a param into GET or POST supervariable. - * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder'] - * Note: The property $user->default_values is loaded by main.php when loading the user. - * - * @param string $paramname Name of parameter to found - * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get) - * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails) - * @param mixed $options Options to pass to filter_var when $check is set to 'custom' - * @param string $noreplace Force disable of replacement of __xxx__ strings. - * @return int Value found (int) - */ -function GETPOSTINT($paramname, $method = 0, $filter = null, $options = null, $noreplace = 0) -{ - return (int) GETPOST($paramname, 'int', $method, $filter, $options, $noreplace); -} - -/** - * Return a value after checking on a rule. - * - * @param string $out Value to get/check - * @param string $check Type of check - * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails) - * @param mixed $options Options to pass to filter_var when $check is set to 'custom' - * @return string|array Value found (string or array), or '' if check fails - */ -function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null) -{ // Check is done after replacement switch ($check) { @@ -645,12 +557,17 @@ case 'intcomma': if (preg_match('/[^0-9,-]+/i', $out)) $out = ''; break; + case 'alpha': + if (!is_array($out)) + { + // '"' is dangerous because param in url can close the href= or src= and add javascript functions. + // '../' is dangerous because it allows dir transversals + $out = str_replace(array('"', '../'), '', trim($out)); + } + break; case 'san_alpha': $out = filter_var($out, FILTER_SANITIZE_STRING); break; - case 'email': - $out = filter_var($out, FILTER_SANITIZE_EMAIL); - break; case 'aZ': if (!is_array($out)) { @@ -672,30 +589,23 @@ if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) $out = ''; } break; - case 'nohtml': // No html + case 'array': + if (!is_array($out) || empty($out)) $out = array(); + break; + case 'nohtml': $out = dol_string_nohtmltag($out, 0); break; - case 'alpha': // No html and no ../ and " case 'alphanohtml': // Recommended for most scalar parameters and search parameters - if (!is_array($out)) { + if (!is_array($out)) + { // '"' is dangerous because param in url can close the href= or src= and add javascript functions. // '../' is dangerous because it allows dir transversals - $out = str_replace(array('"', '"'), '', trim($out)); - $out = str_replace(array('../'), '', $out); - // keep lines feed - $out = dol_string_nohtmltag($out, 0); - } - break; - case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name " - if (!is_array($out)) { - // '"' is dangerous because param in url can close the href= or src= and add javascript functions. - // '../' is dangerous because it allows dir transversals - $out = str_replace(array('"', '"'), '', trim($out)); - $out = str_replace(array('../'), '', $out); + $out = str_replace(array('"', '../'), '', trim($out)); + $out = dol_string_nohtmltag($out, 1); } break; case 'restricthtml': // Recommended for most html textarea - $out = dol_string_onlythesehtmltags($out, 0, 1, 1); + $out = dol_string_onlythesehtmltags($out, 0); break; case 'custom': if (empty($filter)) return 'BadFourthParameterForGETPOST'; @@ -703,29 +613,47 @@ break; } + // Code for search criteria persistence. + // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year' + if (empty($method) || $method == 3 || $method == 4) + { + if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) + { + //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]); + + // We save search key only if $out not empty that means: + // - posted value not empty, or + // - if posted value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not). + + if ($out != '') // $out = '0' or 'abc', it is a search criteria to keep + { + $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out; + } + } + } + return $out; } - if (!function_exists('dol_getprefix')) { - /** - * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id. - * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir - * or two instances in same virtual servers. - * - * @param string $mode '' (prefix for session name) or 'email' (prefix for email id) - * @return string A calculated prefix - */ - function dol_getprefix($mode = '') - { - // If prefix is for email (we need to have $conf alreayd loaded for this case) + /** + * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id. + * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir + * or two instances in same virtual servers. + * + * @param string $mode '' (prefix for session name) or 'email' (prefix for email id) + * @return string A calculated prefix + */ + function dol_getprefix($mode = '') + { + global $conf; + + // If prefix is for email if ($mode == 'email') { - global $conf; - - if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended) + if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended) { if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID; elseif (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"]; @@ -738,17 +666,12 @@ return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3'); } - // If prefix is for session (no need to have $conf loaded) - global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php - $tmp_instance_unique_id = empty($dolibarr_main_instance_unique_id) ? (empty($dolibarr_main_cookie_cryptkey) ? '' : $dolibarr_main_cookie_cryptkey) : $dolibarr_main_instance_unique_id; // Unique id of instance - // The recommended value (may be not defined for old versions) - if (!empty($tmp_instance_unique_id)) { - return $tmp_instance_unique_id; - } + if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id; // For backward compatibility - if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) { + if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) + { return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3'); } @@ -768,7 +691,7 @@ */ function dol_include_once($relpath, $classname = '') { - global $conf, $langs, $user, $mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retrieved with $GLOBALS['var'] + global $conf, $langs, $user, $mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retreived with $GLOBALS['var'] $fullpath = dol_buildpath($relpath); @@ -823,7 +746,8 @@ { if ($returnemptyifnotfound == 1 || !file_exists($res)) return ''; } - } else // For an url path + } + else // For an url path { // We try to get local path of file on filesystem from url // Note that trying to know if a file on disk exist by forging path on disk from url @@ -900,8 +824,10 @@ if (empty($native)) { $myclone = unserialize(serialize($object)); - } else { - $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep the reference (refering to the same target/variable) + } + else + { + $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep references (refer to the same target/variable) } return $myclone; @@ -940,9 +866,8 @@ // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file // Char '>' '<' '|' '$' and ';' are special chars for shells. // Char '/' and '\' are file delimiters. - // -- car can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command - $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '--'); - return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars); + $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';'); + return dol_string_nospecial($unaccent ?dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars); } /** @@ -992,9 +917,11 @@ ); $string = strtr($string, $replacements); return rawurldecode($string); - } else { + } + else + { // See http://www.ascii-code.com/ - $string = strtr( + $string = strtr( $str, "\xC0\xC1\xC2\xC3\xC4\xC5\xC7 \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1 @@ -1023,7 +950,7 @@ * @param array $badcharstoreplace List of forbidden characters * @return string Cleaned string * - * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii() + * @see dol_sanitizeFilename(), dol_string_unaccent() */ function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '') { @@ -1037,29 +964,6 @@ /** - * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains. - * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars. - * Note, for information: UTF8 on 1 byte are: \x00-\7F - * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf - * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf - * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf - * @param string $str String to clean - * @param int $removetabcrlf Remove also CR-LF - * @return string Cleaned string - * - * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial() - */ -function dol_string_nounprintableascii($str, $removetabcrlf = 1) -{ - if ($removetabcrlf) { - return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace - } else { - return preg_replace('/[\x00-\x08\x11-\x12\x14-\x1F\x7F]/u', '', $str); // /u operator should make UTF8 valid characters being ignored so are not included into the replace - } -} - - -/** * Returns text escaped for inclusion into javascript code * * @param string $stringtoescape String to escape @@ -1073,8 +977,10 @@ $substitjs = array("'"=>"\\'", "\r"=>'\\r'); //$substitjs['. * @param string $keepmoretags '' or 'common' or list of tags * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents. @@ -1102,7 +1008,7 @@ */ function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $keepmoretags = '', $escapeonlyhtmltags = 0) { - if ($keepmoretags == 'common') $keepmoretags = 'html,body,a,b,em,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody'; + if ($keepmoretags == 'common') $keepmoretags = 'html,body,a,em,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody'; // TODO Implement $keepmoretags // escape quotes and backslashes, newlines, etc. @@ -1120,69 +1026,29 @@ } } + /** * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings. * - * @param string $string String to encode - * @param string $encoding Character set encoding + * @param string $utf8_string String to encode * @return string String converted */ -function dol_strtolower($string, $encoding = "UTF-8") -{ - if (function_exists('mb_strtolower')) { - return mb_strtolower($string, $encoding); - } else { - return strtolower($string); - } +function dol_strtolower($utf8_string) +{ + return mb_strtolower($utf8_string, "UTF-8"); } /** * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings. * - * @param string $string String to encode - * @param string $encoding Character set encoding + * @param string $utf8_string String to encode * @return string String converted */ -function dol_strtoupper($string, $encoding = "UTF-8") -{ - if (function_exists('mb_strtoupper')) { - return mb_strtoupper($string, $encoding); - } else { - return strtoupper($string); - } -} - -/** - * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings. - * - * @param string $string String to encode - * @param string $encoding Character set encodign - * @return string String converted - */ -function dol_ucfirst($string, $encoding = "UTF-8") -{ - if (function_exists('mb_substr')) { - return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding); - } else { - return ucfirst($string); - } -} - -/** - * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings. - * - * @param string $string String to encode - * @param string $encoding Character set encodign - * @return string String converted - */ -function dol_ucwords($string, $encoding = "UTF-8") -{ - if (function_exists('mb_convert_case')) { - return mb_convert_case($string, MB_CASE_TITLE, $encoding); - } else { - return ucwords($string); - } -} +function dol_strtoupper($utf8_string) +{ + return mb_strtoupper($utf8_string, "UTF-8"); +} + /** * Write log message into outputs. Possible outputs can be: @@ -1207,16 +1073,16 @@ */ function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null) { - global $conf, $user, $debugbar; + global $conf, $user, $debugbar; // If syslog module enabled if (empty($conf->syslog->enabled)) return; // Check if we are into execution of code of a website - if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) { + if (defined('USEEXTERNALSERVER') && ! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { global $website, $websitekey; - if (is_object($website) && !empty($website->ref)) $suffixinfilename .= '_website_'.$website->ref; - elseif (!empty($websitekey)) $suffixinfilename .= '_website_'.$websitekey; + if (is_object($website) && ! empty($website->ref)) $suffixinfilename.='_website_'.$website->ref; + elseif (! empty($websitekey)) $suffixinfilename.='_website_'.$websitekey; } if ($ident < 0) @@ -1241,9 +1107,9 @@ // If adding log inside HTML page is required if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML)) - || (!empty($user->rights->debugbar->read) && is_object($debugbar))) - { - $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message; + || (!empty($user->rights->debugbar->read) && is_object($debugbar))) + { + $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message; } //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output @@ -1269,7 +1135,8 @@ // This is when server run behind a reverse proxy if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip']; elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip']; - } // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache) + } + // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache) elseif (!empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR']; // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it). elseif (!empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']); @@ -1293,44 +1160,6 @@ } } -/** - * Return HTML code to output a button to open a dialog popup box. - * Such buttons must be included inside a HTML form. - * - * @param string $name A name for the html component - * @param string $label Label of button - * @param string $buttonstring button string - * @param string $url Url to open - * @param string $disabled Disabled text - * @return string HTML component with button - */ -function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '') -{ - if (strpos($url, '?') > 0) { - $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=1'; - } else { - $url .= '?dol_hide_menuinpopup=1&dol_hide_leftmenu=1&dol_openinpopup=1'; - } - - //print ''; - $out = ''.$buttonstring.''; - $out .= ''; - return $out; -} /** * Show tab header of a card @@ -1338,19 +1167,17 @@ * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head * @param string $active Active tab name (document', 'info', 'ldap', ....) * @param string $title Title - * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after) + * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using dol_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after) * @param string $picto Add a picto on tab title * @param int $pictoisfullpath If 1, image path is a full path. If you set this to 1, you can use url returned by dol_buildpath('/mymodyle/img/myimg.png',1) for $picto. * @param string $morehtmlright Add more html content on right of tabs title * @param string $morecss More Css * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value. - * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page * @return void - * @deprecated Use print dol_get_fiche_head() instead - */ -function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '') -{ - print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix); + */ +function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0) +{ + print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow); } /** @@ -1359,16 +1186,15 @@ * @param array $links Array of tabs * @param string $active Active tab name * @param string $title Title - * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after) + * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using dol_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after) * @param string $picto Add a picto on tab title * @param int $pictoisfullpath If 1, image path is a full path. If you set this to 1, you can use url returned by dol_buildpath('/mymodyle/img/myimg.png',1) for $picto. * @param string $morehtmlright Add more html content on right of tabs title * @param string $morecss More Css * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value. - * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page * @return string */ -function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '') +function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0) { global $conf, $langs, $hookmanager; @@ -1376,7 +1202,7 @@ $showtitle = 1; if (!empty($conf->dol_optimize_smallscreen)) $showtitle = 0; - $out = "\n".''; + $out = "\n".''; if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) { $out .= '
'."\n"; @@ -1386,11 +1212,11 @@ if ($morehtmlright) $out .= '
'.$morehtmlright.'
'; // Output right area first so when space is missing, text is in front of tabs and not under. // Show title - if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($title) && $showtitle) { $limittitle = 30; $out .= ''; - if ($picto) $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' '; + if ($picto && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' '; $out .= ''.dol_trunc($title, $limittitle).''; $out .= ''; } @@ -1428,7 +1254,8 @@ { if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) { $isactive = true; - } else { + } + else { $isactive = false; } @@ -1440,10 +1267,13 @@ if (!empty($links[$i][0])) { $out .= ''.$links[$i][1].''."\n"; - } else { + } + else + { $out .= ''.$links[$i][1].''."\n"; } - } elseif (!empty($links[$i][1])) + } + elseif (!empty($links[$i][1])) { //print "x $i $active ".$links[$i][2]." z"; if ($isactive) @@ -1451,14 +1281,18 @@ $out .= ''; $out .= $links[$i][1]; $out .= ''."\n"; - } else { + } + else + { $out .= ''; $out .= $links[$i][1]; $out .= ''."\n"; } } $out .= '
'; - } else { + } + else + { // The popup with the other tabs if (!$popuptab) { @@ -1470,8 +1304,10 @@ { if (!empty($links[$i][0])) $outmore .= ''.$links[$i][1].''."\n"; - else $outmore .= ''.$links[$i][1].''."\n"; - } elseif (!empty($links[$i][1])) + else + $outmore .= ''.$links[$i][1].''."\n"; + } + elseif (!empty($links[$i][1])) { $outmore .= ''; $outmore .= preg_replace('/([a-z])\/([a-z])/i', '\\1 / \\2', $links[$i][1]); // Replace x/y with x / y to allow wrap on long composed texts. @@ -1489,28 +1325,18 @@ { $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left'); $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right'); - $widthofpopup = 200; - - $tabsname = $moretabssuffix; - if (empty($tabsname)) { $tabsname = str_replace("@", "", $picto); } + + $tabsname = str_replace("@", "", $picto); $out .= '
'; - $out .= ''.$langs->trans("More").'... ('.$nbintab.')'; // Do not use "reposition" class in the "More". - $out .= '
'; + $out .= ''.$langs->trans("More").'... ('.$nbintab.')'; + $out .= '
'; $out .= $outmore; $out .= '
'; $out .= '
'; $out .= "
\n"; $out .= ""; } @@ -1536,7 +1362,6 @@ * * @param int $notab -1 or 0=Add tab footer, 1=no tab footer * @return void - * @deprecated Use print dol_get_fiche_end() instead */ function dol_fiche_end($notab = 0) { @@ -1613,30 +1438,34 @@ $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]); $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5); if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1; - if ($showimage) { - $morehtmlleft .= '
'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'
'; - } else { + if ($showimage) $morehtmlleft .= '
'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'
'; + else + { if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) { $nophoto = ''; $morehtmlleft .= '
'; - } else { // Show no photo link + } + else { // Show no photo link $nophoto = '/public/theme/common/nophoto.png'; $morehtmlleft .= '
No photo
'; } } - } elseif ($object->element == 'ticket') { + } + elseif ($object->element == 'ticket') + { $width = 80; $cssclass = 'photoref'; $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref); $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2); if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1; - if ($showimage) { $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0); if ($object->nbphoto > 0) { $morehtmlleft .= '
'.$showphoto.'
'; - } else { + } + else + { $showimage = 0; } } @@ -1645,15 +1474,15 @@ if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) { $nophoto = ''; $morehtmlleft .= '
'; - } else { // Show no photo link - $nophoto = img_picto('No photo', 'object_ticket'); - $morehtmlleft .= ''; - $morehtmlleft .= '
'; - $morehtmlleft .= $nophoto; - $morehtmlleft .= '
'; - } - } - } else { + } + else { // Show no photo link + $nophoto = '/public/theme/common/nophoto.png'; + $morehtmlleft .= '
No photo
'; + } + } + } + else + { if ($showimage) { if ($modulepart != 'unknown') @@ -1668,7 +1497,9 @@ { $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart); $subdir .= ((!empty($subdir) && !preg_match('/\/$/', $subdir)) ? '/' : '').$objectref; // the objectref dir is not included into get_exdir when used with level=2, so we add it at end - } else { + } + else + { $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart); } if (empty($subdir)) $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path @@ -1701,21 +1532,24 @@ if ($pdfexists && !$error) { - $heightforphotref = 80; + $heightforphotref = 70; if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60; // If the preview file is found if (file_exists($fileimage)) { - $phototoshow = '
'; + $phototoshow = '
'; $phototoshow .= ''; - $phototoshow .= '
'; + $phototoshow .= '
'; } } - } elseif (!$phototoshow) { // example if modulepart = 'photo' + } + elseif (!$phototoshow) + { $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos); } - if ($phototoshow) { + if ($phototoshow) + { $morehtmlleft .= '
'; $morehtmlleft .= $phototoshow; $morehtmlleft .= '
'; @@ -1724,13 +1558,15 @@ if (!$phototoshow) // Show No photo link (picto of object) { - $morehtmlleft .= '
'; + $morehtmlleft .= '
'; if ($object->element == 'action') { $width = 80; $cssclass = 'photorefcenter'; $nophoto = img_picto('No photo', 'title_agenda'); - } else { + } + else + { $width = 14; $cssclass = 'photorefcenter'; $picto = $object->picto; if ($object->element == 'project' && !$object->public) $picto = 'project'; // instead of projectpub @@ -1753,10 +1589,12 @@ if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased'); - } else { + } + else { $morehtmlstatus .= $object->getLibStatut(6); } - } elseif ($object->element == 'product') + } + elseif ($object->element == 'product') { //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') '; if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { @@ -1771,32 +1609,40 @@ } else { $morehtmlstatus .= ''.$object->getLibStatut(6, 1).''; } - } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan'))) { + } + elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan'))) + { $tmptxt = $object->getLibStatut(6, $object->totalpaye); if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5, $object->totalpaye); $morehtmlstatus .= $tmptxt; - } elseif ($object->element == 'contrat' || $object->element == 'contract') { + } + elseif ($object->element == 'contrat' || $object->element == 'contract') + { if ($object->statut == 0) $morehtmlstatus .= $object->getLibStatut(5); else $morehtmlstatus .= $object->getLibStatut(4); - } elseif ($object->element == 'facturerec') { + } + elseif ($object->element == 'facturerec') + { if ($object->frequency == 0) $morehtmlstatus .= $object->getLibStatut(2); else $morehtmlstatus .= $object->getLibStatut(5); - } elseif ($object->element == 'project_task') { + } + elseif ($object->element == 'project_task') + { $object->fk_statut = 1; if ($object->progress > 0) $object->fk_statut = 2; if ($object->progress >= 100) $object->fk_statut = 3; $tmptxt = $object->getLibStatut(5); $morehtmlstatus .= $tmptxt; // No status on task - } else { // Generic case + } + else { // Generic case $tmptxt = $object->getLibStatut(6); if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5); $morehtmlstatus .= $tmptxt; } // Add if object was dispatched "into accountancy" - if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) - { - // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank') + if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) + { if (method_exists($object, 'getVentilExportCompta')) { $accounted = $object->getVentilExportCompta(); @@ -1825,8 +1671,7 @@ } if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && ($conf->global->MAIN_SHOW_TECHNICAL_ID == '1' || preg_match('/'.preg_quote($object->element, '/').'/i', $conf->global->MAIN_SHOW_TECHNICAL_ID)) && !empty($object->id)) { - $morehtmlref .= '
'; - $morehtmlref .= '
'; + $morehtmlref .= '
'; $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id; $morehtmlref .= '
'; } @@ -1899,44 +1744,58 @@ $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : $object->address); } // Zip/Town/State - if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) { // US: title firstname name \n address lines \n town, state, zip \n country + if (in_array($object->country_code, array('AU', 'CA', 'US')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) // US: title firstname name \n address lines \n town, state, zip \n country + { $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town); $ret .= ($ret ? $sep : '').$town; - if (!empty($object->state)) { + if ($object->state) + { $ret .= ($ret ? ", " : '').$object->state; } if ($object->zip) $ret .= ($ret ? ", " : '').$object->zip; - } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) { // UK: title firstname name \n address lines \n town state \n zip \n country + } + elseif (in_array($object->country_code, array('GB', 'UK'))) // UK: title firstname name \n address lines \n town state \n zip \n country + { $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town); $ret .= ($ret ? $sep : '').$town; - if (!empty($object->state)) { + if ($object->state) + { $ret .= ($ret ? ", " : '').$object->state; } if ($object->zip) $ret .= ($ret ? $sep : '').$object->zip; - } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) { // ES: title firstname name \n address lines \n zip town \n state \n country + } + elseif (in_array($object->country_code, array('ES', 'TR'))) // ES: title firstname name \n address lines \n zip town \n state \n country + { $ret .= ($ret ? $sep : '').$object->zip; $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town); $ret .= ($town ? (($object->zip ? ' ' : '').$town) : ''); - if (!empty($object->state)) { + if ($object->state) + { $ret .= "\n".$object->state; } - } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) { // IT: tile firstname name\n address lines \n zip (Code Departement) \n country + } + elseif (in_array($object->country_code, array('IT'))) // IT: tile firstname name\n address lines \n zip (Code Departement) \n country + { $ret .= ($ret ? $sep : '').$object->zip; $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town); $ret .= ($town ? (($object->zip ? ' ' : '').$town) : ''); - $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code)); - } else { // Other: title firstname name \n address lines \n zip town \n country + $ret .= ($object->state_code ? (' '.($object->state_code)) : ''); + } + else // Other: title firstname name \n address lines \n zip town \n country + { $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town); $ret .= $object->zip ? (($ret ? $sep : '').$object->zip) : ''; $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : ''); - if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) { + if ($object->state && in_array($object->country_code, $countriesusingstate)) + { $ret .= ($ret ? ", " : '').$object->state; } } if (!is_object($outputlangs)) $outputlangs = $langs; - if ($withcountry) { + if ($withcountry) + { $langs->load("dict"); - $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code))); + $ret .= ($object->country_code ? ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)) : ''); } return $ret; @@ -1956,7 +1815,8 @@ { if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts); - } else return 'Error date into a not supported range'; + } + else return 'Error date into a not supported range'; } /** @@ -1969,7 +1829,7 @@ * "%d/%m/%Y %H:%M", * "%d/%m/%Y %H:%M:%S", * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day - * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat" + * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...reduceformat" * @param string $tzoutput true or 'gmt' => string is for Greenwich location * false or 'tzserver' => output string is for local PHP server TZ usage * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel' @@ -1980,13 +1840,9 @@ * * @see dol_mktime(), dol_stringtotime(), dol_getdate() */ -function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false) +function dol_print_date($time, $format = '', $tzoutput = 'tzserver', $outputlangs = '', $encodetooutput = false) { global $conf, $langs; - - if ($tzoutput === 'auto') { - $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver')); - } // Clean parameters $to_gmt = false; @@ -2002,7 +1858,8 @@ $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion' $offsettz = 0; $offsetdst = 0; - } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') + } + elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') { $to_gmt = true; $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion' @@ -2013,17 +1870,13 @@ } if (!is_object($outputlangs)) $outputlangs = $langs; if (!$format) $format = 'daytextshort'; - - // Do we have to reduce the length of date (year on 2 chars) to save space. - // Note: dayinputnoreduce is same than day but no reduction of year length will be done - $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param. - $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day + $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; $formatwithoutreduce = preg_replace('/reduceformat/', '', $format); if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat = 1; } // so format 'dayreduceformat' is processed like day // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default. // TODO Add format daysmallyear and dayhoursmallyear - if ($format == 'day') $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short); + if ($format == 'day') $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short); elseif ($format == 'hour') $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short); elseif ($format == 'hourduration') $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration); elseif ($format == 'daytext') $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text); @@ -2069,31 +1922,35 @@ $reg = array(); if (preg_match('/^([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])$/i', $time, $reg)) // Deprecated. Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000 { - dol_print_error("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]); - return ''; - } elseif (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $time, $reg)) // Still available to solve problems in extrafields of type date - { - // This part of code should not be used. - dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING); - //if (function_exists('debug_print_backtrace')) debug_print_backtrace(); - // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' - $syear = (!empty($reg[1]) ? $reg[1] : ''); - $smonth = (!empty($reg[2]) ? $reg[2] : ''); - $sday = (!empty($reg[3]) ? $reg[3] : ''); - $shour = (!empty($reg[4]) ? $reg[4] : ''); - $smin = (!empty($reg[5]) ? $reg[5] : ''); - $ssec = (!empty($reg[6]) ? $reg[6] : ''); - - $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true); - $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt); - } else { + dol_print_error("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]); + return ''; + } + elseif (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $time, $reg)) // Still available to solve problems in extrafields of type date + { + // This part of code should not be used. + dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING); + //if (function_exists('debug_print_backtrace')) debug_print_backtrace(); + // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' + $syear = (!empty($reg[1]) ? $reg[1] : ''); + $smonth = (!empty($reg[2]) ? $reg[2] : ''); + $sday = (!empty($reg[3]) ? $reg[3] : ''); + $shour = (!empty($reg[4]) ? $reg[4] : ''); + $smin = (!empty($reg[5]) ? $reg[5] : ''); + $ssec = (!empty($reg[6]) ? $reg[6] : ''); + + $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true); + $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt); + } + else + { // Date is a timestamps if ($time < 100000000000) // Protection against bad date values { $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. $ret = adodb_strftime($format, $timetouse, $to_gmt); - } else $ret = 'Bad value '.$time.' for date'; + } + else $ret = 'Bad value '.$time.' for date'; } if (preg_match('/__b__/i', $format)) @@ -2107,7 +1964,9 @@ { $monthtext = $outputlangs->transnoentities('Month'.$month); $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month); - } else { + } + else + { $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month); $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month); } @@ -2133,13 +1992,15 @@ /** * Return an array with locale date info. - * WARNING: This function use PHP server timezone by default to return locale informations. - * Be aware to add the third parameter to "UTC" if you need to work on UTC. + * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows + * WARNING: This function always use PHP server timezone to return locale informations !!! + * Usage must be avoid. + * FIXME: Replace this with PHP date function and a parameter $gm * * @param int $timestamp Timestamp - * @param boolean $fast Fast mode. deprecated. - * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'Europe/Paris' or '+0200' to force timezone. + * @param boolean $fast Fast mode * @return array Array of informations + * If no fast mode: * 'seconds' => $secs, * 'minutes' => $min, * 'hours' => $hour, @@ -2147,42 +2008,36 @@ * 'wday' => $dow, 0=sunday, 6=saturday * 'mon' => $month, * 'year' => $year, - * 'yday' => floor($secsInYear/$_day_power) - * '0' => original timestamp + * 'yday' => floor($secsInYear/$_day_power), + * 'weekday' => gmdate('l',$_day_power*(3+$dow)), + * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)), + * If fast mode: + * 'seconds' => $secs, + * 'minutes' => $min, + * 'hours' => $hour, + * 'mday' => $day, + * 'mon' => $month, + * 'year' => $year, + * 'yday' => floor($secsInYear/$_day_power), + * 'leap' => $leaf, + * 'ndays' => $ndays * @see dol_print_date(), dol_stringtotime(), dol_mktime() */ -function dol_getdate($timestamp, $fast = false, $forcetimezone = '') +function dol_getdate($timestamp, $fast = false) { global $conf; - if (empty($conf->global->MAIN_USE_OLD_FUNCTIONS_FOR_GETDATE)) { - //$datetimeobj = new DateTime('@'.$timestamp); - $datetimeobj = new DateTime(); - $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone - if ($forcetimezone) $datetimeobj->setTimezone(new DateTimeZone($forcetimezone)); // (add timezone relative to the date entered) - $arrayinfo = array( - 'year'=>((int) date_format($datetimeobj, 'Y')), - 'mon'=>((int) date_format($datetimeobj, 'm')), - 'mday'=>((int) date_format($datetimeobj, 'd')), - 'wday'=>((int) date_format($datetimeobj, 'w')), - 'yday'=>((int) date_format($datetimeobj, 'z')), - 'hours'=>((int) date_format($datetimeobj, 'H')), - 'minutes'=>((int) date_format($datetimeobj, 'i')), - 'seconds'=>((int) date_format($datetimeobj, 's')), - '0'=>$timestamp - ); - } else { - // PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows - $usealternatemethod = false; - if ($timestamp <= 0) $usealternatemethod = true; // <= 1970 - if ($timestamp >= 2145913200) $usealternatemethod = true; // >= 2038 - - if ($usealternatemethod) - { - $arrayinfo = adodb_getdate($timestamp, $fast); - } else { - $arrayinfo = getdate($timestamp); - } + $usealternatemethod = false; + if ($timestamp <= 0) $usealternatemethod = true; // <= 1970 + if ($timestamp >= 2145913200) $usealternatemethod = true; // >= 2038 + + if ($usealternatemethod) + { + $arrayinfo = adodb_getdate($timestamp, $fast); + } + else + { + $arrayinfo = getdate($timestamp); } return $arrayinfo; @@ -2200,24 +2055,17 @@ * @param int $day Day (1 to 31) * @param int $year Year * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values - * False or 0 or 'tzserver' = local to server TZ - * 'auto' - * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented. - * 'tzuserrel' = local to user TZ taking dst into account at the given date. Use this one to convert date input from user. + * False or 0 or 'server' = local to server TZ + * 'user' = local to user TZ * 'tz,TimeZone' = use specified timezone * @param int $check 0=No check on parameters (Can use day 32, etc...) * @return int|string Date as a timestamp, '' or false if error * @see dol_print_date(), dol_stringtotime(), dol_getdate() */ -function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1) +function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = false, $check = 1) { global $conf; //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -"; - //print 'gm:'.$gm.' gm==auto:'.($gm == 'auto').'
'; - - if ($gm === 'auto') { - $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey); - } // Clean parameters if ($hour == -1 || empty($hour)) $hour = 0; @@ -2235,27 +2083,32 @@ if ($second < 0 || $second > 60) return ''; } - if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) + if (empty($gm) || $gm === 'server') { $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin' $localtz = new DateTimeZone($default_timezone); - } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') + } + elseif ($gm === 'user') { // We use dol_tz_string first because it is more reliable. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin' try { $localtz = new DateTimeZone($default_timezone); - } catch (Exception $e) + } + catch (Exception $e) { dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING); $default_timezone = @date_default_timezone_get(); } - } elseif (strrpos($gm, "tz,") !== false) + } + elseif (strrpos($gm, "tz,") !== false) { $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin' - try { + try + { $localtz = new DateTimeZone($timezone); - } catch (Exception $e) + } + catch (Exception $e) { dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING); } @@ -2278,20 +2131,15 @@ /** * Return date for now. In most cases, we use this function without parameters (that means GMT time). * - * @param string $mode 'auto' => for backward compatibility (avoid this), - * 'gmt' => we return GMT timestamp, + * @param string $mode 'gmt' => we return GMT timestamp, * 'tzserver' => we add the PHP server timezone - * 'tzref' => we add the company timezone. Not implemented. - * 'tzuser' or 'tzuserrel' => we add the user timezone + * 'tzref' => we add the company timezone + * 'tzuser' => we add the user timezone * @return int $date Timestamp */ -function dol_now($mode = 'auto') +function dol_now($mode = 'gmt') { $ret = 0; - - if ($mode === 'auto') { - $mode = 'gmt'; - } if ($mode == 'gmt') $ret = time(); // Time for now at greenwich. elseif ($mode == 'tzserver') // Time for now with PHP server timezone added @@ -2299,13 +2147,14 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time $ret = (int) (dol_now('gmt') + ($tzsecond * 3600)); - } /*elseif ($mode == 'tzref') // Time for now with parent company timezone is added + } + /*elseif ($mode == 'tzref') // Time for now with parent company timezone is added { require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time $ret=dol_now('gmt')+($tzsecond*3600); }*/ - elseif ($mode == 'tzuser' || $mode == 'tzuserrel') // Time for now with user timezone added + elseif ($mode == 'tzuser') // Time for now with user timezone added { //print 'time: '.time(); $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; @@ -2338,13 +2187,16 @@ $ret = $size; $textunitshort = $langs->trans("b"); $textunitlong = $langs->trans("Bytes"); - } else { + } + else + { $ret = round($size / $level, 0); $textunitshort = $langs->trans("Kb"); $textunitlong = $langs->trans("KiloBytes"); } // Use long or short text unit - if (empty($shortunit)) { $ret .= ' '.$textunitlong; } else { $ret .= ' '.$textunitshort; } + if (empty($shortunit)) { $ret .= ' '.$textunitlong; } + else { $ret .= ' '.$textunitshort; } return $ret; } @@ -2377,7 +2229,7 @@ } /** - * Show EMail link formatted for HTML output. + * Show EMail link * * @param string $email EMail to show (only email, without 'Name of recipient' before) * @param int $cid Id of contact if known @@ -2392,7 +2244,7 @@ { global $conf, $user, $langs, $hookmanager; - $newemail = dol_escape_htmltag($email); + $newemail = $email; if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) $withpicto = 0; @@ -2418,7 +2270,9 @@ if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $link = ''.img_object($langs->trans("AddAction"), "calendar").''; if ($link) $newemail = '
'.$newemail.' '.$link.'
'; } - } else { + } + else + { if ($showinvalid && !isValidEmail($email)) { $langs->load("errors"); @@ -2448,36 +2302,35 @@ */ function getArrayOfSocialNetworks() { - global $conf, $db; - $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks"; - $sql .= " WHERE entity=".$conf->entity; - $socialnetworks = array(); - $resql = $db->query($sql); - if ($resql) { - while ($obj = $db->fetch_object($resql)) { - $socialnetworks[$obj->code] = array( - 'rowid' => $obj->rowid, - 'label' => $obj->label, - 'url' => $obj->url, - 'icon' => $obj->icon, - 'active' => $obj->active, - ); - } - } - return $socialnetworks; + global $conf, $db; + $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks"; + $sql .= " WHERE entity=".$conf->entity; + $socialnetworks = array(); + $resql = $db->query($sql); + if ($resql) { + while ($obj = $db->fetch_object($resql)) { + $socialnetworks[$obj->code] = array( + 'rowid' => $obj->rowid, + 'label' => $obj->label, + 'url' => $obj->url, + 'icon' => $obj->icon, + 'active' => $obj->active, + ); + } + } + return $socialnetworks; } /** * Show social network link * - * @param string $value Skype to show (only skype, without 'Name of recipient' before) - * @param int $cid Id of contact if known - * @param int $socid Id of third party if known - * @param string $type 'skype','facebook',... - * @param array $dictsocialnetworks socialnetworks availables - * @return string HTML Link - */ -function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array()) + * @param string $value Skype to show (only skype, without 'Name of recipient' before) + * @param int $cid Id of contact if known + * @param int $socid Id of third party if known + * @param string $type 'skype','facebook',... + * @return string HTML Link + */ +function dol_print_socialnetworks($value, $cid, $socid, $type) { global $conf, $user, $langs; @@ -2485,12 +2338,13 @@ if (empty($value)) return ' '; - if (!empty($type)) { + if (!empty($type)) + { $htmllink = '
'; - // TODO use dictionary definition for picto $dictsocialnetworks[$type]['icon'] - $htmllink .= img_picto($langs->trans(dol_ucfirst($type)), $type.'.png', '', false, 0, 0, '', 'paddingright', 0); - if ($type == 'skype') { - $htmllink .= $value; + $htmllink .= img_picto($langs->trans(strtoupper($type)), $type.'.png', '', false, 0, 0, '', 'paddingright', 0); + $htmllink .= $value; + if ($type == 'skype') + { $htmllink .= ' '; $htmllink .= ''; $htmllink .= ''; $htmllink .= ''; - if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) { - $addlink = 'AC_SKYPE'; - $link = ''; - if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $link = ''.img_object($langs->trans("AddAction"), "calendar").''; - $htmllink .= ($link ? ' '.$link : ''); - } - } else { - if (!empty($dictsocialnetworks[$type]['url'])) { - $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']); - $htmllink .= ' '.$value.''; - } else { - $htmllink .= $value; - } + } + if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type == 'skype') + { + $addlink = 'AC_SKYPE'; + $link = ''; + if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $link = ''.img_object($langs->trans("AddAction"), "calendar").''; + $htmllink .= ($link ? ' '.$link : ''); } $htmllink .= '
'; - } else { + } + else + { $langs->load("errors"); $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value)); } @@ -2544,7 +2394,7 @@ // Clean phone parameter $phone = preg_replace("/[\s.-]/", "", trim($phone)); if (empty($phone)) { return ''; } - if (!empty($conf->global->MAIN_PHONE_SEPAR)) $separ = $conf->global->MAIN_PHONE_SEPAR; + if ($conf->global->MAIN_PHONE_SEPAR) $separ = $conf->global->MAIN_PHONE_SEPAR; if (empty($countrycode)) $countrycode = $mysoc->country_code; // Short format for small screens @@ -2556,241 +2406,289 @@ // France if (dol_strlen($phone) == 10) { $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 2).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2); - } elseif (dol_strlen($phone) == 7) + } + elseif (dol_strlen($phone) == 7) { $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2); - } elseif (dol_strlen($phone) == 9) + } + elseif (dol_strlen($phone) == 9) { $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2); - } elseif (dol_strlen($phone) == 11) + } + elseif (dol_strlen($phone) == 11) { $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2); - } elseif (dol_strlen($phone) == 12) + } + elseif (dol_strlen($phone) == 12) { $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } - } elseif (strtoupper($countrycode) == "CA") + } + + elseif (strtoupper($countrycode) == "CA") { if (dol_strlen($phone) == 10) { $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4); } - } elseif (strtoupper($countrycode) == "PT") + } + elseif (strtoupper($countrycode) == "PT") {//Portugal if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3); } - } elseif (strtoupper($countrycode) == "SR") + } + elseif (strtoupper($countrycode) == "SR") {//Suriname if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3); - } elseif (dol_strlen($phone) == 11) + } + elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4); } - } elseif (strtoupper($countrycode) == "DE") + } + elseif (strtoupper($countrycode) == "DE") {//Allemagne if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3); - } elseif (dol_strlen($phone) == 13) + } + elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3); } - } elseif (strtoupper($countrycode) == "ES") + } + elseif (strtoupper($countrycode) == "ES") {//Espagne if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3); } - } elseif (strtoupper($countrycode) == "BF") + } + elseif (strtoupper($countrycode) == "BF") {// Burkina Faso if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } - } elseif (strtoupper($countrycode) == "RO") + } + elseif (strtoupper($countrycode) == "RO") {// Roumanie if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } - } elseif (strtoupper($countrycode) == "TR") + } + elseif (strtoupper($countrycode) == "TR") {//Turquie if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4); } - } elseif (strtoupper($countrycode) == "US") + } + elseif (strtoupper($countrycode) == "US") {//Etat-Unis if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4); } - } elseif (strtoupper($countrycode) == "MX") + } + elseif (strtoupper($countrycode) == "MX") {//Mexique if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2); - } elseif (dol_strlen($phone) == 11) + } + elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2); - } elseif (dol_strlen($phone) == 13) + } + elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4); } - } elseif (strtoupper($countrycode) == "ML") + } + elseif (strtoupper($countrycode) == "ML") {//Mali if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } - } elseif (strtoupper($countrycode) == "TH") + } + elseif (strtoupper($countrycode) == "TH") {//Thaïlande if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3); - } elseif (dol_strlen($phone) == 12) + } + elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 3); } - } elseif (strtoupper($countrycode) == "MU") - { - //Maurice + } + elseif (strtoupper($countrycode) == "MU") + { + //Maurice if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2); - } elseif (dol_strlen($phone) == 12) + } + elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } - } elseif (strtoupper($countrycode) == "ZA") + } + elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } - } elseif (strtoupper($countrycode) == "SY") + } + elseif (strtoupper($countrycode) == "SY") {//Syrie if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); - } elseif (dol_strlen($phone) == 13) + } + elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 3); } - } elseif (strtoupper($countrycode) == "AE") + } + elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2); - } elseif (dol_strlen($phone) == 13) + } + elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3); - } elseif (dol_strlen($phone) == 14) + } + elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4); } - } elseif (strtoupper($countrycode) == "DZ") + } + elseif (strtoupper($countrycode) == "DZ") {//Algérie if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3); } - } elseif (strtoupper($countrycode) == "BE") + } + elseif (strtoupper($countrycode) == "BE") {//Belgique if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3); - } elseif (dol_strlen($phone) == 12) + } + elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3); } - } elseif (strtoupper($countrycode) == "PF") + } + elseif (strtoupper($countrycode) == "PF") {//Polynésie française if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } - } elseif (strtoupper($countrycode) == "CO") + } + elseif (strtoupper($countrycode) == "CO") {//Colombie if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2); } - } elseif (strtoupper($countrycode) == "JO") + } + elseif (strtoupper($countrycode) == "JO") {//Jordanie if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 1).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2); } - } elseif (strtoupper($countrycode) == "JM") + } + elseif (strtoupper($countrycode) == "JM") {//Jamaïque if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4); } - } elseif (strtoupper($countrycode) == "MG") + } + elseif (strtoupper($countrycode) == "MG") {//Madagascar if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 3); } - } elseif (strtoupper($countrycode) == "GB") + } + elseif (strtoupper($countrycode) == "GB") {//Royaume uni if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3); } - } elseif (strtoupper($countrycode) == "CH") + } + elseif (strtoupper($countrycode) == "CH") {//Suisse if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); - } elseif (dol_strlen($phone) == 15) + } + elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL $newphone = $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 4); } - } elseif (strtoupper($countrycode) == "TN") + } + elseif (strtoupper($countrycode) == "TN") {//Tunisie if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3); } - } elseif (strtoupper($countrycode) == "GF") + } + elseif (strtoupper($countrycode) == "GF") {//Guyane francaise if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau) $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2); } - } elseif (strtoupper($countrycode) == "GP") + } + elseif (strtoupper($countrycode) == "GP") {//Guadeloupe if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau) $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2); } - } elseif (strtoupper($countrycode) == "MQ") + } + elseif (strtoupper($countrycode) == "MQ") {//Martinique if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau) $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2); } - } elseif (strtoupper($countrycode) == "IT") + } + elseif (strtoupper($countrycode) == "IT") {//Italie if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3); - } elseif (dol_strlen($phone) == 13) + } + elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2); } - } elseif (strtoupper($countrycode) == "AU") - { - //Australie + } + elseif (strtoupper($countrycode) == "AU") + { + //Australie if (dol_strlen($phone) == 12) { - //ex: +61_A_BCDE_FGHI + //ex: +61_A_BCDE_FGHI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4); } } @@ -2801,7 +2699,8 @@ $newphoneform = $newphone; $newphone = ''; - } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url + } + elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url { if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial(); @@ -2854,9 +2753,9 @@ if ($withpicto) { if ($withpicto == 'fax') { $picto = 'phoning_fax'; - } elseif ($withpicto == 'phone') { + }elseif ($withpicto == 'phone') { $picto = 'phoning'; - } elseif ($withpicto == 'mobile') { + }elseif ($withpicto == 'mobile') { $picto = 'phoning_mobile'; } else { $picto = ''; @@ -2895,8 +2794,11 @@ if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) { $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1); - } else $ret .= ' ('.$countrycode.')'; - } else { + } + else $ret .= ' ('.$countrycode.')'; + } + else + { // Nothing } } @@ -2914,40 +2816,8 @@ */ function getUserRemoteIP() { - if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) { - if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) { - if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) { - $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been forged by client - } else { - $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client - } - } else { - $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy - } - } else { - $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy - } + $ip = empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? (empty($_SERVER['HTTP_CLIENT_IP']) ? (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']) : $_SERVER['HTTP_CLIENT_IP']) : $_SERVER['HTTP_X_FORWARDED_FOR']; return $ip; -} - -/** - * Return if we are using a HTTPS connexion - * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy) - * Take HTTP_X_FORWARDED_PROTO (defined when using proxy) - * Then HTTP_X_FORWARDED_SSL - * - * @return boolean True if user is using HTTPS - */ -function isHTTPS() -{ - $isSecure = false; - if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { - $isSecure = true; - } - elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') { - $isSecure = true; - } - return $isSecure; } /** @@ -3059,12 +2929,11 @@ /** - * Return true if email syntax is ok. - * - * @param string $address email (Ex: "toto@examle.com". Long form "John Do " will be false) + * Return true if email syntax is ok + * + * @param string $address email (Ex: "toto@examle.com", "John Do ") * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid * @return boolean true if email syntax is OK, false if KO or empty string - * @see isValidMXRecord() */ function isValidEmail($address, $acceptsupervisorkey = 0) { @@ -3080,7 +2949,6 @@ * * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr") * @return int -1 if error (function not available), 0=Not valid, 1=Valid - * @see isValidEmail() */ function isValidMXRecord($domain) { @@ -3152,14 +3020,20 @@ if (function_exists('mb_substr')) { $ret = mb_substr($string, $start, $length, $stringencoding); - } else { + } + else + { $ret = substr($string, $start, $length); } - } else { + } + else + { if (function_exists('mb_strcut')) { $ret = mb_strcut($string, $start, $length, $stringencoding); - } else { + } + else + { $ret = substr($string, $start, $length); } } @@ -3174,7 +3048,7 @@ * * @param string $string String to truncate * @param int $size Max string size visible (excluding ...). 0 for no limit. WARNING: Final string size can have 3 more chars (if we added ..., or if size was max+1 or max+2 or max+3 so it does not worse to replace with ...) - * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap' + * @param string $trunc Where to trunc: right, left, middle (size must be a 2 power), wrap * @param string $stringencoding Tell what is source string encoding * @param int $nodot Truncation do not add ... after truncation. So it's an exact truncation. * @param int $display Trunc is used to display data and can be changed for small screen. TODO Remove this param (must be dealt with CSS) @@ -3196,9 +3070,11 @@ $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string; if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ... return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '...'); - else //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string; + else + //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string; return $string; - } elseif ($trunc == 'middle') + } + elseif ($trunc == 'middle') { $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string; if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) @@ -3206,20 +3082,27 @@ $size1 = round($size / 2); $size2 = round($size / 2); return dol_substr($newstring, 0, $size1, $stringencoding).'...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding); - } else return $string; - } elseif ($trunc == 'left') + } + else + return $string; + } + elseif ($trunc == 'left') { $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string; if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ... return '...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding); - else return $string; - } elseif ($trunc == 'wrap') + else + return $string; + } + elseif ($trunc == 'wrap') { $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string; if (dol_strlen($newstring, $stringencoding) > ($size + 1)) return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc); - else return $string; - } else return 'BadParam3CallingDolTrunc'; + else + return $string; + } + else return 'BadParam3CallingDolTrunc'; } /** @@ -3247,8 +3130,9 @@ // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto $url = DOL_URL_ROOT; - $theme = isset($conf->theme) ? $conf->theme : null; + $theme = $conf->theme; $path = 'theme/'.$theme; + // Define fullpathpicto to use into src if ($pictoisfullpath) { // Clean parameters @@ -3258,112 +3142,113 @@ $fullpathpicto = $picto; $reg = array(); if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) { - $morecss .= ($morecss ? ' ' : '').$reg[1]; - $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt); + $morecss .= ($morecss ? ' ' : '').$reg[1]; + $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt); } } else { $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto); - if (empty($srconly) && in_array($pictowithouttext, array( - '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected', - 'accountancy', 'account', 'accountline', 'action', 'add', 'address', 'bank_account', 'barcode', 'bank', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'building', - 'cash-register', 'category', 'check', 'clock', 'close_title', 'company', 'contact', 'contract', 'cron', 'cubes', - 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'edit', 'ellipsis-h', 'email', 'eraser', 'external-link-alt', 'external-link-square-alt', - 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'folder', 'folder-open', 'globe', 'globe-americas', 'grip', 'grip_title', 'group', - 'help', 'holiday', - 'intervention', 'label', 'language', 'link', 'list', 'listlight', 'lot', - 'map-marker-alt', 'member', 'money-bill-alt', 'mrp', 'note', 'next', - 'object_accounting', 'object_account', 'object_accountline', 'object_action', 'object_barcode', 'object_bill', 'object_billa', 'object_billr', 'object_billd', 'object_bom', - 'object_category', 'object_conversation', 'object_bookmark', 'object_bug', 'object_clock', 'object_dolly', 'object_dollyrevert', 'object_generic', 'object_folder', - 'object_list-alt', 'object_calendar', 'object_calendarweek', 'object_calendarmonth', 'object_calendarday', 'object_calendarperuser', - 'object_cash-register', 'object_company', 'object_contact', 'object_contract', 'object_donation', 'object_dynamicprice', - 'object_globe', 'object_holiday', 'object_hrm', 'object_invoice', 'object_intervention', 'object_label', - 'object_margin', 'object_money-bill-alt', 'object_multicurrency', 'object_order', 'object_payment', - 'object_lot', 'object_mrp', 'object_other', - 'object_payment', 'object_pdf', 'object_product', 'object_propal', - 'object_paragraph', 'object_poll', 'object_printer', 'object_project', 'object_projectpub', 'object_propal', 'object_resource', 'object_rss', 'object_projecttask', - 'object_recruitmentjobposition', 'object_recruitmentcandidature', - 'object_shipment', 'object_share-alt', 'object_supplier_invoice', 'object_supplier_invoicea', 'object_supplier_invoiced', 'object_supplier_order', 'object_supplier_proposal', 'object_service', 'object_stock', - 'object_technic', 'object_ticket', 'object_trip', 'object_user', 'object_group', 'object_member', - 'object_phoning', 'object_phoning_mobile', 'object_phoning_fax', 'object_email', 'object_website', 'object_movement', - 'off', 'on', 'order', - 'paiment', 'play', 'pdf', 'playdisabled', 'previous', 'poll', 'printer', 'product', 'propal', 'projecttask', 'stock', 'resize', 'service', 'stats', 'trip', - 'setup', 'share-alt', 'sign-out', 'split', 'stripe-s', 'switch_off', 'switch_on', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench', + + if (empty($srconly) && in_array($pictowithouttext, array( + '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected', + 'accountancy', 'address', 'bank_account', 'barcode', 'bank', 'bill', 'bookmark', 'bom', 'building', + 'cash-register', 'category', 'check', 'close_title', 'company', 'contact', 'contract', 'cubes', + 'delete', 'dolly', 'dollyrevert', 'edit', 'ellipsis-h', 'external-link-alt', 'external-link-square-alt', + 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'folder', 'folder-open', 'globe', 'globe-americas', 'grip', 'grip_title', 'help', + 'intervention', 'label', 'language', 'list', 'listlight', 'lot', + 'map-marker-alt', 'money-bill-alt', 'mrp', 'note', + 'object_accounting', 'object_action', 'object_account', 'object_barcode', 'object_bill', 'object_billa', 'object_billd', 'object_bom', + 'object_category', 'object_conversation', 'object_bookmark', 'object_bug', 'object_dolly', 'object_dollyrevert', 'object_generic', 'object_folder', + 'object_list-alt', 'object_calendar', 'object_calendarweek', 'object_calendarmonth', 'object_calendarday', 'object_calendarperuser', + 'object_cash-register', 'object_company', 'object_contact', 'object_contract', 'object_donation', 'object_dynamicprice', + 'object_globe', 'object_holiday', 'object_hrm', 'object_invoice', 'object_intervention', 'object_label', + 'object_margin', 'object_money-bill-alt', 'object_multicurrency', 'object_order', 'object_payment', + 'object_lot', 'object_mrp', 'object_payment', 'object_product', 'object_propal', + 'object_other', 'object_paragraph', 'object_poll', 'object_printer', 'object_project', 'object_projectpub', 'object_propal', 'object_resource', 'object_rss', 'object_projecttask', + 'object_shipment', 'object_supplier_invoice', 'object_supplier_invoicea', 'object_supplier_invoiced', 'object_supplier_order', 'object_supplier_proposal', 'object_service', 'object_stock', + 'object_technic', 'object_ticket', 'object_trip', 'object_user', 'object_group', 'object_member', + 'object_phoning', 'object_phoning_mobile', 'object_phoning_fax', 'object_email', 'object_website', + 'off', 'on', 'order', + 'paiment', 'play', 'playdisabled', 'poll', 'printer', 'product', 'propal', 'projecttask', 'stock', 'resize', 'service', 'stats', 'trip', + 'setup', 'sign-out', 'split', 'stripe-s', 'switch_off', 'switch_on', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp', - 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies', - 'generic', 'home', 'hrm', 'members', 'products', 'invoicing', - 'payment', 'pencil-ruler', 'preview', 'project', 'projectpub', 'refresh', 'supplier_invoice', 'ticket', - 'error', 'warning', - 'recruitmentcandidature', 'recruitmentjobposition', 'resource', - 'supplier_proposal', 'supplier_order', 'supplier_invoice', - 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda' + 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', + 'home', 'companies', 'products', 'commercial', 'invoicing', 'preview', 'project', 'projectpub', 'supplier_invoice', 'hrm', 'members', 'ticket', 'generic', + 'error', 'warning', 'supplier_proposal', 'supplier_order', 'supplier_invoice', + 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda' ) )) { - $pictowithouttext = str_replace('object_', '', $pictowithouttext); - $fakey = $pictowithouttext; $facolor = ''; $fasize = ''; $fa = 'fas'; - if (in_array($pictowithouttext, array('clock', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) { + if (in_array($pictowithouttext, array('object_generic', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) { $fa = 'far'; } - if (in_array($pictowithouttext, array('black-tie', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) { + if (in_array($pictowithouttext, array('skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) { $fa = 'fab'; } - $arrayconvpictotofa = array( - 'account'=>'university', 'accountline'=>'receipt', 'accountancy'=>'money-check-alt', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', - 'bank_account'=>'university', 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'billd'=>'file-medical', 'supplier_invoiced'=>'file-medical', 'bom'=>'cubes', - 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'conversation'=>'comments', 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd', - 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins', - 'accounting'=>'chart-line', 'category'=>'tag', 'dollyrevert'=>'dolly', - 'hrm'=>'user-tie', 'margin'=>'calculator', 'members'=>'users', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode', - 'email'=>'at', - 'edit'=>'pencil-alt', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle', - 'generic'=>'file', 'holiday'=>'umbrella-beach', 'label'=>'layer-group', - 'member'=>'users', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right', - 'trip'=>'wallet', 'group'=>'users', 'movement'=>'people-carry', - 'sign-out'=>'sign-out-alt', - 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star', 'bookmark'=>'star', - 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'edit'=>'pencil-alt', 'filter'=>'filter', - 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarmonth'=>'calendar-alt', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table', - 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice', - 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle', - 'other'=>'square', - 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'preview'=>'binoculars', 'project'=>'sitemap', 'projectpub'=>'sitemap', 'projecttask'=>'tasks', 'propal'=>'file-signature', - 'payment'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell', - 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge', + $pictowithouttext = str_replace('object_', '', $pictowithouttext); + + $arrayconvpictotofa = array( + 'account'=>'university', 'accountancy'=>'money-check-alt', 'action'=>'calendar-alt', 'address'=> 'address-book', + 'bank_account'=>'university', 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'supplier_invoicea'=>'file-excel', 'billd'=>'file-medical', 'supplier_invoiced'=>'file-medical', 'bom'=>'cubes', + 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'conversation'=>'comments', 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd', + 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins', + 'accounting'=>'chart-line', 'category'=>'tag', 'dollyrevert'=>'dolly', + 'hrm'=>'umbrella-beach', 'margin'=>'calculator', 'members'=>'users', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode', + 'email'=>'at', + 'edit'=>'pencil-alt', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'info-circle', + 'generic'=>'file', 'holiday'=>'umbrella-beach', 'label'=>'layer-group', + 'member'=>'users', 'mrp'=>'cubes', 'trip'=>'wallet', 'group'=>'users', + 'sign-out'=>'sign-out-alt', + 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star', 'bookmark'=>'star', + 'bank'=>'university', 'close_title'=>'window-close', 'delete'=>'trash', 'edit'=>'pencil-alt', 'filter'=>'filter', + 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarmonth'=>'calendar-alt', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table', + 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice', + 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle', + 'other'=>'square', + 'playdisabled'=>'play', 'poll'=>'check-double', 'preview'=>'binoculars', 'project'=>'sitemap', 'projectpub'=>'sitemap', 'projecttask'=>'tasks', 'propal'=>'file-signature', 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature', - 'refresh'=>'redo', 'resource'=>'laptop-house', - 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'supplier_invoice'=>'file-invoice-dollar', 'technic'=>'cogs', 'ticket'=>'ticket-alt', - 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach', - 'title_agenda'=>'calendar-alt', - 'uparrow'=>'mail-forward', 'vcard'=>'address-card', - 'jabber'=>'comment-o', - 'website'=>'globe-americas' - ); + 'payment'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell', + 'resource'=>'laptop-house', + 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'supplier_invoice'=>'file-invoice-dollar', 'technic'=>'cogs', 'ticket'=>'ticket-alt', + 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach', + 'title_agenda'=>'calendar-alt', + 'uparrow'=>'mail-forward', 'vcard'=>'address-card', + 'jabber'=>'comment-o', + 'website'=>'globe-americas' + ); if ($pictowithouttext == 'off') { - $fakey = 'fa-square'; + $fakey = 'fa-square'; $fasize = '1.3em'; - } elseif ($pictowithouttext == 'on') { - $fakey = 'fa-check-square'; + } + elseif ($pictowithouttext == 'on') { + $fakey = 'fa-check-square'; $fasize = '1.3em'; - } elseif ($pictowithouttext == 'listlight') { + } + elseif ($pictowithouttext == 'listlight') { $fakey = 'fa-download'; $marginleftonlyshort = 1; - } elseif ($pictowithouttext == 'printer') { + } + elseif ($pictowithouttext == 'printer') { $fakey = 'fa-print'; $fasize = '1.2em'; - } elseif ($pictowithouttext == 'note') { - $fakey = 'fa-sticky-note'; + } + elseif ($pictowithouttext == 'note') { + $fakey = 'fa-sticky-note'; $marginleftonlyshort = 1; - } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) { - $convertarray = array('1uparrow'=>'caret-up', '1downarrow'=>'caret-down', '1leftarrow'=>'caret-left', '1rightarrow'=>'caret-right', '1uparrow_selected'=>'caret-up', '1downarrow_selected'=>'caret-down', '1leftarrow_selected'=>'caret-left', '1rightarrow_selected'=>'caret-right'); - $fakey = 'fa-'.$convertarray[$pictowithouttext]; - if (preg_match('/selected/', $pictowithouttext)) $facolor = '#888'; + } + elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) { + $convertarray = array('1uparrow'=>'caret-up', '1downarrow'=>'caret-down', '1leftarrow'=>'caret-left', '1rightarrow'=>'caret-right', '1uparrow_selected'=>'caret-up', '1downarrow_selected'=>'caret-down', '1leftarrow_selected'=>'caret-left', '1rightarrow_selected'=>'caret-right'); + $fakey = 'fa-'.$convertarray[$pictowithouttext]; + if (preg_match('/selected/', $pictowithouttext)) $facolor = '#888'; $marginleftonlyshort = 1; - } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) { + } + elseif (!empty($arrayconvpictotofa[$pictowithouttext])) + { $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext]; - } else { + } + else { $fakey = 'fa-'.$pictowithouttext; } @@ -3379,9 +3264,9 @@ // Add CSS $arrayconvpictotomorcess = array( - 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', + 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'bank_account'=>'bg-infobox-bank_account', - 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande', + 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billd'=>'infobox-commande', 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'conversation'=>'infobox-contrat', 'donation'=>'infobox-commande', 'dollyrevert'=>'flip', 'ecm'=>'infobox-action', 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat', @@ -3392,7 +3277,6 @@ 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'holiday'=>'infobox-holiday', 'invoice'=>'infobox-commande', 'payment'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'project'=>'infobox-project', 'projecttask'=>'infobox-project', 'propal'=>'infobox-propal', - 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent', 'resource'=>'infobox-action', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal', @@ -3406,11 +3290,11 @@ // Define $color $arrayconvpictotocolor = array( - 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944', - 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'dynamicprice'=>'#a69944', - 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', + 'address'=>'#37a', 'building'=>'#37a', 'bom'=>'#a69944', + 'companies'=>'#37a', 'company'=>'#37a', 'contact'=>'#37a', 'dynamicprice'=>'#a69944', + 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'listlight'=>'#999', 'dolly'=>'#a69944', 'dollyrevert'=>'#a69944', 'lot'=>'#a69944', - 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944', + 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'stock'=>'#a69944', 'other'=>'#ddd', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'resize'=>'#444', 'rss'=>'#cba', 'shipment'=>'#a69944', 'stats'=>'#444', 'switch_off'=>'#999', 'uparrow'=>'#555', 'globe-americas'=>'#aaa', @@ -3421,24 +3305,23 @@ } // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only. - // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes. - $morestyle = ''; - $reg = array(); + // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes. + $reg = array(); if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) { - $morecss .= ($morecss ? ' ' : '').$reg[1]; - $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt); - } - if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) { - $morestyle = $reg[1]; - $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt); - } - $moreatt = trim($moreatt); - - $enabledisablehtml = ''; - /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $morecss .= ($morecss ? ' ' : '').$reg[1]; + $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt); + } + if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) { + $morestyle = ' '.$reg[1]; + $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt); + } + $moreatt = trim($moreatt); + + $enabledisablehtml = ''; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $enabledisablehtml .= $titlealt; - }*/ + } $enabledisablehtml .= ''; return $enabledisablehtml; @@ -3446,9 +3329,11 @@ if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) { $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module - } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) { + } + elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) { $path = $conf->global->MAIN_OVERWRITE_THEME_RES.'/theme/'.$conf->global->MAIN_OVERWRITE_THEME_RES; // To allow an external module to overwrite image resources whatever is activated theme - } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) { + } + elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) { $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module } @@ -3484,7 +3369,7 @@ return $fullpathpicto; } // tag title is used for tooltip on , tag alt can be used with very simple text on image for blind people - return ''.dol_escape_htmltag($alt).''; // Alt is used for accessibility, title for popup + return ''.dol_escape_htmltag($alt).''; // Alt is used for accessibility, title for popup } /** @@ -3521,13 +3406,13 @@ { global $conf; - if (is_numeric($picto)) { - //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png'); - //$picto = $leveltopicto[$picto]; - return ''; - } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) { - $picto .= '.png'; - } + if (is_numeric($picto)) + { + $leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png'); + //return ''; + $picto = $leveltopicto[$picto]; + } + elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png'; $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto; @@ -3551,7 +3436,8 @@ if (!preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png'; if ($pictoisfullpath) $path = $picto; - else { + else + { $path = DOL_URL_ROOT.'/theme/common/'.$picto; if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) @@ -3570,42 +3456,24 @@ * * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title. * @param string $numaction Action id or code to show - * @param string $picto Name of image file to show ('filenew', ...) - * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory. - * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img - * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img - * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1) * @return string Return an img tag */ -function img_action($titlealt, $numaction, $picto = '') +function img_action($titlealt, $numaction) { global $langs; if (empty($titlealt) || $titlealt == 'default') { - if ($numaction == '-1' || $numaction == 'ST_NO') { - $numaction = -1; - $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact'); - } elseif ($numaction == '0' || $numaction == 'ST_NEVER') { - $numaction = 0; - $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted'); - } elseif ($numaction == '1' || $numaction == 'ST_TODO') { - $numaction = 1; - $titlealt = $langs->transnoentitiesnoconv('ChangeToContact'); - } elseif ($numaction == '2' || $numaction == 'ST_PEND') { - $numaction = 2; - $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess'); - } elseif ($numaction == '3' || $numaction == 'ST_DONE') { - $numaction = 3; - $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone'); - } else { - $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction); - $numaction = 0; - } + if ($numaction == '-1' || $numaction == 'ST_NO') { $numaction = -1; $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact'); } + elseif ($numaction == '0' || $numaction == 'ST_NEVER') { $numaction = 0; $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted'); } + elseif ($numaction == '1' || $numaction == 'ST_TODO') { $numaction = 1; $titlealt = $langs->transnoentitiesnoconv('ChangeToContact'); } + elseif ($numaction == '2' || $numaction == 'ST_PEND') { $numaction = 2; $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess'); } + elseif ($numaction == '3' || $numaction == 'ST_DONE') { $numaction = 3; $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone'); } + else { $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction); $numaction = 0; } } if (!is_numeric($numaction)) $numaction = 0; - return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png'); + return img_picto($titlealt, 'stcomm'.$numaction.'.png'); } /** @@ -3886,9 +3754,7 @@ { global $langs; - if ($titlealt == 'default') { - $titlealt = $langs->trans('Left'); - } + if ($titlealt == 'default') $titlealt = $langs->trans('Left'); return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt); } @@ -3931,29 +3797,21 @@ /** * Return image of a credit card according to its brand name * - * @param string $brand Brand name of credit card - * @param string $morecss More CSS + * @param string $brand Brand name of credit card + * @param string $morecss More CSS * @return string Return img tag */ function img_credit_card($brand, $morecss = null) { if (is_null($morecss)) $morecss = 'fa-2x'; - if ($brand == 'visa' || $brand == 'Visa') { - $brand = 'cc-visa'; - } elseif ($brand == 'mastercard' || $brand == 'MasterCard') { - $brand = 'cc-mastercard'; - } elseif ($brand == 'amex' || $brand == 'American Express') { - $brand = 'cc-amex'; - } elseif ($brand == 'discover' || $brand == 'Discover') { - $brand = 'cc-discover'; - } elseif ($brand == 'jcb' || $brand == 'JCB') { - $brand = 'cc-jcb'; - } elseif ($brand == 'diners' || $brand == 'Diners club') { - $brand = 'cc-diners-club'; - } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) { - $brand = 'credit-card'; - } + if ($brand == 'visa' || $brand == 'Visa') {$brand = 'cc-visa'; } + elseif ($brand == 'mastercard' || $brand == 'MasterCard') {$brand = 'cc-mastercard'; } + elseif ($brand == 'amex' || $brand == 'American Express') {$brand = 'cc-amex'; } + elseif ($brand == 'discover' || $brand == 'Discover') {$brand = 'cc-discover'; } + elseif ($brand == 'jcb' || $brand == 'JCB') {$brand = 'cc-jcb'; } + elseif ($brand == 'diners' || $brand == 'Diners club') {$brand = 'cc-diners-club'; } + elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {$brand = 'credit-card'; } return ''; } @@ -4029,7 +3887,7 @@ * @param string $text Text info * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto * @param int $nodiv No div - * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other + * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error','xxx'=Other * @param string $morecss More CSS ('', 'warning', 'error') * @param string $textfordropdown Show a text to click to dropdown the info box. * @return string String with info text @@ -4041,14 +3899,15 @@ if ($infoonimgalt) { $result = img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"'); - } else { + } + else { if (empty($conf->use_javascript_ajax)) $textfordropdown = ''; $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin)); $result = ($nodiv ? '' : '
').' '.$text.($nodiv ? '' : '
'); if ($textfordropdown) { - $tmpresult .= ''.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').''; + $tmpresult .= ''.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').''; $tmpresult .= ''; - } else { + } + else + { $return = $out; } } @@ -7097,7 +6931,8 @@ if ($val && preg_match('/class="error"/i', $val)) { $iserror++; break; } if ($val && preg_match('/class="warning"/i', $val)) { $iswarning++; break; } } - } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) $iserror++; + } + elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) $iserror++; elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) $iswarning++; if ($style == 'error') $iserror++; if ($style == 'warning') $iswarning++; @@ -7120,14 +6955,17 @@ $tmpmesgstring = preg_replace('/
/', '', $tmpmesgstring); $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring); $newmesgarray[] = $tmpmesgstring; - } else { + } + else + { dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING); } } $mesgarray = $newmesgarray; } print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded); - } else print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded); + } + else print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded); } /** @@ -7172,19 +7010,22 @@ $temp = array(); foreach (array_keys($array) as $key) { - if (is_object($array[$key])) { - $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index; - } else { - $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index]; + if (is_object($array[$key])) + { + $temp[$key] = $array[$key]->$index; } - } - - if (!$natsort) { - ($order == 'asc') ? asort($temp) : arsort($temp); - } else { - ($case_sensitive) ? natsort($temp) : natcasesort($temp); - if ($order != 'asc') $temp = array_reverse($temp, true); - } + else + { + $temp[$key] = $array[$key][$index]; + } + } + + if (!$natsort) { + ($order == 'asc') ? asort($temp) : arsort($temp); + } else { + ($case_sensitive) ? natsort($temp) : natcasesort($temp); + if ($order != 'asc') $temp = array_reverse($temp, true); + } $sorted = array(); @@ -7208,11 +7049,10 @@ */ function utf8_check($str) { - $str = (string) $str; // Sometimes string is an int. - // We must use here a binary strlen function (so not dol_strlen) $strLength = dol_strlen($str); - for ($i = 0; $i < $strLength; $i++) { + for ($i = 0; $i < $strLength; $i++) + { if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n = 1; // 110bbbbb elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n = 2; // 1110bbbb @@ -7310,7 +7150,9 @@ else $cache_codes[$tablename][$key][$fieldid] = ''; $db->free($resql); return $cache_codes[$tablename][$key][$fieldid]; - } else { + } + else + { return -1; } } @@ -7344,7 +7186,7 @@ * @param string $s String to evaluate * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)). * @param int $hideerrors 1=Hide errors - * @return mixed Nothing or return result of eval + * @return mixed Nothing or return of eval */ function dol_eval($s, $returnvalue = 0, $hideerrors = 1) { @@ -7359,10 +7201,13 @@ global $soc; // For backward compatibility //print $s."
\n"; - if ($returnvalue) { + if ($returnvalue) + { if ($hideerrors) return @eval('return '.$s.';'); else return eval('return '.$s.';'); - } else { + } + else + { if ($hideerrors) @eval($s); else eval($s); } @@ -7382,12 +7227,14 @@ /** * Return img flag of country for a language code or country code * - * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR') - * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"') + * @param string $codelang Language code (en_IN, fr_CA...) or Country code (IN, FR) + * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"') * @return string HTML img string with flag. */ function picto_from_langcode($codelang, $moreatt = '') { + global $langs; + if (empty($codelang)) return ''; if ($codelang == 'auto') @@ -7400,19 +7247,12 @@ 'ca_ES' => 'catalonia', 'da_DA' => 'dk', 'fr_CA' => 'mq', - 'sv_SV' => 'se', - 'sw_SW' => 'unknown', - 'AQ' => 'unknown', - 'CW' => 'unknown', - 'IM' => 'unknown', - 'JE' => 'unknown', - 'MF' => 'unknown', - 'BL' => 'unknown', - 'SX' => 'unknown' + 'sv_SV' => 'se' ); if (isset($langtocountryflag[$codelang])) $flagImage = $langtocountryflag[$codelang]; - else { + else + { $tmparray = explode('_', $codelang); $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1]; } @@ -7620,18 +7460,20 @@ if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) // Need extension php-intl { - foreach ($locales as $locale) - { - $locale_language = locale_get_primary_language($locale); - $locale_region = locale_get_region($locale); - if (strtoupper($countrycode) == $locale_region) - { - //var_dump($locale.'-'.$locale_language.'-'.$locale_region); - return strtolower($locale_language).'_'.strtoupper($locale_region); - } - } - } else { - dol_syslog("Warning Exention php-intl is not available", LOG_WARNING); + foreach ($locales as $locale) + { + $locale_language = locale_get_primary_language($locale); + $locale_region = locale_get_region($locale); + if (strtoupper($countrycode) == $locale_region) + { + //var_dump($locale.'-'.$locale_language.'-'.$locale_region); + return strtolower($locale_language).'_'.strtoupper($locale_region); + } + } + } + else + { + dol_syslog("Warning Exention php-intl is not available", LOG_WARNING); } return null; @@ -7690,14 +7532,16 @@ $substitutionarray = array(); complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2])); $label = make_substitutions($reg[1], $substitutionarray); - } else $label = $langs->trans($values[2]); + } + else $label = $langs->trans($values[2]); $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1); $head[$h][1] = $label; $head[$h][2] = str_replace('+', '', $values[1]); $h++; } - } elseif (count($values) == 5) // deprecated + } + elseif (count($values) == 5) // deprecated { dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING); @@ -7708,14 +7552,16 @@ $substitutionarray = array(); complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2])); $label = make_substitutions($reg[1], $substitutionarray); - } else $label = $langs->trans($values[2]); + } + else $label = $langs->trans($values[2]); $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1); $head[$h][1] = $label; $head[$h][2] = str_replace('+', '', $values[1]); $h++; } - } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) + } + elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) { if ($values[0] != $type) continue; $tabname = str_replace('-', '', $values[1]); @@ -7741,7 +7587,7 @@ if ($reshook > 0) { $head = $hookmanager->resArray; - $h = count($head); + $h = count($head); } } } @@ -7768,7 +7614,7 @@ // A div to store page_y POST parameter so we can read it using javascript print "\n\n"; - print ''."\n"; + print ''."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks @@ -7820,7 +7666,8 @@ } if (!$foundintru) $qualified = 1; //var_dump($defkey.'-'.$qualified); - } else $qualified = 1; + } + else $qualified = 1; if ($qualified) { @@ -7851,7 +7698,8 @@ } if (!$foundintru) $qualified = 1; //var_dump($defkey.'-'.$qualified); - } else $qualified = 1; + } + else $qualified = 1; if ($qualified) { @@ -7903,7 +7751,7 @@ if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) { $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID); - foreach ($tmptagarray as $tmptag) { + foreach($tmptagarray as $tmptag) { print "\n"; print "\n"; print " @@ -7924,17 +7772,17 @@ // Add Xdebug coverage of code if (defined('XDEBUGCOVERAGE')) { - print_r(xdebug_get_code_coverage()); + print_r(xdebug_get_code_coverage()); } // Add DebugBar data - if (!empty($user->rights->debugbar->read) && is_object($debugbar)) - { - $debugbar['time']->stopMeasure('pageaftermaster'); - print ''."\n"; - $renderer = $debugbar->getRenderer(); - print $debugbar->getRenderer()->render(); - } elseif (count($conf->logbuffer)) // If there is some logs in buffer to show + if (!empty($user->rights->debugbar->read) && is_object($debugbar)) + { + $debugbar['time']->stopMeasure('pageaftermaster'); + print ''."\n"; + print $debugbar->getRenderer()->render(); + } + elseif (count($conf->logbuffer)) // If there is some logs in buffer to show { print "\n"; print "/msU', '', $content); - //} - //else - //{ - // $content = $content; - //} + if (is_array($replaceimagepath)) + { + foreach ($replaceimagepath as $key => $val) + { + $keytoreplace = ']('.$key; + $valafter = ']('.$val; + $content = preg_replace('/'.preg_quote($keytoreplace, '/').'/m', $valafter, $content); + } + } + //if ($parser == 'dolibarr') + //{ + $content = preg_replace('//msU', '', $content); + //} + //else + //{ + // $content = $content; + //} - return $content; + return $content; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_payments.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_payments.lib.php @@ -2,7 +2,6 @@ /** * Copyright (C) 2013 Marcos García * Copyright (C) 2018 Frédéric France - * Copyright (C) 2020 Abbes Bahfir * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -39,11 +38,11 @@ $head[$h][2] = 'payment'; $h++; - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment'); $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/info.php?id='.$object->id; $head[$h][1] = $langs->trans("Info"); @@ -56,41 +55,6 @@ } /** - * Returns an array with the tabs for the "Bannkline" section - * It loads tabs from modules looking for the entity payment - * - * @param int $id ID of bank line - * @return array Tabs for the Bankline section - */ -function bankline_prepare_head($id) -{ - global $langs, $conf; - - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/compta/bank/line.php?rowid='.$id; - $head[$h][1] = $langs->trans('BankTransaction'); - $head[$h][2] = 'bankline'; - $h++; - - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline'); - - $head[$h][0] = DOL_URL_ROOT.'/compta/bank/info.php?rowid='.$id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; - - complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline', 'remove'); - - return $head; -} - -/** * Returns an array with the tabs for the "Supplier payment" section * It loads tabs from modules looking for the entity payment_supplier * @@ -109,11 +73,11 @@ $head[$h][2] = 'payment'; $h++; - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment_supplier'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment_supplier'); $head[$h][0] = DOL_URL_ROOT.'/fourn/paiement/info.php?id='.$object->id; $head[$h][1] = $langs->trans('Info'); @@ -170,7 +134,7 @@ global $langs; // Load translation files required by the page - $langs->loadLangs(array('payment', 'stripe')); + $langs->loadLangs(array('payment', 'stripe')); $servicename = $langs->transnoentitiesnoconv('Online'); @@ -194,7 +158,7 @@ */ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag = 'your_tag', $localorexternal = 0) { - global $conf, $dolibarr_main_url_root; + global $conf, $dolibarr_main_url_root; $ref = str_replace(' ', '', $ref); $out = ''; @@ -209,71 +173,79 @@ if ($type == 'free') { - $out = $urltouse.'/public/payment/newpayment.php?amount='.($mode ? '' : '').$amount.($mode ? '' : '').'&tag='.($mode ? '' : '').$freetag.($mode ? '' : ''); + $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 ($mode) $out.='&noidempotency=1'; - } elseif ($type == 'order') - { - $out = $urltouse.'/public/payment/newpayment.php?source=order&ref='.($mode ? '' : ''); + } + 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); $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 { + 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); $out .= ($mode ? '' : ''); } } - } elseif ($type == 'invoice') - { - $out = $urltouse.'/public/payment/newpayment.php?source=invoice&ref='.($mode ? '' : ''); + } + 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); $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 { + 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); $out .= ($mode ? '' : ''); } } - } elseif ($type == 'contractline') - { - $out = $urltouse.'/public/payment/newpayment.php?source=contractline&ref='.($mode ? '' : ''); + } + 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); $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 { + 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); $out .= ($mode ? '' : ''); } } - } elseif ($type == 'member' || $type == 'membersubscription') - { - $out = $urltouse.'/public/payment/newpayment.php?source=membersubscription&ref='.($mode ? '' : ''); + } + 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); $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 { + 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); @@ -283,14 +255,15 @@ } if ($type == 'donation') { - $out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '' : ''); 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 { + 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); @@ -319,82 +292,82 @@ */ function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0, $suffix = '', $object = null) { - global $conf; - - // Juridical status - $line1 = ""; - if ($fromcompany->forme_juridique_code) - { - $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); - } - // 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)) - { - $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1; - } - // Prof Id 2 - if ($fromcompany->idprof2) - { - $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code); - 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) - { - $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3; - } - // Prof Id 4 - if ($fromcompany->idprof4) - { - $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4; - } - // IntraCommunautary VAT - if ($fromcompany->tva_intra != '') - { - $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; - } - - print '
'; - - print '
'."\n"; - 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); - - // Add other message if VAT exists - 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); - } - } - - print '

'."\n"; - print $fromcompany->name.'
'; - print $line1; - if (strlen($line1.$line2) > 50) print '
'; - else print ' - '; - print $line2; - print '
'."\n"; -} + global $conf; + + // Juridical status + $line1 = ""; + if ($fromcompany->forme_juridique_code) + { + $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); + } + // 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)) + { + $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1; + } + // Prof Id 2 + if ($fromcompany->idprof2) + { + $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code); + 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) + { + $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3; + } + // Prof Id 4 + if ($fromcompany->idprof4) + { + $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4; + } + // IntraCommunautary VAT + if ($fromcompany->tva_intra != '') + { + $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; + } + + print '
'; + + print '
'."\n"; + 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); + + // Add other message if VAT exists + 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); + } + } + + print '

'."\n"; + print $fromcompany->name.'
'; + print $line1; + if (strlen($line1.$line2) > 50) print '
'; + else print ' - '; + print $line2; + print '
'."\n"; +} --- /tmp/dsg/dolibarr/htdocs/core/lib/github_pdf.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_pdf.lib.php @@ -11,7 +11,6 @@ * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com> * Copyright (C) 2015-2016 Marcos García * Copyright (C) 2019 Lenin Rivas - * Copyright (C) 2020 Nicolas ZABOURI * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -55,7 +54,9 @@ { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $pdfformat = dol_getDefaultFormat($outputlangs); - } else { + } + else + { $pdfformat = $conf->global->MAIN_PDF_FORMAT; } @@ -122,11 +123,7 @@ define('K_SMALL_RATIO', 2 / 3); define('K_THAI_TOPCHARS', true); define('K_TCPDF_CALLS_IN_HTML', true); - if (!empty($conf->global->TCPDF_THROW_ERRORS_INSTEAD_OF_DIE)) { - define('K_TCPDF_THROW_EXCEPTION_ERROR', true); - } else { - define('K_TCPDF_THROW_EXCEPTION_ERROR', false); - } + define('K_TCPDF_THROW_EXCEPTION_ERROR', false); } // Load TCPDF @@ -270,7 +267,7 @@ function pdf_getHeightForLogo($logo, $url = false) { global $conf; - $height = (empty($conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT) ? 20 : $conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT); + $height = (empty($conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT) ? 22 : $conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT); $maxwidth = 130; include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; $tmp = dol_getImageSize($logo, $url); @@ -293,41 +290,43 @@ */ function pdfGetHeightForHtmlContent(&$pdf, $htmlcontent) { - // store current object - $pdf->startTransaction(); - // store starting values - $start_y = $pdf->GetY(); - //var_dump($start_y); - $start_page = $pdf->getPage(); - // call printing functions with content - $pdf->writeHTMLCell(0, 0, 0, $start_y, $htmlcontent, 0, 1, false, true, 'J', true); - // get the new Y - $end_y = $pdf->GetY(); - $end_page = $pdf->getPage(); - // calculate height - $height = 0; - if ($end_page == $start_page) { - $height = $end_y - $start_y; - } else { - for ($page = $start_page; $page <= $end_page; ++$page) { - $pdf->setPage($page); - $tmpm = $pdf->getMargins(); - $tMargin = $tmpm['top']; - if ($page == $start_page) { - // first page - $height = $pdf->getPageHeight() - $start_y - $pdf->getBreakMargin(); - } elseif ($page == $end_page) { - // last page - $height = $end_y - $tMargin; - } else { - $height = $pdf->getPageHeight() - $tMargin - $pdf->getBreakMargin(); - } - } + // store current object + $pdf->startTransaction(); + // store starting values + $start_y = $pdf->GetY(); + //var_dump($start_y); + $start_page = $pdf->getPage(); + // call printing functions with content + $pdf->writeHTMLCell(0, 0, 0, $start_y, $htmlcontent, 0, 1, false, true, 'J', true); + // get the new Y + $end_y = $pdf->GetY(); + $end_page = $pdf->getPage(); + // calculate height + $height = 0; + if ($end_page == $start_page) { + $height = $end_y - $start_y; + } + else + { + for ($page = $start_page; $page <= $end_page; ++$page) { + $pdf->setPage($page); + $tmpm = $pdf->getMargins(); + $tMargin = $tmpm['top']; + if ($page == $start_page) { + // first page + $height = $pdf->getPageHeight() - $start_y - $pdf->getBreakMargin(); + } elseif ($page == $end_page) { + // last page + $height = $end_y - $tMargin; + } else { + $height = $pdf->getPageHeight() - $tMargin - $pdf->getBreakMargin(); + } + } } // restore previous object $pdf = $pdf->rollbackTransaction(); - return $height; + return $height; } @@ -341,7 +340,7 @@ */ function pdfBuildThirdpartyName($thirdparty, Translate $outputlangs, $includealias = 0) { - global $conf; + global $conf; // Recipient name $socname = ''; @@ -349,7 +348,7 @@ if ($thirdparty instanceof Societe) { $socname .= $thirdparty->name; if (($includealias || !empty($conf->global->PDF_INCLUDE_ALIAS_IN_THIRDPARTY_NAME)) && !empty($thirdparty->name_alias)) { - $socname .= " - ".$thirdparty->name_alias; + $socname .= " - ".$thirdparty->name_alias; } } elseif ($thirdparty instanceof Contact) { $socname = $thirdparty->socname; @@ -394,82 +393,82 @@ } if (empty($reshook)) { - if ($mode == 'source') - { - $withCountry = 0; - 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)) - { - // 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); - // 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); - } - // 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); - } - // Professionnal Ids - $reg = array(); - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1); - } - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2); - } - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3); - } - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4); - } - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5); - } - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6); - } - if (!empty($conf->global->PDF_ADD_MORE_AFTER_SOURCE_ADDRESS)) { - $stringaddress .= ($stringaddress ? "\n" : '').$conf->global->PDF_ADD_MORE_AFTER_SOURCE_ADDRESS; - } - } - - if ($mode == 'target' || preg_match('/targetwithdetails/', $mode)) - { - if ($usecontact) - { - $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs, 1)); - - if (!empty($targetcontact->address)) { - $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($targetcontact)); - } else { - $companytouseforaddress = $targetcompany; + if ($mode == 'source') + { + $withCountry = 0; + 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)) + { + // 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); + // 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); + } + // 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); + } + // Professionnal Ids + $reg = array(); + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1); + } + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2); + } + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3); + } + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4); + } + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5); + } + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6); + } + if (!empty($conf->global->PDF_ADD_MORE_AFTER_SOURCE_ADDRESS)) { + $stringaddress .= ($stringaddress ? "\n" : '').$conf->global->PDF_ADD_MORE_AFTER_SOURCE_ADDRESS; + } + } + + if ($mode == 'target' || preg_match('/targetwithdetails/', $mode)) + { + if ($usecontact) + { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs, 1)); + + if (!empty($targetcontact->address)) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($targetcontact)); + } else { + $companytouseforaddress = $targetcompany; // Contact on a thirdparty that is a different thirdparty than the thirdparty of object if ($targetcontact->socid > 0 && $targetcontact->socid != $targetcompany->id) @@ -480,129 +479,132 @@ $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($companytouseforaddress)); } - // Country - if (!empty($targetcontact->country_code) && $targetcontact->country_code != $sourcecompany->country_code) { - $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcontact->country_code)); - } elseif (empty($targetcontact->country_code) && !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)) - { - // 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); - } - // 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); - } - // 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); - } - } - } 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($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); - } - // 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); - } - // 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); - } - } - } - - // 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); - } - - // Professionnal Ids - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1); - } - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2); - } - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3); - } - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4); - } - 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]; - $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5); - } - 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]; - $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)) - { - $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($sourcecompany->note_public); - } - if (($mode == 'target' || preg_match('/targetwithdetails/', $mode)) && !empty($targetcompany->note_public)) - { - $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($targetcompany->note_public); - } - } - } + // Country + if (!empty($targetcontact->country_code) && $targetcontact->country_code != $sourcecompany->country_code) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcontact->country_code)); + } + elseif (empty($targetcontact->country_code) && !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)) + { + // 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); + } + // 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); + } + // 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); + } + } + } + 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($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); + } + // 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); + } + // 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); + } + } + } + + // 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); + } + + // Professionnal Ids + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1); + } + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2); + } + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3); + } + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4); + } + 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]; + $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5); + } + 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]; + $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)) + { + $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($sourcecompany->note_public); + } + if (($mode == 'target' || preg_match('/targetwithdetails/', $mode)) && !empty($targetcompany->note_public)) + { + $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($targetcompany->note_public); + } + } + } } return $stringaddress; @@ -642,10 +644,10 @@ */ function pdf_getSubstitutionArray($outputlangs, $exclude = null, $object = null, $onlykey = 0) { - $substitutionarray = getCommonSubstitutionArray($outputlangs, $onlykey, $exclude, $object); - $substitutionarray['__FROM_NAME__'] = '__FROM_NAME__'; - $substitutionarray['__FROM_EMAIL__'] = '__FROM_EMAIL__'; - return $substitutionarray; + $substitutionarray = getCommonSubstitutionArray($outputlangs, $onlykey, $exclude, $object); + $substitutionarray['__FROM_NAME__'] = '__FROM_NAME__'; + $substitutionarray['__FROM_EMAIL__'] = '__FROM_EMAIL__'; + return $substitutionarray; } @@ -750,12 +752,12 @@ 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); + // 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); foreach ($account->getFieldsToShow() as $val) @@ -779,7 +781,7 @@ // Key $tmplength = 15; $content = $account->cle_rib; - } elseif ($val == 'IBAN' || $val == 'BIC') { + }elseif ($val == 'IBAN' || $val == 'BIC') { // Key $tmplength = 0; $content = ''; @@ -796,12 +798,14 @@ if (empty($onlynumber)) { $pdf->line($curx, $cury + 1, $curx, $cury + 7); } - } - - $curx = $savcurx; - $cury += 8; - } - } else { + } + + $curx = $savcurx; + $cury += 8; + } + } + else + { $pdf->SetFont('', 'B', $default_font_size - $diffsizecontent); $pdf->SetXY($curx, $cury); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': '.$outputlangs->convToOutputCharset($account->bank), 0, 'L', 0); @@ -817,7 +821,8 @@ $pdf->SetFont('', '', $default_font_size - $diffsizecontent); - if (empty($onlynumber) && !empty($account->domiciliation)) { + if (empty($onlynumber) && !empty($account->domiciliation)) + { $pdf->SetXY($curx, $cury); $val = $outputlangs->transnoentities("Residence").': '.$outputlangs->convToOutputCharset($account->domiciliation); $pdf->MultiCell(100, 3, $val, 0, 'L', 0); @@ -827,15 +832,17 @@ $cury += $tmpy; } - if (!empty($account->proprio)) { + if (!empty($account->proprio)) + { $pdf->SetXY($curx, $cury); $val = $outputlangs->transnoentities("BankAccountOwner").': '.$outputlangs->convToOutputCharset($account->proprio); $pdf->MultiCell(100, 3, $val, 0, 'L', 0); $tmpy = $pdf->getStringHeight(100, $val); $cury += $tmpy; - } elseif (!$usedetailedbban) { - $cury += 1; - } + $cur += 1; + } + + elseif (!$usedetailedbban) $cury += 1; // Use correct name of bank id according to country $ibankey = FormBank::getIBANLabel($account); @@ -915,7 +922,7 @@ // First line of company infos $line1 = ""; $line2 = ""; $line3 = ""; $line4 = ""; - if ($showdetails == 1 || $showdetails == 3) + if ($showdetails == 1 || $showdetails == 3) { // Company name if ($fromcompany->name) @@ -1044,16 +1051,18 @@ if ($line) // Free text { //$line="sample text
\nfdsfsdf
\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'; - } - $freetextheight = $pdf->getStringHeight($width, $line); - } else { - $freetextheight = pdfGetHeightForHtmlContent($pdf, dol_htmlentitiesbr($line, 1, 'UTF-8', 0)); // New method (works for HTML content) - //print '
'.$freetextheight;exit; + if (!empty($conf->global->MAIN_USE_AUTOWRAP_ON_FREETEXT)) { + $width = 200; $align = 'C'; + } + $freetextheight = $pdf->getStringHeight($width, $line); + } + else + { + $freetextheight = pdfGetHeightForHtmlContent($pdf, dol_htmlentitiesbr($line, 1, 'UTF-8', 0)); // New method (works for HTML content) + //print '
'.$freetextheight;exit; } } @@ -1065,9 +1074,11 @@ $pdf->SetXY($dims['lm'], -$posy); 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)); + $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)); } $posy -= $freetextheight; } @@ -1139,11 +1150,11 @@ { foreach ($linkedobjects as $linkedobject) { - $reftoshow = $linkedobject["ref_title"].' : '.$linkedobject["ref_value"]; - if (!empty($linkedobject["date_value"])) - { - $reftoshow .= ' / '.$linkedobject["date_value"]; - } + $reftoshow = $linkedobject["ref_title"].' : '.$linkedobject["ref_value"]; + if (!empty($linkedobject["date_value"])) + { + $reftoshow .= ' / '.$linkedobject["date_value"]; + } $posy += 3; $pdf->SetXY($posx, $posy); @@ -1180,7 +1191,7 @@ //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 { - $special_code = empty($object->lines[$i]->special_code) ? '' : $object->lines[$i]->special_code; + $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); $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 = ''; @@ -1233,7 +1244,9 @@ { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $prodser = new ProductFournisseur($db); - } else { + } + else + { include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $prodser = new Product($db); } @@ -1253,15 +1266,13 @@ // If we want another language, and if label is same than default language (we did force it to a specific value), we can use translation. //var_dump($outputlangs->defaultlang.' - '.$langs->defaultlang.' - '.$label.' - '.$prodser->label);exit; $textwasmodified = ($label == $prodser->label); - if (!empty($prodser->multilangs[$outputlangs->defaultlang]["label"]) && ($textwasmodified || $translatealsoifmodified)) { - $label = $prodser->multilangs[$outputlangs->defaultlang]["label"]; - } + if (!empty($prodser->multilangs[$outputlangs->defaultlang]["label"]) && ($textwasmodified || $translatealsoifmodified)) $label = $prodser->multilangs[$outputlangs->defaultlang]["label"]; // Set desc // Manage HTML entities description test because $prodser->description is store with htmlentities but $desc no $textwasmodified = false; if (!empty($desc) && dol_textishtml($desc) && !empty($prodser->description) && dol_textishtml($prodser->description)) { - $textwasmodified = (strpos(dol_html_entity_decode($desc, ENT_QUOTES | ENT_HTML5), dol_html_entity_decode($prodser->description, ENT_QUOTES | ENT_HTML5)) !== false); + $textwasmodified = (strpos(dol_html_entity_decode($desc, ENT_QUOTES | ENT_HTML401), dol_html_entity_decode($prodser->description, ENT_QUOTES | ENT_HTML401)) !== false); } else { $textwasmodified = ($desc == $prodser->description); } @@ -1271,7 +1282,8 @@ $textwasmodified = ($note == $prodser->note); if (!empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified)) $note = $prodser->multilangs[$outputlangs->defaultlang]["note"]; } - } elseif ($object->element == 'facture' || $object->element == 'facturefourn') { + } + elseif ($object->element == 'facture' || $object->element == 'facturefourn') { if ($object->type == $object::TYPE_DEPOSIT) { $desc = str_replace('(DEPOSIT)', $outputlangs->trans('Deposit'), $desc); } @@ -1279,20 +1291,6 @@ // Description short of product line $libelleproduitservice = $label; - if (!empty($libelleproduitservice) && !empty($conf->global->PDF_BOLD_PRODUCT_LABEL)) { - $libelleproduitservice = ''.$libelleproduitservice.''; - } - - // Add ref of subproducts - if (!empty($conf->global->SHOW_SUBPRODUCT_REF_IN_PDF)) { - $prodser->get_sousproduits_arbo(); - if (!empty($prodser->sousprods) && is_array($prodser->sousprods) && count($prodser->sousprods)) { - $tmparrayofsubproducts = reset($prodser->sousprods); - foreach ($tmparrayofsubproducts as $subprodval) { - $libelleproduitservice .= "\n * ".$subprodval[5].(($subprodval[5] && $subprodval[3]) ? ' - ' : '').$subprodval[3].' ('.$subprodval[1].')'; - } - } - } // Description long of product line if (!empty($desc) && ($desc != $label)) @@ -1308,7 +1306,8 @@ $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); @@ -1316,37 +1315,37 @@ $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) + } + 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); - } else { - if ($idprod) { - // Check if description must be output - if (!empty($object->element)) { - $tmpkey = 'MAIN_DOCUMENTS_HIDE_DESCRIPTION_FOR_'.strtoupper($object->element); - if (!empty($conf->global->$tmpkey)) { - $hidedesc = 1; + } + else + { + if ($idprod) + { + if (empty($hidedesc)) + { + if (!empty($conf->global->MAIN_DOCUMENTS_DESCRIPTION_FIRST)) + { + $libelleproduitservice = $desc."\n".$libelleproduitservice; + } + else + { + $libelleproduitservice .= $desc; } } - if (empty($hidedesc)) { - if (!empty($conf->global->MAIN_DOCUMENTS_DESCRIPTION_FIRST)) { - $libelleproduitservice = $desc."\n".$libelleproduitservice; - } else { - if (!empty($conf->global->HIDE_LABEL_VARIANT_PDF) && $prodser->isVariant()) { - $libelleproduitservice = $desc; - } else { - $libelleproduitservice .= $desc; - } - } - } - } else { + } + else + { $libelleproduitservice .= $desc; } } @@ -1355,25 +1354,34 @@ // We add ref of product (and supplier ref if defined) $prefix_prodserv = ""; $ref_prodserv = ""; - if (!empty($conf->global->PRODUCT_ADD_TYPE_IN_DOCUMENTS)) { // In standard mode, we do not show this - if ($prodser->isService()) { + if (!empty($conf->global->PRODUCT_ADD_TYPE_IN_DOCUMENTS)) // In standard mode, we do not show this + { + if ($prodser->isService()) + { $prefix_prodserv = $outputlangs->transnoentitiesnoconv("Service")." "; - } else { + } + else + { $prefix_prodserv = $outputlangs->transnoentitiesnoconv("Product")." "; } } - if (empty($hideref)) { - if ($issupplierline) { - if (empty($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES)) { // Common case + if (empty($hideref)) + { + if ($issupplierline) + { + if ($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) + $ref_prodserv = $ref_supplier.' ('.$outputlangs->transnoentitiesnoconv("InternalRef").' '.$prodser->ref.')'; + else // Common case + { $ref_prodserv = $prodser->ref; // Show local 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) { - $ref_prodserv = $ref_supplier.' ('.$outputlangs->transnoentitiesnoconv("InternalRef").' '.$prodser->ref.')'; } - } else { + } + else + { $ref_prodserv = $prodser->ref; // Show local ref only } @@ -1402,7 +1410,7 @@ if (!empty($object->lines[$i]->date_start) || !empty($object->lines[$i]->date_end)) { $format = 'day'; - $period = ''; + $period = ''; // Show duration if exists if ($object->lines[$i]->date_start && $object->lines[$i]->date_end) { @@ -1418,9 +1426,9 @@ } //print '>'.$outputlangs->charset_output.','.$period; if (!empty($conf->global->PDF_BOLD_PRODUCT_REF_AND_PERIOD)) { - $libelleproduitservice .= ''."__N__ ".$period.''; + $libelleproduitservice .= ''."__N__ ".$period.''; } else { - $libelleproduitservice .= "__N__".$period; + $libelleproduitservice .= "__N__".$period; } //print $libelleproduitservice; } @@ -1636,7 +1644,7 @@ { if (empty($hidedetails) || $hidedetails > 1) { - $subprice = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_subprice : $object->lines[$i]->subprice); + $subprice = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_subprice : $object->lines[$i]->subprice); $result .= price($sign * $subprice, 0, $outputlangs); } } @@ -1705,10 +1713,10 @@ 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; } @@ -1741,8 +1749,8 @@ } if (empty($reshook)) { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_asked; + if ($object->lines[$i]->special_code == 3) return ''; + if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_asked; } return $result; } @@ -1775,8 +1783,8 @@ } if (empty($reshook)) { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_shipped; + if ($object->lines[$i]->special_code == 3) return ''; + if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_shipped; } return $result; } @@ -1795,8 +1803,8 @@ global $hookmanager; $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) ) ) + $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 { $special_code = $object->lines[$i]->special_code; @@ -1809,7 +1817,7 @@ } if (empty($reshook)) { - if ($object->lines[$i]->special_code == 3) return ''; + 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; @@ -1830,8 +1838,8 @@ global $langs; $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) ) ) + $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 { $special_code = $object->lines[$i]->special_code; @@ -1851,7 +1859,8 @@ } if (empty($reshook)) { - if (empty($hidedetails) || $hidedetails > 1) $result .= $langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short')); + if ($object->lines[$i]->special_code == 3) return ''; + if (empty($hidedetails) || $hidedetails > 1) $result .= $langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short')); } return $result; } @@ -1887,8 +1896,8 @@ } 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 ($object->lines[$i]->special_code == 3) return ''; + if (empty($hidedetails) || $hidedetails > 1) $result .= dol_print_reduction($object->lines[$i]->remise_percent, $outputlangs); } return $result; } @@ -1909,8 +1918,8 @@ 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) ) ) + $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 { $special_code = $object->lines[$i]->special_code; @@ -1923,7 +1932,7 @@ } if (empty($reshook)) { - if ($object->lines[$i]->special_code == 3) return ''; + if ($object->lines[$i]->special_code == 3) return ''; if (empty($hidedetails) || $hidedetails > 1) { if ($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF) @@ -1934,7 +1943,9 @@ $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.'%'; + } + else + $result = $object->lines[$i]->situation_percent.'%'; } } return $result; @@ -1969,32 +1980,34 @@ if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; } - 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) - { - // 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 (empty($reshook)) + { + if ($object->lines[$i]->special_code == 3) + { + return $outputlangs->transnoentities("Option"); + } + if (empty($hidedetails) || $hidedetails > 1) + { + $total_ht = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ht : $object->lines[$i]->total_ht); + 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')) + { $prev_progress = $object->lines[$i]->get_prev_progress($object->id); $progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100; - } + } $result .= price($sign * ($total_ht / ($object->lines[$i]->situation_percent / 100)) * $progress, 0, $outputlangs); - } else { - $result .= price($sign * $total_ht, 0, $outputlangs); - } - } - } - return $result; + } + else + { + $result .= price($sign * $total_ht, 0, $outputlangs); + } + } + } + return $result; } /** @@ -2029,27 +2042,10 @@ 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) - { - // 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')) - { - $prev_progress = $object->lines[$i]->get_prev_progress($object->id); - $progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100; - } - $result .= price($sign * ($total_ttc / ($object->lines[$i]->situation_percent / 100)) * $progress, 0, $outputlangs); - } else { - $result .= price($sign * $total_ttc, 0, $outputlangs); - } - } + { + $result .= $outputlangs->transnoentities("Option"); + } + elseif (empty($hidedetails) || $hidedetails > 1) $result .= price($sign * ($object->lines[$i]->total_ht) + ($object->lines[$i]->total_ht) * ($object->lines[$i]->tva_tx) / 100, 0, $outputlangs); } return $result; } @@ -2078,7 +2074,8 @@ 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); @@ -2086,13 +2083,15 @@ $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) - { - $total += $object->lines[$i]->qty; - } elseif ($type == 1 && $object->lines[$i]->product_type == 1) + } + elseif ($type == 0 && $object->lines[$i]->product_type == 0) { $total += $object->lines[$i]->qty; } + elseif ($type == 1 && $object->lines[$i]->product_type == 1) + { + $total += $object->lines[$i]->qty; + } } } @@ -2109,7 +2108,7 @@ */ function pdf_getLinkedObjects($object, $outputlangs) { - global $db, $hookmanager; + global $hookmanager; $linkedobjects = array(); @@ -2117,10 +2116,11 @@ 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') + 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') { $outputlangs->load('propal'); @@ -2131,7 +2131,8 @@ $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) @@ -2141,7 +2142,8 @@ $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) @@ -2151,7 +2153,8 @@ $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) @@ -2161,40 +2164,38 @@ $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) { - $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 - { - $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 (!is_object($order)) - { - $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefSending"); - 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.')' : ''); - $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); - //$linkedobjects[$objecttype]['date_value'].= ($elementobject->date_delivery ? ' / ' . dol_print_date($elementobject->date_delivery,'day','',$outputlangs) : ''); - } + $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 + { + $elementobject->fetchObjectLinked(); + if (!empty($elementobject->linkedObjects['commande'])) $order = reset($elementobject->linkedObjects['commande']); + } + if (!is_object($order)) + { + $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefSending"); + 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.')' : ''); + $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); + //$linkedobjects[$objecttype]['date_value'].= ($elementobject->date_delivery ? ' / ' . dol_print_date($elementobject->date_delivery,'day','',$outputlangs) : ''); + } } } } @@ -2233,7 +2234,8 @@ { $width = $maxwidth; $height = (int) round($maxwidth * $tmp['height'] / $tmp['width']); - } else // No pb with maxheight + } + else // No pb with maxheight { $height = $maxheight; } @@ -2258,7 +2260,9 @@ if ($object->lines[$i]->special_code == 3) { return $outputlangs->transnoentities("Option"); - } else { + } + else + { if (is_object($hookmanager)) { $special_code = $object->lines[$i]->special_code; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_prelevement.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_prelevement.lib.php @@ -39,13 +39,8 @@ $h = 0; $head = array(); - $titleoftab = "WithdrawalsReceipts"; - if ($object->type == 'bank-transfer') { - $titleoftab = "BankTransferReceipts"; - } - $head[$h][0] = DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$object->id; - $head[$h][1] = $langs->trans($titleoftab); + $head[$h][1] = $langs->trans("WithdrawalsReceipts"); $head[$h][2] = 'prelevement'; $h++; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_price.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_price.lib.php @@ -40,8 +40,8 @@ * @param float $pu Unit price (HT or TTC selon price_base_type) * @param float $remise_percent_ligne Discount for line * @param float $txtva 0=do not apply VAT tax, VAT rate=apply (this is VAT rate only without text code, we don't need text code because we alreaydy have all tax info into $localtaxes_array) - * @param float $uselocaltax1_rate 0=do not use localtax1, >0=apply and get value from localtaxes_array (or database if empty), -1=autodetect according to seller if we must apply, get value from localtaxes_array (or database if empty). Try to always use -1. - * @param float $uselocaltax2_rate 0=do not use localtax2, >0=apply and get value from localtaxes_array (or database if empty), -1=autodetect according to seller if we must apply, get value from localtaxes_array (or database if empty). Try to always use -1. + * @param float $uselocaltax1_rate 0=do not use this localtax, >0=apply and get value from localtaxes_array (or database if empty), -1=autodetect according to seller if we must apply, get value from localtaxes_array (or database if empty). Try to always use -1. + * @param float $uselocaltax2_rate 0=do not use this localtax, >0=apply and get value from localtaxes_array (or database if empty), -1=autodetect according to seller if we must apply, get value from localtaxes_array (or database if empty). Try to always use -1. * @param float $remise_percent_global 0 * @param string $price_base_type HT=Unit price parameter is HT, TTC=Unit price parameter is TTC * @param int $info_bits Miscellaneous informations on line @@ -103,13 +103,9 @@ $seller = $mysoc; // If sell is done to a customer, $seller is not provided, we use $mysoc //var_dump($seller->country_id);exit; } - if (empty($localtaxes_array) || !is_array($localtaxes_array)) { - dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter localtaxes_array that is missing or empty", LOG_WARNING); - } - if (!is_numeric($txtva)) { - dol_syslog("Price.lib::calcul_price_total Warning: function was called with a parameter vat rate that is not a real numeric value. There is surely a bug.", LOG_ERR); - } elseif ($txtva >= 1000) { - dol_syslog("Price.lib::calcul_price_total Warning: function was called with a bad value for vat rate (should be often < 100, always < 1000). There is surely a bug.", LOG_ERR); + if (empty($localtaxes_array) || !is_array($localtaxes_array)) + { + dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter localtaxes_array that is missing", LOG_WARNING); } // Too verbose. Enable for debug only //dol_syslog("Price.lib::calcul_price_total qty=".$qty." pu=".$pu." remiserpercent_ligne=".$remise_percent_ligne." txtva=".$txtva." uselocaltax1_rate=".$uselocaltax1_rate." uselocaltax2_rate=".$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$ice_base_type.' type='.$type.' progress='.$progress); @@ -125,21 +121,22 @@ //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); - // Now we search localtaxes information ourself (rates and types). + // Now we search localtaxes information ourself (rates and types). $localtax1_type = 0; $localtax2_type = 0; - if (is_array($localtaxes_array) && count($localtaxes_array)) { + if (is_array($localtaxes_array)) + { $localtax1_type = $localtaxes_array[0]; $localtax1_rate = $localtaxes_array[1]; $localtax2_type = $localtaxes_array[2]; $localtax2_rate = $localtaxes_array[3]; - } else { - // deprecated method. values and type for localtaxes must be provided by caller and loaded with getLocalTaxesFromRate using the full vat rate (including text code) - // also, with this method, we may get several possible values (for example with localtax2 in spain), so we take the first one. - dol_syslog("Price.lib::calcul_price_total search vat information using old deprecated method", LOG_WARNING); - - $sql = "SELECT taux, localtax1, localtax2, localtax1_type, localtax2_type"; + } + else // deprecated method. values and type for localtaxes must be provided by caller and loaded with getLocalTaxesFromRate using the full vat rate (including text code) + { + dol_syslog("Price.lib::calcul_price_total search vat information using old deprecated method", LOG_WARNING); + + $sql = "SELECT taux, localtax1, localtax2, localtax1_type, localtax2_type"; $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as cv"; $sql .= " WHERE cv.taux = ".$txtva; $sql .= " AND cv.fk_pays = ".$countryid; @@ -149,19 +146,21 @@ $obj = $db->fetch_object($resql); 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_rate = $obj->localtax1; + $localtax2_rate = $obj->localtax2; $localtax1_type = $obj->localtax1_type; $localtax2_type = $obj->localtax2_type; - //var_dump($localtax1_rate.' '.$localtax2_rate.' '.$localtax1_type.' '.$localtax2_type); + //var_dump($localtax1_rate.' '.$localtax2_rate.' '.$localtax1_type.' '.$localtax2_type);exit; } - } 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 { + 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(); } @@ -170,7 +169,8 @@ // 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 { + 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(); } @@ -186,35 +186,37 @@ // 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') - { - $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'); - } else { - $tot_sans_remise_wt = $tot_sans_remise; - $tot_avec_remise_wt = $tot_avec_remise; - $pu_wt = $pu; - } + // if input unit price is 'HT', we need to have the totals with main VAT for a correct calculation + 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'); + } + else + { + $tot_sans_remise_wt = $tot_sans_remise; + $tot_avec_remise_wt = $tot_avec_remise; + $pu_wt = $pu; + } //print 'rr'.$price_base_type.'-'.$txtva.'-'.$tot_sans_remise_wt."-".$pu_wt."-".$uselocaltax1_rate."-".$localtax1_rate."-".$localtax1_type."\n"; - $localtaxes = array(0, 0, 0); - $apply_tax = false; - switch ($localtax1_type) { - case '2': // localtax on product or service - $apply_tax = true; - break; - case '4': // localtax on product - if ($type == 0) $apply_tax = true; - break; - case '6': // localtax on service - if ($type == 1) $apply_tax = true; - break; - } - - if ($uselocaltax1_rate && $apply_tax) { + $localtaxes = array(0, 0, 0); + $apply_tax = false; + switch ($localtax1_type) { + case '2': // localtax on product or service + $apply_tax = true; + break; + case '4': // localtax on product + if ($type == 0) $apply_tax = true; + break; + case '6': // localtax on service + 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]; @@ -223,21 +225,21 @@ $result[11] = price2num(($pu_wt * (1 + ($localtax1_rate / 100))) - $pu_wt, 'MU'); $localtaxes[2] += $result[11]; - } - - $apply_tax = false; - switch ($localtax2_type) { - case '2': // localtax on product or service - $apply_tax = true; - break; - case '4': // localtax on product - if ($type == 0) $apply_tax = true; - break; - case '6': // localtax on service - if ($type == 1) $apply_tax = true; - break; - } - if ($uselocaltax2_rate && $apply_tax) { + } + + $apply_tax = false; + switch ($localtax2_type) { + case '2': // localtax on product or service + $apply_tax = true; + break; + case '4': // localtax on product + if ($type == 0) $apply_tax = true; + break; + case '6': // localtax on service + 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]; @@ -246,7 +248,7 @@ $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') @@ -266,7 +268,9 @@ $result[5] = price2num($pu * (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)) + $localtaxes[2], 'MU'); // Selon TVA NPR ou non $result5bis = price2num($pu * (1 + ($txtva / 100)) + $localtaxes[2], 'MU'); // Si TVA consideree normale (non NPR) $result[4] = price2num($result5bis - ($result[3] + $localtaxes[2]), 'MU'); - } else { + } + else + { // We work to define prices using the price with tax $result[8] = price2num($tot_sans_remise + $localtaxes[0], 'MT'); $result[6] = price2num($tot_sans_remise / (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)), 'MT'); // Selon TVA NPR ou non @@ -286,27 +290,27 @@ // 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') - { - $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'); - } + //If input unit price is 'TTC', we need to have the totals without main VAT for a correct calculation + 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'); + } $apply_tax = false; - switch ($localtax1_type) { - case '1': // localtax on product or service - $apply_tax = true; - break; - case '3': // localtax on product - if ($type == 0) $apply_tax = true; - break; - case '5': // localtax on service - if ($type == 1) $apply_tax = true; - break; - } - if ($uselocaltax1_rate && $apply_tax) { + switch ($localtax1_type) { + case '1': // localtax on product or service + $apply_tax = true; + break; + case '3': // localtax on product + if ($type == 0) $apply_tax = true; + break; + case '5': // localtax on service + 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 @@ -315,21 +319,21 @@ $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; - switch ($localtax2_type) { - case '1': // localtax on product or service - $apply_tax = true; - break; - case '3': // localtax on product - if ($type == 0) $apply_tax = true; - break; - case '5': // localtax on service - if ($type == 1) $apply_tax = true; - break; - } - if ($uselocaltax2_rate && $apply_tax) { + } + + $apply_tax = false; + switch ($localtax2_type) { + case '1': // localtax on product or service + $apply_tax = true; + break; + case '3': // localtax on product + if ($type == 0) $apply_tax = true; + break; + case '5': // localtax on service + 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 @@ -338,7 +342,7 @@ $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)) @@ -347,15 +351,17 @@ { $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[2] = price2num($result[0] + $result[1], 'MT'); $result[9] = round($result[9] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; $result[10] = round($result[10] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; - $result[2] = price2num($result[0] + $result[1] + $result[9] + $result[10], 'MT'); - } else { + } + else + { $result[1] = round($result[1] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; $result[2] = round($result[2] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; + $result[0] = price2num($result[2] - $result[1], 'MT'); $result[9] = round($result[9] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; $result[10] = round($result[10] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; - $result[0] = price2num($result[2] - $result[1] - $result[9] - $result[10], 'MT'); } } @@ -399,7 +405,9 @@ $result[24] = $newresult[8]; $result[25] = $newresult[9]; $result[26] = $newresult[10]; - } else { + } + else + { $result[16] = $result[0]; $result[17] = $result[1]; $result[18] = $result[2]; @@ -417,7 +425,7 @@ // initialize result array //for ($i=0; $i <= 18; $i++) $result[$i] = (float) $result[$i]; - dol_syslog('Price.lib::calcul_price_total MAIN_ROUNDING_RULE_TOT='.(empty($conf->global->MAIN_ROUNDING_RULE_TOT)?'':$conf->global->MAIN_ROUNDING_RULE_TOT).' pu='.$pu.' qty='.$qty.' price_base_type='.$price_base_type.' total_ht='.$result[0].'-total_vat='.$result[1].'-total_ttc='.$result[2]); + dol_syslog('Price.lib::calcul_price_total MAIN_ROUNDING_RULE_TOT='.$conf->global->MAIN_ROUNDING_RULE_TOT.' pu='.$pu.' qty='.$qty.' price_base_type='.$price_base_type.' total_ht='.$result[0].'-total_vat='.$result[1].'-total_ttc='.$result[2]); return $result; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_product.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_product.lib.php @@ -50,23 +50,24 @@ 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++; - } + $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($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'; - $h++; - } + 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'; + $h++; + } } // Multilangs @@ -90,6 +91,16 @@ $h++; } + $head[$h][0] = DOL_URL_ROOT."/product/stats/card.php?id=".$object->id; + $head[$h][1] = $langs->trans('Statistics'); + $head[$h][2] = 'stats'; + $h++; + + $head[$h][0] = DOL_URL_ROOT."/product/stats/facture.php?showmessage=1&id=".$object->id; + $head[$h][1] = $langs->trans('Referers'); + $head[$h][2] = 'referers'; + $h++; + if (!empty($conf->variants->enabled) && ($object->isProduct() || $object->isService())) { global $db; @@ -97,107 +108,105 @@ $prodcomb = new ProductCombination($db); - if ($prodcomb->fetchByFkProductChild($object->id) <= 0) + if ($prodcomb->fetchByFkProductChild($object->id) == -1) { $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) - { - $head[$h][0] = DOL_URL_ROOT."/product/stock/product.php?id=".$object->id; - $head[$h][1] = $langs->trans("Stock"); - $head[$h][2] = 'stock'; - $h++; - } - } - - // Tab to link resources - 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)) - { - $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'; - $h++; - } - } - - $head[$h][0] = DOL_URL_ROOT."/product/stats/facture.php?showmessage=1&id=".$object->id; - $head[$h][1] = $langs->trans('Referers'); - $head[$h][2] = 'referers'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/product/stats/card.php?id=".$object->id; - $head[$h][1] = $langs->trans('Statistics'); - $head[$h][2] = 'stats'; - $h++; - - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'product'); - - // Notes - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $nbNote = 0; - 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.''; - $head[$h][2] = 'note'; - $h++; - } - - // Attachments + + if (!empty($object->status)) + { + $head[$h][0] = DOL_URL_ROOT."/product/declin.php?id=".$object->id; + $head[$h][1] = $langs->trans("Déclinaisons"); + $head[$h][2] = 'declin'; + $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) + { + $head[$h][0] = DOL_URL_ROOT."/product/stock/product.php?id=".$object->id; + $head[$h][1] = $langs->trans("Stock"); + $head[$h][2] = 'stock'; + $h++; + } + } + + // Tab to link resources + 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)) + { + $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'; + $h++; + } + } + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'product'); + + // Notes + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $nbNote = 0; + 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.''; + $head[$h][2] = 'note'; + $h++; + } + + // 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); - $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'; - $nbFiles += count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - } - $nbLinks = Link::count($db, $object->element, $object->id); + 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); + $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'; + $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).''; $head[$h][2] = 'documents'; $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'product', 'remove'); - - // 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))) - { - $head[$h][1] .= '/'; - $head[$h][1] .= $langs->trans("Agenda"); - } - $head[$h][2] = 'agenda'; - $h++; + complete_head_from_modules($conf, $langs, $object, $head, $h, 'product', 'remove'); + + // 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))) + { + $head[$h][1] .= '/'; + $head[$h][1] .= $langs->trans("Agenda"); + } + $head[$h][2] = 'agenda'; + $h++; return $head; } @@ -210,48 +219,48 @@ */ function productlot_prepare_head($object) { - global $db, $langs, $conf, $user; - - // Load translation files required by the page - $langs->loadLangs(array("products", "productbatch")); - - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT."/product/stock/productlot_card.php?id=".$object->id; - $head[$h][1] = $langs->trans("Lot"); - $head[$h][2] = 'card'; + global $db, $langs, $conf, $user; + + // Load translation files required by the page + $langs->loadLangs(array("products", "productbatch")); + + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT."/product/stock/productlot_card.php?id=".$object->id; + $head[$h][1] = $langs->trans("Lot"); + $head[$h][2] = 'card'; $h++; // Attachments require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->productbatch->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); - $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->productbatch->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); + $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/stock/productlot_document.php?id=".$object->id; $head[$h][1] = $langs->trans("Documents"); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; - $head[$h][2] = 'documents'; - $h++; - - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'productlot'); - - complete_head_from_modules($conf, $langs, $object, $head, $h, 'productlot', 'remove'); - - // Log - /* + $head[$h][2] = 'documents'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'productlot'); + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'productlot', 'remove'); + + // Log + /* $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; + return $head; } @@ -285,8 +294,8 @@ // Show more tabs from modules // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, null, $head, $h, 'product_admin'); $head[$h][0] = DOL_URL_ROOT.'/product/admin/product_extrafields.php'; @@ -313,25 +322,25 @@ */ function product_lot_admin_prepare_head() { - global $langs, $conf, $user; - - $h = 0; - $head = array(); - - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, null, $head, $h, 'product_lot_admin'); - - $head[$h][0] = DOL_URL_ROOT.'/product/admin/product_lot_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes'; - $h++; - - complete_head_from_modules($conf, $langs, null, $head, $h, 'product_lot_admin', 'remove'); - - return $head; + global $langs, $conf, $user; + + $h = 0; + $head = array(); + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'product_lot_admin'); + + $head[$h][0] = DOL_URL_ROOT.'/product/admin/product_lot_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFields"); + $head[$h][2] = 'attributes'; + $h++; + + complete_head_from_modules($conf, $langs, null, $head, $h, 'product_lot_admin', 'remove'); + + return $head; } @@ -346,7 +355,6 @@ function show_stats_for_company($product, $socid) { global $conf, $langs, $user, $db; - $form = new Form($db); $nblines = 0; @@ -357,6 +365,24 @@ print ''.$langs->trans("TotalQuantity").''; print ''; + // MO + if (!empty($conf->mrp->enabled) && $user->rights->mrp->read) + { + $nblines++; + //$ret = $product->load_stats_mo($socid); + if ($ret < 0) dol_print_error($db); + $langs->load("orders"); + print ''; + print '
'.img_object('', 'mrp').' '.$langs->trans("MO").''; + print ''; + print $product->stats_mo['suppliers']; + print ''; + print $product->stats_mo['nb']; + print ''; + print $product->stats_mo['qty']; + print ''; + print ''; + } // Customer proposals if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { @@ -365,7 +391,7 @@ if ($ret < 0) dol_print_error($db); $langs->load("propal"); print ''; - print ''.img_object('', 'propal', 'class="paddingright"').$langs->trans("Proposals").''; + print ''.img_object('', 'propal').' '.$langs->trans("Proposals").''; print ''; print $product->stats_propale['customers']; print ''; @@ -381,9 +407,9 @@ $nblines++; $ret = $product->load_stats_proposal_supplier($socid); if ($ret < 0) dol_print_error($db); - $langs->load("supplier_proposal"); - print ''; - print ''.img_object('', 'supplier_proposal', 'class="paddingright"').$langs->trans("SupplierProposals").''; + $langs->load("propal"); + print ''; + print ''.img_object('', 'supplier_proposal').' '.$langs->trans("SupplierProposals").''; print ''; print $product->stats_proposal_supplier['suppliers']; print ''; @@ -401,7 +427,7 @@ if ($ret < 0) dol_print_error($db); $langs->load("orders"); print ''; - print ''.img_object('', 'order', 'class="paddingright"').$langs->trans("CustomersOrders").''; + print ''.img_object('', 'order').' '.$langs->trans("CustomersOrders").''; print ''; print $product->stats_commande['customers']; print ''; @@ -419,7 +445,7 @@ if ($ret < 0) dol_print_error($db); $langs->load("orders"); print ''; - print ''.img_object('', 'supplier_order', 'class="paddingright"').$langs->trans("SuppliersOrders").''; + print ''.img_object('', 'supplier_order').' '.$langs->trans("SuppliersOrders").''; print ''; print $product->stats_commande_fournisseur['suppliers']; print ''; @@ -455,7 +481,7 @@ if ($ret < 0) dol_print_error($db); $langs->load("bills"); print ''; - print ''.img_object('', 'supplier_invoice', 'class="paddingright"').$langs->trans("SuppliersInvoices").''; + print ''.img_object('', 'supplier_invoice').' '.$langs->trans("SuppliersInvoices").''; print ''; print $product->stats_facture_fournisseur['suppliers']; print ''; @@ -474,67 +500,13 @@ if ($ret < 0) dol_print_error($db); $langs->load("contracts"); print ''; - print ''.img_object('', 'contract', 'class="paddingright"').$langs->trans("Contracts").''; + print ''.img_object('', 'contract').' '.$langs->trans("Contracts").''; print ''; print $product->stats_contrat['customers']; print ''; print $product->stats_contrat['nb']; print ''; print $product->stats_contrat['qty']; - print ''; - print ''; - } - - // BOM - if (!empty($conf->bom->enabled) && $user->rights->bom->read) - { - $nblines++; - $ret = $product->load_stats_bom($socid); - if ($ret < 0) { - setEventMessage($product->error, 'errors'); - } - $langs->load("mrp"); - - print ''; - print ''.img_object('', 'bom', 'class="paddingright"').$langs->trans("BOM").''; - print ''; - - print ''; - 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_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) - { - $nblines++; - $ret = $product->load_stats_mo($socid); - if ($ret < 0) { - setEventMessage($product->error, 'errors'); - } - $langs->load("mrp"); - print ''; - 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")); - print $form->textwithpicto($product->stats_mo['customers_toproduce'], $langs->trans("QtyToProduce")); - print $form->textwithpicto($product->stats_mo['customers_produced'], $langs->trans("QtyAlreadyProduced")); - print ''; - print $form->textwithpicto($product->stats_mo['nb_toconsume'], $langs->trans("ToConsume")); - print $form->textwithpicto($product->stats_mo['nb_consumed'], $langs->trans("QtyAlreadyConsumed")); - print $form->textwithpicto($product->stats_mo['nb_toproduce'], $langs->trans("QtyToProduce")); - print $form->textwithpicto($product->stats_mo['nb_produced'], $langs->trans("QtyAlreadyProduced")); - print ''; - print $form->textwithpicto($product->stats_mo['qty_toconsume'], $langs->trans("ToConsume")); - print $form->textwithpicto($product->stats_mo['qty_consumed'], $langs->trans("QtyAlreadyConsumed")); - print $form->textwithpicto($product->stats_mo['qty_toproduce'], $langs->trans("QtyToProduce")); - print $form->textwithpicto($product->stats_mo['qty_produced'], $langs->trans("QtyAlreadyProduced")); print ''; print ''; } @@ -546,17 +518,16 @@ * Return translation label of a unit key. * Function kept for backward compatibility. * - * @param string $scale Scale of unit: '0', '-3', '6', ... - * @param string $measuring_style Style of unit: weight, volume,... - * @param int $unit ID of unit (rowid in llx_c_units table) - * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated. - * @param Translate $outputlangs Language object - * @return string Unit string + * @param string $scale Scale of unit: '0', '-3', '6', ... + * @param string $measuring_style Style of unit: weight, volume,... + * @param int $unit ID of unit (rowid in llx_c_units table) + * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated. + * @return string Unit string * @see measuringUnitString() formproduct->selectMeasuringUnits() */ -function measuring_units_string($scale = '', $measuring_style = '', $unit = 0, $use_short_label = 0, $outputlangs = null) -{ - return measuringUnitString($unit, $measuring_style, $scale, $use_short_label, $outputlangs); +function measuring_units_string($scale = '', $measuring_style = '', $unit = 0, $use_short_label = 0) +{ + return measuringUnitString($unit, $measuring_style, $scale, $use_short_label); } /** @@ -566,18 +537,13 @@ * @param string $measuring_style Style of unit: 'weight', 'volume', ..., '' = 'net_measure' for option PRODUCT_ADD_NET_MEASURE * @param string $scale Scale of unit: '0', '-3', '6', ... * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated. - * @param Translate $outputlangs Language object * @return string Unit string * @see formproduct->selectMeasuringUnits() */ -function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_short_label = 0, $outputlangs = null) +function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_short_label = 0) { global $langs, $db; global $measuring_unit_cache; - - if (empty($outputlangs)) { - $outputlangs = $langs; - } if (empty($measuring_unit_cache[$unit.'_'.$measuring_style.'_'.$scale.'_'.$use_short_label])) { @@ -590,14 +556,17 @@ 't.rowid' => $unit, 't.active' => 1 ); - } elseif ($scale !== '') + } + elseif ($scale !== '') { $arrayforfilter = array( 't.scale' => $scale, 't.unit_type' => $measuring_style, 't.active' => 1 ); - } else { + } + else + { $arrayforfilter = array( 't.rowid' => $unit, 't.unit_type' => $measuring_style, @@ -611,14 +580,15 @@ } 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); + else $labeltoreturn = $langs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label); } else { $labeltoreturn = ''; } $measuring_unit_cache[$unit.'_'.$measuring_style.'_'.$scale.'_'.$use_short_label] = $labeltoreturn; return $labeltoreturn; } - } else { + } + else { return $measuring_unit_cache[$unit.'_'.$measuring_style.'_'.$scale.'_'.$use_short_label]; } } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_project.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_project.lib.php @@ -30,23 +30,23 @@ /** * Prepare array with list of tabs * - * @param Project $project Object related to tabs - * @return array Array of tabs to show + * @param Object $object Object related to tabs + * @return array Array of tabs to show */ -function project_prepare_head(Project $project) +function project_prepare_head($object) { global $db, $langs, $conf, $user; $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/projet/card.php?id='.$project->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/card.php?id='.$object->id; $head[$h][1] = $langs->trans("Project"); $head[$h][2] = 'project'; $h++; - $nbContact = count($project->liste_contact(-1, 'internal')) + count($project->liste_contact(-1, 'external')); - $head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$project->id; + $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$object->id; $head[$h][1] = $langs->trans("ProjectContact"); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; $head[$h][2] = 'contact'; @@ -55,12 +55,12 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) { // Then tab for sub level of projet, i mean tasks - $head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$project->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$object->id; $head[$h][1] = $langs->trans("Tasks"); require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; $taskstatic = new Task($db); - $nbTasks = count($taskstatic->getTasksArray(0, 0, $project->id, 0, 0)); + $nbTasks = count($taskstatic->getTasksArray(0, 0, $object->id, 0, 0)); if ($nbTasks > 0) $head[$h][1] .= ''.($nbTasks).''; $head[$h][2] = 'tasks'; $h++; @@ -71,15 +71,16 @@ //$sql .= " WHERE t.fk_user = u.rowid AND t.fk_task = pt.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt"; $sql .= " WHERE t.fk_task = pt.rowid"; - $sql .= " AND pt.fk_projet =".$project->id; + $sql .= " AND pt.fk_projet =".$object->id; $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); if ($obj) $nbTimeSpent = 1; - } else dol_print_error($db); - - $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?withproject=1&projectid='.$project->id; + } + else dol_print_error($db); + + $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?withproject=1&projectid='.$object->id; $head[$h][1] = $langs->trans("TimeSpent"); if ($nbTimeSpent > 0) $head[$h][1] .= '...'; $head[$h][2] = 'timespent'; @@ -91,32 +92,8 @@ || !empty($conf->facture->enabled) || !empty($conf->contrat->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) { - $count = 0; - - if (!empty($conf->propal->enabled)) $count += $project->getElementCount('propal', 'propal'); - if (!empty($conf->commande->enabled)) $count += $project->getElementCount('order', 'commande'); - if (!empty($conf->facture->enabled)) $count += $project->getElementCount('invoice', 'facture'); - if (!empty($conf->facture->enabled)) $count += $project->getElementCount('invoice_predefined', 'facture_rec'); - if (!empty($conf->supplier_proposal->enabled)) $count += $project->getElementCount('proposal_supplier', 'supplier_proposal'); - if (!empty($conf->supplier_order->enabled)) $count += $project->getElementCount('order_supplier', 'commande_fournisseur'); - if (!empty($conf->supplier_invoice->enabled)) $count += $project->getElementCount('invoice_supplier', 'facture_fourn'); - if (!empty($conf->contrat->enabled)) $count += $project->getElementCount('contract', 'contrat'); - if (!empty($conf->ficheinter->enabled)) $count += $project->getElementCount('intervention', 'fichinter'); - if (!empty($conf->expedition->enabled)) $count += $project->getElementCount('shipping', 'expedition'); - if (!empty($conf->mrp->enabled)) $count += $project->getElementCount('mrp', 'mrp_mo', 'fk_project'); - if (!empty($conf->deplacement->enabled)) $count += $project->getElementCount('trip', 'deplacement'); - if (!empty($conf->expensereport->enabled)) $count += $project->getElementCount('expensereport', 'expensereport'); - if (!empty($conf->don->enabled)) $count += $project->getElementCount('donation', 'don'); - if (!empty($conf->loan->enabled)) $count += $project->getElementCount('loan', 'loan'); - if (!empty($conf->tax->enabled)) $count += $project->getElementCount('chargesociales', 'chargesociales'); - if (!empty($conf->projet->enabled)) $count += $project->getElementCount('project_task', 'projet_task'); - if (!empty($conf->stock->enabled)) $count += $project->getElementCount('stock_mouvement', 'stock'); - if (!empty($conf->salaries->enabled)) $count += $project->getElementCount('salaries', 'payment_salary'); - if (!empty($conf->banque->enabled)) $count += $project->getElementCount('variouspayment', 'payment_various'); - - $head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$project->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$object->id; $head[$h][1] = $langs->trans("ProjectOverview"); - if ($count > 0) $head[$h][1] .= ''.$count.''; $head[$h][2] = 'element'; $h++; } @@ -125,15 +102,15 @@ // Entries must be declared in modules descriptor with line // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $project, $head, $h, 'project'); + complete_head_from_modules($conf, $langs, $object, $head, $h, 'project'); if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($project->note_private)) $nbNote++; - if (!empty($project->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/projet/note.php?id='.$project->id; + if (!empty($object->note_private)) $nbNote++; + if (!empty($object->note_public)) $nbNote++; + $head[$h][0] = DOL_URL_ROOT.'/projet/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; $head[$h][2] = 'notes'; @@ -142,10 +119,10 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($project->ref); + $upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $project->element, $project->id); - $head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$project->id; + $nbLinks = Link::count($db, $object->element, $object->id); + $head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; $head[$h][2] = 'document'; @@ -154,15 +131,15 @@ // Manage discussion if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) { - $nbComments = $project->getNbComments(); - $head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$project->id; + $nbComments = $object->getNbComments(); + $head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$object->id; $head[$h][1] = $langs->trans("CommentLink"); if ($nbComments > 0) $head[$h][1] .= ''.$nbComments.''; $head[$h][2] = 'project_comment'; $h++; } - $head[$h][0] = DOL_URL_ROOT.'/projet/info.php?id='.$project->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/info.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))) { @@ -172,7 +149,7 @@ $head[$h][2] = 'agenda'; $h++; - complete_head_from_modules($conf, $langs, $project, $head, $h, 'project', 'remove'); + complete_head_from_modules($conf, $langs, $object, $head, $h, 'project', 'remove'); return $head; } @@ -191,7 +168,7 @@ $head = array(); $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/task.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); - $head[$h][1] = $langs->trans("Task"); + $head[$h][1] = $langs->trans("Project"); $head[$h][2] = 'task_task'; $h++; @@ -214,7 +191,8 @@ { $obj = $db->fetch_object($resql); if ($obj) $nbTimeSpent = 1; - } else dol_print_error($db); + } + 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"); @@ -409,7 +387,7 @@ $total_projectlinesa_spent = 0; $total_projectlinesa_planned = 0; $total_projectlinesa_spent_if_planned = 0; - $total_projectlinesa_declared_if_planned = 0; + $total_projectlinesa_declared_if_planned = 0; $total_projectlinesa_tobill = 0; $total_projectlinesa_billed = 0; } @@ -440,11 +418,15 @@ if ($foundtaskforuserdeeper > 0) { $showlineingray = 1; // We will show line but in gray - } else { + } + else + { $showline = 0; // No reason to show line } } - } else { + } + 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)) @@ -476,7 +458,6 @@ $projectstatic->public = $lines[$i]->public; $projectstatic->title = $lines[$i]->projectlabel; $projectstatic->usage_bill_time = $lines[$i]->usage_bill_time; - $projectstatic->status = $lines[$i]->projectstatus; $taskstatic->id = $lines[$i]->id; $taskstatic->ref = $lines[$i]->ref; @@ -484,11 +465,9 @@ $taskstatic->projectstatus = $lines[$i]->projectstatus; $taskstatic->progress = $lines[$i]->progress; $taskstatic->fk_statut = $lines[$i]->status; - $taskstatic->date_start = $lines[$i]->date_start; - $taskstatic->date_end = $lines[$i]->date_end; - $taskstatic->datee = $lines[$i]->date_end; // deprecated - $taskstatic->planned_workload = $lines[$i]->planned_workload; - $taskstatic->duration_effective = $lines[$i]->duration; + $taskstatic->datee = $lines[$i]->date_end; + $taskstatic->planned_workload = $lines[$i]->planned_workload; + $taskstatic->duration_effective = $lines[$i]->duration; if ($showproject) @@ -625,7 +604,7 @@ if ($showbilltime) { - // Time not billed + // Time not billed if (count($arrayfields) > 0 && !empty($arrayfields['t.tobill']['checked'])) { print ''; if ($lines[$i]->usage_bill_time) { @@ -637,7 +616,7 @@ print ''; } - // Time billed + // Time billed if (count($arrayfields) > 0 && !empty($arrayfields['t.billed']['checked'])) { print ''; if ($lines[$i]->usage_bill_time) { @@ -681,7 +660,10 @@ print $hookmanager->resPrint; // Tick to drag and drop - print ''; + if ($addordertick) + { + print ' '; + } print "\n"; @@ -697,15 +679,17 @@ $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_declared_if_planned += $lines[$i]->planned_workload * $lines[$i]->progress / 100; } - } else { + } + else + { //$level--; } } 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").''; @@ -728,28 +712,28 @@ print ''; } - if ($total_projectlinesa_planned) { - $totalAverageDeclaredProgress = round(100 * $total_projectlinesa_declared_if_planned / $total_projectlinesa_planned, 2); - $totalCalculatedProgress = round(100 * $total_projectlinesa_spent / $total_projectlinesa_planned, 2); - - // this conf is actually hidden, by default we use 10% for "be carefull or warning" - $warningRatio = !empty($conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT) ? (1 + $conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT / 100) : 1.10; - - // define progress color according to time spend vs workload - $progressBarClass = 'progress-bar-info'; - $badgeClass = 'badge '; - - if ($totalCalculatedProgress > $totalAverageDeclaredProgress) { - $progressBarClass = 'progress-bar-danger'; - $badgeClass .= 'badge-danger'; - } elseif ($totalCalculatedProgress * $warningRatio >= $totalAverageDeclaredProgress) { // warning if close at 1% - $progressBarClass = 'progress-bar-warning'; - $badgeClass .= 'badge-warning'; - } else { - $progressBarClass = 'progress-bar-success'; - $badgeClass .= 'badge-success'; - } - } + if ($total_projectlinesa_planned) { + $totalAverageDeclaredProgress = round(100 * $total_projectlinesa_declared_if_planned / $total_projectlinesa_planned, 2); + $totalCalculatedProgress = round(100 * $total_projectlinesa_spent / $total_projectlinesa_planned, 2); + + // this conf is actually hidden, by default we use 10% for "be carefull or warning" + $warningRatio = !empty($conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT) ? (1 + $conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT / 100) : 1.10; + + // define progress color according to time spend vs workload + $progressBarClass = 'progress-bar-info'; + $badgeClass = 'badge '; + + if ($totalCalculatedProgress > $totalAverageDeclaredProgress) { + $progressBarClass = 'progress-bar-danger'; + $badgeClass .= 'badge-danger'; + } elseif ($totalCalculatedProgress * $warningRatio >= $totalAverageDeclaredProgress) { // warning if close at 1% + $progressBarClass = 'progress-bar-warning'; + $badgeClass .= 'badge-warning'; + } else { + $progressBarClass = 'progress-bar-success'; + $badgeClass .= 'badge-success'; + } + } if (count($arrayfields) > 0 && !empty($arrayfields['t.progress_calculated']['checked'])) { print ''; @@ -765,7 +749,7 @@ } - // resume + // resume if (count($arrayfields) > 0 && !empty($arrayfields['t.progress_summary']['checked'])) { print ''; if ($total_projectlinesa_planned) { @@ -796,7 +780,7 @@ { print ''; } - print ''; + if ($addordertick) print ''; print ''; } @@ -882,7 +866,6 @@ $projectstatic->ref = $lines[$i]->project_ref; $projectstatic->title = $lines[$i]->project_label; $projectstatic->public = $lines[$i]->public; - $projectstatic->status = $lines[$i]->project_status; $taskstatic->id = $lines[$i]->task_id; $taskstatic->ref = ($lines[$i]->task_ref ? $lines[$i]->task_ref : $lines[$i]->task_id); @@ -1083,7 +1066,7 @@ if ($lines[$i]->fk_task_parent == $parent) { - $obj = &$lines[$i]; // To display extrafields + $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])) @@ -1131,13 +1114,13 @@ 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++; - } + $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++; + } print ''."\n"; print ''; @@ -1227,17 +1210,17 @@ // 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]); - print ""; + print ""; + 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)) { - print ''; - if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10); - print ''; + print ''; + if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10); + print ''; } // Ref @@ -1251,27 +1234,27 @@ for ($k = 0; $k < $level; $k++) print "
"; print "\n"; - // TASK extrafields - $extrafieldsobjectkey = 'projet_task'; - $extrafieldsobjectprefix = 'efpt.'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - - // Planned Workload - if (!empty($arrayfields['t.planned_workload']['checked'])) - { - print ''; - if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); - else print '--:--'; - print ''; - } + // TASK extrafields + $extrafieldsobjectkey = 'projet_task'; + $extrafieldsobjectprefix = 'efpt.'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + + // Planned Workload + if (!empty($arrayfields['t.planned_workload']['checked'])) + { + print ''; + if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); + else print '--:--'; + print ''; + } // Progress declared % - if (!empty($arrayfields['t.progress']['checked'])) - { - print ''; - print $formother->select_percent($lines[$i]->progress, $lines[$i]->id.'progress'); - print ''; - } + if (!empty($arrayfields['t.progress']['checked'])) + { + print ''; + print $formother->select_percent($lines[$i]->progress, $lines[$i]->id.'progress'); + print ''; + } // Time spent by everybody print ''; @@ -1281,7 +1264,8 @@ print ''; print convertSecondToTime($lines[$i]->duration, 'allhourmin'); print ''; - } else print '--:--'; + } + else print '--:--'; print "\n"; // Time spent by user @@ -1320,11 +1304,11 @@ global $daytoparse; $tmparray = dol_getdate($daytoparse, true); // detail of current day - - $idw = ($tmparray['wday'] - (empty($conf->global->MAIN_START_WEEK) ? 0 : 1)); + $idw = $tmparray['wday']; + 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'; } @@ -1395,7 +1379,9 @@ //var_dump($totalforeachday); } $level--; - } else { + } + else + { //$level--; } } @@ -1440,7 +1426,7 @@ { for ($i = 0; $i < $numlines; $i++) { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; + if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; } } @@ -1457,7 +1443,7 @@ if ($lines[$i]->fk_task_parent == $parent) { - $obj = &$lines[$i]; // To display extrafields + $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])) @@ -1504,13 +1490,13 @@ 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++; - } + $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++; + } print ''."\n"; print ''; @@ -1522,7 +1508,7 @@ print ''.$projectstatic->title.''; } - /*$colspan=5+(empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:2); + /*$colspan=5+(empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:2); print ''; print ''; @@ -1600,17 +1586,17 @@ // Project if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { - print '"; + print '"; } // Thirdparty if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { - print ''; + print ''; } // Ref @@ -1625,26 +1611,26 @@ print "\n"; // TASK extrafields - $extrafieldsobjectkey = 'projet_task'; - $extrafieldsobjectprefix = 'efpt.'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - - // Planned Workload - if (!empty($arrayfields['t.planned_workload']['checked'])) - { - print ''; - } - - if (!empty($arrayfields['t.progress']['checked'])) - { - // Progress declared % - print ''; - } + $extrafieldsobjectkey = 'projet_task'; + $extrafieldsobjectprefix = 'efpt.'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + + // Planned Workload + if (!empty($arrayfields['t.planned_workload']['checked'])) + { + print ''; + } + + if (!empty($arrayfields['t.progress']['checked'])) + { + // Progress declared % + print ''; + } // Time spent by everybody print '\n"; // Time spent by user @@ -1703,13 +1690,12 @@ 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'; } $tableCell = '\n"; // Time spent by user @@ -2017,7 +2005,9 @@ //var_dump($totalforeachday); } $level--; - } else { + } + else + { //$level--; } } @@ -2119,7 +2109,9 @@ $sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; - } else { + } + else + { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t ON p.rowid = t.fk_projet"; } $sql .= " WHERE p.entity IN (".getEntity('project').")"; @@ -2167,30 +2159,25 @@ $arrayidofprojects[$objp->projectid] = $objp->projectid; $i++; } - } else dol_print_error($db); + } + else dol_print_error($db); if (empty($arrayidofprojects)) $arrayidofprojects[0] = -1; // Get list of project with calculation on tasks - $sql2 = "SELECT p.rowid as projectid, p.ref, p.title, p.fk_soc,"; - $sql2 .= " s.rowid as socid, s.nom as socname, s.name_alias,"; - $sql2 .= " s.code_client, s.code_compta, s.client,"; - $sql2 .= " s.code_fournisseur, s.code_compta_fournisseur, s.fournisseur,"; - $sql2 .= " s.logo, s.email, s.entity,"; - $sql2 .= " p.fk_user_creat, p.public, p.fk_statut as status, p.fk_opp_status as opp_status, p.opp_percent, p.opp_amount,"; + $sql2 = "SELECT p.rowid as projectid, p.ref, p.title, p.fk_soc, s.nom as socname, p.fk_user_creat, p.public, p.fk_statut as status, p.fk_opp_status as opp_status, p.opp_percent, p.opp_amount,"; $sql2 .= " p.dateo, p.datee,"; $sql2 .= " COUNT(t.rowid) as nb, SUM(t.planned_workload) as planned_workload, SUM(t.planned_workload * t.progress / 100) as declared_progess_workload"; $sql2 .= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql2 .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc"; $sql2 .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t ON p.rowid = t.fk_projet"; $sql2 .= " WHERE p.rowid IN (".join(',', $arrayidofprojects).")"; - $sql2 .= " GROUP BY p.rowid, p.ref, p.title, p.fk_soc, s.rowid, s.nom, s.name_alias, s.code_client, s.code_compta, s.client, s.code_fournisseur, s.code_compta_fournisseur, s.fournisseur,"; - $sql2 .= " s.logo, s.email, s.entity, p.fk_user_creat, p.public, p.fk_statut, p.fk_opp_status, p.opp_percent, p.opp_amount, p.dateo, p.datee"; + $sql2 .= " GROUP BY p.rowid, p.ref, p.title, p.fk_soc, s.nom, p.fk_user_creat, p.public, p.fk_statut, p.fk_opp_status, p.opp_percent, p.opp_amount, p.dateo, p.datee"; $sql2 .= " ORDER BY p.title, p.ref"; $resql = $db->query($sql2); if ($resql) { - $total_task = 0; + $total_task = 0; $total_opp_amount = 0; $ponderated_opp_amount = 0; @@ -2230,6 +2217,7 @@ if ($userAccess >= 0) { $projectstatic->ref = $objp->ref; + $projectstatic->statut = $objp->status; // deprecated $projectstatic->status = $objp->status; $projectstatic->title = $objp->title; $projectstatic->datee = $db->jdate($objp->datee); @@ -2245,18 +2233,9 @@ print ''; @@ -2360,7 +2339,9 @@ print ''; $db->free($resql); - } else { + } + else + { dol_print_error($db); } @@ -2391,117 +2372,123 @@ */ function getTaskProgressView($task, $label = true, $progressNumber = true, $hideOnProgressNull = false, $spaced = false) { - global $langs, $conf; - - $out = ''; - - $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($task->progress) && !empty($hideOnProgressNull)) { - return ''; - } - - $spaced = !empty($spaced) ? 'spaced' : ''; - - $diff = ''; - - // define progress color according to time spend vs workload - $progressBarClass = 'progress-bar-info'; - if ($task->planned_workload) { - $progressCalculated = round(100 * doubleval($task->duration_effective) / doubleval($task->planned_workload), 2); - - // this conf is actually hidden, by default we use 10% for "be carefull or warning" - $warningRatio = !empty($conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT) ? (1 + $conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT / 100) : 1.10; - - $diffTitle = '
'.$langs->trans('ProgressDeclared').' : '.$task->progress.($task->progress ? '%' : ''); - $diffTitle .= '
'.$langs->trans('ProgressCalculated').' : '.$progressCalculated.($progressCalculated ? '%' : ''); - - //var_dump($progressCalculated.' '.$warningRatio.' '.$task->progress.' '.doubleval($task->progress * $warningRatio)); - if (doubleval($progressCalculated) > doubleval($task->progress * $warningRatio)) { - $progressBarClass = 'progress-bar-danger'; - $title = $langs->trans('TheReportedProgressIsLessThanTheCalculatedProgressionByX', abs($task->progress - $progressCalculated).' '.$langs->trans("point")); - $diff = ' '.($task->progress - $progressCalculated).'%'; - } elseif (doubleval($progressCalculated) > doubleval($task->progress)) { // warning if close at 10% - $progressBarClass = 'progress-bar-warning'; - $title = $langs->trans('TheReportedProgressIsLessThanTheCalculatedProgressionByX', abs($task->progress - $progressCalculated).' '.$langs->trans("point")); - $diff = ' '.($task->progress - $progressCalculated).'%'; - } else { - $progressBarClass = 'progress-bar-success'; - $title = $langs->trans('TheReportedProgressIsMoreThanTheCalculatedProgressionByX', ($task->progress - $progressCalculated).' '.$langs->trans("point")); - $diff = ' '.($task->progress - $progressCalculated).'%'; - } - } - - $out .= '
'; - - if ($label !== false) - { - $out .= ' '; - - if ($label !== true) { - $out .= $label; // replace label by param - } else { - $out .= $task->getNomUrl(1).' '.dol_htmlentities($task->label); - } - $out .= ' '; - } - - - if ($progressNumber !== false) - { - $out .= ' '; - if ($progressNumber !== true) { - $out .= $progressNumber; // replace label by param - } else { - if ($task->hasDelay()) $out .= img_warning($langs->trans("Late")).' '; + global $langs, $conf; + + $out = ''; + + $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($task->progress) && !empty($hideOnProgressNull)) { + return ''; + } + + $spaced = !empty($spaced) ? 'spaced' : ''; + + $diff = ''; + + // define progress color according to time spend vs workload + $progressBarClass = 'progress-bar-info'; + if ($task->planned_workload) { + $progressCalculated = round(100 * doubleval($task->duration_effective) / doubleval($task->planned_workload), 2); + + // this conf is actually hidden, by default we use 10% for "be carefull or warning" + $warningRatio = !empty($conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT) ? (1 + $conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT / 100) : 1.10; + + $diffTitle = '
'.$langs->trans('ProgressDeclared').' : '.$task->progress.($task->progress ? '%' : ''); + $diffTitle .= '
'.$langs->trans('ProgressCalculated').' : '.$progressCalculated.($progressCalculated ? '%' : ''); + + //var_dump($progressCalculated.' '.$warningRatio.' '.$task->progress.' '.doubleval($task->progress * $warningRatio)); + if (doubleval($progressCalculated) > doubleval($task->progress * $warningRatio)) { + $progressBarClass = 'progress-bar-danger'; + $title = $langs->trans('TheReportedProgressIsLessThanTheCalculatedProgressionByX', abs($task->progress - $progressCalculated).' '.$langs->trans("point")); + $diff = ' '.($task->progress - $progressCalculated).'%'; + } + elseif (doubleval($progressCalculated) > doubleval($task->progress)) { // warning if close at 10% + $progressBarClass = 'progress-bar-warning'; + $title = $langs->trans('TheReportedProgressIsLessThanTheCalculatedProgressionByX', abs($task->progress - $progressCalculated).' '.$langs->trans("point")); + $diff = ' '.($task->progress - $progressCalculated).'%'; + } + else { + $progressBarClass = 'progress-bar-success'; + $title = $langs->trans('TheReportedProgressIsMoreThanTheCalculatedProgressionByX', ($task->progress - $progressCalculated).' '.$langs->trans("point")); + $diff = ' '.($task->progress - $progressCalculated).'%'; + } + } + + $out .= '
'; + + if ($label !== false) + { + $out .= ' '; + + if ($label !== true) { + $out .= $label; // replace label by param + } + else { + $out .= $task->getNomUrl(1).' '.dol_htmlentities($task->label); + } + $out .= ' '; + } + + + if ($progressNumber !== false) + { + $out .= ' '; + if ($progressNumber !== true) { + $out .= $progressNumber; // replace label by param + } + else { + if ($task->hasDelay()) $out .= img_warning($langs->trans("Late")).' '; $url = DOL_URL_ROOT.'/projet/tasks/time.php?id='.$task->id; - $out .= !empty($diff) ? $diff.' ' : ''; + $out .= !empty($diff) ? $diff.' ' : ''; $out .= ''; - $out .= ''; - if ($task->duration_effective) $out .= convertSecondToTime($task->duration_effective, $timespentoutputformat); - else $out .= '--:--'; - $out .= ''; + $out .= ''; + if ($task->duration_effective) $out .= convertSecondToTime($task->duration_effective, $timespentoutputformat); + else $out .= '--:--'; + $out .= ''; $out .= ''; - $out .= ' / '; + $out .= '/'; $out .= ''; - $out .= ''; - if ($task->planned_workload) $out .= convertSecondToTime($task->planned_workload, $plannedworkloadoutputformat); - else $out .= '--:--'; + $out .= ''; + if ($task->planned_workload) $out .= convertSecondToTime($task->planned_workload, $plannedworkloadoutputformat); + else $out .= '--:--'; $out .= ''; - } - $out .= ' '; - } - - - $out .= ''; - $out .= '
'; - $diffval = doubleval($task->progress) - doubleval($progressCalculated); - if ($diffval >= 0) { - // good - $out .= '
'; - if (!empty($task->progress)) { + } + $out .= ' '; + } + + + $out .= ''; + $out .= '
'; + $diffval = doubleval($task->progress) - doubleval($progressCalculated); + if ($diffval >= 0) { + // good + $out .= '
'; + if (!empty($task->progress)) { $out .= '
'; } - $out .= '
'; - } else { - // bad - $out .= '
'; - $out .= '
'; - $out .= '
'; - } - $out .= '
'; - $out .= '
'; - - - - return $out; + $out .= '
'; + } + else + { + // bad + $out .= '
'; + $out .= '
'; + $out .= '
'; + } + $out .= '
'; + $out .= '
'; + + + + return $out; } /** * @param Task $task the task object @@ -2512,50 +2499,50 @@ */ function getTaskProgressBadge($task, $label = '', $tooltip = '') { - global $conf, $langs; - - $out = ''; - $badgeClass = ''; - if ($task->progress != '') - { - // TODO : manage 100% - - // define color according to time spend vs workload - $badgeClass = 'badge '; - if ($task->planned_workload) { - $progressCalculated = round(100 * doubleval($task->duration_effective) / doubleval($task->planned_workload), 2); - - // this conf is actually hidden, by default we use 10% for "be carefull or warning" - $warningRatio = !empty($conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT) ? (1 + $conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT / 100) : 1.10; - - if (doubleval($progressCalculated) > doubleval($task->progress * $warningRatio)) { - $badgeClass .= 'badge-danger'; - if (empty($tooltip)) { - $tooltip = $task->progress.'% < '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; - } - } elseif (doubleval($progressCalculated) > doubleval($task->progress)) { // warning if close at 10% - $badgeClass .= 'badge-warning'; - if (empty($tooltip)) $tooltip = $task->progress.'% < '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; - } else { - $badgeClass .= 'badge-success'; - if (empty($tooltip)) $tooltip = $task->progress.'% >= '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; - } - } - } - - $title = ''; - if (!empty($tooltip)) { - $badgeClass .= ' classfortooltip'; - $title = 'title="'.dol_htmlentities($tooltip).'"'; - } - - if (empty($label)) { - $label = $task->progress.' %'; - } - - if (!empty($label)) { - $out = ''.$label.''; - } - - return $out; + global $conf, $langs; + + $out = ''; + $badgeClass = ''; + if ($task->progress != '') + { + // TODO : manage 100% + + // define color according to time spend vs workload + $badgeClass = 'badge '; + if ($task->planned_workload) { + $progressCalculated = round(100 * doubleval($task->duration_effective) / doubleval($task->planned_workload), 2); + + // this conf is actually hidden, by default we use 10% for "be carefull or warning" + $warningRatio = !empty($conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT) ? (1 + $conf->global->PROJECT_TIME_SPEND_WARNING_PERCENT / 100) : 1.10; + + if (doubleval($progressCalculated) > doubleval($task->progress * $warningRatio)) { + $badgeClass .= 'badge-danger'; + if (empty($tooltip)) $tooltip = $task->progress.'% < '.$langs->trans("Expected").' '.$progressCalculated.'%'; + } + elseif (doubleval($progressCalculated) > doubleval($task->progress)) { // warning if close at 10% + $badgeClass .= 'badge-warning'; + if (empty($tooltip)) $tooltip = $task->progress.'% < '.$langs->trans("Expected").' '.$progressCalculated.'%'; + } + else { + $badgeClass .= 'badge-success'; + if (empty($tooltip)) $tooltip = $task->progress.'% >= '.$langs->trans("Expected").' '.$progressCalculated.'%'; + } + } + } + + $title = ''; + if (!empty($tooltip)) { + $badgeClass .= ' classfortooltip'; + $title = 'title="'.dol_htmlentities($tooltip).'"'; + } + + if (empty($label)) { + $label = $task->progress.' %'; + } + + if (!empty($label)) { + $out = ''.$label.''; + } + + return $out; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_propal.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_propal.lib.php @@ -38,18 +38,18 @@ $head = array(); $head[$h][0] = DOL_URL_ROOT.'/comm/propal/card.php?id='.$object->id; - $head[$h][1] = $langs->trans('Proposal'); + $head[$h][1] = $langs->trans('ProposalCard'); $head[$h][2] = 'comm'; $h++; if ((empty($conf->commande->enabled) && ((!empty($conf->expedition->enabled) && !empty($conf->expedition_bon->enabled) && $user->rights->expedition->lire) - || (!empty($conf->expedition->enabled) && !empty($conf->delivery_note->enabled) && $user->rights->expedition->delivery->lire)))) + || (!empty($conf->expedition->enabled) && !empty($conf->livraison_bon->enabled) && $user->rights->expedition->livraison->lire)))) { $langs->load("sendings"); $text = ''; $head[$h][0] = DOL_URL_ROOT.'/expedition/propal.php?id='.$object->id; if ($conf->expedition_bon->enabled) $text = $langs->trans("Shipment"); - if ($conf->delivery_note->enabled) $text .= '/'.$langs->trans("Receivings"); + if ($conf->livraison_bon->enabled) $text .= '/'.$langs->trans("Receivings"); $head[$h][1] = $text; $head[$h][2] = 'shipping'; $h++; @@ -57,7 +57,7 @@ if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { - $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); + $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/comm/propal/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; @@ -65,29 +65,29 @@ $h++; } - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'propal'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'propal'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; if (!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/comm/propal/note.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/comm/propal/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; $head[$h][2] = 'note'; $h++; - } + } require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->propal->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref); + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->propal->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/comm/propal/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; @@ -129,13 +129,13 @@ $head[$h][0] = DOL_URL_ROOT.'/comm/admin/propal_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes'; - $h++; + $head[$h][2] = 'attributes'; + $h++; - $head[$h][0] = DOL_URL_ROOT.'/comm/admin/propaldet_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsLines"); - $head[$h][2] = 'attributeslines'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/comm/admin/propaldet_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsLines"); + $head[$h][2] = 'attributeslines'; + $h++; complete_head_from_modules($conf, $langs, null, $head, $h, 'propal_admin', 'remove'); --- /tmp/dsg/dolibarr/htdocs/core/lib/github_reception.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_reception.lib.php @@ -47,40 +47,41 @@ $head[$h][2] = 'reception'; $h++; + + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { - $objectsrc = $object; - if ($object->origin == 'commande' && $object->origin_id > 0) - { - $objectsrc = new Commande($db); - $objectsrc->fetch($object->origin_id); - } - $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); - $head[$h][0] = DOL_URL_ROOT."/reception/contact.php?id=".$object->id; - $head[$h][1] = $langs->trans("ContactsAddresses"); + $objectsrc = $object; + if ($object->origin == 'commande' && $object->origin_id > 0) + { + $objectsrc = new Commande($db); + $objectsrc->fetch($object->origin_id); + } + $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT."/reception/contact.php?id=".$object->id; + $head[$h][1] = $langs->trans("ContactsAddresses"); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; - $head[$h][2] = 'contact'; - $h++; + $head[$h][2] = 'contact'; + $h++; } - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'reception'); - - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; + if (!empty($object->note_public)) $nbNote++; $head[$h][0] = DOL_URL_ROOT."/reception/note.php?id=".$object->id; $head[$h][1] = $langs->trans("Notes"); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; $head[$h][2] = 'note'; $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'reception', 'remove'); - return $head; + + + + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'order', 'remove'); + + return $head; } /** @@ -101,23 +102,24 @@ $head[$h][2] = 'reception'; $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'reception_admin'); if (!empty($conf->global->MAIN_SUBMODULE_RECEPTION)) { - $head[$h][0] = DOL_URL_ROOT.'/admin/reception_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes_reception'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/reception_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFields"); + $head[$h][2] = 'attributes_reception'; + $h++; } if (!empty($conf->global->MAIN_SUBMODULE_RECEPTION)) { - $head[$h][0] = DOL_URL_ROOT.'/admin/commande_fournisseur_dispatch_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsLines"); - $head[$h][2] = 'attributeslines_reception'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/commande_fournisseur_dispatch_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsLines"); + $head[$h][2] = 'attributeslines_reception'; + $h++; } + + complete_head_from_modules($conf, $langs, null, $head, $h, 'reception_admin', 'remove'); --- /tmp/dsg/dolibarr/htdocs/core/lib/github_report.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_report.lib.php @@ -56,7 +56,7 @@ print ''."\n"; print ''."\n"; - print dol_get_fiche_head($head, 'report'); + dol_fiche_head($head, 'report'); foreach ($moreparam as $key => $value) { @@ -69,7 +69,7 @@ // Ligne de titre print ''; - print ''; + print ''; print ''; @@ -80,7 +80,7 @@ if ($calcmode) { print ''; - print ''; + print ''; print ''; @@ -115,7 +115,7 @@ print '
'; - if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); - print "'; + if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + print "'; - if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project'); - print ''; + if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project'); + print ''; - if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); - else print '--:--'; - print ''; - print $formother->select_percent($lines[$i]->progress, $lines[$i]->id.'progress'); - print ''; + if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); + else print '--:--'; + print ''; + print $formother->select_percent($lines[$i]->progress, $lines[$i]->id.'progress'); + print ''; @@ -1654,7 +1640,8 @@ print ''; print convertSecondToTime($lines[$i]->duration, 'allhourmin'); print ''; - } else print '--:--'; + } + else print '--:--'; print "'; - //$tableCell .= 'idw='.$idw.' '.$conf->global->MAIN_START_WEEK.' '.$numstartworkingday.'-'.$numendworkingday; $placeholder = ''; if ($alreadyspent) { @@ -1758,7 +1744,9 @@ //var_dump($totalforeachday); } $level--; - } else { + } + else + { //$level--; } } @@ -1845,7 +1833,6 @@ $projectstatic->title = $lines[$i]->projectlabel; $projectstatic->public = $lines[$i]->public; $projectstatic->thirdparty_name = $lines[$i]->thirdparty_name; - $projectstatic->status = $lines[$i]->projectstatus; $taskstatic->id = $lines[$i]->id; $taskstatic->ref = ($lines[$i]->ref ? $lines[$i]->ref : $lines[$i]->id); @@ -1922,7 +1909,8 @@ print ''; print convertSecondToTime($lines[$i]->duration, 'allhourmin'); print ''; - } else print '--:--'; + } + else print '--:--'; print "'; if ($objp->fk_soc > 0) { - $thirdpartystatic->id = $objp->socid; + $thirdpartystatic->id = $objp->fk_soc; + $thirdpartystatic->ref = $objp->socname; $thirdpartystatic->name = $objp->socname; - //$thirdpartystatic->name_alias = $objp->name_alias; - //$thirdpartystatic->code_client = $objp->code_client; - $thirdpartystatic->code_compta = $objp->code_compta; - $thirdpartystatic->client = $objp->client; - //$thirdpartystatic->code_fournisseur = $objp->code_fournisseur; - $thirdpartystatic->code_compta_fournisseur = $objp->code_compta_fournisseur; - $thirdpartystatic->fournisseur = $objp->fournisseur; - $thirdpartystatic->logo = $objp->logo; - $thirdpartystatic->email = $objp->email; - $thirdpartystatic->entity = $objp->entity; print $thirdpartystatic->getNomUrl(1); } print '
'.$langs->trans("ReportName").''.$langs->trans("ReportName").''; print $reportname; print '
'.$langs->trans("CalculationMode").''.$langs->trans("CalculationMode").''; print $calcmode; if ($variante) print '
'."\n"; - print dol_get_fiche_end(); + dol_fiche_end(); print '
'; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_resource.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_resource.lib.php @@ -37,13 +37,13 @@ $head[$h][0] = dol_buildpath('/resource/card.php', 1).'?id='.$object->id; $head[$h][1] = $langs->trans("ResourceCard"); - $head[$h][2] = 'resource'; + $head[$h][2] = 'resource'; $h++; if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && (empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_USER) || empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_THIPARTY))) { - $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); - $head[$h][0] = DOL_URL_ROOT.'/resource/contact.php?id='.$object->id; + $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT.'/resource/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; $head[$h][2] = 'contact'; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_salaries.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_salaries.lib.php @@ -27,41 +27,42 @@ */ function salaries_prepare_head($object) { - global $db, $langs, $conf; - $h = 0; - $head = array(); + global $db, $langs, $conf; - $head[$h][0] = DOL_URL_ROOT.'/salaries/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("SalaryPayment"); - $head[$h][2] = 'card'; - $h++; + $h = 0; + $head = array(); - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'salaries'); + $head[$h][0] = DOL_URL_ROOT.'/salaries/card.php?id='.$object->id; + $head[$h][1] = $langs->trans("SalaryPayment"); + $head[$h][2] = 'card'; + $h++; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->salaries->dir_output."/".dol_sanitizeFileName($object->ref); - $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.'/salaries/document.php?id='.$object->id; - $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; - $head[$h][2] = 'documents'; - $h++; + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'salaries'); - $head[$h][0] = DOL_URL_ROOT.'/salaries/info.php?id='.$object->id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->salaries->dir_output."/".dol_sanitizeFileName($object->ref); + $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.'/salaries/document.php?id='.$object->id; + $head[$h][1] = $langs->trans('Documents'); + if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + $head[$h][2] = 'documents'; + $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'salaries', 'remove'); + $head[$h][0] = DOL_URL_ROOT.'/salaries/info.php?id='.$object->id; + $head[$h][1] = $langs->trans("Info"); + $head[$h][2] = 'info'; + $h++; - return $head; + complete_head_from_modules($conf, $langs, $object, $head, $h, 'salaries', 'remove'); + + return $head; } /** @@ -71,28 +72,28 @@ */ function salaries_admin_prepare_head() { - global $langs, $conf, $user; + global $langs, $conf, $user; - $h = 0; - $head = array(); + $h = 0; + $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/salaries/admin/salaries.php'; - $head[$h][1] = $langs->trans("Miscellaneous"); - $head[$h][2] = 'general'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/salaries/admin/salaries.php'; + $head[$h][1] = $langs->trans("Miscellaneous"); + $head[$h][2] = 'general'; + $h++; - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab - complete_head_from_modules($conf, $langs, null, $head, $h, 'salaries_admin'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab + complete_head_from_modules($conf, $langs, '', $head, $h, 'salaries_admin'); - $head[$h][0] = DOL_URL_ROOT.'/salaries/admin/salaries_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsSalaries"); - $head[$h][2] = 'attributes'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/salaries/admin/salaries_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsSalaries"); + $head[$h][2] = 'attributes'; + $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'salaries_admin', 'remove'); + complete_head_from_modules($conf, $langs, '', $head, $h, 'salaries_admin', 'remove'); - return $head; + return $head; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_security.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_security.lib.php @@ -1,7 +1,6 @@ * Copyright (C) 2008-2017 Regis Houssin - * Copyright (C) 2020 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -46,7 +45,8 @@ $output_tab[$i] = chr(ord(substr($chain, $i, 1)) + 17); } $chain = implode("", $output_tab); - } elseif ($key) + } + elseif ($key) { $result = ''; $strlength = dol_strlen($chain); @@ -84,7 +84,8 @@ } $chain = implode("", $output_tab); - } elseif ($key) + } + elseif ($key) { $result = ''; $strlength = dol_strlen($chain); @@ -165,43 +166,35 @@ /** * Check permissions of a user to show a page and an object. Check read permission. * If GETPOST('action','aZ09') defined, we also check write and delete permission. - * This method check permission on module then call checkUserAccessToObject() for permission on object (according to entity and socid of user). * * @param User $user User to check * @param string $features Features to check (it must be module $object->element. Examples: 'societe', 'contact', 'produit&service', 'produit|service', ...) * @param int $objectid Object ID if we want to check a particular record (optional) is linked to a owned thirdparty (optional). - * @param string $tableandshare 'TableName&SharedElement' with Tablename is table where object is stored. SharedElement is an optional key to define where to check entity for multicompany module. Param not used if objectid is null (optional). + * @param string $tableandshare 'TableName&SharedElement' with Tablename is table where object is stored. SharedElement is an optional key to define where to check entity for multicompany modume. Param not used if objectid is null (optional). * @param string $feature2 Feature to check, second level of permission (optional). Can be a 'or' check with 'sublevela|sublevelb'. * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional) * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional) * @param int $isdraft 1=The object with id=$objectid is a draft * @return int Always 1, die process if not allowed - * @see dol_check_secure_access_document(), checkUserAccessToObject() + * @see dol_check_secure_access_document() */ function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid', $isdraft = 0) { global $db, $conf; global $hookmanager; - //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft"); + //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename,$feature2,$dbt_socfield,$dbt_select"); //print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", objectid=".$objectid; //print ", dbtablename=".$dbtablename.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select; //print ", perm: ".$features."->".$feature2."=".($user->rights->$features->$feature2->lire)."
"; - $parentfortableentity = ''; - - // Fix syntax of $features param - $originalfeatures = $features; if ($features == 'facturerec') $features = 'facture'; if ($features == 'mo') $features = 'mrp'; if ($features == 'member') $features = 'adherent'; if ($features == 'subscription') { $features = 'adherent'; $feature2 = 'cotisation'; }; - if ($features == 'websitepage') { $features = 'website'; $tableandshare = 'website_page'; $parentfortableentity = 'fk_website@website'; } - if ($features == 'project') $features = 'projet'; - if ($features == 'product') $features = 'produit'; // Get more permissions checks from hooks - $parameters = array('features'=>$features, 'originalfeatures'=>$originalfeatures, 'objectid'=>$objectid, 'dbt_select'=>$dbt_select, 'idtype'=>$dbt_select, 'isdraft'=>$isdraft); + $parameters = array('features'=>$features, 'objectid'=>$objectid, 'idtype'=>$dbt_select); $reshook = $hookmanager->executeHooks('restrictedArea', $parameters); if (isset($hookmanager->resArray['result'])) { @@ -220,6 +213,11 @@ // More subfeatures to check if (!empty($feature2)) $feature2 = explode("|", $feature2); + + // More parameters + $params = explode('&', $tableandshare); + $dbtablename = (!empty($params[0]) ? $params[0] : ''); + $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); $listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); @@ -245,15 +243,13 @@ if (!$user->rights->banque->cheque) { $readok = 0; $nbko++; } } elseif ($feature == 'projet') { if (!$user->rights->projet->lire && !$user->rights->projet->all->lire) { $readok = 0; $nbko++; } - } elseif ($feature == 'payment') { - if (!$user->rights->facture->lire) { $readok = 0; $nbko++; } - } elseif ($feature == 'payment_supplier') { - if (!$user->rights->fournisseur->facture->lire) { $readok = 0; $nbko++; } } elseif (!empty($feature2)) { // This is for permissions on 2 levels $tmpreadok = 1; foreach ($feature2 as $subfeature) { if ($subfeature == 'user' && $user->id == $objectid) continue; // A user can always read its own card - if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { $tmpreadok = 0; } elseif (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { $tmpreadok = 0; } else { $tmpreadok = 1; break; } // Break is to bypass second test if the first is ok + if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { $tmpreadok = 0; } + elseif (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { $tmpreadok = 0; } + else { $tmpreadok = 1; break; } // Break is to bypass second test if the first is ok } if (!$tmpreadok) { // We found a test on feature that is ko $readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko). @@ -297,7 +293,8 @@ if (!$user->rights->import->run) { $createok = 0; $nbko++; } } elseif ($feature == 'ecm') { if (!$user->rights->ecm->upload) { $createok = 0; $nbko++; } - } elseif (!empty($feature2)) { // This is for permissions on one level + } + elseif (!empty($feature2)) { // This is for permissions on one level foreach ($feature2 as $subfeature) { if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->creer) continue; // User can edit its own card if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->password) continue; // User can edit its own password @@ -313,7 +310,7 @@ break; } } - } elseif (!empty($feature)) { // This is for permissions on 2 levels ('creer' or 'write') + } elseif (!empty($feature)) { // This is for permissions on 2 levels ('creer' or 'write') //print '
feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write; exit; if (empty($user->rights->$feature->creer) && empty($user->rights->$feature->write) @@ -350,38 +347,47 @@ if ($feature == 'contact') { if (!$user->rights->societe->contact->supprimer) $deleteok = 0; - } elseif ($feature == 'produit|service') + } + elseif ($feature == 'produit|service') { if (!$user->rights->produit->supprimer && !$user->rights->service->supprimer) $deleteok = 0; - } elseif ($feature == 'commande_fournisseur') + } + elseif ($feature == 'commande_fournisseur') { if (!$user->rights->fournisseur->commande->supprimer) $deleteok = 0; - } elseif ($feature == 'banque') + } + elseif ($feature == 'banque') { if (!$user->rights->banque->modifier) $deleteok = 0; - } elseif ($feature == 'cheque') + } + elseif ($feature == 'cheque') { if (!$user->rights->banque->cheque) $deleteok = 0; - } elseif ($feature == 'ecm') + } + elseif ($feature == 'ecm') { if (!$user->rights->ecm->upload) $deleteok = 0; - } elseif ($feature == 'ftp') + } + elseif ($feature == 'ftp') { if (!$user->rights->ftp->write) $deleteok = 0; - } elseif ($feature == 'salaries') + }elseif ($feature == 'salaries') { if (!$user->rights->salaries->delete) $deleteok = 0; - } elseif ($feature == 'salaries') + } + elseif ($feature == 'salaries') { if (!$user->rights->salaries->delete) $deleteok = 0; - } elseif (!empty($feature2)) // This is for permissions on 2 levels + } + elseif (!empty($feature2)) // This is for permissions on 2 levels { foreach ($feature2 as $subfeature) { if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) $deleteok = 0; else { $deleteok = 1; break; } // For bypass the second test if the first is ok } - } elseif (!empty($feature)) // This is used for permissions on 1 level + } + elseif (!empty($feature)) // This is used for permissions on 1 level { //print '
feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete; if (empty($user->rights->$feature->supprimer) @@ -401,7 +407,7 @@ // is linked to a company allowed to $user. if (!empty($objectid) && $objectid > 0) { - $ok = checkUserAccessToObject($user, $featuresarray, $objectid, $tableandshare, $feature2, $dbt_keyfield, $dbt_select, $parentfortableentity); + $ok = checkUserAccessToObject($user, $featuresarray, $objectid, $tableandshare, $feature2, $dbt_keyfield, $dbt_select); $params = array('objectid' => $objectid, 'features' => join(',', $featuresarray), 'features2' => $feature2); return $ok ? 1 : accessforbidden('', 1, 1, 0, $params); } @@ -413,24 +419,19 @@ * Check access by user to object. * This function is also called by restrictedArea * - * @param User $user User to check - * @param array $featuresarray Features/modules to check. Example: ('user','service','member','project','task',...) - * @param int|string $objectid Object ID if we want to check a particular record (optional) is linked to a owned thirdparty (optional). - * @param string $tableandshare 'TableName&SharedElement' with Tablename is table where object is stored. SharedElement is an optional key to define where to check entity for multicompany modume. Param not used if objectid is null (optional). - * @param string $feature2 Feature to check, second level of permission (optional). Can be or check with 'level1|level2'. - * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional) - * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional) - * @param string $parenttableforentity Parent table for entity. Example 'fk_website@website' - * @return bool True if user has access, False otherwise + * @param User $user User to check + * @param array $featuresarray Features/modules to check. Example: ('user','service','member','project','task',...) + * @param int|string $objectid Object ID if we want to check a particular record (optional) is linked to a owned thirdparty (optional). + * @param string $tableandshare 'TableName&SharedElement' with Tablename is table where object is stored. SharedElement is an optional key to define where to check entity for multicompany modume. Param not used if objectid is null (optional). + * @param string $feature2 Feature to check, second level of permission (optional). Can be or check with 'level1|level2'. + * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional) + * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional) + * @return bool True if user has access, False otherwise * @see restrictedArea() */ -function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = '', $dbt_select = 'rowid', $parenttableforentity = '') +function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = '', $dbt_select = 'rowid') { global $db, $conf; - - //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft"); - //print "user_id=".$user->id.", features=".join(',', $featuresarray).", feature2=".$feature2.", objectid=".$objectid; - //print ", tableandshare=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select."
"; // More parameters $params = explode('&', $tableandshare); @@ -446,13 +447,13 @@ if ($feature == 'project') $feature = 'projet'; if ($feature == 'task') $feature = 'projet_task'; - $check = array('adherent', 'banque', 'bom', 'don', 'mrp', 'user', 'usergroup', 'payment', 'payment_supplier', 'product', 'produit', 'service', 'produit|service', 'categorie', 'resource', 'expensereport', 'holiday', 'website'); // Test on entity only (Objects with no link to company) + $check = array('adherent', 'banque', 'bom', 'don', 'mrp', 'user', 'usergroup', 'product', 'produit', 'service', 'produit|service', 'categorie', 'resource', 'expensereport', 'holiday'); // Test on entity only (Objects with no link to company) $checksoc = array('societe'); // Test for societe object - $checkother = array('contact', 'agenda'); // Test on entity + link to third party on field $dbt_keyfield. Allowed if link is empty (Ex: contacts...). + $checkother = array('contact', 'agenda'); // Test on entity and link to third party. Allowed if link is empty (Ex: contacts...). $checkproject = array('projet', 'project'); // Test for project object - $checktask = array('projet_task'); // Test for task object + $checktask = array('projet_task'); $nocheck = array('barcode', 'stock'); // No test - //$checkdefault = 'all other not already defined'; // Test on entity + link to third party on field $dbt_keyfield. Not allowed if link is empty (Ex: invoice, orders...). + //$checkdefault = 'all other not already defined'; // Test on entity and link to third party. Not allowed if link is empty (Ex: invoice, orders...). // If dbtablename not defined, we use same name for table than module name if (empty($dbtablename)) @@ -461,44 +462,50 @@ $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too. } - // Check permission for object on entity only + // Check permission for object with entity if (in_array($feature, $check)) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; - if (($feature == 'user' || $feature == 'usergroup') && !empty($conf->multicompany->enabled)) { // Special for multicompany - if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { - if ($conf->entity == 1 && $user->admin && !$user->entity) { + if (($feature == 'user' || $feature == 'usergroup') && !empty($conf->multicompany->enabled)) + { + if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + if ($conf->entity == 1 && $user->admin && !$user->entity) + { $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.entity IS NOT NULL"; - } else { + } + else + { $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND ((ug.fk_user = dbt.rowid"; $sql .= " AND ug.entity IN (".getEntity('usergroup')."))"; $sql .= " OR dbt.entity = 0)"; // Show always superadmin } - } else { + } + else { $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; } - } else { - $reg = array(); - if ($parenttableforentity && preg_match('/(.*)@(.*)/', $parenttableforentity, $reg)) { - $sql .= ", ".MAIN_DB_PREFIX.$reg[2]." as dbtp"; - $sql .= " WHERE dbt.".$reg[1]." = dbtp.rowid AND dbt.".$dbt_select." IN (".$objectid.")"; - $sql .= " AND dbtp.entity IN (".getEntity($sharedelement, 1).")"; - } else { - $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; - $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; - } - } - } elseif (in_array($feature, $checksoc)) { // We check feature = checksoc - if ($user->socid > 0) { - // If external user: Check permission for external users + } + else + { + $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; + $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; + } + } + elseif (in_array($feature, $checksoc)) // We check feature = checksoc + { + // If external user: Check permission for external users + if ($user->socid > 0) + { if ($user->socid <> $objectid) return false; - } elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) { - // If internal user: Check permission for internal users that are restricted on their objects + } + // If internal user: Check permission for internal users that are restricted on their objects + elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) + { $sql = "SELECT COUNT(sc.fk_soc) as nb"; $sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= ", ".MAIN_DB_PREFIX."societe as s)"; @@ -506,14 +513,17 @@ $sql .= " AND sc.fk_user = ".$user->id; $sql .= " AND sc.fk_soc = s.rowid"; $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")"; - } elseif (!empty($conf->multicompany->enabled)) { - // If multicompany and internal users with all permissions, check user is in correct entity + } + // If multicompany and internal users with all permissions, check user is in correct entity + elseif (!empty($conf->multicompany->enabled)) + { $sql = "SELECT COUNT(s.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " WHERE s.rowid IN (".$objectid.")"; $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")"; } - } elseif (in_array($feature, $checkother)) // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...). + } + elseif (in_array($feature, $checkother)) // Test on entity and link to societe. Allowed if link is empty (Ex: contacts...). { // If external user: Check permission for external users if ($user->socid > 0) @@ -522,16 +532,18 @@ $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.fk_soc = ".$user->socid; - } // If internal user: Check permission for internal users that are restricted on their objects + } + // If internal user: Check permission for internal users that are restricted on their objects elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id); + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = '".$user->id."'"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)"; // Contact not linked to a company or to a company of user $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; - } // If multicompany and internal users with all permissions, check user is in correct entity + } + // If multicompany and internal users with all permissions, check user is in correct entity elseif (!empty($conf->multicompany->enabled)) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; @@ -539,18 +551,9 @@ $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; } - if ($feature == 'agenda')// Also check owner or attendee for users without allactions->read - { - if ($objectid > 0 && empty($user->rights->agenda->allactions->read)) { - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - $action = new ActionComm($db); - $action->fetch($objectid); - if ($action->authorid != $user->id && $action->userownerid != $user->id && !(array_key_exists($user->id, $action->userassigned))) { - return false; - } - } - } - } elseif (in_array($feature, $checkproject)) { + } + elseif (in_array($feature, $checkproject)) + { if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) { include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; @@ -558,13 +561,17 @@ $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0); $tmparray = explode(',', $tmps); if (!in_array($objectid, $tmparray)) return false; - } else { + } + else + { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; } - } elseif (in_array($feature, $checktask)) { + } + elseif (in_array($feature, $checktask)) + { if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) { $task = new Task($db); @@ -575,41 +582,41 @@ $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0); $tmparray = explode(',', $tmps); if (!in_array($task->fk_project, $tmparray)) return false; - } else { + } + else + { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; } - } elseif (!in_array($feature, $nocheck)) { // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield + } + elseif (!in_array($feature, $nocheck)) // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield + { // If external user: Check permission for external users - if ($user->socid > 0) { + if ($user->socid > 0) + { if (empty($dbt_keyfield)) dol_print_error('', 'Param dbt_keyfield is required but not defined'); $sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.rowid IN (".$objectid.")"; $sql .= " AND dbt.".$dbt_keyfield." = ".$user->socid; - } elseif (!empty($conf->societe->enabled) && !$user->rights->societe->client->voir) { - // If internal user: Check permission for internal users that are restricted on their objects - if ($feature != 'ticket') { - if (empty($dbt_keyfield)) dol_print_error('', 'Param dbt_keyfield is required but not defined'); - $sql = "SELECT COUNT(sc.fk_soc) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; - $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; - $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; - $sql .= " AND sc.fk_soc = dbt.".$dbt_keyfield; - $sql .= " AND sc.fk_user = ".$user->id; - } else { - // On ticket, the thirdparty is not mandatory, so we need a special test to accept record with no thirdparties. - $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = dbt.".$dbt_keyfield." AND sc.fk_user = ".$user->id; - $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; - $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; - $sql .= " AND (sc.fk_user = ".$user->id." OR sc.fk_user IS NULL)"; - } - } // If multicompany and internal users with all permissions, check user is in correct entity + } + // If internal user: Check permission for internal users that are restricted on their objects + elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) + { + if (empty($dbt_keyfield)) dol_print_error('', 'Param dbt_keyfield is required but not defined'); + $sql = "SELECT COUNT(sc.fk_soc) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; + $sql .= " AND sc.fk_soc = dbt.".$dbt_keyfield; + $sql .= " AND dbt.".$dbt_keyfield." = s.rowid"; + $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; + $sql .= " AND sc.fk_user = ".$user->id; + } + // If multicompany and internal users with all permissions, check user is in correct entity elseif (!empty($conf->multicompany->enabled)) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; @@ -626,12 +633,13 @@ { $obj = $db->fetch_object($resql); if (!$obj || $obj->nb < count(explode(',', $objectid))) return false; - } else { + } + else + { return false; } } } - return true; } @@ -643,18 +651,18 @@ * @param int $printheader Show header before * @param int $printfooter Show footer after * @param int $showonlymessage Show only message parameter. Otherwise add more information. - * @param array|null $params More parameters provided to hook + * @param array|null $params Send params * @return void */ function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null) { - global $conf, $db, $user, $langs, $hookmanager; - if (!is_object($langs)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; - $langs = new Translate('', $conf); - $langs->setDefaultLang(); - } + global $conf, $db, $user, $langs, $hookmanager; + if (!is_object($langs)) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; + $langs = new Translate('', $conf); + $langs->setDefaultLang(); + } $langs->load("errors"); @@ -686,7 +694,9 @@ { print $langs->trans("CurrentLogin").': '.$user->login.'
'; print $langs->trans("ErrorForbidden2", $langs->transnoentitiesnoconv("Home"), $langs->transnoentitiesnoconv("Users")); - } else { + } + else + { print $langs->trans("ErrorForbidden3"); } } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_security2.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_security2.lib.php @@ -34,10 +34,10 @@ */ function dol_getwebuser($mode) { - $t = '?'; - if ($mode == 'user') $t = getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty - if ($mode == 'group') $t = getenv('APACHE_RUN_GROUP'); - return $t; + $t = '?'; + if ($mode == 'user') $t = getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty + if ($mode == 'group') $t = getenv('APACHE_RUN_GROUP'); + return $t; } /** @@ -53,64 +53,66 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode, $context = '') { global $conf, $langs; - //global $dolauthmode; // To return authentication finally used + //global $dolauthmode; // To return authentication finally used // Check parameters if ($entitytotest == '') $entitytotest = 1; - dol_syslog("checkLoginPassEntity usertotest=".$usertotest." entitytotest=".$entitytotest." authmode=".join(',', $authmode)); + dol_syslog("checkLoginPassEntity usertotest=".$usertotest." entitytotest=".$entitytotest." authmode=".join(',', $authmode)); $login = ''; // Validation of login/pass/entity with standard modules if (empty($login)) { - $test = true; - foreach ($authmode as $mode) - { - if ($test && $mode && !$login) - { - // Validation of login/pass/entity for mode $mode - $mode = trim($mode); - $authfile = 'functions_'.$mode.'.php'; - $fullauthfile = ''; - - $dirlogin = array_merge(array("/core/login"), (array) $conf->modules_parts['login']); - foreach ($dirlogin as $reldir) - { - $dir = dol_buildpath($reldir, 0); - $newdir = dol_osencode($dir); - - // Check if file found (do not use dol_is_file to avoid loading files.lib.php) - $tmpnewauthfile = $newdir.(preg_match('/\/$/', $newdir) ? '' : '/').$authfile; - if (is_file($tmpnewauthfile)) $fullauthfile = $tmpnewauthfile; - } - - $result = false; - if ($fullauthfile) $result = include_once $fullauthfile; - if ($fullauthfile && $result) - { - // Call function to check user/password - $function = 'check_user_password_'.$mode; - $login = call_user_func($function, $usertotest, $passwordtotest, $entitytotest, $context); - if ($login && $login != '--bad-login-validity--') // Login is successfull - { - $test = false; // To stop once at first login success - $conf->authmode = $mode; // This properties is defined only when logged to say what mode was successfully used - $dol_tz = GETPOST('tz'); - $dol_dst = GETPOST('dst'); - $dol_screenwidth = GETPOST('screenwidth'); - $dol_screenheight = GETPOST('screenheight'); - } - } else { - dol_syslog("Authentication KO - failed to load file '".$authfile."'", LOG_ERR); - sleep(1); - // Load translation files required by the page - $langs->loadLangs(array('other', 'main', 'errors')); - - $_SESSION["dol_loginmesg"] = $langs->trans("ErrorFailedToLoadLoginFileForMode", $mode); - } - } - } + $test = true; + foreach ($authmode as $mode) + { + if ($test && $mode && !$login) + { + // Validation of login/pass/entity for mode $mode + $mode = trim($mode); + $authfile = 'functions_'.$mode.'.php'; + $fullauthfile = ''; + + $dirlogin = array_merge(array("/core/login"), (array) $conf->modules_parts['login']); + foreach ($dirlogin as $reldir) + { + $dir = dol_buildpath($reldir, 0); + $newdir = dol_osencode($dir); + + // Check if file found (do not use dol_is_file to avoid loading files.lib.php) + $tmpnewauthfile = $newdir.(preg_match('/\/$/', $newdir) ? '' : '/').$authfile; + if (is_file($tmpnewauthfile)) $fullauthfile = $tmpnewauthfile; + } + + $result = false; + if ($fullauthfile) $result = include_once $fullauthfile; + if ($fullauthfile && $result) + { + // Call function to check user/password + $function = 'check_user_password_'.$mode; + $login = call_user_func($function, $usertotest, $passwordtotest, $entitytotest, $context); + if ($login) // Login is successfull + { + $test = false; // To stop once at first login success + $conf->authmode = $mode; // This properties is defined only when logged to say what mode was successfully used + $dol_tz = GETPOST('tz'); + $dol_dst = GETPOST('dst'); + $dol_screenwidth = GETPOST('screenwidth'); + $dol_screenheight = GETPOST('screenheight'); + } + } + else + { + dol_syslog("Authentication KO - failed to load file '".$authfile."'", LOG_ERR); + sleep(1); + // Load translation files required by the page + $langs->loadLangs(array('other', 'main', 'errors')); + + $_SESSION["dol_loginmesg"] = $langs->trans("ErrorFailedToLoadLoginFileForMode", $mode); + } + } + } } return $login; @@ -119,19 +121,19 @@ if (!function_exists('dol_loginfunction')) { - /** - * Show Dolibarr default login page. - * Part of this code is also duplicated into main.inc.php::top_htmlhead - * - * @param Translate $langs Lang object (must be initialized by a new). - * @param Conf $conf Conf object - * @param Societe $mysoc Company object - * @return void - */ - function dol_loginfunction($langs, $conf, $mysoc) - { - global $dolibarr_main_demo, $dolibarr_main_force_https; - global $db, $hookmanager; + /** + * Show Dolibarr default login page. + * Part of this code is also duplicated into main.inc.php::top_htmlhead + * + * @param Translate $langs Lang object (must be initialized by a new). + * @param Conf $conf Conf object + * @param Societe $mysoc Company object + * @return void + */ + function dol_loginfunction($langs, $conf, $mysoc) + { + global $dolibarr_main_demo, $db; + global $hookmanager; $langs->loadLangs(array("main", "other", "help", "admin")); @@ -177,14 +179,16 @@ $tmp = dol_buildpath($reldir.'login.tpl.php'); if (file_exists($tmp)) { $template_dir = preg_replace('/login\.tpl\.php$/', '', $tmp); break; } } - } else { + } + else + { $template_dir = DOL_DOCUMENT_ROOT."/core/tpl/"; } // Set cookie for timeout management $prefix = dol_getprefix(''); $sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix; - if (!empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, (empty($dolibarr_main_force_https) ? false : true), true); + if (!empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, false, true); if (GETPOST('urlfrom', 'alpha')) $_SESSION["urlfrom"] = GETPOST('urlfrom', 'alpha'); else unset($_SESSION["urlfrom"]); @@ -222,11 +226,13 @@ if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_small); - } elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) + } + elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) { $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/'.$mysoc->logo); $width = 128; - } elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) + } + elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) { $urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg'; } @@ -260,9 +266,9 @@ $main_home = ''; if (!empty($conf->global->MAIN_HOME)) { - $substitutionarray = getCommonSubstitutionArray($langs); - complete_substitutions_array($substitutionarray, $langs); - $texttoshow = make_substitutions($conf->global->MAIN_HOME, $substitutionarray, $langs); + $substitutionarray = getCommonSubstitutionArray($langs); + complete_substitutions_array($substitutionarray, $langs); + $texttoshow = make_substitutions($conf->global->MAIN_HOME, $substitutionarray, $langs); $main_home = dol_htmlcleanlastbr($texttoshow); } @@ -290,8 +296,6 @@ // Include login page template include $template_dir.'login.tpl.php'; - // Global html output events ($mesgs, $errors, $warnings) - dol_htmloutput_events(0); $_SESSION["dol_loginmesg"] = ''; } @@ -359,7 +363,8 @@ $passwd = $val; $lineofpass = 1; } - } elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) + } + elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) { $val = trim($reg[1]); // This also remove CR/LF $val = preg_replace('/^["\']/', '', $val); @@ -370,7 +375,9 @@ $passwd_crypted = $val; $val = dol_decode($val); $passwd = $val; - } else { + } + else + { $passwd = $val; $val = dol_encode($val); $passwd_crypted = $val; @@ -393,7 +400,9 @@ //print 'passwd = '.$passwd.' - passwd_crypted = '.$passwd_crypted; //exit; - } else { + } + else + { $config .= $buffer; } } @@ -413,11 +422,15 @@ //@chmod($file, octdec('0600')); return 1; - } else { + } + else + { dol_syslog("encodedecode_dbpassconf Failed to open conf.php file for writing", LOG_WARNING); return -1; } - } else { + } + else + { dol_syslog("encodedecode_dbpassconf Failed to read conf.php", LOG_ERR); return -2; } @@ -450,42 +463,38 @@ { $max = strlen($lowercase) - 1; for ($x = 0; $x < $nbofchar; $x++) { - $tmp = random_int(0, $max); - $randomCode .= $lowercase[$tmp]; + $randomCode .= $lowercase[random_int(0, $max)]; } $max = strlen($uppercase) - 1; for ($x = 0; $x < $nbofchar; $x++) { - $tmp = random_int(0, $max); - $randomCode .= $uppercase[$tmp]; + $randomCode .= $uppercase[random_int(0, $max)]; } $max = strlen($numbers) - 1; for ($x = 0; $x < $nbofcharlast; $x++) { - $tmp = random_int(0, $max); - $randomCode .= $numbers[$tmp]; + $randomCode .= $numbers[random_int(0, $max)]; } $generated_password = str_shuffle($randomCode); - } else // Old platform, non cryptographic random + } + else // Old platform, non cryptographic random { $max = strlen($lowercase) - 1; for ($x = 0; $x < $nbofchar; $x++) { - $tmp = mt_rand(0, $max); - $randomCode .= $lowercase[$tmp]; + $randomCode .= $lowercase[mt_rand(0, $max)]; } $max = strlen($uppercase) - 1; for ($x = 0; $x < $nbofchar; $x++) { - $tmp = mt_rand(0, $max); - $randomCode .= $uppercase[$tmp]; + $randomCode .= $uppercase[mt_rand(0, $max)]; } $max = strlen($numbers) - 1; for ($x = 0; $x < $nbofcharlast; $x++) { - $tmp = mt_rand(0, $max); - $randomCode .= $numbers[$tmp]; + $randomCode .= $numbers[mt_rand(0, $max)]; } $generated_password = str_shuffle($randomCode); } - } elseif (!empty($conf->global->USER_PASSWORD_GENERATED)) + } + elseif (!empty($conf->global->USER_PASSWORD_GENERATED)) { $nomclass = "modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED); $nomfichier = $nomclass.".class.php"; @@ -501,12 +510,13 @@ { $numbers = "ABCDEF"; $max = strlen($numbers) - 1; - if (function_exists('random_int')) { // Cryptographic random - $tmp = random_int(0, $max); - $generated_password = str_replace($replaceambiguouschars, $numbers[$tmp], $generated_password); - } else { - $tmp = mt_rand(0, $max); - $generated_password = str_replace($replaceambiguouschars, $numbers[$tmp], $generated_password); + if (function_exists('random_int')) // Cryptographic random + { + $generated_password = str_replace($replaceambiguouschars, $numbers[random_int(0, $max)], $generated_password); + } + else + { + $generated_password = str_replace($replaceambiguouschars, $numbers[mt_rand(0, $max)], $generated_password); } } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_sendings.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_sendings.lib.php @@ -37,7 +37,7 @@ global $db, $langs, $conf, $user; // Load translation files required by the page - $langs->loadLangs(array("sendings", "deliveries")); + $langs->loadLangs(array("sendings", "deliveries")); $h = 0; $head = array(); @@ -47,16 +47,16 @@ $head[$h][2] = 'shipping'; $h++; - if ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire) + if ($conf->livraison_bon->enabled && $user->rights->expedition->livraison->lire) { // delivery link $object->fetchObjectLinked($object->id, $object->element); if (is_array($object->linkedObjectsIds['delivery']) && count($object->linkedObjectsIds['delivery']) > 0) // If there is a delivery { - // Take first one element of array - $tmp = reset($object->linkedObjectsIds['delivery']); - - $head[$h][0] = DOL_URL_ROOT."/delivery/card.php?id=".$tmp; + // Take first one element of array + $tmp = reset($object->linkedObjectsIds['delivery']); + + $head[$h][0] = DOL_URL_ROOT."/livraison/card.php?id=".$tmp; $head[$h][1] = $langs->trans("DeliveryCard"); $head[$h][2] = 'delivery'; $h++; @@ -65,34 +65,34 @@ if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { - $objectsrc = $object; - if ($object->origin == 'commande' && $object->origin_id > 0) - { - $objectsrc = new Commande($db); - $objectsrc->fetch($object->origin_id); - } - $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); - $head[$h][0] = DOL_URL_ROOT."/expedition/contact.php?id=".$object->id; - $head[$h][1] = $langs->trans("ContactsAddresses"); + $objectsrc = $object; + if ($object->origin == 'commande' && $object->origin_id > 0) + { + $objectsrc = new Commande($db); + $objectsrc->fetch($object->origin_id); + } + $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT."/expedition/contact.php?id=".$object->id; + $head[$h][1] = $langs->trans("ContactsAddresses"); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; - $head[$h][2] = 'contact'; - $h++; + $head[$h][2] = 'contact'; + $h++; } require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->expedition->dir_output."/sending/".dol_sanitizeFileName($object->ref); + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->commande->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/expedition/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; $head[$h][2] = 'documents'; $h++; - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; + if (!empty($object->note_public)) $nbNote++; $head[$h][0] = DOL_URL_ROOT."/expedition/note.php?id=".$object->id; $head[$h][1] = $langs->trans("Notes"); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; @@ -101,8 +101,8 @@ // Show more tabs from modules // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'delivery'); complete_head_from_modules($conf, $langs, $object, $head, $h, 'delivery', 'remove'); @@ -122,7 +122,7 @@ global $langs, $db, $conf, $user; // Load translation files required by the page - $langs->loadLangs(array("sendings", "deliveries")); + $langs->loadLangs(array("sendings", "deliveries")); $h = 0; $head = array(); @@ -135,7 +135,7 @@ $h++; } - $head[$h][0] = DOL_URL_ROOT."/delivery/card.php?id=".$object->id; + $head[$h][0] = DOL_URL_ROOT."/livraison/card.php?id=".$object->id; $head[$h][1] = $langs->trans("DeliveryCard"); $head[$h][2] = 'delivery'; $h++; @@ -157,21 +157,11 @@ $tmpobject = $object; } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { - $objectsrc = $tmpobject; - if ($tmpobject->origin == 'commande' && $tmpobject->origin_id > 0) - { - $objectsrc = new Commande($db); - $objectsrc->fetch($tmpobject->origin_id); - } - $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); - $head[$h][0] = DOL_URL_ROOT."/expedition/contact.php?id=".$tmpobject->id; - $head[$h][1] = $langs->trans("ContactsAddresses"); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; - $head[$h][2] = 'contact'; - $h++; - } + $head[$h][0] = DOL_URL_ROOT."/expedition/contact.php?id=".$tmpobject->id; + $head[$h][1] = $langs->trans("ContactsAddresses"); + $head[$h][2] = 'contact'; + $h++; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; @@ -195,7 +185,7 @@ $object->id = $tmpobject->id; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'delivery'); + complete_head_from_modules($conf, $langs, $object, $head, $h, 'delivery'); complete_head_from_modules($conf, $langs, $object, $head, $h, 'delivery', 'remove'); @@ -223,13 +213,13 @@ $sql = "SELECT obj.rowid, obj.fk_product, obj.label, obj.description, obj.product_type as fk_product_type, obj.qty as qty_asked, obj.date_start, obj.date_end,"; $sql .= " ed.rowid as edrowid, ed.qty as qty_shipped, ed.fk_expedition as expedition_id, ed.fk_origin_line, ed.fk_entrepot as warehouse_id,"; $sql .= " e.rowid as sendingid, e.ref as exp_ref, e.date_creation, e.date_delivery, e.date_expedition,"; - //if ($conf->delivery_note->enabled) $sql .= " l.rowid as livraison_id, l.ref as livraison_ref, l.date_delivery, ld.qty as qty_received,"; + //if ($conf->livraison_bon->enabled) $sql .= " l.rowid as livraison_id, l.ref as livraison_ref, l.date_delivery, ld.qty as qty_received,"; $sql .= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.tobatch as product_tobatch,'; $sql .= ' p.description as product_desc'; $sql .= " FROM ".MAIN_DB_PREFIX."expeditiondet as ed"; $sql .= ", ".MAIN_DB_PREFIX."expedition as e"; $sql .= ", ".MAIN_DB_PREFIX.$origin."det as obj"; - //if ($conf->delivery_note->enabled) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."delivery as l ON l.fk_expedition = e.rowid LEFT JOIN ".MAIN_DB_PREFIX."deliverydet as ld ON ld.fk_delivery = l.rowid AND obj.rowid = ld.fk_origin_line"; + //if ($conf->livraison_bon->enabled) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."livraison as l ON l.fk_expedition = e.rowid LEFT JOIN ".MAIN_DB_PREFIX."livraisondet as ld ON ld.fk_livraison = l.rowid AND obj.rowid = ld.fk_origin_line"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON obj.fk_product = p.rowid"; //TODO Add link to expeditiondet_batch $sql .= " WHERE e.entity IN (".getEntity('expedition').")"; @@ -262,7 +252,7 @@ print ''.$langs->trans("QtyPreparedOrShipped").''; if (!empty($conf->stock->enabled)) { - print ''.$langs->trans("Warehouse").''; + print ''.$langs->trans("Warehouse").''; } /*TODO Add link to expeditiondet_batch if (! empty($conf->productbatch->enabled)) @@ -270,7 +260,7 @@ print ''; print ''; }*/ - if (!empty($conf->delivery_note->enabled)) + if (!empty($conf->livraison_bon->enabled)) { print ''.$langs->trans("DeliveryOrder").''; //print ''.$langs->trans("QtyReceived").''; @@ -314,7 +304,9 @@ } $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $objp->product_label; - } else { + } + else + { $label = (!empty($objp->label) ? $objp->label : $objp->product_label); } @@ -340,7 +332,9 @@ } print ''; - } else { + } + else + { print ""; if ($objp->fk_product_type == 1) $text = img_object($langs->trans('Service'), 'service'); else $text = img_object($langs->trans('Product'), 'product'); @@ -371,13 +365,13 @@ // Warehouse if (!empty($conf->stock->enabled)) { - print ''; - if ($objp->warehouse_id > 0) - { - $warehousestatic->fetch($objp->warehouse_id); - print $warehousestatic->getNomUrl(1); - } - print ''; + print ''; + if ($objp->warehouse_id > 0) + { + $warehousestatic->fetch($objp->warehouse_id); + print $warehousestatic->getNomUrl(1); + } + print ''; } // Batch number managment @@ -413,9 +407,9 @@ }*/ // Informations on receipt - if (!empty($conf->delivery_note->enabled)) + if (!empty($conf->livraison_bon->enabled)) { - include_once DOL_DOCUMENT_ROOT.'/delivery/class/delivery.class.php'; + include_once DOL_DOCUMENT_ROOT.'/livraison/class/livraison.class.php'; $expedition->id = $objp->sendingid; $expedition->fetchObjectLinked($expedition->id, $expedition->element); //var_dump($expedition->linkedObjects); @@ -433,7 +427,7 @@ // Ref print ''; print $receiving->getNomUrl($db); - //print ''.img_object($langs->trans("ShowReceiving"),'sending').' '.$objp->livraison_ref.''; + //print ''.img_object($langs->trans("ShowReceiving"),'sending').' '.$objp->livraison_ref.''; print ''; // Qty received //print ''; @@ -445,7 +439,9 @@ print ''; print dol_print_date($receiving->date_delivery, 'day'); print ''; - } else { + } + else + { //print ' '; print ' '; print ' '; @@ -458,7 +454,9 @@ print ''; } $db->free($resql); - } else { + } + else + { dol_print_error($db); } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_signature.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_signature.lib.php @@ -29,7 +29,7 @@ global $conf, $langs; // Load translation files required by the page - $langs->loadLangs(array("payment", "paybox")); + $langs->loadLangs(array("payment", "paybox")); $servicename = 'Online'; @@ -63,7 +63,8 @@ if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '
' : ''); if ($mode == 1) $out .= '&hashp=hash_of_file'; - else { + else + { include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $propaltmp = new Propal($db); $res = $propaltmp->fetch(0, $ref); @@ -79,7 +80,9 @@ { $out = $langs->trans("FeatureOnlineSignDisabled"); return $out; - } else { + } + else + { $out .= '&hashp='.$hashp; } } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_stock.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_stock.lib.php @@ -66,20 +66,20 @@ } */ - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'stock'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'stock'); - $head[$h][0] = DOL_URL_ROOT.'/product/stock/info.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/product/stock/info.php?id='.$object->id; $head[$h][1] = $langs->trans("Info"); $head[$h][2] = 'info'; $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'stock', 'remove'); + complete_head_from_modules($conf, $langs, $object, $head, $h, 'stock', 'remove'); - return $head; + return $head; } /** @@ -89,28 +89,28 @@ */ function stock_admin_prepare_head() { - global $langs, $conf, $user; + global $langs, $conf, $user; - $h = 0; - $head = array(); + $h = 0; + $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/admin/stock.php'; - $head[$h][1] = $langs->trans("Miscellaneous"); - $head[$h][2] = 'general'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/stock.php'; + $head[$h][1] = $langs->trans("Miscellaneous"); + $head[$h][2] = 'general'; + $h++; - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab - complete_head_from_modules($conf, $langs, null, $head, $h, 'stock_admin'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'stock_admin'); - $head[$h][0] = DOL_URL_ROOT.'/product/admin/stock_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/product/admin/stock_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFields"); + $head[$h][2] = 'attributes'; + $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'stock_admin', 'remove'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'stock_admin', 'remove'); - return $head; + return $head; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_supplier_proposal.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_supplier_proposal.lib.php @@ -34,7 +34,7 @@ global $db, $langs, $conf, $user; // Load translation files required by the page - $langs->loadLangs(array("supplier_proposal", "compta")); + $langs->loadLangs(array("supplier_proposal", "compta")); $h = 0; $head = array(); @@ -54,29 +54,29 @@ $h++; } - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_proposal'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_proposal'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; if (!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/note.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; $head[$h][2] = 'note'; $h++; - } + } require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $upload_dir = $conf->supplier_proposal->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; @@ -118,13 +118,13 @@ $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/admin/supplier_proposal_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes'; - $h++; + $head[$h][2] = 'attributes'; + $h++; - $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/admin/supplier_proposaldet_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsLines"); - $head[$h][2] = 'attributeslines'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/admin/supplier_proposaldet_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsLines"); + $head[$h][2] = 'attributeslines'; + $h++; complete_head_from_modules($conf, $langs, null, $head, $h, 'supplier_proposal_admin', 'remove'); --- /tmp/dsg/dolibarr/htdocs/core/lib/github_takepos.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_takepos.lib.php @@ -26,7 +26,7 @@ * * @return array Array of tabs */ -function takepos_admin_prepare_head() +function takepos_prepare_head() { global $langs, $conf; @@ -38,20 +38,18 @@ $head[$h][2] = 'setup'; $h++; - $head[$h][0] = DOL_URL_ROOT.'/takepos/admin/appearance.php'; - $head[$h][1] = $langs->trans("Appearance"); - $head[$h][2] = 'appearance'; - $h++; - $head[$h][0] = DOL_URL_ROOT.'/takepos/admin/receipt.php'; $head[$h][1] = $langs->trans("Receipt"); $head[$h][2] = 'receipt'; $h++; - $head[$h][0] = DOL_URL_ROOT.'/takepos/admin/bar.php'; - $head[$h][1] = $langs->trans("BarRestaurant"); - $head[$h][2] = 'bar'; - $h++; + if ($conf->global->TAKEPOS_BAR_RESTAURANT) + { + $head[$h][0] = DOL_URL_ROOT.'/takepos/admin/bar.php'; + $head[$h][1] = $langs->trans("BarRestaurant"); + $head[$h][2] = 'bar'; + $h++; + } $numterminals = max(1, $conf->global->TAKEPOS_NUM_TERMINALS); for ($i = 1; $i <= $numterminals; $i++) @@ -67,9 +65,7 @@ $head[$h][2] = 'other'; $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'takepos_admin'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'takepos'); - complete_head_from_modules($conf, $langs, null, $head, $h, 'takepos_admin', 'remove'); - - return $head; + return $head; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_tax.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_tax.lib.php @@ -36,41 +36,41 @@ */ function tax_prepare_head(ChargeSociales $object) { - global $db, $langs, $conf, $user; - - $h = 0; - $head = array(); + global $db, $langs, $conf, $user; + + $h = 0; + $head = array(); $head[$h][0] = DOL_URL_ROOT.'/compta/sociales/card.php?id='.$object->id; - $head[$h][1] = $langs->trans('SocialContribution'); + $head[$h][1] = $langs->trans('Card'); $head[$h][2] = 'card'; $h++; - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'tax'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'tax'); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $upload_dir = $conf->tax->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/compta/sociales/document.php?id='.$object->id; $head[$h][1] = $langs->trans("Documents"); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; $head[$h][2] = 'documents'; $h++; - $head[$h][0] = DOL_URL_ROOT.'/compta/sociales/info.php?id='.$object->id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; - - complete_head_from_modules($conf, $langs, $object, $head, $h, 'tax', 'remove'); - - return $head; + $head[$h][0] = DOL_URL_ROOT.'/compta/sociales/info.php?id='.$object->id; + $head[$h][1] = $langs->trans("Info"); + $head[$h][2] = 'info'; + $h++; + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'tax', 'remove'); + + return $head; } @@ -90,438 +90,454 @@ */ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $direction, $m = 0, $q = 0) { - global $conf; - - // If we use date_start and date_end, we must not use $y, $m, $q - if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) - { - dol_print_error('', 'Bad value of input parameter for tax_by_rate'); - } - - $list = array(); - if ($direction == 'sell') - { - $invoicetable = 'facture'; - $invoicedettable = 'facturedet'; - $fk_facture = 'fk_facture'; - $fk_facture2 = 'fk_facture'; - $fk_payment = 'fk_paiement'; - $total_tva = 'total_tva'; - $paymenttable = 'paiement'; - $paymentfacturetable = 'paiement_facture'; - $invoicefieldref = 'ref'; - } elseif ($direction == 'buy') - { - $invoicetable = 'facture_fourn'; - $invoicedettable = 'facture_fourn_det'; - $fk_facture = 'fk_facture_fourn'; - $fk_facture2 = 'fk_facturefourn'; - $fk_payment = 'fk_paiementfourn'; - $total_tva = 'tva'; - $paymenttable = 'paiementfourn'; - $paymentfacturetable = 'paiementfourn_facturefourn'; - $invoicefieldref = 'ref'; - } - - if (strpos($type, 'localtax') === 0) { - $f_rate = $type.'_tx'; - } else { - $f_rate = 'tva_tx'; - } - - $total_localtax1 = 'total_localtax1'; - $total_localtax2 = 'total_localtax2'; - - - // CAS DES BIENS/PRODUITS - - // Define sql request - $sql = ''; - if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) - { - // Count on delivery date (use invoice date as delivery is unknown) - $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; - $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; - $sql .= " d.date_start as date_start, d.date_end as date_end,"; - $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; - $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; - $sql .= " 0 as payment_id, 0 as payment_amount"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; - $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; - $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { - $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; - $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { - $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; - $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; - } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; - $sql .= " AND (d.product_type = 0"; // Limit to products - $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; - $sql .= " ORDER BY d.rowid, d.".$fk_facture; - } else { - // Count on payments date - $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; - $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; - $sql .= " d.date_start as date_start, d.date_end as date_end,"; - $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; - $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; - $sql .= " pf.".$fk_payment." as payment_id, pf.amount as payment_amount,"; - $sql .= " pa.datep as datep"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX.$paymentfacturetable." as pf,"; - $sql .= " ".MAIN_DB_PREFIX.$paymenttable." as pa,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; - $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; - $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - $sql .= " AND pf.".$fk_facture2." = f.rowid"; - $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { - $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; - $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { - $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; - $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; - } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; - $sql .= " AND (d.product_type = 0"; // Limit to products - $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; - $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; - } - - if (!$sql) return -1; - if ($sql == 'TODO') return -2; - if ($sql != 'TODO') - { - dol_syslog("Tax.lib.php::tax_by_thirdparty", LOG_DEBUG); - - $resql = $db->query($sql); - if ($resql) - { - $company_id = -1; - $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; - if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; - if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; - if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; - - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { - $oldrowid = $assoc['rowid']; - $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; - $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; - $list[$assoc['company_id']]['localtax1'] += $assoc['total_localtax1']; - $list[$assoc['company_id']]['localtax2'] += $assoc['total_localtax2']; - } - $list[$assoc['company_id']]['dtotal_ttc'][] = $assoc['total_ttc']; - $list[$assoc['company_id']]['dtype'][] = $assoc['dtype']; - $list[$assoc['company_id']]['datef'][] = $db->jdate($assoc['datef']); - $list[$assoc['company_id']]['datep'][] = $db->jdate($assoc['datep']); - $list[$assoc['company_id']]['company_name'][] = $assoc['company_name']; - $list[$assoc['company_id']]['company_id'][] = $assoc['company_id']; - $list[$assoc['company_id']]['drate'][] = $assoc['rate']; - $list[$assoc['company_id']]['ddate_start'][] = $db->jdate($assoc['date_start']); - $list[$assoc['company_id']]['ddate_end'][] = $db->jdate($assoc['date_end']); - - $list[$assoc['company_id']]['facid'][] = $assoc['facid']; - $list[$assoc['company_id']]['facnum'][] = $assoc['facnum']; - $list[$assoc['company_id']]['type'][] = $assoc['type']; - $list[$assoc['company_id']]['ftotal_ttc'][] = $assoc['ftotal_ttc']; - $list[$assoc['company_id']]['descr'][] = $assoc['descr']; - - $list[$assoc['company_id']]['totalht_list'][] = $assoc['total_ht']; - $list[$assoc['company_id']]['vat_list'][] = $assoc['total_vat']; - $list[$assoc['company_id']]['localtax1_list'][] = $assoc['total_localtax1']; - $list[$assoc['company_id']]['localtax2_list'][] = $assoc['total_localtax2']; - - $list[$assoc['company_id']]['pid'][] = $assoc['pid']; - $list[$assoc['company_id']]['pref'][] = $assoc['pref']; - $list[$assoc['company_id']]['ptype'][] = $assoc['ptype']; - - $list[$assoc['company_id']]['payment_id'][] = $assoc['payment_id']; - $list[$assoc['company_id']]['payment_amount'][] = $assoc['payment_amount']; - - $company_id = $assoc['company_id']; - } - } else { - dol_print_error($db); - return -3; - } - } - - - // CAS DES SERVICES - - // Define sql request - $sql = ''; - if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) - { - // Count on invoice date - $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; - $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; - $sql .= " d.date_start as date_start, d.date_end as date_end,"; - $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; - $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; - $sql .= " 0 as payment_id, 0 as payment_amount"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; - $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; - $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { - $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; - $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { - $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; - $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; - } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; - $sql .= " AND (d.product_type = 1"; // Limit to services - $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; - $sql .= " ORDER BY d.rowid, d.".$fk_facture; - } else { - // Count on payments date - $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; - $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; - $sql .= " d.date_start as date_start, d.date_end as date_end,"; - $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; - $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; - $sql .= " pf.".$fk_payment." as payment_id, pf.amount as payment_amount,"; - $sql .= " pa.datep as datep"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX.$paymentfacturetable." as pf,"; - $sql .= " ".MAIN_DB_PREFIX.$paymenttable." as pa,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; - $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; - $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - $sql .= " AND pf.".$fk_facture2." = f.rowid"; - $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { - $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; - $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { - $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; - $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; - } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; - $sql .= " AND (d.product_type = 1"; // Limit to services - $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; - $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; - } - - if (!$sql) - { - dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); - return -1; // -1 = Not accountancy module enabled - } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { - dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $company_id = -1; - $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; - if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; - if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; - if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; - - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { - $oldrowid = $assoc['rowid']; - $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; - $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; - $list[$assoc['company_id']]['localtax1'] += $assoc['total_localtax1']; - $list[$assoc['company_id']]['localtax2'] += $assoc['total_localtax2']; - } - $list[$assoc['company_id']]['dtotal_ttc'][] = $assoc['total_ttc']; - $list[$assoc['company_id']]['dtype'][] = $assoc['dtype']; - $list[$assoc['company_id']]['datef'][] = $db->jdate($assoc['datef']); - $list[$assoc['company_id']]['datep'][] = $db->jdate($assoc['datep']); - $list[$assoc['company_id']]['company_name'][] = $assoc['company_name']; - $list[$assoc['company_id']]['company_id'][] = $assoc['company_id']; - $list[$assoc['company_id']]['drate'][] = $assoc['rate']; - $list[$assoc['company_id']]['ddate_start'][] = $db->jdate($assoc['date_start']); - $list[$assoc['company_id']]['ddate_end'][] = $db->jdate($assoc['date_end']); - - $list[$assoc['company_id']]['facid'][] = $assoc['facid']; - $list[$assoc['company_id']]['facnum'][] = $assoc['facnum']; - $list[$assoc['company_id']]['type'][] = $assoc['type']; - $list[$assoc['company_id']]['ftotal_ttc'][] = $assoc['ftotal_ttc']; - $list[$assoc['company_id']]['descr'][] = $assoc['descr']; - - $list[$assoc['company_id']]['totalht_list'][] = $assoc['total_ht']; - $list[$assoc['company_id']]['vat_list'][] = $assoc['total_vat']; - $list[$assoc['company_id']]['localtax1_list'][] = $assoc['total_localtax1']; - $list[$assoc['company_id']]['localtax2_list'][] = $assoc['total_localtax2']; - - $list[$assoc['company_id']]['pid'][] = $assoc['pid']; - $list[$assoc['company_id']]['pref'][] = $assoc['pref']; - $list[$assoc['company_id']]['ptype'][] = $assoc['ptype']; - - $list[$assoc['company_id']]['payment_id'][] = $assoc['payment_id']; - $list[$assoc['company_id']]['payment_amount'][] = $assoc['payment_amount']; - - $company_id = $assoc['company_id']; - } - } else { - dol_print_error($db); - return -3; - } - } - - - // CASE OF EXPENSE REPORT - - if ($direction == 'buy') // buy only for expense reports - { - // Define sql request - $sql = ''; - - // Count on payments date - $sql = "SELECT d.rowid, d.product_type as dtype, e.rowid as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.total_tva as total_vat, e.note_private as descr,"; - $sql .= " d.total_localtax1 as total_localtax1, d.total_localtax2 as total_localtax2, "; - $sql .= " e.date_debut as date_start, e.date_fin as date_end, e.fk_user_author,"; - $sql .= " e.ref as facnum, e.total_ttc as ftotal_ttc, e.date_create, d.fk_c_type_fees as type,"; - $sql .= " p.fk_bank as payment_id, p.amount as payment_amount, p.rowid as pid, e.ref as pref"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as e"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expensereport_det as d ON d.fk_expensereport = e.rowid "; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_expensereport as p ON p.fk_expensereport = e.rowid "; - $sql .= " WHERE e.entity = ".$conf->entity; - $sql .= " AND e.fk_statut in (6)"; - if ($y && $m) - { - $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; - $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { - $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; - $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; - } - if ($q) $sql .= " AND (date_format(p.datep,'%m') > ".(($q - 1) * 3)." AND date_format(p.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; - $sql .= " AND (d.product_type = -1"; - $sql .= " OR e.date_debut is NOT null OR e.date_fin IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; - $sql .= " ORDER BY e.rowid"; - - if (!$sql) - { - dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); - return -1; // -1 = Not accountancy module enabled - } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { - dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $company_id = -1; - $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; - if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; - if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; - if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; - - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { - $oldrowid = $assoc['rowid']; - $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; - $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; - $list[$assoc['company_id']]['localtax1'] += $assoc['total_localtax1']; - $list[$assoc['company_id']]['localtax2'] += $assoc['total_localtax2']; - } - - $list[$assoc['company_id']]['dtotal_ttc'][] = $assoc['total_ttc']; - $list[$assoc['company_id']]['dtype'][] = 'ExpenseReportPayment'; - $list[$assoc['company_id']]['datef'][] = $assoc['datef']; - $list[$assoc['company_id']]['company_name'][] = ''; - $list[$assoc['company_id']]['company_id'][] = ''; - $list[$assoc['company_id']]['user_id'][] = $assoc['fk_user_author']; - $list[$assoc['company_id']]['drate'][] = $assoc['rate']; - $list[$assoc['company_id']]['ddate_start'][] = $db->jdate($assoc['date_start']); - $list[$assoc['company_id']]['ddate_end'][] = $db->jdate($assoc['date_end']); - - $list[$assoc['company_id']]['facid'][] = $assoc['facid']; - $list[$assoc['company_id']]['facnum'][] = $assoc['facnum']; - $list[$assoc['company_id']]['type'][] = $assoc['type']; - $list[$assoc['company_id']]['ftotal_ttc'][] = $assoc['ftotal_ttc']; - $list[$assoc['company_id']]['descr'][] = $assoc['descr']; - - $list[$assoc['company_id']]['totalht_list'][] = $assoc['total_ht']; - $list[$assoc['company_id']]['vat_list'][] = $assoc['total_vat']; - $list[$assoc['company_id']]['localtax1_list'][] = $assoc['total_localtax1']; - $list[$assoc['company_id']]['localtax2_list'][] = $assoc['total_localtax2']; - - $list[$assoc['company_id']]['pid'][] = $assoc['pid']; - $list[$assoc['company_id']]['pref'][] = $assoc['pref']; - $list[$assoc['company_id']]['ptype'][] = 'ExpenseReportPayment'; - - $list[$assoc['company_id']]['payment_id'][] = $assoc['payment_id']; - $list[$assoc['company_id']]['payment_amount'][] = $assoc['payment_amount']; - - $company_id = $assoc['company_id']; - } - } else { - dol_print_error($db); - return -3; - } - } - } - - return $list; + global $conf; + + // If we use date_start and date_end, we must not use $y, $m, $q + if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) + { + dol_print_error('', 'Bad value of input parameter for tax_by_rate'); + } + + $list = array(); + if ($direction == 'sell') + { + $invoicetable = 'facture'; + $invoicedettable = 'facturedet'; + $fk_facture = 'fk_facture'; + $fk_facture2 = 'fk_facture'; + $fk_payment = 'fk_paiement'; + $total_tva = 'total_tva'; + $paymenttable = 'paiement'; + $paymentfacturetable = 'paiement_facture'; + $invoicefieldref = 'ref'; + } + elseif ($direction == 'buy') + { + $invoicetable = 'facture_fourn'; + $invoicedettable = 'facture_fourn_det'; + $fk_facture = 'fk_facture_fourn'; + $fk_facture2 = 'fk_facturefourn'; + $fk_payment = 'fk_paiementfourn'; + $total_tva = 'tva'; + $paymenttable = 'paiementfourn'; + $paymentfacturetable = 'paiementfourn_facturefourn'; + $invoicefieldref = 'ref'; + } + + if (strpos($type, 'localtax') === 0) { + $f_rate = $type.'_tx'; + } else { + $f_rate = 'tva_tx'; + } + + $total_localtax1 = 'total_localtax1'; + $total_localtax2 = 'total_localtax2'; + + + // CAS DES BIENS/PRODUITS + + // Define sql request + $sql = ''; + if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) + { + // Count on delivery date (use invoice date as delivery is unknown) + $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; + $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; + $sql .= " d.date_start as date_start, d.date_end as date_end,"; + $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; + $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; + $sql .= " 0 as payment_id, 0 as payment_amount"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; + $sql .= " ".MAIN_DB_PREFIX."societe as s,"; + $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; + $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; + $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; + else $sql .= " AND f.type IN (0,1,2,3,5)"; + $sql .= " AND f.rowid = d.".$fk_facture; + $sql .= " AND s.rowid = f.fk_soc"; + if ($y && $m) + { + $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; + $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; + } + elseif ($y) + { + $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; + $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; + } + if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + $sql .= " AND (d.product_type = 0"; // Limit to products + $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products + if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + $sql .= " ORDER BY d.rowid, d.".$fk_facture; + } + else + { + // Count on payments date + $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; + $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; + $sql .= " d.date_start as date_start, d.date_end as date_end,"; + $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; + $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; + $sql .= " pf.".$fk_payment." as payment_id, pf.amount as payment_amount,"; + $sql .= " pa.datep as datep"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; + $sql .= " ".MAIN_DB_PREFIX.$paymentfacturetable." as pf,"; + $sql .= " ".MAIN_DB_PREFIX.$paymenttable." as pa,"; + $sql .= " ".MAIN_DB_PREFIX."societe as s,"; + $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; + $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; + $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; + else $sql .= " AND f.type IN (0,1,2,3,5)"; + $sql .= " AND f.rowid = d.".$fk_facture; + $sql .= " AND s.rowid = f.fk_soc"; + $sql .= " AND pf.".$fk_facture2." = f.rowid"; + $sql .= " AND pa.rowid = pf.".$fk_payment; + if ($y && $m) + { + $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; + $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; + } + elseif ($y) + { + $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; + $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; + } + if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + $sql .= " AND (d.product_type = 0"; // Limit to products + $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products + if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; + } + + if (!$sql) return -1; + if ($sql == 'TODO') return -2; + if ($sql != 'TODO') + { + dol_syslog("Tax.lib.php::tax_by_thirdparty", LOG_DEBUG); + + $resql = $db->query($sql); + if ($resql) + { + $company_id = -1; + $oldrowid = ''; + while ($assoc = $db->fetch_array($resql)) + { + if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; + if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; + if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; + if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; + + if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid + { + $oldrowid = $assoc['rowid']; + $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; + $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; + $list[$assoc['company_id']]['localtax1'] += $assoc['total_localtax1']; + $list[$assoc['company_id']]['localtax2'] += $assoc['total_localtax2']; + } + $list[$assoc['company_id']]['dtotal_ttc'][] = $assoc['total_ttc']; + $list[$assoc['company_id']]['dtype'][] = $assoc['dtype']; + $list[$assoc['company_id']]['datef'][] = $db->jdate($assoc['datef']); + $list[$assoc['company_id']]['datep'][] = $db->jdate($assoc['datep']); + $list[$assoc['company_id']]['company_name'][] = $assoc['company_name']; + $list[$assoc['company_id']]['company_id'][] = $assoc['company_id']; + $list[$assoc['company_id']]['drate'][] = $assoc['rate']; + $list[$assoc['company_id']]['ddate_start'][] = $db->jdate($assoc['date_start']); + $list[$assoc['company_id']]['ddate_end'][] = $db->jdate($assoc['date_end']); + + $list[$assoc['company_id']]['facid'][] = $assoc['facid']; + $list[$assoc['company_id']]['facnum'][] = $assoc['facnum']; + $list[$assoc['company_id']]['type'][] = $assoc['type']; + $list[$assoc['company_id']]['ftotal_ttc'][] = $assoc['ftotal_ttc']; + $list[$assoc['company_id']]['descr'][] = $assoc['descr']; + + $list[$assoc['company_id']]['totalht_list'][] = $assoc['total_ht']; + $list[$assoc['company_id']]['vat_list'][] = $assoc['total_vat']; + $list[$assoc['company_id']]['localtax1_list'][] = $assoc['total_localtax1']; + $list[$assoc['company_id']]['localtax2_list'][] = $assoc['total_localtax2']; + + $list[$assoc['company_id']]['pid'][] = $assoc['pid']; + $list[$assoc['company_id']]['pref'][] = $assoc['pref']; + $list[$assoc['company_id']]['ptype'][] = $assoc['ptype']; + + $list[$assoc['company_id']]['payment_id'][] = $assoc['payment_id']; + $list[$assoc['company_id']]['payment_amount'][] = $assoc['payment_amount']; + + $company_id = $assoc['company_id']; + } + } + else + { + dol_print_error($db); + return -3; + } + } + + + // CAS DES SERVICES + + // Define sql request + $sql = ''; + if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice') + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) + { + // Count on invoice date + $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; + $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; + $sql .= " d.date_start as date_start, d.date_end as date_end,"; + $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; + $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; + $sql .= " 0 as payment_id, 0 as payment_amount"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; + $sql .= " ".MAIN_DB_PREFIX."societe as s,"; + $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; + $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; + $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; + else $sql .= " AND f.type IN (0,1,2,3,5)"; + $sql .= " AND f.rowid = d.".$fk_facture; + $sql .= " AND s.rowid = f.fk_soc"; + if ($y && $m) + { + $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; + $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; + } + elseif ($y) + { + $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; + $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; + } + if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + $sql .= " AND (d.product_type = 1"; // Limit to services + $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service + if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + $sql .= " ORDER BY d.rowid, d.".$fk_facture; + } + else + { + // Count on payments date + $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; + $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; + $sql .= " d.date_start as date_start, d.date_end as date_end,"; + $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; + $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; + $sql .= " pf.".$fk_payment." as payment_id, pf.amount as payment_amount,"; + $sql .= " pa.datep as datep"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; + $sql .= " ".MAIN_DB_PREFIX.$paymentfacturetable." as pf,"; + $sql .= " ".MAIN_DB_PREFIX.$paymenttable." as pa,"; + $sql .= " ".MAIN_DB_PREFIX."societe as s,"; + $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; + $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; + $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; + else $sql .= " AND f.type IN (0,1,2,3,5)"; + $sql .= " AND f.rowid = d.".$fk_facture; + $sql .= " AND s.rowid = f.fk_soc"; + $sql .= " AND pf.".$fk_facture2." = f.rowid"; + $sql .= " AND pa.rowid = pf.".$fk_payment; + if ($y && $m) + { + $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; + $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; + } + elseif ($y) + { + $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; + $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; + } + if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + $sql .= " AND (d.product_type = 1"; // Limit to services + $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service + if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; + } + + if (!$sql) + { + dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); + return -1; // -1 = Not accountancy module enabled + } + if ($sql == 'TODO') return -2; // -2 = Feature not yet available + if ($sql != 'TODO') + { + dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $company_id = -1; + $oldrowid = ''; + while ($assoc = $db->fetch_array($resql)) + { + if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; + if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; + if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; + if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; + + if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid + { + $oldrowid = $assoc['rowid']; + $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; + $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; + $list[$assoc['company_id']]['localtax1'] += $assoc['total_localtax1']; + $list[$assoc['company_id']]['localtax2'] += $assoc['total_localtax2']; + } + $list[$assoc['company_id']]['dtotal_ttc'][] = $assoc['total_ttc']; + $list[$assoc['company_id']]['dtype'][] = $assoc['dtype']; + $list[$assoc['company_id']]['datef'][] = $db->jdate($assoc['datef']); + $list[$assoc['company_id']]['datep'][] = $db->jdate($assoc['datep']); + $list[$assoc['company_id']]['company_name'][] = $assoc['company_name']; + $list[$assoc['company_id']]['company_id'][] = $assoc['company_id']; + $list[$assoc['company_id']]['drate'][] = $assoc['rate']; + $list[$assoc['company_id']]['ddate_start'][] = $db->jdate($assoc['date_start']); + $list[$assoc['company_id']]['ddate_end'][] = $db->jdate($assoc['date_end']); + + $list[$assoc['company_id']]['facid'][] = $assoc['facid']; + $list[$assoc['company_id']]['facnum'][] = $assoc['facnum']; + $list[$assoc['company_id']]['type'][] = $assoc['type']; + $list[$assoc['company_id']]['ftotal_ttc'][] = $assoc['ftotal_ttc']; + $list[$assoc['company_id']]['descr'][] = $assoc['descr']; + + $list[$assoc['company_id']]['totalht_list'][] = $assoc['total_ht']; + $list[$assoc['company_id']]['vat_list'][] = $assoc['total_vat']; + $list[$assoc['company_id']]['localtax1_list'][] = $assoc['total_localtax1']; + $list[$assoc['company_id']]['localtax2_list'][] = $assoc['total_localtax2']; + + $list[$assoc['company_id']]['pid'][] = $assoc['pid']; + $list[$assoc['company_id']]['pref'][] = $assoc['pref']; + $list[$assoc['company_id']]['ptype'][] = $assoc['ptype']; + + $list[$assoc['company_id']]['payment_id'][] = $assoc['payment_id']; + $list[$assoc['company_id']]['payment_amount'][] = $assoc['payment_amount']; + + $company_id = $assoc['company_id']; + } + } + else + { + dol_print_error($db); + return -3; + } + } + + + // CASE OF EXPENSE REPORT + + if ($direction == 'buy') // buy only for expense reports + { + // Define sql request + $sql = ''; + + // Count on payments date + $sql = "SELECT d.rowid, d.product_type as dtype, e.rowid as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.total_tva as total_vat, e.note_private as descr,"; + $sql .= " d.total_localtax1 as total_localtax1, d.total_localtax2 as total_localtax2, "; + $sql .= " e.date_debut as date_start, e.date_fin as date_end, e.fk_user_author,"; + $sql .= " e.ref as facnum, e.total_ttc as ftotal_ttc, e.date_create, d.fk_c_type_fees as type,"; + $sql .= " p.fk_bank as payment_id, p.amount as payment_amount, p.rowid as pid, e.ref as pref"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as e"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expensereport_det as d ON d.fk_expensereport = e.rowid "; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_expensereport as p ON p.fk_expensereport = e.rowid "; + $sql .= " WHERE e.entity = ".$conf->entity; + $sql .= " AND e.fk_statut in (6)"; + if ($y && $m) + { + $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; + $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; + } + elseif ($y) + { + $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; + $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; + } + if ($q) $sql .= " AND (date_format(p.datep,'%m') > ".(($q - 1) * 3)." AND date_format(p.datep,'%m') <= ".($q * 3).")"; + if ($date_start && $date_end) $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + $sql .= " AND (d.product_type = -1"; + $sql .= " OR e.date_debut is NOT null OR e.date_fin IS NOT NULL)"; // enhance detection of service + if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + $sql .= " ORDER BY e.rowid"; + + if (!$sql) + { + dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); + return -1; // -1 = Not accountancy module enabled + } + if ($sql == 'TODO') return -2; // -2 = Feature not yet available + if ($sql != 'TODO') + { + dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $company_id = -1; + $oldrowid = ''; + while ($assoc = $db->fetch_array($resql)) + { + if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; + if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; + if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; + if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; + + if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid + { + $oldrowid = $assoc['rowid']; + $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; + $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; + $list[$assoc['company_id']]['localtax1'] += $assoc['total_localtax1']; + $list[$assoc['company_id']]['localtax2'] += $assoc['total_localtax2']; + } + + $list[$assoc['company_id']]['dtotal_ttc'][] = $assoc['total_ttc']; + $list[$assoc['company_id']]['dtype'][] = 'ExpenseReportPayment'; + $list[$assoc['company_id']]['datef'][] = $assoc['datef']; + $list[$assoc['company_id']]['company_name'][] = ''; + $list[$assoc['company_id']]['company_id'][] = ''; + $list[$assoc['company_id']]['user_id'][] = $assoc['fk_user_author']; + $list[$assoc['company_id']]['drate'][] = $assoc['rate']; + $list[$assoc['company_id']]['ddate_start'][] = $db->jdate($assoc['date_start']); + $list[$assoc['company_id']]['ddate_end'][] = $db->jdate($assoc['date_end']); + + $list[$assoc['company_id']]['facid'][] = $assoc['facid']; + $list[$assoc['company_id']]['facnum'][] = $assoc['facnum']; + $list[$assoc['company_id']]['type'][] = $assoc['type']; + $list[$assoc['company_id']]['ftotal_ttc'][] = $assoc['ftotal_ttc']; + $list[$assoc['company_id']]['descr'][] = $assoc['descr']; + + $list[$assoc['company_id']]['totalht_list'][] = $assoc['total_ht']; + $list[$assoc['company_id']]['vat_list'][] = $assoc['total_vat']; + $list[$assoc['company_id']]['localtax1_list'][] = $assoc['total_localtax1']; + $list[$assoc['company_id']]['localtax2_list'][] = $assoc['total_localtax2']; + + $list[$assoc['company_id']]['pid'][] = $assoc['pid']; + $list[$assoc['company_id']]['pref'][] = $assoc['pref']; + $list[$assoc['company_id']]['ptype'][] = 'ExpenseReportPayment'; + + $list[$assoc['company_id']]['payment_id'][] = $assoc['payment_id']; + $list[$assoc['company_id']]['payment_amount'][] = $assoc['payment_amount']; + + $company_id = $assoc['company_id']; + } + } + else + { + dol_print_error($db); + return -3; + } + } + } + + return $list; } /** @@ -542,38 +558,40 @@ */ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $direction, $m = 0) { - global $conf; - - // If we use date_start and date_end, we must not use $y, $m, $q - if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) - { - dol_print_error('', 'Bad value of input parameter for tax_by_rate'); - } - - $list = array(); - - if ($direction == 'sell') - { - $invoicetable = 'facture'; - $invoicedettable = 'facturedet'; - $fk_facture = 'fk_facture'; - $fk_facture2 = 'fk_facture'; - $fk_payment = 'fk_paiement'; - $total_tva = 'total_tva'; - $paymenttable = 'paiement'; - $paymentfacturetable = 'paiement_facture'; - $invoicefieldref = 'ref'; - } else { - $invoicetable = 'facture_fourn'; - $invoicedettable = 'facture_fourn_det'; - $fk_facture = 'fk_facture_fourn'; - $fk_facture2 = 'fk_facturefourn'; - $fk_payment = 'fk_paiementfourn'; - $total_tva = 'tva'; - $paymenttable = 'paiementfourn'; - $paymentfacturetable = 'paiementfourn_facturefourn'; - $invoicefieldref = 'ref'; - } + global $conf; + + // If we use date_start and date_end, we must not use $y, $m, $q + if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) + { + dol_print_error('', 'Bad value of input parameter for tax_by_rate'); + } + + $list = array(); + + if ($direction == 'sell') + { + $invoicetable = 'facture'; + $invoicedettable = 'facturedet'; + $fk_facture = 'fk_facture'; + $fk_facture2 = 'fk_facture'; + $fk_payment = 'fk_paiement'; + $total_tva = 'total_tva'; + $paymenttable = 'paiement'; + $paymentfacturetable = 'paiement_facture'; + $invoicefieldref = 'ref'; + } + else + { + $invoicetable = 'facture_fourn'; + $invoicedettable = 'facture_fourn_det'; + $fk_facture = 'fk_facture_fourn'; + $fk_facture2 = 'fk_facturefourn'; + $fk_payment = 'fk_paiementfourn'; + $total_tva = 'tva'; + $paymenttable = 'paiementfourn'; + $paymentfacturetable = 'paiementfourn_facturefourn'; + $invoicefieldref = 'ref'; + } if (strpos($type, 'localtax') === 0) { $f_rate = $type.'_tx'; @@ -585,294 +603,306 @@ $total_localtax2 = 'total_localtax2'; - // CAS DES BIENS/PRODUITS - - // Define sql request - $sql = ''; - if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) - { - // Count on delivery date (use invoice date as delivery is unknown) - $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; - $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; - $sql .= " d.date_start as date_start, d.date_end as date_end,"; - $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; - $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; - $sql .= " 0 as payment_id, 0 as payment_amount"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; - $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; - $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; + // CAS DES BIENS/PRODUITS + + // Define sql request + $sql = ''; + if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) + { + // Count on delivery date (use invoice date as delivery is unknown) + $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; + $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; + $sql .= " d.date_start as date_start, d.date_end as date_end,"; + $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; + $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; + $sql .= " 0 as payment_id, 0 as payment_amount"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; + $sql .= " ".MAIN_DB_PREFIX."societe as s,"; + $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; + $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; + $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; + else $sql .= " AND f.type IN (0,1,2,3,5)"; + $sql .= " AND f.rowid = d.".$fk_facture; + $sql .= " AND s.rowid = f.fk_soc"; + if ($y && $m) + { + $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; + $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; + } + elseif ($y) + { + $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; + $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; + } + if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + $sql .= " AND (d.product_type = 0"; // Limit to products + $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products + if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + $sql .= " ORDER BY d.rowid, d.".$fk_facture; + } + else + { + // Count on payments date + $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; + $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; + $sql .= " d.date_start as date_start, d.date_end as date_end,"; + $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; + $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; + $sql .= " pf.".$fk_payment." as payment_id, pf.amount as payment_amount,"; + $sql .= " pa.datep as datep"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; + $sql .= " ".MAIN_DB_PREFIX.$paymentfacturetable." as pf,"; + $sql .= " ".MAIN_DB_PREFIX.$paymenttable." as pa,"; + $sql .= " ".MAIN_DB_PREFIX."societe as s,"; + $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; + $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; + $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; + else $sql .= " AND f.type IN (0,1,2,3,5)"; + $sql .= " AND f.rowid = d.".$fk_facture; + $sql .= " AND s.rowid = f.fk_soc"; + $sql .= " AND pf.".$fk_facture2." = f.rowid"; + $sql .= " AND pa.rowid = pf.".$fk_payment; + if ($y && $m) + { + $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; + $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; + } + elseif ($y) + { + $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; + $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; + } + if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + $sql .= " AND (d.product_type = 0"; // Limit to products + $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products + if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; + } + + if (!$sql) return -1; + if ($sql == 'TODO') return -2; + if ($sql != 'TODO') + { + dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); + + $resql = $db->query($sql); + if ($resql) + { + $rate = -1; + $oldrowid = ''; + while ($assoc = $db->fetch_array($resql)) + { + // Code to avoid warnings when array entry not defined + if (!isset($list[$assoc['rate']]['totalht'])) $list[$assoc['rate']]['totalht'] = 0; + if (!isset($list[$assoc['rate']]['vat'])) $list[$assoc['rate']]['vat'] = 0; + if (!isset($list[$assoc['rate']]['localtax1'])) $list[$assoc['rate']]['localtax1'] = 0; + if (!isset($list[$assoc['rate']]['localtax2'])) $list[$assoc['rate']]['localtax2'] = 0; + + if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid + { + $oldrowid = $assoc['rowid']; + $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; + $list[$assoc['rate']]['vat'] += $assoc['total_vat']; + $list[$assoc['rate']]['localtax1'] += $assoc['total_localtax1']; + $list[$assoc['rate']]['localtax2'] += $assoc['total_localtax2']; + } + $list[$assoc['rate']]['dtotal_ttc'][] = $assoc['total_ttc']; + $list[$assoc['rate']]['dtype'][] = $assoc['dtype']; + $list[$assoc['rate']]['datef'][] = $db->jdate($assoc['datef']); + $list[$assoc['rate']]['datep'][] = $db->jdate($assoc['datep']); + $list[$assoc['rate']]['company_name'][] = $assoc['company_name']; + $list[$assoc['rate']]['company_id'][] = $assoc['company_id']; + $list[$assoc['rate']]['ddate_start'][] = $db->jdate($assoc['date_start']); + $list[$assoc['rate']]['ddate_end'][] = $db->jdate($assoc['date_end']); + + $list[$assoc['rate']]['facid'][] = $assoc['facid']; + $list[$assoc['rate']]['facnum'][] = $assoc['facnum']; + $list[$assoc['rate']]['type'][] = $assoc['type']; + $list[$assoc['rate']]['ftotal_ttc'][] = $assoc['ftotal_ttc']; + $list[$assoc['rate']]['descr'][] = $assoc['descr']; + + $list[$assoc['rate']]['totalht_list'][] = $assoc['total_ht']; + $list[$assoc['rate']]['vat_list'][] = $assoc['total_vat']; + $list[$assoc['rate']]['localtax1_list'][] = $assoc['total_localtax1']; + $list[$assoc['rate']]['localtax2_list'][] = $assoc['total_localtax2']; + + $list[$assoc['rate']]['pid'][] = $assoc['pid']; + $list[$assoc['rate']]['pref'][] = $assoc['pref']; + $list[$assoc['rate']]['ptype'][] = $assoc['ptype']; + + $list[$assoc['rate']]['payment_id'][] = $assoc['payment_id']; + $list[$assoc['rate']]['payment_amount'][] = $assoc['payment_amount']; + + $rate = $assoc['rate']; + } + } + else + { + dol_print_error($db); + return -3; + } + } + + + // CAS DES SERVICES + + // Define sql request + $sql = ''; + if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice') + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) + { + // Count on invoice date + $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; + $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; + $sql .= " d.date_start as date_start, d.date_end as date_end,"; + $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; + $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; + $sql .= " 0 as payment_id, 0 as payment_amount"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; + $sql .= " ".MAIN_DB_PREFIX."societe as s,"; + $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; + $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; + $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { - $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; - $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { - $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; - $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; - } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; - $sql .= " AND (d.product_type = 0"; // Limit to products - $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; - $sql .= " ORDER BY d.rowid, d.".$fk_facture; - } else { - // Count on payments date - $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; - $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; - $sql .= " d.date_start as date_start, d.date_end as date_end,"; - $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; - $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; - $sql .= " pf.".$fk_payment." as payment_id, pf.amount as payment_amount,"; - $sql .= " pa.datep as datep"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX.$paymentfacturetable." as pf,"; - $sql .= " ".MAIN_DB_PREFIX.$paymenttable." as pa,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; - $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; - $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; + $sql .= " AND f.rowid = d.".$fk_facture; + $sql .= " AND s.rowid = f.fk_soc"; + if ($y && $m) + { + $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; + $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; + } + elseif ($y) + { + $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; + $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; + } + if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + $sql .= " AND (d.product_type = 1"; // Limit to services + $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service + if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + $sql .= " ORDER BY d.rowid, d.".$fk_facture; + } + else + { + // Count on payments date + $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; + $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; + $sql .= " d.date_start as date_start, d.date_end as date_end,"; + $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; + $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; + $sql .= " pf.".$fk_payment." as payment_id, pf.amount as payment_amount,"; + $sql .= " pa.datep as datep"; + $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; + $sql .= " ".MAIN_DB_PREFIX.$paymentfacturetable." as pf,"; + $sql .= " ".MAIN_DB_PREFIX.$paymenttable." as pa,"; + $sql .= " ".MAIN_DB_PREFIX."societe as s,"; + $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; + $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; + $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - $sql .= " AND pf.".$fk_facture2." = f.rowid"; - $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { - $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; - $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { - $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; - $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; - } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; - $sql .= " AND (d.product_type = 0"; // Limit to products - $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; - $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; - } - - if (!$sql) return -1; - if ($sql == 'TODO') return -2; - if ($sql != 'TODO') - { - dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); - - $resql = $db->query($sql); - if ($resql) - { - $rate = -1; - $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - // Code to avoid warnings when array entry not defined - if (!isset($list[$assoc['rate']]['totalht'])) $list[$assoc['rate']]['totalht'] = 0; - if (!isset($list[$assoc['rate']]['vat'])) $list[$assoc['rate']]['vat'] = 0; + $sql .= " AND f.rowid = d.".$fk_facture; + $sql .= " AND s.rowid = f.fk_soc"; + $sql .= " AND pf.".$fk_facture2." = f.rowid"; + $sql .= " AND pa.rowid = pf.".$fk_payment; + if ($y && $m) + { + $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; + $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; + } + elseif ($y) + { + $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; + $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; + } + if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + $sql .= " AND (d.product_type = 1"; // Limit to services + $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service + if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; + } + + if (!$sql) + { + dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); + return -1; // -1 = Not accountancy module enabled + } + if ($sql == 'TODO') return -2; // -2 = Feature not yet available + if ($sql != 'TODO') + { + dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $rate = -1; + $oldrowid = ''; + while ($assoc = $db->fetch_array($resql)) + { + // Code to avoid warnings when array entry not defined + if (!isset($list[$assoc['rate']]['totalht'])) $list[$assoc['rate']]['totalht'] = 0; + if (!isset($list[$assoc['rate']]['vat'])) $list[$assoc['rate']]['vat'] = 0; if (!isset($list[$assoc['rate']]['localtax1'])) $list[$assoc['rate']]['localtax1'] = 0; - if (!isset($list[$assoc['rate']]['localtax2'])) $list[$assoc['rate']]['localtax2'] = 0; - - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { - $oldrowid = $assoc['rowid']; - $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; - $list[$assoc['rate']]['vat'] += $assoc['total_vat']; - $list[$assoc['rate']]['localtax1'] += $assoc['total_localtax1']; - $list[$assoc['rate']]['localtax2'] += $assoc['total_localtax2']; - } - $list[$assoc['rate']]['dtotal_ttc'][] = $assoc['total_ttc']; - $list[$assoc['rate']]['dtype'][] = $assoc['dtype']; - $list[$assoc['rate']]['datef'][] = $db->jdate($assoc['datef']); - $list[$assoc['rate']]['datep'][] = $db->jdate($assoc['datep']); - $list[$assoc['rate']]['company_name'][] = $assoc['company_name']; - $list[$assoc['rate']]['company_id'][] = $assoc['company_id']; - $list[$assoc['rate']]['ddate_start'][] = $db->jdate($assoc['date_start']); - $list[$assoc['rate']]['ddate_end'][] = $db->jdate($assoc['date_end']); - - $list[$assoc['rate']]['facid'][] = $assoc['facid']; - $list[$assoc['rate']]['facnum'][] = $assoc['facnum']; - $list[$assoc['rate']]['type'][] = $assoc['type']; - $list[$assoc['rate']]['ftotal_ttc'][] = $assoc['ftotal_ttc']; - $list[$assoc['rate']]['descr'][] = $assoc['descr']; - - $list[$assoc['rate']]['totalht_list'][] = $assoc['total_ht']; - $list[$assoc['rate']]['vat_list'][] = $assoc['total_vat']; - $list[$assoc['rate']]['localtax1_list'][] = $assoc['total_localtax1']; - $list[$assoc['rate']]['localtax2_list'][] = $assoc['total_localtax2']; - - $list[$assoc['rate']]['pid'][] = $assoc['pid']; - $list[$assoc['rate']]['pref'][] = $assoc['pref']; - $list[$assoc['rate']]['ptype'][] = $assoc['ptype']; - - $list[$assoc['rate']]['payment_id'][] = $assoc['payment_id']; - $list[$assoc['rate']]['payment_amount'][] = $assoc['payment_amount']; - - $rate = $assoc['rate']; - } - } else { - dol_print_error($db); - return -3; - } - } - - - // CAS DES SERVICES - - // Define sql request - $sql = ''; - if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) - { - // Count on invoice date - $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; - $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; - $sql .= " d.date_start as date_start, d.date_end as date_end,"; - $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; - $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; - $sql .= " 0 as payment_id, 0 as payment_amount"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; - $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; - $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { - $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; - $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { - $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; - $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; - } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; - $sql .= " AND (d.product_type = 1"; // Limit to services - $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; - $sql .= " ORDER BY d.rowid, d.".$fk_facture; - } else { - // Count on payments date - $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; - $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; - $sql .= " d.date_start as date_start, d.date_end as date_end,"; - $sql .= " f.".$invoicefieldref." as facnum, f.type, f.total_ttc as ftotal_ttc, f.datef, s.nom as company_name, s.rowid as company_id,"; - $sql .= " p.rowid as pid, p.ref as pref, p.fk_product_type as ptype,"; - $sql .= " pf.".$fk_payment." as payment_id, pf.amount as payment_amount,"; - $sql .= " pa.datep as datep"; - $sql .= " FROM ".MAIN_DB_PREFIX.$invoicetable." as f,"; - $sql .= " ".MAIN_DB_PREFIX.$paymentfacturetable." as pf,"; - $sql .= " ".MAIN_DB_PREFIX.$paymenttable." as pa,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s,"; - $sql .= " ".MAIN_DB_PREFIX.$invoicedettable." as d"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; - $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; - $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; - $sql .= " AND f.rowid = d.".$fk_facture; - $sql .= " AND s.rowid = f.fk_soc"; - $sql .= " AND pf.".$fk_facture2." = f.rowid"; - $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { - $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; - $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { - $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; - $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; - } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; - $sql .= " AND (d.product_type = 1"; // Limit to services - $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; - $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; - } - - if (!$sql) - { - dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); - return -1; // -1 = Not accountancy module enabled - } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { - dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $rate = -1; - $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - // Code to avoid warnings when array entry not defined - if (!isset($list[$assoc['rate']]['totalht'])) $list[$assoc['rate']]['totalht'] = 0; - if (!isset($list[$assoc['rate']]['vat'])) $list[$assoc['rate']]['vat'] = 0; - if (!isset($list[$assoc['rate']]['localtax1'])) $list[$assoc['rate']]['localtax1'] = 0; - if (!isset($list[$assoc['rate']]['localtax2'])) $list[$assoc['rate']]['localtax2'] = 0; - - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { - $oldrowid = $assoc['rowid']; - $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; - $list[$assoc['rate']]['vat'] += $assoc['total_vat']; - $list[$assoc['rate']]['localtax1'] += $assoc['total_localtax1']; - $list[$assoc['rate']]['localtax2'] += $assoc['total_localtax2']; - } - $list[$assoc['rate']]['dtotal_ttc'][] = $assoc['total_ttc']; - $list[$assoc['rate']]['dtype'][] = $assoc['dtype']; - $list[$assoc['rate']]['datef'][] = $db->jdate($assoc['datef']); - $list[$assoc['rate']]['datep'][] = $db->jdate($assoc['datep']); - $list[$assoc['rate']]['company_name'][] = $assoc['company_name']; - $list[$assoc['rate']]['company_id'][] = $assoc['company_id']; - $list[$assoc['rate']]['ddate_start'][] = $db->jdate($assoc['date_start']); - $list[$assoc['rate']]['ddate_end'][] = $db->jdate($assoc['date_end']); - - $list[$assoc['rate']]['facid'][] = $assoc['facid']; - $list[$assoc['rate']]['facnum'][] = $assoc['facnum']; - $list[$assoc['rate']]['type'][] = $assoc['type']; - $list[$assoc['rate']]['ftotal_ttc'][] = $assoc['ftotal_ttc']; - $list[$assoc['rate']]['descr'][] = $assoc['descr']; - - $list[$assoc['rate']]['totalht_list'][] = $assoc['total_ht']; - $list[$assoc['rate']]['vat_list'][] = $assoc['total_vat']; - $list[$assoc['rate']]['localtax1_list'][] = $assoc['total_localtax1']; - $list[$assoc['rate']]['localtax2_list'][] = $assoc['total_localtax2']; - - $list[$assoc['rate']]['pid'][] = $assoc['pid']; - $list[$assoc['rate']]['pref'][] = $assoc['pref']; - $list[$assoc['rate']]['ptype'][] = $assoc['ptype']; - - $list[$assoc['rate']]['payment_id'][] = $assoc['payment_id']; - $list[$assoc['rate']]['payment_amount'][] = $assoc['payment_amount']; - - $rate = $assoc['rate']; - } - } else { - dol_print_error($db); - return -3; - } - } - - - // CASE OF EXPENSE REPORT + if (!isset($list[$assoc['rate']]['localtax2'])) $list[$assoc['rate']]['localtax2'] = 0; + + if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid + { + $oldrowid = $assoc['rowid']; + $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; + $list[$assoc['rate']]['vat'] += $assoc['total_vat']; + $list[$assoc['rate']]['localtax1'] += $assoc['total_localtax1']; + $list[$assoc['rate']]['localtax2'] += $assoc['total_localtax2']; + } + $list[$assoc['rate']]['dtotal_ttc'][] = $assoc['total_ttc']; + $list[$assoc['rate']]['dtype'][] = $assoc['dtype']; + $list[$assoc['rate']]['datef'][] = $db->jdate($assoc['datef']); + $list[$assoc['rate']]['datep'][] = $db->jdate($assoc['datep']); + $list[$assoc['rate']]['company_name'][] = $assoc['company_name']; + $list[$assoc['rate']]['company_id'][] = $assoc['company_id']; + $list[$assoc['rate']]['ddate_start'][] = $db->jdate($assoc['date_start']); + $list[$assoc['rate']]['ddate_end'][] = $db->jdate($assoc['date_end']); + + $list[$assoc['rate']]['facid'][] = $assoc['facid']; + $list[$assoc['rate']]['facnum'][] = $assoc['facnum']; + $list[$assoc['rate']]['type'][] = $assoc['type']; + $list[$assoc['rate']]['ftotal_ttc'][] = $assoc['ftotal_ttc']; + $list[$assoc['rate']]['descr'][] = $assoc['descr']; + + $list[$assoc['rate']]['totalht_list'][] = $assoc['total_ht']; + $list[$assoc['rate']]['vat_list'][] = $assoc['total_vat']; + $list[$assoc['rate']]['localtax1_list'][] = $assoc['total_localtax1']; + $list[$assoc['rate']]['localtax2_list'][] = $assoc['total_localtax2']; + + $list[$assoc['rate']]['pid'][] = $assoc['pid']; + $list[$assoc['rate']]['pref'][] = $assoc['pref']; + $list[$assoc['rate']]['ptype'][] = $assoc['ptype']; + + $list[$assoc['rate']]['payment_id'][] = $assoc['payment_id']; + $list[$assoc['rate']]['payment_amount'][] = $assoc['payment_amount']; + + $rate = $assoc['rate']; + } + } + else + { + dol_print_error($db); + return -3; + } + } + + + // CASE OF EXPENSE REPORT if ($direction == 'buy') // buy only for expense reports { @@ -894,7 +924,8 @@ { $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) + } + elseif ($y) { $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; @@ -903,7 +934,7 @@ if ($date_start && $date_end) $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = -1"; $sql .= " OR e.date_debut is NOT null OR e.date_fin IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; $sql .= " ORDER BY e.rowid"; if (!$sql) @@ -932,7 +963,7 @@ { $oldrowid = $assoc['rowid']; $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; - $list[$assoc['rate']]['vat'] += $assoc['total_vat']; + $list[$assoc['rate']]['vat'] += $assoc['total_vat']; $list[$assoc['rate']]['localtax1'] += $assoc['total_localtax1']; $list[$assoc['rate']]['localtax2'] += $assoc['total_localtax2']; } @@ -966,7 +997,9 @@ $rate = $assoc['rate']; } - } else { + } + else + { dol_print_error($db); return -3; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_ticket.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_ticket.lib.php @@ -1,7 +1,7 @@ * Copyright (C) 2016 Christophe Battarel - * Copyright (C) 2019-2020 Frédéric France + * Copyright (C) 2019 Frédéric France * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -30,41 +30,39 @@ */ function ticketAdminPrepareHead() { - global $langs, $conf; - - $langs->load("ticket"); - - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/admin/ticket.php'; - $head[$h][1] = $langs->trans("TicketSettings"); - $head[$h][2] = 'settings'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/admin/ticket_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsTicket"); - $head[$h][2] = 'attributes'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/admin/ticket_public.php'; - $head[$h][1] = $langs->trans("PublicInterface"); - $head[$h][2] = 'public'; - $h++; - - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - //$this->tabs = array( - // 'entity:+tabname:Title:@ticket:/ticket/mypage.php?id=__ID__' - //); // to add new tab - //$this->tabs = array( - // 'entity:-tabname:Title:@ticket:/ticket/mypage.php?id=__ID__' - //); // to remove a tab - complete_head_from_modules($conf, $langs, null, $head, $h, 'ticketadmin'); - - complete_head_from_modules($conf, $langs, null, $head, $h, 'ticketadmin', 'remove'); - - return $head; + global $langs, $conf; + + $langs->load("ticket"); + + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/admin/ticket.php'; + $head[$h][1] = $langs->trans("TicketSettings"); + $head[$h][2] = 'settings'; + $h++; + + $head[$h][0] = DOL_URL_ROOT.'/admin/ticket_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsTicket"); + $head[$h][2] = 'attributes'; + $h++; + + $head[$h][0] = DOL_URL_ROOT.'/admin/ticket_public.php'; + $head[$h][1] = $langs->trans("PublicInterface"); + $head[$h][2] = 'public'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@ticket:/ticket/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@ticket:/ticket/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'ticketadmin'); + + return $head; } /** @@ -75,66 +73,71 @@ */ function ticket_prepare_head($object) { - global $db, $langs, $conf, $user; - - $h = 0; - $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/ticket/card.php?action=view&track_id='.$object->track_id; - $head[$h][1] = $langs->trans("Ticket"); - $head[$h][2] = 'tabTicket'; - $h++; - - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && empty($user->socid)) { - $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); - $head[$h][0] = DOL_URL_ROOT.'/ticket/contact.php?track_id='.$object->track_id; - $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; - $head[$h][2] = 'contact'; - $h++; - } - - complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticket'); - - // Attached files - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $upload_dir = $conf->ticket->dir_output."/".$object->ref; - $nbFiles = count(dol_dir_list($upload_dir, 'files')); - $head[$h][0] = dol_buildpath('/ticket/document.php', 1).'?id='.$object->id; - $head[$h][1] = $langs->trans("Documents"); - if ($nbFiles > 0) { - $head[$h][1] .= ''.$nbFiles.''; - } - - $head[$h][2] = 'tabTicketDocument'; - $h++; - - - // History + global $db, $langs, $conf, $user; + + $h = 0; + $head = array(); + $head[$h][0] = DOL_URL_ROOT.'/ticket/card.php?action=view&track_id='.$object->track_id; + $head[$h][1] = $langs->trans("Ticket"); + $head[$h][2] = 'tabTicket'; + $h++; + + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && empty($user->socid)) + { + $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT.'/ticket/contact.php?track_id='.$object->track_id; + $head[$h][1] = $langs->trans('ContactsAddresses'); + if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + $head[$h][2] = 'contact'; + $h++; + } + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticket'); + + // Attached files + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + $upload_dir = $conf->ticket->dir_output."/".$object->ref; + $nbFiles = count(dol_dir_list($upload_dir, 'files')); + $head[$h][0] = dol_buildpath('/ticket/document.php', 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Documents"); + if ($nbFiles > 0) { + $head[$h][1] .= ''.$nbFiles.''; + } + + $head[$h][2] = 'tabTicketDocument'; + $h++; + + + // History $ticketViewType = "messaging"; if (empty($_SESSION['ticket-view-type'])) { $_SESSION['ticket-view-type'] = $ticketViewType; - } else { + } + else { $ticketViewType = $_SESSION['ticket-view-type']; } if ($ticketViewType == "messaging") { $head[$h][0] = DOL_URL_ROOT.'/ticket/messaging.php?track_id='.$object->track_id; - } else { + } + else { // $ticketViewType == "list" $head[$h][0] = DOL_URL_ROOT.'/ticket/agenda.php?track_id='.$object->track_id; } - $head[$h][1] = $langs->trans('Events'); - 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"); - } - $head[$h][2] = 'tabTicketLogs'; - $h++; - - complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticket', 'remove'); - - return $head; + $head[$h][1] = $langs->trans('Events'); + 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"); + } + $head[$h][2] = 'tabTicketLogs'; + $h++; + + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticket', 'remove'); + + + return $head; } /** @@ -156,14 +159,20 @@ } $out = ''; - if (empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) { + if (empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) + { $out .= ''.$langs->trans("PublicInterfaceNotEnabled").''; - } else { + } + else + { $out .= img_picto('', 'object_globe.png').' '.$langs->trans("TicketPublicAccess").':
'; - if ($url) { + if ($url) + { $out .= ''; $out .= ajax_autoselect("directpubliclink", 0); - } else { + } + else + { $out .= ''.$langs->trans("TicketNotCreatedFromPublicInterface").''; } } @@ -179,13 +188,13 @@ */ function generate_random_id($car = 16) { - $string = ""; - $chaine = "abcdefghijklmnopqrstuvwxyz123456789"; - srand((double) microtime() * 1000000); - for ($i = 0; $i < $car; $i++) { - $string .= $chaine[rand() % strlen($chaine)]; - } - return $string; + $string = ""; + $chaine = "abcdefghijklmnopqrstuvwxyz123456789"; + srand((double) microtime() * 1000000); + for ($i = 0; $i < $car; $i++) { + $string .= $chaine[rand() % strlen($chaine)]; + } + return $string; } /** @@ -201,52 +210,58 @@ */ function llxHeaderTicket($title, $head = "", $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '') { - global $user, $conf, $langs, $mysoc; - - top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, 1); // Show html headers - - print ''; - print '
'; - - print '
'; + global $user, $conf, $langs, $mysoc; + + top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); // Show html headers + + print ''; + + // Define urllogo + $width = 0; + if (!empty($conf->global->TICKET_SHOW_COMPANY_LOGO) || !empty($conf->global->TICKET_PUBLIC_INTERFACE_TOPIC)) { + // Print logo + if (!empty($conf->global->TICKET_SHOW_COMPANY_LOGO)) + { + $urllogo = DOL_URL_ROOT.'/theme/common/login_logo.png'; + + if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) { + $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$mysoc->logo_small); + $width = 150; + } elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) { + $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$mysoc->logo); + $width = 150; + } elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) { + $urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg'; + } + } + } + + print '
'; + // Output html code for logo + if ($urllogo || !empty($conf->global->TICKET_PUBLIC_INTERFACE_TOPIC)) + { + print '
'; + print '
'; + if ($urllogo) { + print ''; + print ''; + print ''; + } + if (!empty($conf->global->TICKET_PUBLIC_INTERFACE_TOPIC)) { + print '
'.($conf->global->TICKET_PUBLIC_INTERFACE_TOPIC ? $conf->global->TICKET_PUBLIC_INTERFACE_TOPIC : $langs->trans("TicketSystem")).''; + } + print '
'; + if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { + print ''; + } + print '
'; + } + + print '
'; + + print '
'; } @@ -270,290 +285,278 @@ */ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC') { - global $user, $conf; - global $form; - - global $param, $massactionbutton; - - dol_include_once('/comm/action/class/actioncomm.class.php'); - - // Check parameters - if (!is_object($filterobj) && !is_object($objcon)) dol_print_error('', 'BadParameter'); - - $histo = array(); - $numaction = 0; - $now = dol_now(); - - $sortfield_list = explode(',', $sortfield); - $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent'); - $sortfield_new_list = array(); - foreach ($sortfield_list as $sortfield_value) { - $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)]; - } - $sortfield_new = implode(',', $sortfield_new_list); - - if (!empty($conf->agenda->enabled)) { - // Search histo on actioncomm - if (is_object($objcon) && $objcon->id > 0) { - $sql = "SELECT DISTINCT a.id, a.label as label,"; - } else { - $sql = "SELECT a.id, a.label as label,"; - } - $sql .= " a.datep as dp,"; - $sql .= " a.note as message,"; - $sql .= " a.datep2 as dp2,"; - $sql .= " a.percent as percent, 'action' as type,"; - $sql .= " a.fk_element, a.elementtype,"; - $sql .= " a.fk_contact,"; - $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,"; - $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; - if (is_object($filterobj) && get_class($filterobj) == 'Societe') { - $sql .= ", sp.lastname, sp.firstname"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { - $sql .= ", m.lastname, m.firstname"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { - $sql .= ", o.ref"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { - $sql .= ", o.ref"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { - $sql .= ", o.ref"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') { - $sql .= ", o.ref"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') { - $sql .= ", o.ref"; - } - $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id"; - - $force_filter_contact = false; - if (is_object($objcon) && $objcon->id > 0) { - $force_filter_contact = true; - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm"; - $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".$objcon->id; - } - - if (is_object($filterobj) && get_class($filterobj) == 'Societe') { - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er"; - $sql .= " ON er.resource_type = 'dolresource'"; - $sql .= " AND er.element_id = a.id"; - $sql .= " AND er.resource_id = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { - $sql .= ", ".MAIN_DB_PREFIX."adherent as m"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { - $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { - $sql .= ", ".MAIN_DB_PREFIX."product as o"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { - $sql .= ", ".MAIN_DB_PREFIX."ticket as o"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') { - $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') { - $sql .= ", ".MAIN_DB_PREFIX."contrat as o"; - } - - $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; - if ($force_filter_contact === false) { - if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) { - $sql .= " AND a.fk_soc = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) { - $sql .= " AND a.fk_project = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { - $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') { - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') { - $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } - } - - // Condition on actioncode - if (!empty($actioncode)) { - if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { - if ($actioncode == 'AC_NON_AUTO') { - $sql .= " AND c.type != 'systemauto'"; - } elseif ($actioncode == 'AC_ALL_AUTO') { - $sql .= " AND c.type = 'systemauto'"; - } else { - if ($actioncode == 'AC_OTH') { - $sql .= " AND c.type != 'systemauto'"; - } elseif ($actioncode == 'AC_OTH_AUTO') { - $sql .= " AND c.type = 'systemauto'"; - } - } - } else { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; - else $sql .= " AND c.code = '".$db->escape($actioncode)."'"; - } - } - if ($donetodo == 'todo') $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; - elseif ($donetodo == 'done') $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; - if (is_array($filters) && $filters['search_agenda_label']) $sql .= natural_search('a.label', $filters['search_agenda_label']); - } - - // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing. - if (!empty($conf->mailing->enabled) && !empty($objcon->email) - && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) - { - $langs->load("mails"); - - $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type"; - $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id"; - $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto"; - $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action - if (is_object($filterobj) && get_class($filterobj) == 'Societe') { - $sql2 .= ", '' as lastname, '' as firstname"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { - $sql2 .= ", '' as lastname, '' as firstname"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { - $sql2 .= ", '' as ref"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { - $sql2 .= ", '' as ref"; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { - $sql2 .= ", '' as ref"; - } - $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u"; - $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email. - $sql2 .= " AND mc.statut = 1"; - $sql2 .= " AND u.rowid = m.fk_user_valid"; - $sql2 .= " AND mc.fk_mailing=m.rowid"; - } - - if (!empty($sql) && !empty($sql2)) { - $sql = $sql." UNION ".$sql2; - } elseif (empty($sql) && !empty($sql2)) { - $sql = $sql2; - } - - // TODO Add limit in nb of results - if ($sql) { // May not be defined if module Agenda is not enabled and mailing module disabled too - $sql .= $db->order($sortfield_new, $sortorder); - - dol_syslog("company.lib::show_actions_done", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) { - $i = 0; - $num = $db->num_rows($resql); - - while ($i < $num) { - $obj = $db->fetch_object($resql); - - if ($obj->type == 'action') { - $contactaction = new ActionComm($db); - $contactaction->id = $obj->id; - $result = $contactaction->fetchResources(); - if ($result < 0) { - dol_print_error($db); - setEventMessage("company.lib::show_actions_done Error fetch ressource", 'errors'); - } - - //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; - //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; - $tododone = ''; - if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) $tododone = 'todo'; - - $histo[$numaction] = array( - 'type'=>$obj->type, - 'tododone'=>$tododone, - 'id'=>$obj->id, - 'datestart'=>$db->jdate($obj->dp), - 'dateend'=>$db->jdate($obj->dp2), - 'note'=>$obj->label, - 'message'=>$obj->message, - 'percent'=>$obj->percent, - - 'userid'=>$obj->user_id, - 'login'=>$obj->user_login, - 'userfirstname'=>$obj->user_firstname, - 'userlastname'=>$obj->user_lastname, - 'userphoto'=>$obj->user_photo, - - 'contact_id'=>$obj->fk_contact, - 'socpeopleassigned' => $contactaction->socpeopleassigned, - 'lastname'=>$obj->lastname, - 'firstname'=>$obj->firstname, - 'fk_element'=>$obj->fk_element, - 'elementtype'=>$obj->elementtype, - // Type of event - 'acode'=>$obj->acode, - 'alabel'=>$obj->alabel, - 'libelle'=>$obj->alabel, // deprecated - 'apicto'=>$obj->apicto - ); - } else { - $histo[$numaction] = array( - 'type'=>$obj->type, - 'tododone'=>'done', - 'id'=>$obj->id, - 'datestart'=>$db->jdate($obj->dp), - 'dateend'=>$db->jdate($obj->dp2), - 'note'=>$obj->label, - 'message'=>$obj->message, - 'percent'=>$obj->percent, - 'acode'=>$obj->acode, - - 'userid'=>$obj->user_id, - 'login'=>$obj->user_login, - 'userfirstname'=>$obj->user_firstname, - 'userlastname'=>$obj->user_lastname, - 'userphoto'=>$obj->user_photo - ); - } - - $numaction++; - $i++; - } - } else { - dol_print_error($db); - } - } - - // Set $out to sow events - $out = ''; - - if (empty($conf->agenda->enabled)) { - $langs->loadLangs(array("admin", "errors")); - $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning'); - } - - if (!empty($conf->agenda->enabled) || (!empty($conf->mailing->enabled) && !empty($objcon->email))) { - $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60; - - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - - $formactions = new FormActions($db); - - $actionstatic = new ActionComm($db); - $userstatic = new User($db); - $contactstatic = new Contact($db); - $userGetNomUrlCache = array(); + global $user, $conf; + global $form; + + global $param, $massactionbutton; + + dol_include_once('/comm/action/class/actioncomm.class.php'); + + // Check parameters + if (!is_object($filterobj) && !is_object($objcon)) dol_print_error('', 'BadParameter'); + + $out = ''; + $histo = array(); + $numaction = 0; + $now = dol_now('tzuser'); + + // Open DSI -- Fix order by -- Begin + $sortfield_list = explode(',', $sortfield); + $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent'); + $sortfield_new_list = array(); + foreach ($sortfield_list as $sortfield_value) { + $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)]; + } + $sortfield_new = implode(',', $sortfield_new_list); + + if (!empty($conf->agenda->enabled)) + { + // Recherche histo sur actioncomm + if (is_object($objcon) && $objcon->id > 0) { + $sql = "SELECT DISTINCT a.id, a.label as label,"; + } + else + { + $sql = "SELECT a.id, a.label as label,"; + } + $sql .= " a.datep as dp,"; + $sql .= " a.note as message,"; + $sql .= " a.datep2 as dp2,"; + $sql .= " a.percent as percent, 'action' as type,"; + $sql .= " a.fk_element, a.elementtype,"; + $sql .= " a.fk_contact,"; + $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,"; + $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; + if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql .= ", sp.lastname, sp.firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", m.lastname, m.firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", o.ref"; + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id"; + + $force_filter_contact = false; + if (is_object($objcon) && $objcon->id > 0) { + $force_filter_contact = true; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm"; + $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".$objcon->id; + } + + if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er"; + $sql .= " ON er.resource_type = 'dolresource'"; + $sql .= " AND er.element_id = a.id"; + $sql .= " AND er.resource_id = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", ".MAIN_DB_PREFIX."adherent as m"; + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", ".MAIN_DB_PREFIX."product as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", ".MAIN_DB_PREFIX."ticket as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", ".MAIN_DB_PREFIX."contrat as o"; + + $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; + if ($force_filter_contact === false) { + if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) $sql .= " AND a.fk_soc = ".$filterobj->id; + elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) $sql .= " AND a.fk_project = ".$filterobj->id; + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') + { + $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') + { + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + } + } + + // Condition on actioncode + if (!empty($actioncode)) + { + if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) + { + if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; + elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; + else + { + if ($actioncode == 'AC_OTH') $sql .= " AND c.type != 'systemauto'"; + elseif ($actioncode == 'AC_OTH_AUTO') $sql .= " AND c.type = 'systemauto'"; + } + } + else + { + if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; + elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; + else $sql .= " AND c.code = '".$db->escape($actioncode)."'"; + } + } + if ($donetodo == 'todo') $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; + elseif ($donetodo == 'done') $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; + if (is_array($filters) && $filters['search_agenda_label']) $sql .= natural_search('a.label', $filters['search_agenda_label']); + } + + // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing. + if (!empty($conf->mailing->enabled) && !empty($objcon->email) + && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) + { + $langs->load("mails"); + + $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type"; + $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id"; + $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto"; + $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action + if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql2 .= ", '' as lastname, '' as firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql2 .= ", '' as lastname, '' as firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql2 .= ", '' as ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql2 .= ", '' as ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql2 .= ", '' as ref"; + $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u"; + $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email. + $sql2 .= " AND mc.statut = 1"; + $sql2 .= " AND u.rowid = m.fk_user_valid"; + $sql2 .= " AND mc.fk_mailing=m.rowid"; + } + + if (!empty($sql) && !empty($sql2)) { + $sql = $sql." UNION ".$sql2; + } elseif (empty($sql) && !empty($sql2)) { + $sql = $sql2; + } + + //TODO Add limit in nb of results + $sql .= $db->order($sortfield_new, $sortorder); + dol_syslog("company.lib::show_actions_done", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $i = 0; + $num = $db->num_rows($resql); + + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + if ($obj->type == 'action') { + $contactaction = new ActionComm($db); + $contactaction->id = $obj->id; + $result = $contactaction->fetchResources(); + if ($result < 0) { + dol_print_error($db); + setEventMessage("company.lib::show_actions_done Error fetch ressource", 'errors'); + } + + //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; + //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; + $tododone = ''; + if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) $tododone = 'todo'; + + $histo[$numaction] = array( + 'type'=>$obj->type, + 'tododone'=>$tododone, + 'id'=>$obj->id, + 'datestart'=>$db->jdate($obj->dp), + 'dateend'=>$db->jdate($obj->dp2), + 'note'=>$obj->label, + 'message'=>$obj->message, + 'percent'=>$obj->percent, + + 'userid'=>$obj->user_id, + 'login'=>$obj->user_login, + 'userfirstname'=>$obj->user_firstname, + 'userlastname'=>$obj->user_lastname, + 'userphoto'=>$obj->user_photo, + + 'contact_id'=>$obj->fk_contact, + 'socpeopleassigned' => $contactaction->socpeopleassigned, + 'lastname'=>$obj->lastname, + 'firstname'=>$obj->firstname, + 'fk_element'=>$obj->fk_element, + 'elementtype'=>$obj->elementtype, + // Type of event + 'acode'=>$obj->acode, + 'alabel'=>$obj->alabel, + 'libelle'=>$obj->alabel, // deprecated + 'apicto'=>$obj->apicto + ); + } else { + $histo[$numaction] = array( + 'type'=>$obj->type, + 'tododone'=>'done', + 'id'=>$obj->id, + 'datestart'=>$db->jdate($obj->dp), + 'dateend'=>$db->jdate($obj->dp2), + 'note'=>$obj->label, + 'message'=>$obj->message, + 'percent'=>$obj->percent, + 'acode'=>$obj->acode, + + 'userid'=>$obj->user_id, + 'login'=>$obj->user_login, + 'userfirstname'=>$obj->user_firstname, + 'userlastname'=>$obj->user_lastname, + 'userphoto'=>$obj->user_photo + ); + } + + $numaction++; + $i++; + } + } + else + { + dol_print_error($db); + } + + if (!empty($conf->agenda->enabled) || (!empty($conf->mailing->enabled) && !empty($objcon->email))) + { + $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60; + + require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; + + $formactions = new FormActions($db); + + $actionstatic = new ActionComm($db); + $userstatic = new User($db); + $contactstatic = new Contact($db); + $userGetNomUrlCache = array(); $out .= '
'; $out .= ''; - $out .= ''; - if ($objcon && get_class($objcon) == 'Contact' && - (is_null($filterobj) || get_class($filterobj) == 'Societe')) { + (is_null($filterobj) || get_class($filterobj) == 'Societe')) + { $out .= ''; - } else { + } + else + { $out .= ''; } if ($filterobj && get_class($filterobj) == 'Societe') $out .= ''; @@ -569,15 +572,17 @@ $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, '')."\n"; //$out.=''; - $out .= ''.$langs->trans("Search").' : '; - if ($donetodo) { + $out .= ''.$langs->trans("Search").' : '; + if ($donetodo) + { $out .= ''; } $out .= ''.$langs->trans("Type").' '; - $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1, 'minwidth200imp'); + $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1); $out .= ''; $out .= ''; - $out .= ''; + $out .= $langs->trans("Label").' '; + $out .= ''; $out .= ''; $out .= ''; @@ -589,61 +594,115 @@ $out .= ''; - $out .= ''; + $out .= ''; $out .= '
'; - $out .= "\n"; - - $out .= '\n"; + } + + + if ($noprint) return $out; + else print $out; } -/** - * Get timeline icon - * @param ActionComm $actionstatic actioncomm - * @param array $histo histo - * @param int $key key - * @return string - */ -function getTicketTimelineIcon($actionstatic, &$histo, $key) -{ - global $conf, $langs; - $out = ''."\n"; - $iconClass = 'fa fa-comments'; - $img_picto = ''; - $colorClass = ''; - $pictoTitle = ''; - - if ($histo[$key]['percent'] == -1) { - $colorClass = 'timeline-icon-not-applicble'; - $pictoTitle = $langs->trans('StatusNotApplicable'); - } elseif ($histo[$key]['percent'] == 0) { - $colorClass = 'timeline-icon-todo'; - $pictoTitle = $langs->trans('StatusActionToDo').' (0%)'; - } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) { - $colorClass = 'timeline-icon-in-progress'; - $pictoTitle = $langs->trans('StatusActionInProcess').' ('.$histo[$key]['percent'].'%)'; - } elseif ($histo[$key]['percent'] >= 100) { - $colorClass = 'timeline-icon-done'; - $pictoTitle = $langs->trans('StatusActionDone').' (100%)'; - } - - if ($actionstatic->code == 'AC_TICKET_CREATE') { - $iconClass = 'fa fa-ticket'; - } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') { - $iconClass = 'fa fa-pencilxxx'; - } elseif ($actionstatic->code == 'TICKET_MSG') { - $iconClass = 'fa fa-comments'; - } elseif ($actionstatic->code == 'TICKET_MSG_PRIVATE') { - $iconClass = 'fa fa-mask'; - } elseif (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { - if ($actionstatic->type_picto) { - $img_picto = img_picto('', $actionstatic->type_picto); - } else { - if ($actionstatic->type_code == 'AC_RDV') { - $iconClass = 'fa fa-handshake'; - } elseif ($actionstatic->type_code == 'AC_TEL') { - $iconClass = 'fa fa-phone'; - } elseif ($actionstatic->type_code == 'AC_FAX') { - $iconClass = 'fa fa-fax'; - } elseif ($actionstatic->type_code == 'AC_EMAIL') { - $iconClass = 'fa fa-envelope'; - } elseif ($actionstatic->type_code == 'AC_INT') { - $iconClass = 'fa fa-shipping-fast'; - } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') { - $iconClass = 'fa fa-robot'; - } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) { - $iconClass = 'fa fa-robot'; - } - } - } - - $out .= ''.$img_picto.''."\n"; - return $out; -} /** * getTicketActionCommEcmList --- /tmp/dsg/dolibarr/htdocs/core/lib/github_treeview.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_treeview.lib.php @@ -49,7 +49,7 @@ //print 'x'.$key; foreach ($fulltree as $key2 => $val2) { - //print "x".$pos." ".$key2." ".$found." ".$fulltree[$key2]['level']; + //print "x".$pos." ".$key2." ".$found." ".$fulltree[$key2]['level']; if ($found == 1) // We are after the entry to show { if ($fulltree[$key2]['level'] > $pos) @@ -75,14 +75,16 @@ if (!$silent) { - if ($atleastoneofthislevelafter) - { - if ($fulltree[$key]['level'] == $pos) print img_picto_common('', 'treemenu/branch.gif'); - else print img_picto_common('', 'treemenu/line.gif'); - } else { - if ($fulltree[$key]['level'] == $pos) print img_picto_common('', 'treemenu/branchbottom.gif'); - else print img_picto_common('', 'treemenu/linebottom.gif'); - } + if ($atleastoneofthislevelafter) + { + if ($fulltree[$key]['level'] == $pos) print img_picto_common('', 'treemenu/branch.gif'); + else print img_picto_common('', 'treemenu/line.gif'); + } + else + { + if ($fulltree[$key]['level'] == $pos) print img_picto_common('', 'treemenu/branchbottom.gif'); + else print img_picto_common('', 'treemenu/linebottom.gif'); + } } $pos++; } @@ -103,22 +105,21 @@ * $arrayofcss=array('/includes/jquery/plugins/jquerytreeview/jquery.treeview.css'); * TODO Replace with jstree plugin instead of treeview plugin. * - * @param array $tab Array of all elements - * @param array $pere Array with parent ids ('rowid'=>,'mainmenu'=>,'leftmenu'=>,'fk_mainmenu=>,'fk_leftmenu=>) - * @param int $rang Level of element - * @param string $iddivjstree Id to use for parent ul element + * @param array $tab Array of all elements + * @param array $pere Array with parent ids ('rowid'=>,'mainmenu'=>,'leftmenu'=>,'fk_mainmenu=>,'fk_leftmenu=>) + * @param int $rang Level of element + * @param string $iddivjstree Id to use for parent ul element * @param int $donoresetalreadyloaded Do not reset global array $donoresetalreadyloaded used to avoid to go down on an aleady processed record - * @param int $showfk 1=show fk_links to parent into label (used by menu editor only) - * @param string $moreparam Add more param on url of elements + * @param int $showfk 1=show fk_links to parent into label (used by menu editor only) * @return void */ -function tree_recur($tab, $pere, $rang, $iddivjstree = 'iddivjstree', $donoresetalreadyloaded = 0, $showfk = 0, $moreparam = '') +function tree_recur($tab, $pere, $rang, $iddivjstree = 'iddivjstree', $donoresetalreadyloaded = 0, $showfk = 0) { - global $tree_recur_alreadyadded, $menu_handler_to_search; - - if ($rang == 0 && empty($donoresetalreadyloaded)) $tree_recur_alreadyadded = array(); - - if ($rang == 0) + global $tree_recur_alreadyadded, $menu_handler_to_search; + + if ($rang == 0 && empty($donoresetalreadyloaded)) $tree_recur_alreadyadded = array(); + + if ($rang == 0) { // Test also done with jstree and dynatree (not able to have inside label) print ''."\n"; - } elseif ($type == 'organization') + } + elseif ($type == 'organization') { $companyname = $mysoc->name; $url = $mysoc->url; @@ -592,13 +602,14 @@ $ret .= ",\n"; $ret .= '"sameAs": ['; $i = 0; - foreach ($mysoc->socialnetworks as $key => $value) { + foreach($mysoc->socialnetworks as $key => $value) { if ($key == 'linkedin') { - $ret .= '"https://www.'.$key.'.com/company/'.dol_escape_json($value).'"'; + $ret.= '"https://www.'.$key.'.com/company/'.dol_escape_json($value).'"'; } elseif ($key == 'youtube') { - $ret .= '"https://www.'.$key.'.com/user/'.dol_escape_json($value).'"'; - } else { - $ret .= '"https://www.'.$key.'.com/'.dol_escape_json($value).'"'; + $ret.= '"https://www.'.$key.'.com/user/'.dol_escape_json($value).'"'; + } + else { + $ret.= '"https://www.'.$key.'.com/'.dol_escape_json($value).'"'; } $i++; if ($i < count($mysoc->socialnetworks)) $ret .= ', '; @@ -607,7 +618,8 @@ } $ret .= '}'."\n"; $ret .= ''."\n"; - } elseif ($type == 'blogpost') + } + elseif ($type == 'blogpost') { if (!empty($websitepage->author_alias)) { @@ -623,7 +635,7 @@ $pageurl = str_replace('__WEBSITE_KEY__', $website->ref, $pageurl); $title = str_replace('__WEBSITE_KEY__', $website->ref, $title); - $image = '/medias/'.str_replace('__WEBSITE_KEY__', $website->ref, $image); + $image = 'medias/'.str_replace('__WEBSITE_KEY__', $website->ref, $image); $companyname = str_replace('__WEBSITE_KEY__', $website->ref, $companyname); $description = str_replace('__WEBSITE_KEY__', $website->ref, $description); @@ -659,8 +671,8 @@ $ret .= '"keywords": ['; $i = 0; $arrayofkeywords = explode(',', $websitepage->keywords); - foreach ($arrayofkeywords as $keyword) { - $ret .= '"'.dol_escape_json($keyword).'"'; + foreach($arrayofkeywords as $keyword) { + $ret.= '"'.dol_escape_json($keyword).'"'; $i++; if ($i < count($arrayofkeywords)) $ret .= ', '; } @@ -670,7 +682,8 @@ $ret .= "\n".'}'."\n"; $ret .= ''."\n"; } - } elseif ($type == 'product') + } + elseif ($type == 'product') { $ret = ''."\n"; $ret .= ''."\n"; - } elseif ($type == 'qa') - { - $ret = ''."\n"; - $ret .= ''."\n"; } return $ret; } @@ -763,8 +749,7 @@ // Reddit $out .= ''."\n"; // Facebook @@ -808,11 +793,9 @@ * @param string $sortfield Sort Fields * @param string $sortorder Sort order ('DESC' or 'ASC') * @param string $langcode Language code ('' or 'en', 'fr', 'es', ...) - * @param array $otherfilters Other filters - * @param int $status 0 or 1, or -1 for both * @return string HTML content */ -function getPagesFromSearchCriterias($type, $algo, $searchstring, $max = 25, $sortfield = 'date_creation', $sortorder = 'DESC', $langcode = '', $otherfilters = 'null', $status = 1) +function getPagesFromSearchCriterias($type, $algo, $searchstring, $max = 25, $sortfield = 'date_creation', $sortorder = 'DESC', $langcode = '') { global $conf, $db, $hookmanager, $langs, $mysoc, $user, $website, $websitepage, $weblangs; // Very important. Required to have var available when running inluded containers. @@ -821,26 +804,30 @@ if (!is_object($weblangs)) $weblangs = $langs; - if (empty($searchstring) && empty($type) && empty($langcode) && empty($otherfilters)) + if (empty($searchstring)) { $error++; $arrayresult['code'] = 'KO'; $arrayresult['message'] = $weblangs->trans("EmptySearchString"); - } elseif ($searchstring && dol_strlen($searchstring) < 2) { + } + elseif (dol_strlen($searchstring) < 2) + { $weblangs->load("errors"); $error++; $arrayresult['code'] = 'KO'; $arrayresult['message'] = $weblangs->trans("ErrorSearchCriteriaTooSmall"); - } else { + } + else + { $tmparrayoftype = explode(',', $type); - /*foreach ($tmparrayoftype as $tmptype) { + foreach ($tmparrayoftype as $tmptype) { if (!in_array($tmptype, array('', 'page', 'blogpost'))) { $error++; $arrayresult['code'] = 'KO'; $arrayresult['message'] = 'Bad value for parameter type'; break; } - }*/ + } } $searchdone = 0; @@ -848,40 +835,31 @@ if (!$error && (empty($max) || ($found < $max)) && (preg_match('/meta/', $algo) || preg_match('/content/', $algo))) { - $sql = 'SELECT wp.rowid FROM '.MAIN_DB_PREFIX.'website_page as wp'; - if (is_array($otherfilters) && !empty($otherfilters['category'])) { - $sql .= ', '.MAIN_DB_PREFIX.'categorie_website_page as cwp'; - } - $sql .= " WHERE wp.fk_website = ".$website->id; - if ($status >= 0) { - $sql .= " AND wp.status = ".$status; - } + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'website_page'; + $sql .= " WHERE fk_website = ".$website->id; if ($langcode) { - $sql .= " AND wp.lang ='".$db->escape($langcode)."'"; + $sql .= " AND lang ='".$db->escape($langcode)."'"; } if ($type) { $tmparrayoftype = explode(',', $type); $typestring = ''; foreach ($tmparrayoftype as $tmptype) { - $typestring .= ($typestring ? ", " : "")."'".$db->escape(trim($tmptype))."'"; - } - $sql .= " AND wp.type_container IN (".$typestring.")"; + $typestring .= ($typestring ? ", " : "")."'".trim($tmptype)."'"; + } + $sql .= " AND type_container IN (".$typestring.")"; } $sql .= " AND ("; $searchalgo = ''; if (preg_match('/meta/', $algo)) { - $searchalgo .= ($searchalgo ? ' OR ' : '')."wp.title LIKE '%".$db->escape($searchstring)."%' OR wp.description LIKE '%".$db->escape($searchstring)."%'"; - $searchalgo .= ($searchalgo ? ' OR ' : '')."wp.keywords LIKE '".$db->escape($searchstring).",%' OR wp.keywords LIKE '% ".$db->escape($searchstring)."%'"; // TODO Use a better way to scan keywords + $searchalgo .= ($searchalgo ? ' OR ' : '')."title LIKE '%".$db->escape($searchstring)."%' OR description LIKE '%".$db->escape($searchstring)."%'"; + $searchalgo .= ($searchalgo ? ' OR ' : '')."keywords LIKE '".$db->escape($searchstring).",%' OR keywords LIKE '% ".$db->escape($searchstring)."%'"; // TODO Use a better way to scan keywords } if (preg_match('/content/', $algo)) { - $searchalgo .= ($searchalgo ? ' OR ' : '')."wp.content LIKE '%".$db->escape($searchstring)."%'"; + $searchalgo .= ($searchalgo ? ' OR ' : '')."content LIKE '%".$db->escape($searchstring)."%'"; } $sql .= $searchalgo; - if (is_array($otherfilters) && !empty($otherfilters['category'])) { - $sql .= ' AND cwp.fk_website_page = wp.rowid AND cwp.fk_categorie = '.((int) $otherfilters['category']); - } $sql .= ")"; $sql .= $db->order($sortfield, $sortorder); $sql .= $db->plimit($max); @@ -901,7 +879,9 @@ } $i++; } - } else { + } + else + { $error++; $arrayresult['code'] = $db->lasterrno(); $arrayresult['message'] = $db->lasterror(); @@ -960,7 +940,9 @@ $arrayresult['code'] = 'KO'; $arrayresult['message'] = $weblangs->trans("NoRecordFound"); } - } else { + } + else + { $error++; $arrayresult['code'] = 'KO'; $arrayresult['message'] = 'No supported algorithm found'; @@ -1009,7 +991,9 @@ { $urltograbdirrootwithoutslash = getRootURLFromURL($urltograb); $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot - } else { + } + else + { $urltograbbis = $urltograb.'/'.$regs[2][$key]; // We use dir of grabbed file } @@ -1045,12 +1029,15 @@ $error++; setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors'); $action = 'create'; - } elseif ($tmpgeturl['http_code'] != '200') + } + elseif ($tmpgeturl['http_code'] != '200') { $error++; setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors'); $action = 'create'; - } else { + } + else + { $alreadygrabbed[$urltograbbis] = 1; // Track that file was alreay grabbed. dol_mkdir(dirname($filetosave)); @@ -1081,7 +1068,9 @@ { $urltograbdirrootwithoutslash = getRootURLFromURL($urltograb); $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot - } else { + } + else + { $urltograbbis = $urltograb.'/'.$regs[2][$key]; // We use dir of grabbed file } @@ -1119,12 +1108,15 @@ $error++; setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors'); $action = 'create'; - } elseif ($tmpgeturl['http_code'] != '200') + } + elseif ($tmpgeturl['http_code'] != '200') { $error++; setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors'); $action = 'create'; - } else { + } + else + { $alreadygrabbed[$urltograbbis] = 1; // Track that file was alreay grabbed. dol_mkdir(dirname($filetosave)); --- /tmp/dsg/dolibarr/htdocs/core/lib/github_website2.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_website2.lib.php @@ -52,8 +52,8 @@ } /** - * Save an alias page on disk (A page that include the reference page). - * It saves file into the root directory but also into language subdirectory. + * Save content of a page on disk. + * It can save file into root directory or into language subdirectory. * * @param string $filealias Full path of filename to generate * @param Website $object Object website @@ -82,11 +82,11 @@ @chmod($filealias, octdec($conf->global->MAIN_UMASK)); } - // Save also alias into language subdirectory if it is not a main language + // Save also alias into language subdirectory if we have to if ($objectpage->lang && in_array($objectpage->lang, explode(',', $object->otherlang))) { $dirname = dirname($filealias); $filename = basename($filealias); - $filealiassub = $dirname.'/'.$objectpage->lang.'/'.$filename; + $filealias = $dirname.'/'.$objectpage->lang.'/'.$filename; $aliascontent = 'id.'.tpl.php\'; '; $aliascontent .= 'else require $dolibarr_main_data_root.\'/website/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n"; $aliascontent .= '?>'."\n"; - $result = file_put_contents($filealiassub, $aliascontent); + $result = file_put_contents($filealias, $aliascontent); if ($result === false) { - dol_syslog("Failed to write file ".$filealiassub, LOG_WARNING); + dol_syslog("Failed to write file ".$filealias, LOG_WARNING); } if (!empty($conf->global->MAIN_UMASK)) { - @chmod($filealiassub, octdec($conf->global->MAIN_UMASK)); - } - } - // Save also alias into all language subdirectories if it is a main language - elseif (empty($objectpage->lang) || !in_array($objectpage->lang, explode(',', $object->otherlang))) { - if (empty($conf->global->WEBSITE_DISABLE_MAIN_LANGUAGE_INTO_LANGSUBDIR)) { - $dirname = dirname($filealias); - $filename = basename($filealias); - foreach (explode(',', $object->otherlang) as $sublang) { - $filealiassub = $dirname.'/'.$sublang.'/'.$filename; - - $aliascontent = 'id.'.tpl.php\'; '; - $aliascontent .= 'else require $dolibarr_main_data_root.\'/website/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n"; - $aliascontent .= '?>'."\n"; - $result = file_put_contents($filealiassub, $aliascontent); - if ($result === false) { - dol_syslog("Failed to write file ".$filealiassub, LOG_WARNING); - } - if (!empty($conf->global->MAIN_UMASK)) { - @chmod($filealiassub, octdec($conf->global->MAIN_UMASK)); - } - } + @chmod($filealias, octdec($conf->global->MAIN_UMASK)); } } @@ -132,8 +108,8 @@ /** - * Save content of a page on disk (page name is generally ID_of_page.php). - * Page contents are always saved into "root" directory. Only aliases pages saved with dolSavePageAlias() can be in root or language subdir. + * Save content of a page on disk. + * Page contents are always saved into root directory. * * @param string $filetpl Full path of filename to generate * @param Website $object Object website @@ -153,7 +129,6 @@ $shortlangcode = ''; if ($objectpage->lang) $shortlangcode = substr($objectpage->lang, 0, 2); // en_US or en-US -> en - if (empty($shortlangcode)) $shortlangcode = substr($object->lang, 0, 2); // en_US or en-US -> en $tplcontent = ''; $tplcontent .= "id > 0) { $tmpshortlangcode = ''; if ($tmppage->lang) $tmpshortlangcode = preg_replace('/[_-].*$/', '', $tmppage->lang); // en_US or en-US -> en - if (empty($tmpshortlangcode)) $tmpshortlangcode = preg_replace('/[_-].*$/', '', $object->lang); // en_US or en-US -> en if ($tmpshortlangcode != $shortlangcode) { $tplcontent .= ''."\n"; } @@ -223,21 +197,18 @@ } } } - } else { - dol_print_error($db); - } + } + else dol_print_error($db); $tplcontent .= ''."\n"; } - // Add manifest.json. Do we have to add it only on home page ? + // Add manifest.json on homepage $tplcontent .= 'use_manifest) { print \'\'."\n"; } ?>'."\n"; $tplcontent .= ''."\n"; - // Add js $tplcontent .= ''."\n"; $tplcontent .= ''."\n"; $tplcontent .= ''."\n"; - // Add headers $tplcontent .= ''."\n"; - $tplcontent .= ''."\n"; + $tplcontent .= '/ims\', \'\', file_get_contents(DOL_DATA_ROOT."/website/".$websitekey."/htmlheader.html")); ?>'."\n"; $tplcontent .= ''."\n"; $tplcontent .= preg_replace('/<\/?html>/ims', '', $objectpage->htmlheader)."\n"; $tplcontent .= ''."\n"; @@ -254,11 +225,10 @@ //var_dump($filetpl);exit; $result = file_put_contents($filetpl, $tplcontent); - if (!empty($conf->global->MAIN_UMASK)) { + if (!empty($conf->global->MAIN_UMASK)) @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); - } - - return $result; + + return $result; } @@ -298,7 +268,8 @@ if (!empty($conf->global->MAIN_UMASK)) { @chmod($fileindex, octdec($conf->global->MAIN_UMASK)); } - } else { + } + else { $result1 = true; } @@ -469,7 +440,7 @@ /** * Show list of themes. Show all thumbs of themes/skins * - * @param Website $website Object website to load the template into + * @param Website $website Object website to load the tempalte into * @return void */ function showWebsiteTemplates(Website $website) @@ -561,7 +532,8 @@ } } } - } else { + } + else { print ''.$langs->trans("None").''; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_ws.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_ws.lib.php @@ -29,40 +29,41 @@ * @param array $authentication Array with authentication informations ('login'=>,'password'=>,'entity'=>,'dolibarrkey'=>) * @param int $error Number of errors * @param string $errorcode Error string code - * @param string $errorlabel Error string label + * @param string $errorlabel Error string label * @return User Return user object identified by login/pass/entity into authentication array */ function check_authentication($authentication, &$error, &$errorcode, &$errorlabel) { - global $db, $conf, $langs; - global $dolibarr_main_authentication, $dolibarr_auto_user; + global $db, $conf, $langs; + global $dolibarr_main_authentication, $dolibarr_auto_user; - $fuser = new User($db); + $fuser = new User($db); - if (!$error && ($authentication['dolibarrkey'] != $conf->global->WEBSERVICES_KEY)) - { - $error++; - $errorcode = 'BAD_VALUE_FOR_SECURITY_KEY'; $errorlabel = 'Value provided into dolibarrkey entry field does not match security key defined in Webservice module setup'; - } + if (!$error && ($authentication['dolibarrkey'] != $conf->global->WEBSERVICES_KEY)) + { + $error++; + $errorcode = 'BAD_VALUE_FOR_SECURITY_KEY'; $errorlabel = 'Value provided into dolibarrkey entry field does not match security key defined in Webservice module setup'; + } - if (!$error && !empty($authentication['entity']) && !is_numeric($authentication['entity'])) - { - $error++; - $errorcode = 'BAD_PARAMETERS'; $errorlabel = "The entity parameter must be empty (or filled with numeric id of instance if multicompany module is used)."; - } + if (!$error && !empty($authentication['entity']) && !is_numeric($authentication['entity'])) + { + $error++; + $errorcode = 'BAD_PARAMETERS'; $errorlabel = "The entity parameter must be empty (or filled with numeric id of instance if multicompany module is used)."; + } - if (!$error) - { - $result = $fuser->fetch('', $authentication['login'], '', 0); - if ($result < 0) - { - $error++; - $errorcode = 'ERROR_FETCH_USER'; $errorlabel = 'A technical error occurred during fetch of user'; - } elseif ($result == 0) - { - $error++; - $errorcode = 'BAD_CREDENTIALS'; $errorlabel = 'Bad value for login or password'; - } + if (!$error) + { + $result = $fuser->fetch('', $authentication['login'], '', 0); + if ($result < 0) + { + $error++; + $errorcode = 'ERROR_FETCH_USER'; $errorlabel = 'A technical error occurred during fetch of user'; + } + elseif ($result == 0) + { + $error++; + $errorcode = 'BAD_CREDENTIALS'; $errorlabel = 'Bad value for login or password'; + } if (!$error && $fuser->statut == 0) { @@ -70,27 +71,27 @@ $errorcode = 'ERROR_USER_DISABLED'; $errorlabel = 'This user has been locked or disabled'; } - // Validation of login + // Validation of login if (!$error) { $fuser->getrights(); // Load permission of user - // Authentication mode - if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'http,dolibarr'; - // Authentication mode: forceuser - if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; - // Set authmode - $authmode = explode(',', $dolibarr_main_authentication); + // Authentication mode + if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'http,dolibarr'; + // Authentication mode: forceuser + if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; + // Set authmode + $authmode = explode(',', $dolibarr_main_authentication); - include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $login = checkLoginPassEntity($authentication['login'], $authentication['password'], $authentication['entity'], $authmode, 'ws'); + include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $login = checkLoginPassEntity($authentication['login'], $authentication['password'], $authentication['entity'], $authmode, 'ws'); if (empty($login)) { - $error++; - $errorcode = 'BAD_CREDENTIALS'; $errorlabel = 'Bad value for login or password'; + $error++; + $errorcode = 'BAD_CREDENTIALS'; $errorlabel = 'Bad value for login or password'; } } - } + } - return $fuser; + return $fuser; } --- /tmp/dsg/dolibarr/htdocs/core/lib/github_xcal.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_xcal.lib.php @@ -229,7 +229,9 @@ { $enddate = dol_time_plus_duree($startdate, 1, "d"); } - } else { + } + else + { if (empty($enddate)) { $enddate = $startdate + $duration; @@ -313,7 +315,9 @@ { @chmod($outputfile, octdec($conf->global->MAIN_UMASK)); } - } else { + } + else + { dol_syslog("xcal.lib.php::build_calfile Failed to open file ".$outputfile." for writing"); return -2; } @@ -524,7 +528,9 @@ } $out .= $newpara; - } else { + } + else + { $strlength = dol_strlen($line); for ($j = 0; $j < $strlength; $j++)