--- /tmp/dsg/dolibarr/htdocs/core/lib/github_19.0.3_accounting.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_accounting.lib.php @@ -3 +3 @@ - * Copyright (C) 2013-2021 Alexandre Spangaro + * Copyright (C) 2013-2017 Alexandre Spangaro @@ -5,2 +5 @@ - * Copyright (C) 2019 Eric Seigne - * Copyright (C) 2021 Frédéric France + * Copyright (C) 2019 Eric Seigne @@ -60 +59 @@ - $head[$h][1] = $langs->trans("AccountAccounting"); + $head[$h][1] = $langs->trans("Asset"); @@ -98,9 +97,5 @@ - if ($account < 0 || is_empty($account)) { - return ''; - } - - if (getDolGlobalString('ACCOUNTING_MANAGE_ZERO')) { - return $account; - } - - $g = getDolGlobalInt('ACCOUNTING_LENGTH_GACCOUNT'); + if ($account < 0 || is_empty($account)) return ''; + + if (!is_empty($conf->global->ACCOUNTING_MANAGE_ZERO)) return $account; + + $g = $conf->global->ACCOUNTING_LENGTH_GACCOUNT; @@ -137,9 +132,5 @@ - if ($accounta < 0 || is_empty($accounta)) { - return ''; - } - - if (getDolGlobalString('ACCOUNTING_MANAGE_ZERO')) { - return $accounta; - } - - $a = getDolGlobalInt('ACCOUNTING_LENGTH_AACCOUNT'); + if ($accounta < 0 || is_empty($accounta)) return ''; + + if (!is_empty($conf->global->ACCOUNTING_MANAGE_ZERO)) return $accounta; + + $a = $conf->global->ACCOUNTING_LENGTH_AACCOUNT; @@ -185,202 +176,70 @@ - 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; - - $date_start = ''; - $date_end = ''; - $pastmonth = 0; - $pastmonthyear = 0; - - // Period by default on transfer (0: previous month | 1: current month | 2: fiscal year) - $periodbydefaultontransfer = getDolGlobalInt('ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER', 0); - if ($periodbydefaultontransfer == 2) { // fiscal year - $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) { - $obj = $db->fetch_object($res); - - $date_start = $db->jdate($obj->date_start); - $date_end = $db->jdate($obj->date_end); - } else { - $month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); - $year_start = dol_print_date(dol_now(), '%Y'); - if ($month_start > dol_print_date(dol_now(), '%m')) { - $year_start = $year_start - 1; - } - $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) { // current month - $year_current = (int) dol_print_date(dol_now('gmt'), "%Y", 'gmt'); - $pastmonth = (int) dol_print_date(dol_now('gmt'), '%m', 'gmt'); - $pastmonthyear = $year_current; - if ($pastmonth == 0) { - $pastmonth = 12; - $pastmonthyear--; - } - } else { // previous month - $year_current = (int) dol_print_date(dol_now('gmt'), "%Y", 'gmt'); - $pastmonth = (int) dol_print_date(dol_now('gmt'), '%m', 'gmt') - 1; - $pastmonthyear = $year_current; - if ($pastmonth == 0) { - $pastmonth = 12; - $pastmonthyear--; - } - } - - return array( - 'date_start' => $date_start, - 'date_end' => $date_end, - 'pastmonthyear' => $pastmonthyear, - 'pastmonth' => $pastmonth - ); -} - -/** - * Get current period of fiscal year - * - * @param DoliDB $db Database handler - * @param stdClass $conf Config - * @param int $from_time [=null] Get current time or set time to find fiscal period - * @return array Period of fiscal year : [date_start, date_end] - */ -function getCurrentPeriodOfFiscalYear($db, $conf, $from_time = null) -{ - $now = dol_now(); - $now_arr = dol_getdate($now); - if ($from_time === null) { - $from_time = $now; - } - $from_db_time = $db->idate($from_time); - - $sql = "SELECT date_start, date_end FROM ".$db->prefix()."accounting_fiscalyear"; - $sql .= " WHERE date_start <= '".$db->escape($from_db_time)."' AND date_end >= '".$db->escape($from_db_time)."'"; - $sql .= $db->order('date_start', 'DESC'); - $sql .= $db->plimit(1); - $res = $db->query($sql); - if ($db->num_rows($res) > 0) { - $obj = $db->fetch_object($res); - - $date_start = $db->jdate($obj->date_start); - $date_end = $db->jdate($obj->date_end); - } else { - $month_start = 1; - $conf_fiscal_month_start = (int) $conf->global->SOCIETE_FISCAL_MONTH_START; - if ($conf_fiscal_month_start >= 1 && $conf_fiscal_month_start <= 12) { - $month_start = $conf_fiscal_month_start; - } - $year_start = $now_arr['year']; - if ($conf_fiscal_month_start > $now_arr['mon']) { - $year_start = $year_start - 1; - } - $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); - } - - return array( - 'date_start' => $date_start, - 'date_end' => $date_end, - ); -} + 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_19.0.3_admin.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_admin.lib.php @@ -6 +5,0 @@ - * Copyright (C) 2023 Eric Seigne @@ -39,11 +38,5 @@ - $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; @@ -55 +48 @@ - * 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. @@ -69,51 +62,26 @@ - $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; @@ -127 +94,0 @@ - * @see versioncompare() @@ -131 +98 @@ - return explode('.', PHP_VERSION); + return explode('.', PHP_VERSION); @@ -138 +104,0 @@ - * @see versioncompare() @@ -142 +108 @@ - return explode('.', DOL_VERSION); + return explode('.', DOL_VERSION); @@ -155,250 +121,185 @@ - * @param string $sqlfile Full path to sql file - * @param int $silent 1=Do not output anything, 0=Output line for update page - * @param int $entity Entity targeted for multicompany module - * @param int $usesavepoint 1=Run a savepoint before each request and a rollback to savepoint if error (this allow to have some request with errors inside global transactions). - * @param string $handler Handler targeted for menu (replace __HANDLER__ with this value between quotes) - * @param string $okerror Family of errors we accept ('default', 'none') - * @param int $linelengthlimit Limit for length of each line (Use 0 if unknown, may be faster if defined) - * @param int $nocommentremoval Do no try to remove comments (in such a case, we consider that each line is a request, so use also $linelengthlimit=0) - * @param int $offsetforchartofaccount Offset to use to load chart of account table to update sql on the fly to add offset to rowid and account_parent value - * @param int $colspan 2=Add a colspan=2 on td - * @param int $onlysqltoimportwebsite Only sql resquests used to import a website template are allowed - * @param string $database Database (replace __DATABASE__ with this value) - * @return int Return integer <=0 if KO, >0 if OK - */ -function run_sql($sqlfile, $silent = 1, $entity = 0, $usesavepoint = 1, $handler = '', $okerror = 'default', $linelengthlimit = 32768, $nocommentremoval = 0, $offsetforchartofaccount = 0, $colspan = 0, $onlysqltoimportwebsite = 0, $database = '') -{ - 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]); - //var_dump($versionrequest); - //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 - } - if ($buffer) { - $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 ''; - print '
'.$langs->trans("Failed to get max rowid for ".$table)."
"; - 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,...' - // 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,...' - // Note: string with 'PCG99-ABREGE','CAPIT', 1234 instead of 'PCG99-ABREGE','CAPIT', '1234' is also supported - $newsql = preg_replace('/VALUES\s*\(__ENTITY__, \s*(\d+)\s*,(\s*\'[^\',]*\'\s*,\s*\'[^\',]*\'\s*,\s*\'?[^\',]*\'?\s*),\s*\'?([^\',]*)\'?/ims', 'VALUES (__ENTITY__, \1 + '.((int) $offsetforchartofaccount).', \2, \3 + '.((int) $offsetforchartofaccount), $newsql); - $newsql = preg_replace('/([,\s])0 \+ '.((int) $offsetforchartofaccount).'/ims', '\1 0', $newsql); - //var_dump($newsql); - $arraysql[$i] = $newsql; - - // FIXME Because we force the rowid during insert, we must also update the sequence with postgresql by running - // SELECT dol_util_rebuild_sequences(); - } - } - - // Loop on each request to execute request - $cursorinsert = 0; - $listofinsertedrowid = array(); - $keyforsql = md5($sqlfile); - foreach ($arraysql as $i => $sql) { - if ($sql) { - // Test if th SQL is allowed SQL - if ($onlysqltoimportwebsite) { - $newsql = str_replace(array("\'"), '__BACKSLASHQUOTE__', $sql); // Replace the \' char - - // Remove all strings contents including the ' so we can analyse SQL instruction only later - $l = strlen($newsql); - $is = 0; - $quoteopen = 0; - $newsqlclean = ''; - while ($is < $l) { - $char = $newsql[$is]; - if ($char == "'") { - if ($quoteopen) { - $quoteopen--; - } else { - $quoteopen++; - } - } elseif (empty($quoteopen)) { - $newsqlclean .= $char; - } - $is++; - } - $newsqlclean = str_replace(array("null"), '__000__', $newsqlclean); - //print $newsqlclean."
\n"; - - $qualified = 0; - - // A very small control. This can still by bypassed by adding a second SQL request concatenated - if (preg_match('/^--/', $newsqlclean)) { - $qualified = 1; - } elseif (preg_match('/^UPDATE llx_website SET \w+ = \d+\+\d+ WHERE rowid = \d+;$/', $newsqlclean)) { - $qualified = 1; - } elseif (preg_match('/^INSERT INTO llx_website_page\([a-z0-9_\s,]+\) VALUES\([0-9_\s,\+]+\);$/', $newsqlclean)) { - // Insert must match - // INSERT INTO llx_website_page(rowid, fk_page, fk_website, pageurl, aliasalt, title, description, lang, image, keywords, status, date_creation, tms, import_key, grabbed_from, type_container, htmlheader, content, author_alias) VALUES(1+123, null, 17, , , , , , , , , , , null, , , , , ); - $qualified = 1; - } - - // Another check to allow some legitimate original urls - if (!$qualified) { - if (preg_match('/^UPDATE llx_website SET \w+ = \'[a-zA-Z,\s]*\' WHERE rowid = \d+;$/', $sql)) { - $qualified = 1; - } - } - - if (!$qualified) { - $error++; - //print 'Request '.($i + 1)." contains non allowed instructions.
\n"; - //print "newsqlclean = ".$newsqlclean."
\n"; - dol_syslog('Admin.lib::run_sql Request '.($i + 1)." contains non allowed instructions.", LOG_WARNING); - dol_syslog('$newsqlclean='.$newsqlclean, LOG_DEBUG); - break; - } - } - - // 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); - } - - if (!empty($database)) { - $sql = preg_replace('/__DATABASE__/i', $db->escape($database), $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); + * @param string $sqlfile Full path to sql file + * @param int $silent 1=Do not output anything, 0=Output line for update page + * @param int $entity Entity targeted for multicompany module + * @param int $usesavepoint 1=Run a savepoint before each request and a rollback to savepoint if error (this allow to have some request with errors inside global transactions). + * @param string $handler Handler targeted for menu (replace __HANDLER__ with this value) + * @param string $okerror Family of errors we accept ('default', 'none') + * @param int $linelengthlimit Limit for length of each line (Use 0 if unknown, may be faster if defined) + * @param int $nocommentremoval Do no try to remove comments (in such a case, we consider that each line is a request, so use also $linelengthlimit=0) + * @param int $offsetforchartofaccount Offset to use to load chart of account table to update sql on the fly to add offset to rowid and account_parent value + * @return int <=0 if KO, >0 if OK + */ +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', '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); @@ -407,68 +308,69 @@ - // 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]); - $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 the rowid of the result of the insert number x - while (preg_match('/__([0-9]+)__/', $newsql, $reg)) { - $cursor = $reg[1]; - if (empty($listofinsertedrowid[$cursor])) { - if (!$silent) { - print ''; - print '
'.$langs->trans("FileIsNotCorrect")."
"; - 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"; @@ -477 +379 @@ - $okerrors = array( // By default + $okerrors = array( // By default @@ -490 +392 @@ - 'DB_ERROR_22P02' + 'DB_ERROR_22P02' @@ -492,2 +394,10 @@ - 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++; @@ -495,60 +405,25 @@ - - // Is it an error we accept - if (!in_array($errno, $okerrors)) { - if (!$silent) { - print ''; - print '
'.$langs->trans("Error")." ".$db->errno()." (Req ".($i + 1)."): ".$newsql."
".$db->error()."
"; - print ''."\n"; - } - dol_syslog('Admin.lib::run_sql Request '.($i + 1)." Error ".$db->errno()." ".$newsql."
".$db->error(), LOG_ERR); - $error++; - } - } - } - } - - 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)) { // use_javascript_ajax is not defined - print ''; - if (count($arraysql)) { - print ' - '.$langs->trans("ShowHideDetails").''; - } else { - print ' - '.$langs->trans("ScriptIsEmpty").''; - } - //} - - print ''."\n"; - } - - if ($error == 0) { - $ok = 1; - } else { - $ok = 0; - } - - return $ok; -} - - -/** - * Delete a constant + } + + 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; +} + + +/** + * Effacement d'une constante dans la base de donnees @@ -557 +432 @@ - * @param string|int $name Name of constant or rowid of line + * @param string $name Name of constant or rowid of line @@ -559 +434 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -565,30 +440,30 @@ - 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 = ".((int) $name); - } - $sql .= ")"; - if ($entity >= 0) { - $sql .= " AND entity = ".((int) $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; - } -} - -/** - * Get the value of a setup constant from database + 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; + } +} + +/** + * Recupere une constante depuis la base de donnees. @@ -597 +472 @@ - * @param string $name Name of constant + * @param string $name Nom de la constante @@ -599 +474 @@ - * @return string Value of constant + * @return string Valeur de la constante @@ -605,17 +480,16 @@ - $value = ''; - - $sql = "SELECT ".$db->decrypt('value')." as value"; - $sql .= " FROM ".MAIN_DB_PREFIX."const"; - $sql .= " WHERE name = ".$db->encrypt($name); - $sql .= " AND entity = ".((int) $entity); - - dol_syslog("admin.lib::dolibarr_get_const", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) { - $obj = $db->fetch_object($resql); - if ($obj) { - include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php'; - $value = dolDecrypt($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; @@ -631 +505 @@ - * @param string $type Type of constant. Deprecated, only strings are allowed for $value. Caller must json encode/decode to store other type of data. + * @param string $type Type of constante (chaine par defaut) @@ -641,57 +515,49 @@ - 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); - if ($entity >= 0) { - $sql .= " AND entity = ".((int) $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 - if (!preg_match('/^(MAIN_LOGEVENTS|MAIN_AGENDA_ACTIONAUTO)/', $name) && (preg_match('/(_KEY|_EXPORTKEY|_SECUREKEY|_SERVERKEY|_PASS|_PASSWORD|_PW|_PW_TICKET|_PW_EMAILING|_SECRET|_SECURITY_TOKEN|_WEB_TOKEN)$/', $name))) { - // This seems a sensitive constant, we encrypt its value - // To list all sensitive constant, you can make a - // WHERE name like '%\_KEY' or name like '%\_EXPORTKEY' or name like '%\_SECUREKEY' or name like '%\_SERVERKEY' or name like '%\_PASS' or name like '%\_PASSWORD' or name like '%\_SECRET' - // or name like '%\_SECURITY_TOKEN' or name like '%\WEB_TOKEN' - include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php'; - $newvalue = dolEncrypt($value); - } else { - $newvalue = $value; - } - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."const(name, value, type, visible, note, entity)"; - $sql .= " VALUES ("; - $sql .= $db->encrypt($name); - $sql .= ", ".$db->encrypt($newvalue); - $sql .= ", '".$db->escape($type)."', ".((int) $visible).", '".$db->escape($note)."', ".((int) $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; + } @@ -706,12 +572,5 @@ - * @param int $nbofactivatedmodules Number if activated modules - * @param int $nboftotalmodules Nb of total modules - * @param int $nbmodulesnotautoenabled Nb of modules not auto enabled that are activated - * @return array Array of tabs to show - */ -function modules_prepare_head($nbofactivatedmodules, $nboftotalmodules, $nbmodulesnotautoenabled) -{ - global $langs, $conf, $user, $form; - - $desc = $langs->trans("ModulesDesc", '{picto}'); - $desc = str_replace('{picto}', img_picto('', 'switch_off'), $desc); - + * @return array Array of tabs to show + */ +function modules_prepare_head() +{ + global $langs, $conf, $user; @@ -720,11 +579,4 @@ - $mode = getDolGlobalString('MAIN_MODULE_SETUP_ON_LIST_BY_DEFAULT', 'commonkanban'); - $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=".$mode; - if ($nbmodulesnotautoenabled <= getDolGlobalInt('MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING', 1)) { // If only minimal initial modules enabled) - //$head[$h][1] = $form->textwithpicto($langs->trans("AvailableModules"), $desc); - $head[$h][1] = $langs->trans("AvailableModules"); - $head[$h][1] .= $form->textwithpicto('', $langs->trans("YouMustEnableOneModule").'.

'.$desc.'', 1, 'warning'); - } else { - //$head[$h][1] = $langs->trans("AvailableModules").$form->textwithpicto(''.$nbofactivatedmodules.' / '.$nboftotalmodules.'', $desc, 1, 'help', '', 1, 3); - $head[$h][1] = $langs->trans("AvailableModules").''.$nbofactivatedmodules.' / '.$nboftotalmodules.''; - } - $head[$h][2] = 'modules'; + + $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=commonkanban"; + $head[$h][1] = $langs->trans("AvailableModules"); + $head[$h][2] = 'commonkanban'; @@ -750,0 +603 @@ + @@ -756,39 +609,63 @@ -function ihm_prepare_head() -{ - global $langs, $conf, $user; - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=other"; - $head[$h][1] = $langs->trans("LanguageAndPresentation"); - $head[$h][2] = 'other'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=template"; - $head[$h][1] = $langs->trans("SkinAndColors"); - $head[$h][2] = 'template'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=dashboard"; - $head[$h][1] = $langs->trans("Dashboard"); - $head[$h][2] = 'dashboard'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=login"; - $head[$h][1] = $langs->trans("LoginPage"); - $head[$h][2] = 'login'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=css"; - $head[$h][1] = $langs->trans("CSSPage"); - $head[$h][2] = 'css'; - $h++; - - complete_head_from_modules($conf, $langs, null, $head, $h, 'ihm_admin'); - - complete_head_from_modules($conf, $langs, null, $head, $h, 'ihm_admin', 'remove'); - - - return $head; -} - +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++; + */ + + $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; +} @@ -798 +675 @@ - * + * @param object $object descriptor class @@ -801,76 +677,0 @@ -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++; - */ - - $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 = ".((int) $conf->entity); - $sql .= " AND bydefault = 1"; - if (!getDolGlobalString('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] .= (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') ? ''.$nbPerms.'' : ''); - } - $head[$h][2] = 'default'; - $h++; - - return $head; -} - -/** - * Prepare array with list of tabs - * - * @param object $object Descriptor class - * @return array Array of tabs to show - */ @@ -879,6 +680,6 @@ - global $langs, $conf; - $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; @@ -896 +697,2 @@ - if ($object->isCoreOrExternalModule() == 'external') { + if ($object->isCoreOrExternalModule() == 'external') + { @@ -903,6 +705,6 @@ - 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; @@ -917,20 +719,20 @@ - global $langs, $conf; - $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; @@ -947,42 +749,43 @@ - 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; @@ -999,20 +802,24 @@ - 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 @@ -1023,22 +830,21 @@ - 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]+):"('.getDolGlobalString('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; @@ -1055,39 +861,36 @@ - 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]+):"(' . getDolGlobalString('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; @@ -1101,10 +904,9 @@ - * @param string $value Name of module to activate - * @param int $withdeps Activate/Disable also all dependencies - * @param int $noconfverification Remove verification of $conf variable for module - * @return array array('nbmodules'=>nb modules activated with success, 'errors=>array of error messages, 'nbperms'=>Nb permission added); - */ -function activateModule($value, $withdeps = 1, $noconfverification = 0) -{ - global $db, $langs, $conf, $mysoc; - - $ret = array(); + * @param string $value Name of module to activate + * @param int $withdeps Activate/Disable also all dependencies + * @return array array('nbmodules'=>nb modules activated with success, 'errors=>array of error messages, 'nbperms'=>Nb permission added); + */ +function activateModule($value, $withdeps = 1) +{ + global $db, $langs, $conf, $mysoc; + + $ret = array(); @@ -1118,23 +920,23 @@ - $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; @@ -1146,4 +948,4 @@ - // 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; @@ -1162,77 +964,80 @@ - if ($noconfverification == 0) { - if (getDolGlobalString($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('always'=>array('modModule1'), 'FR'=>array('modModule2")) - foreach ($objMod->depends as $key => $modulestringorarray) { - //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; - } - - if (!is_array($modulestringorarray)) { - $modulestringorarray = array($modulestringorarray); - } - - foreach ($modulestringorarray as $modulestring) { - $activate = false; - $activateerr = ''; - foreach ($modulesdir as $dir) { - if (file_exists($dir.$modulestring.".class.php")) { - $resarray = activateModule($modulestring); - if (empty($resarray['errors'])) { - $activate = true; - } else { - $activateerr = join(', ', $resarray['errors']); - foreach ($resarray['errors'] as $errorMessage) { - dol_syslog($errorMessage, LOG_ERR); - } - } - break; - } - } - - if ($activate) { - $ret['nbmodules'] += $resarray['nbmodules']; - $ret['nbperms'] += $resarray['nbperms']; - } else { - if ($activateerr) { - $ret['errors'][] = $activateerr; - } - $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'] += (is_array($objMod->rights) ? count($objMod->rights) : 0); - } - - return $ret; + 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; @@ -1251,53 +1056,54 @@ - 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; @@ -1322 +1128 @@ - * @param array $tabcomplete Tab complete (will replace all other in future). Key is table name. + * @param array $tabfieldcheck Tabfieldcheck @@ -1325,7 +1131,7 @@ -function complete_dictionary_with_modules(&$taborder, &$tabname, &$tablib, &$tabsql, &$tabsqlsort, &$tabfield, &$tabfieldvalue, &$tabfieldinsert, &$tabrowid, &$tabcond, &$tabhelp, &$tabcomplete) -{ - 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 +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 @@ -1333,40 +1139,43 @@ - $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' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && !getDolGlobalString($const_name)) { - $modulequalified = 0; - } - if ($objMod->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && !getDolGlobalString($const_name)) { - $modulequalified = 0; - } - // If module is not activated disqualified - if (!getDolGlobalString($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) + { @@ -1380,3 +1189,97 @@ - // 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'); @@ -1384,89 +1286,0 @@ - - if (!empty($objMod->dictionaries)) { - //var_dump($objMod->dictionaries['tabname']); - $nbtabname = $nbtablib = $nbtabsql = $nbtabsqlsort = $nbtabfield = $nbtabfieldvalue = $nbtabfieldinsert = $nbtabrowid = $nbtabcond = $nbtabfieldcheck = $nbtabhelp = 0; - $tabnamerelwithkey = array(); - foreach ($objMod->dictionaries['tabname'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $val); - $nbtabname++; - $taborder[] = max($taborder) + 1; - $tabname[] = $val; - $tabnamerelwithkey[$key] = $val; - $tabcomplete[$tmptablename]['picto'] = $objMod->picto; - } // Position - foreach ($objMod->dictionaries['tablib'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]); - $nbtablib++; - $tablib[] = $val; - $tabcomplete[$tmptablename]['lib'] = $val; - } - foreach ($objMod->dictionaries['tabsql'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]); - $nbtabsql++; - $tabsql[] = $val; - $tabcomplete[$tmptablename]['sql'] = $val; - } - foreach ($objMod->dictionaries['tabsqlsort'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]); - $nbtabsqlsort++; - $tabsqlsort[] = $val; - $tabcomplete[$tmptablename]['sqlsort'] = $val; - } - foreach ($objMod->dictionaries['tabfield'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]); - $nbtabfield++; - $tabfield[] = $val; - $tabcomplete[$tmptablename]['field'] = $val; - } - foreach ($objMod->dictionaries['tabfieldvalue'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]); - $nbtabfieldvalue++; - $tabfieldvalue[] = $val; - $tabcomplete[$tmptablename]['value'] = $val; - } - foreach ($objMod->dictionaries['tabfieldinsert'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]); - $nbtabfieldinsert++; - $tabfieldinsert[] = $val; - $tabcomplete[$tmptablename]['fieldinsert'] = $val; - } - foreach ($objMod->dictionaries['tabrowid'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]); - $nbtabrowid++; - $tabrowid[] = $val; - $tabcomplete[$tmptablename]['rowid'] = $val; - } - foreach ($objMod->dictionaries['tabcond'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]); - $nbtabcond++; - $tabcond[] = $val; - $tabcomplete[$tmptablename]['rowid'] = $val; - } - if (!empty($objMod->dictionaries['tabhelp'])) { - foreach ($objMod->dictionaries['tabhelp'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]); - $nbtabhelp++; - $tabhelp[] = $val; - $tabcomplete[$tmptablename]['help'] = $val; - } - } - if (!empty($objMod->dictionaries['tabfieldcheck'])) { - foreach ($objMod->dictionaries['tabfieldcheck'] as $key => $val) { - $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]); - $nbtabfieldcheck++; - $tabcomplete[$tmptablename]['fieldcheck'] = $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"); @@ -1473,0 +1288 @@ + else dol_syslog("Module ".get_class($objMod)." not qualified"); @@ -1478 +1293,3 @@ - } else { + } + else + { @@ -1483,64 +1299,0 @@ - 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' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2) { - $modulequalified = 0; - } - if ($objMod->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1) { - $modulequalified = 0; - } - if (getDolGlobalString($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); - } - } - @@ -1558,53 +1311,56 @@ - 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' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && getDolGlobalString($const_name)) { - $modulequalified = 0; - } - if ($objMod->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && getDolGlobalString($const_name)) { - $modulequalified = 0; - } - // If module is not activated disqualified - if (!getDolGlobalString($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) + { @@ -1612,39 +1368,37 @@ - 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); - } - } - - $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; + 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; @@ -1658,3 +1412,2 @@ - * @param int $strictw3c 0=Include form into table (deprecated), 1=Form is outside table to respect W3C (deprecated), 2=No form nor button at all, 3=No form nor button at all and each field has a unique name (form is output by caller, recommended) - * @param string $helptext Tooltip help to use for the column name of values - * @param string $text Text to use for the column name of values + * @param int $strictw3c 0=Include form into table (deprecated), 1=Form is outside table to respect W3C (deprecated), 2=No form nor button at all (form is output by caller, recommended) + * @param string $helptext Help @@ -1663,38 +1416,40 @@ -function form_constantes($tableau, $strictw3c = 0, $helptext = '', $text = 'Value') -{ - 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 ''; - 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']; +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 '
'.$langs->trans("Description").''; - $text = $langs->trans($text); - 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']; @@ -1702,158 +1457,166 @@ - $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 ''; - } - - print ''; - - // Show label of parameter - 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 ''; - if (!empty($tableau[$key]['tooltip'])) { - print $form->textwithpicto($label ? $label : $langs->trans('Desc'.$const), $tableau[$key]['tooltip']); - } else { - 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 ''; - } elseif ($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%'; - } elseif ($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%'; - } elseif (in_array($const, ['ADHERENT_MAIL_FROM', 'ADHERENT_CC_MAIL_FROM'])) { - print ' '.img_help(1, $langs->trans("EMailHelpMsgSPFDKIM")); - } - - 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) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $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'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $obj->value, '', 160, 'dolibarr_notes', '', false, false, isModEnabled('fckeditor'), ROWS_5, '90%'); - $doleditor->Create(); - } elseif ($obj->type == 'yesno') { - print $form->selectyesno('constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $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'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $arrayofmessagename, $obj->value.':'.$tmp[1], 'None', 0, 0, '', 0, 0, 0, '', '', 1); - } elseif (preg_match('/MAIL_FROM$/i', $const)) { - print img_picto('', 'email', 'class="pictofixedwidth"').''; - } else { // type = 'string' ou 'chaine' - print ''; - } - 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"; + } @@ -1874,2 +1637 @@ - $listofmodules = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL')); // List of modules qualified for external user management - + $listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); @@ -1878,2 +1640,2 @@ - $tmpmodules = dol_sort_array($modules, 'module_position'); - foreach ($tmpmodules as $module) { // Loop on array of modules + foreach ($modules as $module) + { @@ -1885,3 +1647 @@ - if (!in_array($modulename, $listofmodules)) { - continue; - } + if (!in_array($modulename, $listofmodules)) continue; @@ -1890,5 +1650,2 @@ - if ($i > 0) { - $text .= ', '; - } else { - $text .= ' '; - } + if ($i > 0) $text .= ', '; + else $text .= ' '; @@ -1896,7 +1653 @@ - - $tmptext = $langs->trans('Module'.$module->numero.'Name'); - if ($tmptext != 'Module'.$module->numero.'Name') { - $text .= $langs->trans('Module'.$module->numero.'Name'); - } else { - $text .= $langs->trans($module->name); - } + $text .= $langs->trans('Module'.$module->numero.'Name'); @@ -1905 +1655,0 @@ - @@ -1917 +1667 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -1925,7 +1675,7 @@ - $sql = "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity, libelle, description)"; - $sql .= " VALUES ('".$db->escape($name)."','".$db->escape($type)."',".((int) $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); @@ -1933 +1683,2 @@ - if ($resql) { + if ($resql) + { @@ -1936 +1687,3 @@ - } else { + } + else + { @@ -1948 +1701 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -1958,2 +1711,2 @@ - $sql .= " AND type = '".$db->escape($type)."'"; - $sql .= " AND entity = ".((int) $conf->entity); + $sql .= " AND type = '".$type."'"; + $sql .= " AND entity = ".$conf->entity; @@ -1963 +1716,2 @@ - if ($resql) { + if ($resql) + { @@ -1966 +1720,3 @@ - } else { + } + else + { @@ -1983,3 +1738,0 @@ - $phpinfostring = ob_get_contents(); - ob_end_clean(); - @@ -1987 +1740 @@ - $info_lines = explode("\n", strip_tags($phpinfostring, "

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

")); // end of ob_start() @@ -1989 +1742,2 @@ - foreach ($info_lines as $line) { + foreach ($info_lines as $line) + { @@ -1994 +1748,2 @@ - if (preg_match("~]+>([^<]*)]+>([^<]*)~", $line, $val)) { + if (preg_match("~]+>([^<]*)]+>([^<]*)~", $line, $val)) + { @@ -1996 +1751,3 @@ - } elseif (preg_match("~]+>([^<]*)]+>([^<]*)]+>([^<]*)~", $line, $val)) { + } + elseif (preg_match("~]+>([^<]*)]+>([^<]*)]+>([^<]*)~", $line, $val)) + { @@ -2020,4 +1777,4 @@ - $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++; @@ -2030,5 +1786,0 @@ - $head[$h][0] = DOL_URL_ROOT."/admin/company_socialnetworks.php"; - $head[$h][1] = $langs->trans("SocialNetworksInformation"); - $head[$h][2] = 'socialnetworks'; - $h++; - @@ -2054 +1806,2 @@ - if (!empty($user->admin) && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) { + if (!empty($user->admin) && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) + { @@ -2060 +1813,2 @@ - if (isModEnabled('mailing')) { + if ($conf->mailing->enabled) + { @@ -2066,7 +1819,0 @@ - - if (isModEnabled('ticket')) { - $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++; - } @@ -2075,2 +1822,7 @@ - // admin and non admin can view this menu entry, but it is not shown yet when we on user menu "Email templates" - if (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')) + { @@ -2083,10 +1834,0 @@ - $head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php"; - $head[$h][1] = $langs->trans("EMailTemplates"); - $head[$h][2] = 'templates'; - $h++; - - $head[$h][0] = DOL_URL_ROOT."/admin/mails_ingoing.php"; - $head[$h][1] = $langs->trans("InGoingEmailSetup", $langs->transnoentitiesnoconv("EMailing")); - $head[$h][2] = 'common_ingoing'; - $h++; - --- /tmp/dsg/dolibarr/htdocs/core/lib/github_19.0.3_agenda.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_agenda.lib.php @@ -5 +4,0 @@ - * Copyright (C) 2022 Frédéric France @@ -23,2 +22,2 @@ - * \file htdocs/core/lib/agenda.lib.php - * \brief Set of function for the agenda module + * \file htdocs/core/lib/agenda.lib.php + * \brief Set of function for the agenda module @@ -55 +53,0 @@ - global $massaction; @@ -65,40 +63,24 @@ - print ''; - print ''; - print ''; - if ($massaction != 'predelete' && $massaction != 'preaffecttag') { // When $massaction == 'predelete', action may be already output to 'delete' by the mass action system. - print ''; - } - print ''; - - print '
'; - // Type - $multiselect = 0; - if (getDolGlobalString('MAIN_ENABLE_MULTISELECT_TYPE')) { // We use an option here because it adds bugs when used on agenda page "peruser" and "list" - $multiselect = (getDolGlobalString('AGENDA_USE_EVENT_TYPE')); - } - print img_picto($langs->trans("ActionType"), 'square', 'class="pictofixedwidth inline-block" style="color: #ddd;"'); - print $formactions->select_type_actions($actioncode, "search_actioncode", $excludetype, (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? 1 : -1), 0, $multiselect, 0, 'maxwidth500 widthcentpercentminusx'); - print '
'; - - if ($canedit) { - // Assigned to user - print '
'; - print img_picto($langs->trans("ActionsToDoBy"), 'user', 'class="pictofixedwidth inline-block"'); - print $form->select_dolusers($filtert, 'search_filtert', 1, '', !$canedit, '', '', 0, 0, 0, '', 0, '', 'minwidth150 maxwidth500 widthcentpercentminusxx'); - print '
'; - - // Assigned to user group - print '
'; - print img_picto($langs->trans("ToUserOfGroup"), 'object_group', 'class="pictofixedwidth inline-block"'); - print $form->select_dolgroups($usergroupid, 'usergroup', 1, '', !$canedit, '', '', '0', false, 'minwidth100 maxwidth500 widthcentpercentminusxx'); - print '
'; - - if (isModEnabled('resource')) { - include_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php'; - $formresource = new FormResource($db); - - // Resource - print '
'; - print img_picto($langs->trans("Resource"), 'object_resource', 'class="pictofixedwidth inline-block"'); - print $formresource->select_resource_list($resourceid, "search_resourceid", '', 1, 0, 0, null, '', 2, 0, 'maxwidth500'); - print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + + print '
'; + + if ($conf->browser->layout == 'phone') print '
'; + else print ''; + + if ($conf->browser->layout == 'phone') print '
'; + else print '
'; + + print ''; + + if ($canedit) + { + // Type + print ''; + print ''; + + // Assigned to + print ''; + print ''; + + if ($conf->resource->enabled) + { + 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 ''; + } + + if (!empty($conf->projet->enabled) && $user->rights->projet->lire) + { @@ -119,2 +137,5 @@ - print '
'; - print img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth inline-block"'); + print '
'; + print ''; + } + + if ($canedit && !preg_match('/list/', $_SERVER["PHP_SELF"])) + { @@ -127,2 +149,4 @@ - print '
'; - print img_picto($langs->trans("Status"), 'setup', 'class="pictofixedwidth inline-block"'); + print '
'; + print ''; + } + + if ($canedit && $action == 'show_peruser') + { + // Filter on hours + print ''; + print ''; + print "'; + + // Filter on days + print ''; + print ''; + print "'; @@ -135 +186,0 @@ - $object = null; @@ -138 +189,22 @@ - print '
'; + 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)); @@ -106,5 +88,40 @@ - } - - if (isModEnabled('societe') && $user->hasRight('societe', 'lire')) { - print '
'; - print img_picto($langs->trans("ThirdParty"), 'company', 'class="pictofixedwidth inline-block"'); + 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 $langs->trans("ActionsToDoBy").'   '; + print ''; + print img_picto('', 'user', 'class="fawidth30 inline-block"'); + 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 $form->select_dolgroups($usergroupid, 'usergroup', 1, '', !$canedit, '', '', '0', false, 'maxwidth500'); + 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"'); @@ -112,4 +129,5 @@ - print ''; - } - - if (isModEnabled('projet') && $user->hasRight('projet', 'lire')) { + print '
'; + print $langs->trans("Project").'   '; + print ''; + print img_picto('', 'project', 'class="fawidth30 inline-block"'); @@ -122,4 +143,5 @@ - print ''; - } - - if ($canedit && !preg_match('/list/', $_SERVER["PHP_SELF"])) { + print '
'; + print $langs->trans("Status"); + print '  '; @@ -130 +154,29 @@ - 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 ''; @@ -150 +222 @@ - global $langs, $conf, $user, $db, $socid; + global $langs, $conf, $user, $db, $bc, $socid; @@ -157,5 +229,3 @@ - $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"; @@ -164,12 +234,6 @@ - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; - if (!$user->hasRight('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)."'))"; - if (!$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id); - } - if ($socid) { - $sql .= " AND s.rowid = ".((int) $socid); - } + $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 = ".$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; @@ -180,2 +244,3 @@ - if ($resql) { - $num = $db->num_rows($resql); + if ($resql) + { + $num = $db->num_rows($resql); @@ -184,3 +249,3 @@ - print ''; - print ''; - print ''; + print '
'.$langs->trans("LastActionsToDo", $max).''.$langs->trans("FullList").'
'; + print ''; + print ''; @@ -189 +254,2 @@ - $i = 0; + $var = true; + $i = 0; @@ -192,35 +258,31 @@ - $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 '
'.$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').' '; @@ -228,15 +290,5 @@ - if ($obj->percent == 0 && $datep && $datep < time()) { - $late = 1; - } - if ($obj->percent == 0 && !$datep && $datep2 && $datep2 < time()) { - $late = 1; - } - if ($obj->percent > 0 && $obj->percent < 100 && $datep2 && $datep2 < time()) { - $late = 1; - } - if ($obj->percent > 0 && $obj->percent < 100 && !$datep2 && $datep && $datep < time()) { - $late = 1; - } - if ($late) { - print img_warning($langs->trans("Late")); - } + if ($obj->percent == 0 && $datep && $datep < time()) $late = 1; + if ($obj->percent == 0 && !$datep && $datep2 && $datep2 < time()) $late = 1; + if ($obj->percent > 0 && $obj->percent < 100 && $datep2 && $datep2 < time()) $late = 1; + if ($obj->percent > 0 && $obj->percent < 100 && !$datep2 && $datep && $datep < time()) $late = 1; + if ($late) print img_warning($langs->trans("Late")); @@ -250,7 +302,9 @@ - $i++; - } - print "

"; - - $db->free($resql); - } else { - dol_print_error($db); + $i++; + } + print "
"; + + $db->free($resql); + } + else + { + dol_print_error($db); @@ -269 +323 @@ - global $langs, $conf, $user, $db, $socid; + global $langs, $conf, $user, $db, $bc, $socid; @@ -273,5 +327,3 @@ - $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"; @@ -280,12 +332,6 @@ - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; - if (!$user->hasRight('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)."'))"; - if (!$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id); - } - if ($socid) { - $sql .= " AND s.rowid = ".((int) $socid); - } + $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 = ".$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; @@ -296 +342,2 @@ - if ($resql) { + if ($resql) + { @@ -302 +349 @@ - print ''.$langs->trans("FullList").''; + print ''.$langs->trans("FullList").''; @@ -304 +351 @@ - + $var = true; @@ -307,4 +354,5 @@ - $staticaction = new ActionComm($db); - $customerstatic = new Societe($db); - - while ($i < $num) { + $staticaction = new ActionComm($db); + $customerstatic = new Societe($db); + + while ($i < $num) + { @@ -317 +365 @@ - $staticaction->label = $obj->label; + $staticaction->libelle = $obj->label; @@ -321 +369 @@ - //print ''.dol_trunc($obj->label,24).''; + //print ''.dol_trunc($obj->label,24).''; @@ -324,11 +372,6 @@ - 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, '', 30); + if ($obj->rowid > 0) + { + $customerstatic->id = $obj->rowid; + $customerstatic->name = $obj->sname; + $customerstatic->client = $obj->client; + print $customerstatic->getNomUrl(1, '', 24); @@ -339 +382 @@ - print ''.dol_print_date($db->jdate($obj->da2), 'day'); + print ''.dol_print_date($db->jdate($obj->da2), 'day'); @@ -342,2 +385,2 @@ - // Status - print ''.$staticaction->LibStatut($obj->percent, 3)."\n"; + // Statut + print "".$staticaction->LibStatut($obj->percent, 3)."\n"; @@ -353 +396,3 @@ - } else { + } + else + { @@ -366,5 +411 @@ - global $langs, $conf, $user, $db; - - $extrafields = new ExtraFields($db); - $extrafields->fetch_name_optionals_label('actioncomm'); - + global $langs, $conf, $user; @@ -384,4 +425,7 @@ - $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++; + } @@ -403,4 +446,0 @@ - $nbExtrafields = $extrafields->attributes['actioncomm']['count']; - if ($nbExtrafields > 0) { - $head[$h][1] .= ''.$nbExtrafields.''; - } @@ -434,4 +474,5 @@ - // Tab to link resources - if (isModEnabled('resource')) { - include_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php'; - $resource = new Dolresource($db); + // Tab to link resources + if ($conf->resource->enabled) + { + include_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php'; + $resource = new DolResource($db); @@ -440,2 +481,2 @@ - $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); @@ -443,3 +484 @@ - if ($nbResources > 0) { - $head[$h][1] .= (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') ? ''.($nbResources).'' : ''); - } + if ($nbResources > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbResources).'' : ''); @@ -450,13 +489,11 @@ - // 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] .= (!getDolGlobalString('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++; @@ -485,50 +522,51 @@ - global $langs, $conf, $user; - - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/comm/action/list.php?mode=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?mode=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?mode=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?mode=show_day'.($param ? '&'.$param : ''); - $head[$h][1] = $langs->trans("ViewDay"); - $head[$h][2] = 'cardday'; - $h++; - - //if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) - if (getDolGlobalString('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_19.0.3_ajax.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_ajax.lib.php @@ -28,11 +28,11 @@ - * 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/ajax/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 if 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 @@ -44,4 +44,3 @@ - * @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()) @@ -49,19 +48,11 @@ - 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'); - } - - $htmlnamejquery = str_replace('.', '\\\\.', $htmlname); - - // 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 = ''; @@ -72 +63 @@ - var autoselect = '.((int) $autoselect).'; + var autoselect = '.$autoselect.'; @@ -76 +67 @@ - $("input#search_'.$htmlnamejquery.'").keydown(function(e) { + $("input#search_'.$htmlname.'").keydown(function(e) { @@ -79 +69,0 @@ - if (e.keyCode == 13) { return false; } /* disable "ENTER" key useful for barcode readers */ @@ -81 +71 @@ - $("#'.$htmlnamejquery.'").val(""); + $("#'.$htmlname.'").val(""); @@ -86 +76 @@ - $("input#search_'.$htmlnamejquery.'").keyup(function() { + $("input#search_'.$htmlname.'").keyup(function() { @@ -89,2 +79,2 @@ - $("#search_'.$htmlnamejquery.'").val(""); - $("#'.$htmlnamejquery.'").val("").trigger("change"); + $("#search_'.$htmlname.'").val(""); + $("#'.$htmlname.'").val("").trigger("change"); @@ -121 +111 @@ - $("input#search_'.$htmlnamejquery.'").autocomplete({ + $("input#search_'.$htmlname.'").autocomplete({ @@ -123 +113 @@ - $.get("'.$url.($urloption ? '?'.$urloption : '').'", { "'.str_replace('.', '_', $htmlname).'": request.term }, function(data){ + $.get("'.$url.($urloption ? '?'.$urloption : '').'", { '.$htmlname.': request.term }, function(data){ @@ -128,7 +118,4 @@ - $("#search_'.$htmlnamejquery.'").val(item.value); - $("#'.$htmlnamejquery.'").val(item.key).trigger("change"); - } - var label = ""; - if (item.label != null) { - label = item.label.toString(); - } + $("#search_'.$htmlname.'").val(item.value); + $("#'.$htmlname.'").val(item.key).trigger("change"); + } + var label = item.label.toString(); @@ -147,22 +134,3 @@ - - console.log("Return value from GET to the rest of code"); - return { label: label, - value: item.value, - id: item.key, - disabled: item.disabled, - update: update, - textarea: textarea, - pbq: item.pbq, - type: item.type, - qty: item.qty, - discount: item.discount, - pricebasetype: item.pricebasetype, - price_ht: item.price_ht, - price_ttc: item.price_ttc, - price_unit_ht: item.price_unit_ht, - price_unit_ht_locale: item.price_unit_ht_locale, - description : item.description, - ref_customer: item.ref_customer, - tva_tx: item.tva_tx, - default_vat_code: item.default_vat_code - } + return { label: label, value: item.value, id: item.key, disabled: item.disabled, + update: update, textarea: textarea, + pbq: item.pbq, type: item.type, qty: item.qty, discount: item.discount, pricebasetype: item.pricebasetype, price_ht: item.price_ht, price_ttc: item.price_ttc } @@ -170,2 +137,0 @@ - } else { - console.error("Error: Ajax url '.$url.($urloption ? '?'.$urloption : '').' has returned an empty page. Should be an empty json array."); @@ -172,0 +139 @@ + else console.error("Error: Ajax url '.$url.($urloption ? '?'.$urloption : '').' has returned an empty page. Should be an empty json array."); @@ -176 +143 @@ - minLength: '.((int) $minLength).', + minLength: '.$minLength.', @@ -178 +145 @@ - console.log("We will trigger change on input '.$htmlname.' because of the select definition of autocomplete code for input#search_'.$htmlname.'"); + console.log("Call change on input '.$htmlname.' because of select definition of autocomplete select call on input#search_'.$htmlname.'"); @@ -181 +147,0 @@ - console.log("Propagate before some properties retrieved by ajax into data-xxx properties of #'.$htmlnamejquery.' component"); @@ -183,30 +149,7 @@ - - // For supplier price and customer when price by quantity is off - $("#'.$htmlnamejquery.'").attr("data-up", ui.item.price_ht); - $("#'.$htmlnamejquery.'").attr("data-up-locale", ui.item.price_unit_ht_locale); - $("#'.$htmlnamejquery.'").attr("data-base", ui.item.pricebasetype); - $("#'.$htmlnamejquery.'").attr("data-qty", ui.item.qty); - $("#'.$htmlnamejquery.'").attr("data-discount", ui.item.discount); - $("#'.$htmlnamejquery.'").attr("data-description", ui.item.description); - $("#'.$htmlnamejquery.'").attr("data-ref-customer", ui.item.ref_customer); - $("#'.$htmlnamejquery.'").attr("data-tvatx", ui.item.tva_tx); - $("#'.$htmlnamejquery.'").attr("data-default-vat-code", ui.item.default_vat_code); - '; - if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) { - $script .= ' - // For customer price when PRODUIT_CUSTOMER_PRICES_BY_QTY is on - console.log("PRODUIT_CUSTOMER_PRICES_BY_QTY is on, propagate also prices by quantity into data-pbqxxx properties"); - $("#'.$htmlnamejquery.'").attr("data-pbq", ui.item.pbq); - $("#'.$htmlnamejquery.'").attr("data-pbqup", ui.item.price_ht); - $("#'.$htmlnamejquery.'").attr("data-pbqbase", ui.item.pricebasetype); - $("#'.$htmlnamejquery.'").attr("data-pbqqty", ui.item.qty); - $("#'.$htmlnamejquery.'").attr("data-pbqpercent", ui.item.discount); - '; - } - $script .= ' - // A new value has been selected, we trigger the handlers on #htmlnamejquery - console.log("Trigger changes on #'.$htmlnamejquery.'"); - $("#'.$htmlnamejquery.'").val(ui.item.id).trigger("change"); // Select new value - - // Complementary actions - + $("#'.$htmlname.'").attr("data-pbq", ui.item.pbq); + $("#'.$htmlname.'").attr("data-pbqup", ui.item.price_ht); + $("#'.$htmlname.'").attr("data-pbqbase", ui.item.pricebasetype); + $("#'.$htmlname.'").attr("data-pbqqty", ui.item.qty); + $("#'.$htmlname.'").attr("data-pbqpercent", ui.item.discount); + + $("#'.$htmlname.'").val(ui.item.id).trigger("change"); // Select new value @@ -228 +170,0 @@ - @@ -241 +182,0 @@ - @@ -244 +185 @@ - console.log("Make action update on each ui.item.update (if there is)") + console.log("Make action update on each ui.item.update") @@ -247 +187,0 @@ - console.log("Set value "+value+" into #"+key); @@ -252 +192 @@ - console.log("Make action textarea on each ui.item.textarea (if there is)") + console.log("Make action textarea on each ui.item.textarea") @@ -263,3 +203,3 @@ - console.log("ajax_autocompleter new value selected, we trigger change also on original component so on field #search_'.$htmlname.'"); - - $("#search_'.$htmlnamejquery.'").trigger("change"); // We have changed value of the combo select, we must be sure to trigger all js hook binded on this event. This is required to trigger other javascript change method binded on original field by other code. + console.log("ajax_autocompleter new value selected, we trigger change on original component so field #search_'.$htmlname.'"); + + $("#search_'.$htmlname.'").trigger("change"); // We have changed value of the combo select, we must be sure to trigger all js hook binded on this event. This is required to trigger other javascript change method binded on original field by other code. @@ -288 +228 @@ - * @param array $fields Array of key of fields to autocomplete + * @param string $fields Other fields to autocomplete @@ -406 +346 @@ - $newtitle = dol_textishtml($title) ? dol_string_nohtmltag($title, 1) : $title; + $newtitle = dol_textishtml($title) ?dol_string_nohtmltag($title, 1) : $title; @@ -410 +350 @@ - $msg .= '\n"; - - $msg .= ajax_event($htmlname, $events); - - return $msg; -} - - -/** - * Add event management script. - * - * @param string $htmlname Name of html select field ('myid' or '.myclass') - * @param array $events Add some Ajax events option on change of $htmlname component to call ajax to autofill a HTML element (select#htmlname and #inputautocompletehtmlname) - * Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @return string Return JS string to manage event - */ -function ajax_event($htmlname, $events) -{ - $out = ''; - - if (is_array($events) && count($events)) { // If an array of js events to do were provided. - $out = ' - '; + }'; @@ -607 +478,4 @@ - return $out; + $msg .= '});'."\n"; + $msg .= "\n"; + + return $msg; @@ -609 +482,0 @@ - @@ -615,3 +488,3 @@ - * @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 int $revertonoff 1=Revert on/off + * @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 @@ -620,6 +493 @@ - * @param string $marginleftonlyshort 1 = Add a short left margin on picto, 2 = Add a larger left margin on picto, 0 = No left margin. - * @param int $forcenoajax 1 = Force to use a ahref link instead of ajax code. - * @param int $setzeroinsteadofdel 1 = Set constantto '0' instead of deleting it - * @param string $suffix Suffix to use on the name of the switch_on picto. Example: '', '_red' - * @param string $mode Add parameter &mode= to the href link (Used for href link) - * @param string $morecss More CSS + * @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. @@ -628 +496 @@ -function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2, $forcenoajax = 0, $setzeroinsteadofdel = 0, $suffix = '', $mode = '', $morecss = 'inline-block') +function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2) @@ -633,2 +501,6 @@ - if (!isset($input)) { - $input = array(); + 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').''; @@ -636,8 +508,2 @@ - - if (empty($conf->use_javascript_ajax) || $forcenoajax) { - if (empty($conf->global->$code)) { - $out = ''.img_picto($langs->trans("Disabled"), 'off').''; - } else { - $out = ''.img_picto($langs->trans("Enabled"), 'on').''; - } - } else { + else + { @@ -649,7 +515,6 @@ - var code = \''.dol_escape_js($code).'\'; - var entity = \''.dol_escape_js($entity).'\'; - var strict = \''.dol_escape_js($strict).'\'; - var userid = \''.dol_escape_js($user->id).'\'; - var yesButton = \''.dol_escape_js($langs->transnoentities("Yes")).'\'; - var noButton = \''.dol_escape_js($langs->transnoentities("No")).'\'; - var token = \''.currentToken().'\'; + var code = \''.$code.'\'; + var entity = \''.$entity.'\'; + var strict = \''.$strict.'\'; + var userid = \''.$user->id.'\'; + var yesButton = "'.dol_escape_js($langs->transnoentities("Yes")).'"; + var noButton = "'.dol_escape_js($langs->transnoentities("No")).'"; @@ -662 +527 @@ - confirmConstantAction("set", url, code, input, input.alert.set, entity, yesButton, noButton, strict, userid, token); + confirmConstantAction("set", url, code, input, input.alert.set, entity, yesButton, noButton, strict, userid); @@ -664 +529 @@ - setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token); + setConstant(url, code, input, entity, 0, '.$forcereload.', userid); @@ -673,8 +538,4 @@ - confirmConstantAction("del", url, code, input, input.alert.del, entity, yesButton, noButton, strict, userid, token); - } else {'; - if (empty($setzeroinsteadofdel)) { - $out .=' delConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token);'; - } else { - $out .=' setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token, 0);'; - } - $out .= ' } + confirmConstantAction("del", url, code, input, input.alert.del, entity, yesButton, noButton, strict, userid); + } else { + delConstant(url, code, input, entity, 0, '.$forcereload.', userid); + } @@ -686,2 +547,2 @@ - $out .= ''.($revertonoff ? img_picto($langs->trans("Enabled"), 'switch_on', '', false, 0, 0, '', '', $marginleftonlyshort) : img_picto($langs->trans("Disabled"), 'switch_off', '', false, 0, 0, '', '', $marginleftonlyshort)).''; - $out .= ''.($revertonoff ? img_picto($langs->trans("Disabled"), 'switch_off'.$suffix, '', false, 0, 0, '', '', $marginleftonlyshort) : img_picto($langs->trans("Enabled"), 'switch_on'.$suffix, '', false, 0, 0, '', '', $marginleftonlyshort)).''; + $out .= ''.($revertonoff ?img_picto($langs->trans("Enabled"), 'switch_on', '', false, 0, 0, '', '', $marginleftonlyshort) : img_picto($langs->trans("Disabled"), 'switch_off', '', false, 0, 0, '', '', $marginleftonlyshort)).''; + $out .= ''.($revertonoff ?img_picto($langs->trans("Disabled"), 'switch_off', '', false, 0, 0, '', '', $marginleftonlyshort) : img_picto($langs->trans("Enabled"), 'switch_on', '', false, 0, 0, '', '', $marginleftonlyshort)).''; @@ -695,2 +556,2 @@ - * On/off button to change a property status of an object - * This uses the ajax service objectonoff.php (May be called when MAIN_DIRECT_STATUS_UPDATE is set for some pages) + * On/off button to change status of an object + * This is called when MAIN_DIRECT_STATUS_UPDATE is set and it use tha ajax service objectonoff.php @@ -699 +560 @@ - * @param string $code Name of property in object : 'status' or 'status_buy' for product by example + * @param string $code Name of constant : status or status_buy for product by example @@ -701,2 +562,2 @@ - * @param string $text_on Text if on ('Text' or 'Text:Picto on:Css picto on') - * @param string $text_off Text if off ('Text' or 'Text:Picto off:Css picto off') + * @param string $text_on Text if on + * @param string $text_off Text if off @@ -704,3 +564,0 @@ - * @param string $morecss More CSS - * @param string $htmlname Name of HTML component. Keep '' or use a different value if you need to use this component several time on the same page for the same field. - * @param int $forcenojs Force the component to work as link post (without javascript) instead of ajax call @@ -709 +567 @@ -function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input = array(), $morecss = '', $htmlname = '', $forcenojs = 0) +function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input = array()) @@ -711,11 +569,3 @@ - global $conf, $langs; - - if (empty($htmlname)) { - $htmlname = $code; - } - //var_dump($object->module); var_dump($object->element); - - $out = ''; - - if (!empty($conf->use_javascript_ajax)) { - $out .= '\n"; - return $out; -} --- /tmp/dsg/dolibarr/htdocs/core/lib/github_19.0.3_fiscalyear.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_fiscalyear.lib.php @@ -44,2 +44,2 @@ - // $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 --- /tmp/dsg/dolibarr/htdocs/core/lib/github_19.0.3_format_cards.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_format_cards.lib.php @@ -37,21 +37,25 @@ -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); +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); @@ -61 +65,2 @@ -foreach ($_Avery_Labels as $key => $val) { +foreach ($_Avery_Labels as $key => $val) +{ --- /tmp/dsg/dolibarr/htdocs/core/lib/github_19.0.3_fourn.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_fourn.lib.php @@ -6,2 +5,0 @@ - * Copyright (C) 2022-2023 Frédéric France - * Copyright (C) 2023 Nick Fragoulis @@ -33 +31 @@ - * @param FactureFournisseur $object Object related to tabs + * @param Object $object Object related to tabs @@ -36 +34 @@ -function facturefourn_prepare_head(FactureFournisseur $object) +function facturefourn_prepare_head($object) @@ -44 +42 @@ - $head[$h][1] = $langs->trans('SupplierInvoice'); + $head[$h][1] = $langs->trans('Card'); @@ -48,3 +46,4 @@ - if (!getDolGlobalString('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; + 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; @@ -52,3 +51 @@ - if ($nbContact > 0) { - $head[$h][1] .= ''.$nbContact.''; - } + if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; @@ -60 +57,2 @@ - if (isModEnabled('paymentbybanktransfer')) { + if (!empty($conf->paymentbybanktransfer->enabled)) + { @@ -63,3 +61,3 @@ - $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as pfd"; - $sql .= " WHERE pfd.fk_facture_fourn = ".((int) $object->id); - $sql .= " AND type = 'ban'"; + $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + $sql .= " WHERE pfd.fk_facture_fourn = ".$object->id; + $sql .= " AND pfd.ext_payment_id IS NULL"; @@ -67 +65,2 @@ - if ($resql) { + if ($resql) + { @@ -69,5 +68 @@ - if ($obj) { - $nbStandingOrders = $obj->nb; - } - } else { - dol_print_error($db); + if ($obj) $nbStandingOrders = $obj->nb; @@ -75 +70 @@ - $langs->load("banks"); + else dol_print_error($db); @@ -78,3 +73 @@ - if ($nbStandingOrders > 0) { - $head[$h][1] .= ''.$nbStandingOrders.''; - } + if ($nbStandingOrders > 0) $head[$h][1] .= ''.$nbStandingOrders.''; @@ -85,22 +78,17 @@ - // 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', 'add', 'core'); - - if (!getDolGlobalString('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'); - if ($nbNote > 0) { - $head[$h][1] .= ''.$nbNote.''; - } - $head[$h][2] = 'note'; - $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++; + 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'); + if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + $head[$h][2] = 'note'; + $h++; + } @@ -109 +97 @@ - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; @@ -112 +100 @@ - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); @@ -115,3 +103 @@ - if (($nbFiles + $nbLinks) > 0) { - $head[$h][1] .= ''.($nbFiles + $nbLinks).''; - } + if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; @@ -126,5 +112,3 @@ - complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice', 'add', 'external'); - - 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; @@ -137,4 +121,4 @@ - * @param CommandeFournisseur $object Object related to tabs - * @return array Array of tabs to show - */ -function ordersupplier_prepare_head(CommandeFournisseur $object) + * @param Object $object Object related to tabs + * @return array Array of tabs to show + */ +function ordersupplier_prepare_head($object) @@ -148 +132 @@ - $head[$h][1] = $langs->trans("SupplierOrder"); + $head[$h][1] = $langs->trans("OrderCard"); @@ -152,3 +136,4 @@ - if (!getDolGlobalString('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; + 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; @@ -156,3 +141 @@ - if ($nbContact > 0) { - $head[$h][1] .= ''.$nbContact.''; - } + if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; @@ -163 +146,2 @@ - if (isModEnabled('stock') && (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER') || getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION') || getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION_CLOSE'))) { + if (!empty($conf->stock->enabled) && (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE))) + { @@ -167,25 +150,0 @@ - - //If dispach process running we add the number of item to dispatch into the head - if (in_array($object->statut, array($object::STATUS_ORDERSENT, $object::STATUS_RECEIVED_PARTIALLY, $object::STATUS_RECEIVED_COMPLETELY))) { - $sumQtyAllreadyDispatched = 0; - $sumQtyOrdered = 0; - - if (empty($object->lines)) { - $object->fetch_lines(); - } - $nbLinesOrdered = count($object->lines); - $dispachedLines = $object->getDispachedLines(1); - $nbDispachedLines = count($dispachedLines); - - for ($line = 0 ; $line < $nbDispachedLines; $line++) { - $sumQtyAllreadyDispatched = $sumQtyAllreadyDispatched + $dispachedLines[$line]['qty']; - } - for ($line = 0 ; $line < $nbLinesOrdered; $line++) { - //If line is a product of conf to manage stocks for services - if ($object->lines[$line]->product_type == 0 || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) { - $sumQtyOrdered = $sumQtyOrdered + $object->lines[$line]->qty; - } - } - $head[$h][1] .= ''.price2num($sumQtyAllreadyDispatched, 'MS').' / '.price2num($sumQtyOrdered, 'MS').''; - } - @@ -197,21 +156,16 @@ - // 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', 'add', 'core'); - - if (!getDolGlobalString('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"); - if ($nbNote > 0) { - $head[$h][1] .= ''.$nbNote.''; - } - $head[$h][2] = 'note'; - $h++; - } + // 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"); + if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + $head[$h][2] = 'note'; + $h++; + } @@ -220 +174 @@ - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; @@ -223 +177 @@ - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); @@ -226,3 +180 @@ - if (($nbFiles + $nbLinks) > 0) { - $head[$h][1] .= ''.($nbFiles + $nbLinks).''; - } + if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; @@ -233,4 +185,5 @@ - $head[$h][1] = $langs->trans("Events"); - if (isModEnabled('agenda') && ($user->hasRight('agenda', 'myactions', 'read') || $user->hasRight('agenda', 'allactions', 'read'))) { - $head[$h][1] .= '/'; - $head[$h][1] .= $langs->trans("Agenda"); + $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"); @@ -240,3 +192,0 @@ - - complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_order', 'add', 'external'); - @@ -244 +193,0 @@ - @@ -255,9 +204 @@ - global $langs, $conf, $user, $db; - - $extrafields = new ExtraFields($db); - $extrafields->fetch_name_optionals_label('commande_fournisseur'); - $extrafields->fetch_name_optionals_label('commande_fournisseurdet'); - $extrafields->fetch_name_optionals_label('facture_fourn'); - $extrafields->fetch_name_optionals_label('facture_fourn_det'); - $extrafields->fetch_name_optionals_label('facture_fourn_rec'); - $extrafields->fetch_name_optionals_label('facture_fourn_det_rec'); + global $langs, $conf, $user; @@ -287,4 +227,0 @@ - $nbExtrafields = $extrafields->attributes['commande_fournisseur']['count']; - if ($nbExtrafields > 0) { - $head[$h][1] .= ''.$nbExtrafields.''; - } @@ -296,4 +232,0 @@ - $nbExtrafields = $extrafields->attributes['commande_fournisseurdet']['count']; - if ($nbExtrafields > 0) { - $head[$h][1] .= ''.$nbExtrafields.''; - } @@ -305,4 +237,0 @@ - $nbExtrafields = $extrafields->attributes['facture_fourn']['count']; - if ($nbExtrafields > 0) { - $head[$h][1] .= ''.$nbExtrafields.''; - } @@ -314,4 +242,0 @@ - $nbExtrafields = $extrafields->attributes['facture_fourn_det']['count']; - if ($nbExtrafields > 0) { - $head[$h][1] .= ''.$nbExtrafields.''; - } @@ -319,18 +243,0 @@ - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/admin/supplierinvoice_rec_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsSupplierInvoicesRec"); - $nbExtrafields = $extrafields->attributes['facture_fourn_rec']['count']; - if ($nbExtrafields > 0) { - $head[$h][1] .= ''.$nbExtrafields.''; - } - $head[$h][2] = 'attributesrec'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/admin/supplierinvoicedet_rec_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsSupplierInvoicesLinesRec"); - $nbExtrafields = $extrafields->attributes['facture_fourn_det_rec']['count']; - if ($nbExtrafields > 0) { - $head[$h][1] .= ''.$nbExtrafields.''; - } - $head[$h][2] = 'attributeslinesrec'; --- /tmp/dsg/dolibarr/htdocs/core/lib/github_19.0.3_functions.lib.php +++ /tmp/dsg/dolibarr/htdocs/core/lib/client_functions.lib.php @@ -4 +4 @@ - * Copyright (C) 2004-2022 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur @@ -12 +12 @@ - * Copyright (C) 2013-2021 Alexandre Spangaro + * Copyright (C) 2013-2017 Alexandre Spangaro @@ -16,8 +16,2 @@ - * Copyright (C) 2018-2023 Frédéric France - * Copyright (C) 2019-2023 Thibault Foucart - * Copyright (C) 2020 Open-Dsi - * Copyright (C) 2021 Gauthier VERDOL - * Copyright (C) 2022 Anthony Berton - * Copyright (C) 2022 Ferran Marcet - * Copyright (C) 2022 Charlene Benke - * Copyright (C) 2023 Joachim Kueter + * Copyright (C) 2018-2020 Frédéric France + * Copyright (C) 2019 Thibault Foucart @@ -48,188 +41,0 @@ -// Function for better PHP x compatibility -if (!function_exists('utf8_encode')) { - /** - * Implement utf8_encode for PHP that does not support it. - * - * @param mixed $elements PHP Object to json encode - * @return string Json encoded string - */ - function utf8_encode($elements) - { - return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1'); - } -} - -if (!function_exists('utf8_decode')) { - /** - * Implement utf8_decode for PHP that does not support it. - * - * @param mixed $elements PHP Object to json encode - * @return string Json encoded string - */ - function utf8_decode($elements) - { - return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8'); - } -} -if (!function_exists('str_starts_with')) { - /** - * str_starts_with - * - * @param string $haystack haystack - * @param string $needle needle - * @return boolean - */ - function str_starts_with($haystack, $needle) - { - return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0; - } -} -if (!function_exists('str_ends_with')) { - /** - * str_ends_with - * - * @param string $haystack haystack - * @param string $needle needle - * @return boolean - */ - function str_ends_with($haystack, $needle) - { - return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle; - } -} -if (!function_exists('str_contains')) { - /** - * str_contains - * - * @param string $haystack haystack - * @param string $needle needle - * @return boolean - */ - function str_contains($haystack, $needle) - { - return $needle !== '' && mb_strpos($haystack, $needle) !== false; - } -} - - -/** - * Return the full path of the directory where a module (or an object of a module) stores its files. Path may depends on the entity if a multicompany module is enabled. - * - * @param CommonObject $object Dolibarr common object - * @param string $module Override object element, for example to use 'mycompany' instead of 'societe' - * @return string|void The path of the relative directory of the module - * @since Dolibarr V18 - */ -function getMultidirOutput($object, $module = '') -{ - global $conf; - - if (!is_object($object) && empty($module)) { - return null; - } - if (empty($module) && !empty($object->element)) { - $module = $object->element; - } - // Special case for backward compatibility - if ($module == 'fichinter') { - $module = 'ficheinter'; - } - if (isset($conf->$module) && property_exists($conf->$module, 'multidir_output')) { - return $conf->$module->multidir_output[(empty($object->entity) ? $conf->entity : $object->entity)]; - } else { - return 'error-diroutput-not-defined-for-this-object='.$module; - } -} - -/** - * Return dolibarr global constant string value - * - * @param string $key key to return value, return '' if not set - * @param string $default value to return - * @return string - */ -function getDolGlobalString($key, $default = '') -{ - global $conf; - return (string) (isset($conf->global->$key) ? $conf->global->$key : $default); -} - -/** - * Return a Dolibarr global constant int value. - * The constants $conf->global->xxx are loaded by the script master.inc.php included at begin of any PHP page. - * - * @param string $key key to return value, return 0 if not set - * @param int $default value to return - * @return int - */ -function getDolGlobalInt($key, $default = 0) -{ - global $conf; - return (int) (isset($conf->global->$key) ? $conf->global->$key : $default); -} - -/** - * Return Dolibarr user constant string value - * - * @param string $key key to return value, return '' if not set - * @param string $default value to return - * @param User $tmpuser To get another user than current user - * @return string - */ -function getDolUserString($key, $default = '', $tmpuser = null) -{ - if (empty($tmpuser)) { - global $user; - $tmpuser = $user; - } - - return (string) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key); -} - -/** - * Return Dolibarr user constant int value - * - * @param string $key key to return value, return 0 if not set - * @param int $default value to return - * @param User $tmpuser To get another user than current user - * @return int - */ -function getDolUserInt($key, $default = 0, $tmpuser = null) -{ - if (empty($tmpuser)) { - global $user; - $tmpuser = $user; - } - - return (int) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key); -} - -/** - * Is Dolibarr module enabled - * - * @param string $module Module name to check - * @return boolean True if module is enabled - */ -function isModEnabled($module) -{ - global $conf; - - // Fix special cases - $arrayconv = array( - 'bank' => 'banque', - 'category' => 'categorie', - 'contract' => 'contrat', - 'project' => 'projet', - 'delivery_note' => 'expedition' - ); - if (!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) { - $arrayconv['supplier_order'] = 'fournisseur'; - $arrayconv['supplier_invoice'] = 'fournisseur'; - } - if (!empty($arrayconv[$module])) { - $module = $arrayconv[$module]; - } - - return !empty($conf->modules[$module]); - //return !empty($conf->$module->enabled); -} @@ -276,26 +82,8 @@ - global $conf, $mc, $hookmanager, $object, $action, $db; - - if (!is_object($hookmanager)) { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager = new HookManager($db); - } - - // fix different element names (France to English) - switch ($element) { - case 'projet': - $element = 'project'; - break; - case 'contrat': - $element = 'contract'; - break; // "/contrat/class/contrat.class.php" - case 'order_supplier': - $element = 'supplier_order'; - break; // "/fourn/class/fournisseur.commande.class.php" - case 'invoice_supplier': - $element = 'supplier_invoice'; - break; // "/fourn/class/fournisseur.facture.class.php" - } - - if (is_object($mc)) { - $out = $mc->getEntity($element, $shared, $currentobject); - } else { + global $conf, $mc; + + if (is_object($mc)) + { + return $mc->getEntity($element, $shared, $currentobject); + } + else + { @@ -303,26 +91,5 @@ - $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans'); - if (in_array($element, $addzero)) { - $out .= '0,'; - } - $out .= ((int) $conf->entity); - } - - // Manipulate entities to query on the fly - $parameters = array( - 'element' => $element, - 'shared' => $shared, - 'object' => $object, - 'currentobject' => $currentobject, - 'out' => $out - ); - $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks - - if (is_numeric($reshook)) { - if ($reshook == 0 && !empty($hookmanager->resPrint)) { - $out .= ','.$hookmanager->resPrint; // add - } elseif ($reshook == 1) { - $out = $hookmanager->resPrint; // replace - } - } - - return $out; + $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values'); + if (in_array($element, $addzero)) $out .= '0,'; + $out .= $conf->entity; + return $out; + } @@ -341 +108,2 @@ - if (is_object($mc) && method_exists($mc, 'setEntity')) { + if (is_object($mc) && method_exists($mc, 'setEntity')) + { @@ -343 +111,3 @@ - } else { + } + else + { @@ -347,27 +116,0 @@ - -/** - * 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); -} - - -/** - * Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA' - * - * @param int|string $n Numeric value - * @return string Column in Excel format - */ -function num2Alpha($n) -{ - for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) { - $r = chr($n % 26 + 0x41) . $r; - } - return $r; -} - @@ -399,2 +141,0 @@ - - $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent @@ -430,7 +171,3 @@ - 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'; } @@ -439,36 +176,11 @@ - $reg = array(); - if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { - $name = 'firefox'; - $version = empty($reg[2]) ? '' : $reg[2]; - } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { - $name = 'edge'; - $version = empty($reg[2]) ? '' : $reg[2]; - } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) { - $name = 'chrome'; - $version = empty($reg[2]) ? '' : $reg[2]; - } elseif (preg_match('/chrome/i', $user_agent, $reg)) { - // we can have 'chrome (Mozilla...) chrome x.y' in one string - $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 = empty($reg[2]) ? '' : $reg[2]; - } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { - // Safari is often present in string for mobile but its not. - $name = 'opera'; - $version = empty($reg[2]) ? '' : $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); - } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { - // MS products at end - $name = 'ie'; - $version = end($reg); - } elseif (preg_match('/l[iy]n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { - // MS products at end - $name = 'lynxlinks'; - $version = empty($reg[3]) ? '' : $reg[3]; - } + 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]; } @@ -488,4 +200,3 @@ - 'browserua' => $user_agent, - 'layout' => $layout, // tablet, phone, classic - 'phone' => $phone, // deprecated - 'tablet' => $tablet // deprecated + 'layout' => $layout, + 'phone' => $phone, + 'tablet' => $tablet @@ -502,15 +213,8 @@ - global $db; - $disconnectdone = false; - $depth = 0; - if (is_object($db) && !empty($db->connected)) { - $depth = $db->transaction_opened; - $disconnectdone = $db->close(); - } - dol_syslog("--- End access to ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]).(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO)); -} - -/** - * Return true if we are in a context of submitting the parameter $paramname from a POST of a form. - * Warning: - * For action=add, use: $var = GETPOST('var'); // No GETPOSTISSET, so GETPOST always called and default value is retreived if not a form POST, and value of form is retreived if it is a form POST. - * For action=update, use: $var = GETPOSTISSET('var') ? GETPOST('var') : $object->var; + global $conf, $user, $langs, $db; + $disconnectdone = false; $depth = 0; + if (is_object($db) && !empty($db->connected)) { $depth = $db->transaction_opened; $disconnectdone = $db->close(); } + dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO)); +} + +/** + * Return true if we are in a context of submitting a parameter @@ -523 +227 @@ - $isset = false; + $isset = 0; @@ -527,3 +231 @@ - if (constant('DOL_URL_ROOT')) { - $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); - } + if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); @@ -537,2 +239,4 @@ - if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST - if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values + if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST + { + if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values + { @@ -540,4 +244,7 @@ - if (is_array($tmp)) { - foreach ($tmp as $key => $val) { - if ($key == $paramname) { // We are on the requested parameter - $isset = true; + if (is_array($tmp)) + { + foreach ($tmp as $key => $val) + { + if ($key == $paramname) // We are on the requested parameter + { + $isset = 1; @@ -549,12 +256,16 @@ - // If there is saved contextpage, limit, page or mode - if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) { - $isset = true; - } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) { - $isset = true; - } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) { - $isset = true; - } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) { - $isset = true; - } - } else { - $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here + // If there is saved contextpage, page or limit + if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) + { + $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])); @@ -567,26 +277,0 @@ - * Return true if the parameter $paramname is submit from a POST OR GET as an array. - * Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string - * - * @param string $paramname Name or parameter to test - * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get) - * @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty) - */ -function GETPOSTISARRAY($paramname, $method = 0) -{ - // for $method test need return the same $val as GETPOST - if (empty($method)) { - $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : ''); - } elseif ($method == 1) { - $val = isset($_GET[$paramname]) ? $_GET[$paramname] : ''; - } elseif ($method == 2) { - $val = isset($_POST[$paramname]) ? $_POST[$paramname] : ''; - } elseif ($method == 3) { - $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : ''); - } else { - $val = 'BadFirstParameterForGETPOST'; - } - - return is_array($val); -} - -/** @@ -594 +279 @@ - * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder'] + * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder'] @@ -600,2 +285 @@ - * 'none'=no check (only for param that should have very rich content like passwords) - * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array + * 'none'=no check (only for param that should have very rich content) @@ -604,3 +288 @@ - * 'alpha'=Same than alphanohtml since v13 - * 'alphawithlgt'=alpha with lgt - * 'alphanohtml'=check there is no html content and no " and no ../ + * 'alpha'=check it's text and sign @@ -609,2 +291 @@ - * 'aZ09arobase'=check it's a string for an element type - * 'aZ09comma'=check it's a string for a sortfield or sortorder + * 'array'=check it's array @@ -612 +293 @@ - * 'nohtml'=check there is no html content + * 'nohtml', 'alphanohtml'=check there is no html content @@ -625,5 +306,4 @@ - if (empty($paramname)) { - return 'BadFirstParameterForGETPOST'; - } - if (empty($check)) { - dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and a 2nd param that is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING); + if (empty($paramname)) return 'BadFirstParameterForGETPOST'; + if (empty($check)) + { + dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING); @@ -634,14 +314,9 @@ - if (empty($method)) { - $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : ''); - } elseif ($method == 1) { - $out = isset($_GET[$paramname]) ? $_GET[$paramname] : ''; - } elseif ($method == 2) { - $out = isset($_POST[$paramname]) ? $_POST[$paramname] : ''; - } elseif ($method == 3) { - $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : ''); - } else { - return 'BadThirdParameterForGETPOST'; - } - - if (empty($method) || $method == 3 || $method == 4) { - $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]); + if (empty($method)) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : ''); + elseif ($method == 1) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : ''; + elseif ($method == 2) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : ''; + elseif ($method == 3) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : ''); + else return 'BadThirdParameterForGETPOST'; + + if (empty($method) || $method == 3 || $method == 4) + { + $relativepathstring = $_SERVER["PHP_SELF"]; @@ -649,3 +324 @@ - if (constant('DOL_URL_ROOT')) { - $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); - } + if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); @@ -658,3 +331,5 @@ - // Retrieve saved values if restore_lastsearch_values is set - if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST - if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values + // Retrieve values if restore_lastsearch_values + if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST + { + if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values + { @@ -662,3 +337,6 @@ - if (is_array($tmp)) { - foreach ($tmp as $key => $val) { - if ($key == $paramname) { // We are on the requested parameter + if (is_array($tmp)) + { + foreach ($tmp as $key => $val) + { + if ($key == $paramname) // We are on the requested parameter + { @@ -672 +350,2 @@ - if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) { + if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) + { @@ -674 +353,7 @@ - } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) { + } + elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) + { + $out = $_SESSION['lastsearch_page_'.$relativepathstring]; + } + elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) + { @@ -676,9 +361,7 @@ - } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) { - $out = $_SESSION['lastsearch_page_'.$relativepathstring]; - } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) { - $out = $_SESSION['lastsearch_mode_'.$relativepathstring]; - } - } elseif (!isset($_GET['sortfield'])) { - // Else, retrieve default values if we are not doing a sort - // 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])) { + } + } + // 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])) + { @@ -687 +370,2 @@ - if (is_object($object) && isset($object->fields[$paramname]['default'])) { + if (is_object($object) && isset($object->fields[$paramname]['default'])) + { @@ -691,2 +375,4 @@ - if (getDolGlobalString('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($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])) + { @@ -694,3 +380,6 @@ - if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values' - if (isset($user->default_values[$relativepathstring]['createform'])) { - foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) { + if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' + { + if (isset($user->default_values[$relativepathstring]['createform'])) + { + foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) + { @@ -698 +387,2 @@ - if ($defkey != '_noquery_') { + if ($defkey != '_noquery_') + { @@ -702,4 +392,3 @@ - foreach ($tmpqueryarraytohave as $tmpquerytohave) { - if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) { - $foundintru = 1; - } + foreach ($tmpqueryarraytohave as $tmpquerytohave) + { + if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1; @@ -707,3 +396 @@ - if (!$foundintru) { - $qualified = 1; - } + if (!$foundintru) $qualified = 1; @@ -711,2 +397,0 @@ - } else { - $qualified = 1; @@ -714,3 +399,7 @@ - - if ($qualified) { - if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) { + else $qualified = 1; + + if ($qualified) + { + //var_dump($user->default_values[$relativepathstring][$defkey]['createform']); + if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) + { @@ -724,4 +413,7 @@ - } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) { - // Management of default search_filters and sort order - if (!empty($user->default_values)) { - // $user->default_values defined from menu 'Setup - Default values' + } + // 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' + { @@ -729,5 +421,6 @@ - if ($paramname == 'sortfield' || $paramname == 'sortorder') { - // Sorted on which fields ? ASC or DESC ? - if (isset($user->default_values[$relativepathstring]['sortorder'])) { - // Even if paramname is sortfield, data are stored into ['sortorder...'] - foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) { + if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ? + { + if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...'] + { + foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) + { @@ -735 +428,2 @@ - if ($defkey != '_noquery_') { + if ($defkey != '_noquery_') + { @@ -739,4 +433,3 @@ - foreach ($tmpqueryarraytohave as $tmpquerytohave) { - if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) { - $foundintru = 1; - } + foreach ($tmpqueryarraytohave as $tmpquerytohave) + { + if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1; @@ -744,3 +437 @@ - if (!$foundintru) { - $qualified = 1; - } + if (!$foundintru) $qualified = 1; @@ -748,2 +438,0 @@ - } else { - $qualified = 1; @@ -751,2 +440,4 @@ - - if ($qualified) { + else $qualified = 1; + + if ($qualified) + { @@ -754,5 +445,5 @@ - foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) { - if ($out) { - $out .= ', '; - } - if ($paramname == 'sortfield') { + foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) + { + if ($out) $out .= ', '; + if ($paramname == 'sortfield') + { @@ -761 +452,2 @@ - if ($paramname == 'sortorder') { + if ($paramname == 'sortorder') + { @@ -769,5 +461,5 @@ - } 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 - if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter - continue; - } + } + 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 + { @@ -775 +467,2 @@ - if ($defkey != '_noquery_') { + if ($defkey != '_noquery_') + { @@ -779,4 +472,3 @@ - foreach ($tmpqueryarraytohave as $tmpquerytohave) { - if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) { - $foundintru = 1; - } + foreach ($tmpqueryarraytohave as $tmpquerytohave) + { + if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1; @@ -784,3 +476 @@ - if (!$foundintru) { - $qualified = 1; - } + if (!$foundintru) $qualified = 1; @@ -788,2 +477,0 @@ - } else { - $qualified = 1; @@ -791,4 +479,6 @@ - - if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) { - // We must keep $_POST and $_GET here - if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) { + else $qualified = 1; + + if ($qualified) + { + if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) + { @@ -796 +486,2 @@ - if (!getDolGlobalString('MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH')) { + if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) + { @@ -800 +491,3 @@ - } else { + } + else + { @@ -814 +507 @@ - // Substitution variables for GETPOST (used to get final url with variable parameters or final default value, when using variable parameters __XXX__ in the GET URL) + // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters) @@ -817 +510,2 @@ - if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) { + if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) + { @@ -819,38 +513,16 @@ - $maxloop = 20; - $loopnb = 0; // Protection against infinite loop - while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) { // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side. - $loopnb++; - $newout = ''; - - if ($reg[1] == 'DAY') { - $tmp = dol_getdate(dol_now(), true); - $newout = $tmp['mday']; - } elseif ($reg[1] == 'MONTH') { - $tmp = dol_getdate(dol_now(), true); - $newout = $tmp['mon']; - } elseif ($reg[1] == 'YEAR') { - $tmp = dol_getdate(dol_now(), true); - $newout = $tmp['year']; - } elseif ($reg[1] == 'PREVIOUS_DAY') { - $tmp = dol_getdate(dol_now(), true); - $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); - $newout = $tmp2['day']; - } elseif ($reg[1] == 'PREVIOUS_MONTH') { - $tmp = dol_getdate(dol_now(), true); - $tmp2 = dol_get_prev_month($tmp['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') { + $maxloop = 20; $loopnb = 0; // Protection against infinite loop + while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side. + { + $loopnb++; $newout = ''; + + if ($reg[1] == 'DAY') { $tmp = dol_getdate(dol_now(), true); $newout = $tmp['mday']; } + elseif ($reg[1] == 'MONTH') { $tmp = dol_getdate(dol_now(), true); $newout = $tmp['mon']; } + elseif ($reg[1] == 'YEAR') { $tmp = dol_getdate(dol_now(), true); $newout = $tmp['year']; } + elseif ($reg[1] == 'PREVIOUS_DAY') { $tmp = dol_getdate(dol_now(), true); $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } + elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp = dol_getdate(dol_now(), true); $tmp2 = dol_get_prev_month($tmp['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') + { @@ -858 +530,3 @@ - } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') { + } + elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') + { @@ -860 +534,3 @@ - } 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') + { @@ -862 +538,3 @@ - } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') { + } + elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') + { @@ -864,3 +542,2 @@ - } else { - $newout = ''; // Key not found, we replace with empty string - } + } + else $newout = ''; // Key not found, we replace with empty string @@ -872,99 +548,0 @@ - // Check type of variable and make sanitization according to this - if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma' - 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] = sanitizeVal($outval, $tmpcheck, $filter, $options); - } - } - } else { - // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means - // we use the < or > to make a search on a numeric value to do higher or lower so we can add a space to break html tags - if (strpos($paramname, 'search_') === 0) { - $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out); - } - - $out = sanitizeVal($out, $check, $filter, $options); - } - - // Sanitizing for special parameters. - // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed. - if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') { - $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements. - $out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retreive it after other replacements. - do { - $oldstringtoclean = $out; - $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out); - $out = preg_replace(array('/^[^\?]*%/'), '', $out); // We remove any % chars before the ?. Example in url: '/product/stock/card.php?action=create&backtopage=%2Fdolibarr_dev%2Fhtdocs%2Fpro%25duct%2Fcard.php%3Fid%3Dabc' - $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL - } while ($oldstringtoclean != $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 != '' && isset($user)) {// $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) - * @return int Value found (int) - */ -function GETPOSTINT($paramname, $method = 0) -{ - return (int) GETPOST($paramname, 'int', $method, null, null, 0); -} - - -/** - * Return a sanitized or empty value after checking value against a rule. - * - * @deprecated - * @param string|array $out Value to check/clear. - * @param string $check Type of check/sanitizing - * @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 sanitized (string or array). It may be '' if format check fails. - */ -function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null) -{ - return sanitizeVal($out, $check, $filter, $options); -} - -/** - * Return a sanitized or empty value after checking value against a rule. - * - * @param string|array $out Value to check/clear. - * @param string $check Type of check/sanitizing - * @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 sanitized (string or array). It may be '' if format check fails. - */ -function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null) -{ - // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize @@ -972 +550,2 @@ - switch ($check) { + switch ($check) + { @@ -976,3 +555 @@ - if (!is_numeric($out)) { - $out = ''; - } + if (!is_numeric($out)) { $out = ''; } @@ -981,5 +558,8 @@ - if (is_array($out)) { - $out = implode(',', $out); - } - if (preg_match('/[^0-9,-]+/i', $out)) { - $out = ''; + 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)); @@ -991,3 +570,0 @@ - case 'email': - $out = filter_var($out, FILTER_SANITIZE_EMAIL); - break; @@ -995 +572,2 @@ - if (!is_array($out)) { + if (!is_array($out)) + { @@ -997,3 +575 @@ - if (preg_match('/[^a-z]+/i', $out)) { - $out = ''; - } + if (preg_match('/[^a-z]+/i', $out)) $out = ''; @@ -1003 +579,2 @@ - if (!is_array($out)) { + if (!is_array($out)) + { @@ -1005,3 +582 @@ - if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) { - $out = ''; - } + if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) $out = ''; @@ -1010,2 +585,3 @@ - case 'aZ09arobase': // great to sanitize $objecttype parameter - if (!is_array($out)) { + case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh + if (!is_array($out)) + { @@ -1013,3 +589 @@ - if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) { - $out = ''; - } + if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) $out = ''; @@ -1018,7 +592,2 @@ - case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh' - if (!is_array($out)) { - $out = trim($out); - if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) { - $out = ''; - } - } + case 'array': + if (!is_array($out) || empty($out)) $out = array(); @@ -1026,32 +595 @@ - case 'alpha': // No html and no ../ and " - case 'alphanohtml': // Recommended for most scalar parameters and search parameters - if (!is_array($out)) { - $out = trim($out); - do { - $oldstringtoclean = $out; - // Remove html tags - $out = dol_string_nohtmltag($out, 0); - // Remove also other dangerous string sequences - // '"' is dangerous because param in url can close the href= or src= and add javascript functions. - // '../' or '..\' is dangerous because it allows dir transversals - // Note &, '&', '&'... is a simple char like '&' alone but there is no reason to accept such way to encode input data. - $out = str_ireplace(array('&', '&', '&', '"', '"', '"', '"', '"', '/', '/', '\', '\', '/', '../', '..\\'), '', $out); - } while ($oldstringtoclean != $out); - // keep lines feed - } - break; - case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name ". Less secured than 'alphanohtml' - if (!is_array($out)) { - $out = trim($out); - do { - $oldstringtoclean = $out; - // Remove html tags - $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8'); - // '"' is dangerous because param in url can close the href= or src= and add javascript functions. - // '../' or '..\' is dangerous because it allows dir transversals - // Note &, '&', '&'... is a simple char like '&' alone but there is no reason to accept such way to encode input data. - $out = str_ireplace(array('&', '&', '&', '"', '"', '"', '"', '"', '/', '/', '\', '\', '/', '../', '..\\'), '', $out); - } while ($oldstringtoclean != $out); - } - break; - case 'nohtml': // No html + case 'nohtml': @@ -1060 +598,9 @@ - case 'restricthtmlnolink': + case 'alphanohtml': // Recommended for most scalar parameters and search parameters + 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 = dol_string_nohtmltag($out, 1); + } + break; @@ -1062,3 +608 @@ - case 'restricthtmlallowclass': - case 'restricthtmlallowunvalid': - $out = dol_htmlwithnojs($out, 1, $check); + $out = dol_string_onlythesehtmltags($out, 0); @@ -1067,9 +611,2 @@ - if (!empty($out)) { - if (empty($filter)) { - return 'BadParameterForGETPOST - Param 3 of sanitizeVal()'; - } - /*if (empty($options)) { - return 'BadParameterForGETPOST - Param 4 of sanitizeVal()'; - }*/ - $out = filter_var($out, $filter, $options); - } + if (empty($filter)) return 'BadFourthParameterForGETPOST'; + $out = filter_var($out, $filter, $options); @@ -1077,3 +614,19 @@ - default: - dol_syslog("Error, you call sanitizeVal() with a bad value for the check type. Data can't be sanitized.", LOG_ERR); - 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; + } + } @@ -1086,36 +639,29 @@ -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. - * This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded. - * - * @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 already loaded for this case) - if ($mode == 'email') { - global $conf; - - if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID')) { // If MAIL_PREFIX_FOR_EMAIL_ID is set - if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID') != 'SERVER_NAME') { - return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID; - } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME' - return $_SERVER["SERVER_NAME"]; - } - } - - // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions) - if (!empty($conf->file->instance_unique_id)) { - return sha1('dolibarr'.$conf->file->instance_unique_id); - } - - // For backward compatibility when instance_unique_id is not set - return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT); - } - - // 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 +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 = '') + { + global $conf; + + // If prefix is for email + if ($mode == 'email') + { + 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"]; + } + + // The recommended value (may be not defined for old versions) + if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id; + + // For backward compatibility + return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3'); + } @@ -1124,10 +670,9 @@ - if (!empty($tmp_instance_unique_id)) { - return sha1('dolibarr'.$tmp_instance_unique_id); - } - - // For backward compatibility when instance_unique_id is not set - if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) { - return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT); - } else { - return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT); - } + 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"])) + { + return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3'); + } + + return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3'); @@ -1149 +694 @@ - 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'] @@ -1182 +727,2 @@ - if (empty($type)) { // For a filesystem path + if (empty($type)) // For a filesystem path + { @@ -1184,3 +730,6 @@ - if (is_array($conf->file->dol_document_root)) { - foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...) - if ($key == 'main') { + if (is_array($conf->file->dol_document_root)) + { + foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...) + { + if ($key == 'main') + { @@ -1189,2 +738,2 @@ - // if (@file_exists($dirroot.'/'.$path)) { - if (@file_exists($dirroot.'/'.$path)) { // avoid [php:warn] + if (file_exists($dirroot.'/'.$path)) + { @@ -1196,8 +745,7 @@ - if ($returnemptyifnotfound) { - // Not found into alternate dir - if ($returnemptyifnotfound == 1 || !file_exists($res)) { - return ''; - } - } - } else { - // For an url path + if ($returnemptyifnotfound) // Not found into alternate dir + { + if ($returnemptyifnotfound == 1 || !file_exists($res)) return ''; + } + } + else // For an url path + { @@ -1209,14 +757,11 @@ - if ($type == 1) { - $res = DOL_URL_ROOT.'/'.$path; // Standard value - } - if ($type == 2) { - $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value - } - if ($type == 3) { - $res = DOL_URL_ROOT.'/'.$path; - } - - foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...) - if ($key == 'main') { - if ($type == 3) { - /*global $dolibarr_main_url_root;*/ + if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value + if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value + if ($type == 3) $res = DOL_URL_ROOT.'/'.$path; + + foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...) + { + if ($key == 'main') + { + if ($type == 3) + { + global $dolibarr_main_url_root; @@ -1225 +770 @@ - $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($conf->file->dol_main_url_root)); + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); @@ -1233 +777,0 @@ - $regs = array(); @@ -1235 +779,2 @@ - if (!empty($regs[1])) { + if (!empty($regs[1])) + { @@ -1237,3 +782,4 @@ - //if (file_exists($dirroot.'/'.$regs[1])) { - if (@file_exists($dirroot.'/'.$regs[1])) { // avoid [php:warn] - if ($type == 1) { + if (file_exists($dirroot.'/'.$regs[1])) + { + if ($type == 1) + { @@ -1242 +788,2 @@ - if ($type == 2) { + if ($type == 2) + { @@ -1245,2 +792,3 @@ - if ($type == 3) { - /*global $dolibarr_main_url_root;*/ + if ($type == 3) + { + global $dolibarr_main_url_root; @@ -1249 +797 @@ - $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($conf->file->dol_main_url_root)); + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); @@ -1265,2 +813,2 @@ - * Create a clone of instance of object (new instance with same value for each properties) - * With native = 0: Property that are reference are different memory area in the new object (full isolation clone). This means $this->db of new object may not be valid. + * Create a clone of instance of object (new instance with same value for properties) + * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid. @@ -1268 +815,0 @@ - * With native = 2: Property that are reference are different memory area in the new object (full isolation clone). Only scalar and array values are cloned. This means method are not availables and $this->db of new object is not valid. @@ -1271 +818 @@ - * @param int $native 0=Full isolation method, 1=Native PHP method, 2=Full isolation method keeping only scalar and array properties (recommended) + * @param int $native 0=Full isolation method, 1=Native PHP method @@ -1277,27 +824,7 @@ - if ($native == 0) { - // deprecated method, use the method with native = 2 instead - $tmpsavdb = null; - if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') { - $tmpsavdb = $object->db; - unset($object->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection') - } - - $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields - - if (!empty($tmpsavdb)) { - $object->db = $tmpsavdb; - } - } elseif ($native == 2) { - // recommended method to have a full isolated cloned object - $myclone = new stdClass(); - $tmparray = get_object_vars($object); // return only public properties - - if (is_array($tmparray)) { - foreach ($tmparray as $propertykey => $propertyval) { - if (is_scalar($propertyval) || is_array($propertyval)) { - $myclone->$propertykey = $propertyval; - } - } - } - } 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) + 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 references (refer to the same target/variable) @@ -1321,40 +848,8 @@ - if (empty($conf->dol_optimize_smallscreen)) { - return $size; - } - if ($type == 'width' && $size > 250) { - return 250; - } else { - return 10; - } -} - - -/** - * Clean a string to use it as a file name. - * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed). - * - * @param string $str String to clean - * @param string $newstr String to replace bad chars with. - * @param int $unaccent 1=Remove also accent (default), 0 do not remove them - * @return string String cleaned (a-zA-Z_) - * - * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName() - */ -function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1) -{ - // 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. - // Chars '--' 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('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`'); - $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars); - $tmp = preg_replace('/\-\-+/', '_', $tmp); - $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp); - $tmp = preg_replace('/\s+\-$/', '', $tmp); - $tmp = str_replace('..', '', $tmp); - return $tmp; -} - -/** - * Clean a string to use it as a path name. Similare to dol_sanitizeFileName but accept / and \ chars. - * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed). + if (empty($conf->dol_optimize_smallscreen)) return $size; + if ($type == 'width' && $size > 250) return 250; + else return 10; +} + + +/** + * Clean a string to use it as a file name @@ -1367,3 +862,3 @@ - * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName() - */ -function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1) + * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName() + */ +function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1) @@ -1373,61 +868,19 @@ - // Chars '--' 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('<', '>', '?', '*', '|', '"', '°', '$', ';', '`'); - $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars); - $tmp = preg_replace('/\-\-+/', '_', $tmp); - $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp); - $tmp = preg_replace('/\s+\-$/', '', $tmp); - $tmp = str_replace('..', '', $tmp); - return $tmp; -} - -/** - * Clean a string to use it as an URL (into a href or src attribute) - * - * @param string $stringtoclean String to clean - * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url) - * @return string Escaped string. - */ -function dol_sanitizeUrl($stringtoclean, $type = 1) -{ - // We clean string because some hacks try to obfuscate evil strings by inserting non printable chars. Example: 'java(ascci09)scr(ascii00)ipt' is processed like 'javascript' (whatever is place of evil ascii char) - // We should use dol_string_nounprintableascii but function may not be yet loaded/available - $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace - // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: onerror=alert(1) - $stringtoclean = preg_replace('//', '', $stringtoclean); - - $stringtoclean = str_replace('\\', '/', $stringtoclean); - if ($type == 1) { - // removing : should disable links to external url like http:aaa) - // removing ';' should disable "named" html entities encode into an url (we should not have this into an url) - $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean); - } - - do { - $oldstringtoclean = $stringtoclean; - // removing '&colon' should disable links to external url like http:aaa) - // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url) - $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean); - } while ($oldstringtoclean != $stringtoclean); - - if ($type == 1) { - // removing '//' should disable links to external url like //aaa or http//) - $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean); - } - - return $stringtoclean; -} - -/** - * Clean a string to use it as an Email. - * - * @param string $stringtoclean String to clean. Example 'abc@mycompany.com ' - * @return string Escaped string. - */ -function dol_sanitizeEmail($stringtoclean) -{ - do { - $oldstringtoclean = $stringtoclean; - $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean); - } while ($oldstringtoclean != $stringtoclean); - - return $stringtoclean; + // Char '/' and '\' are file delimiters. + $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';'); + return dol_string_nospecial($unaccent ?dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars); +} + +/** + * Clean a string to use it as a path name + * + * @param string $str String to clean + * @param string $newstr String to replace bad chars with + * @param int $unaccent 1=Remove also accent (default), 0 do not remove them + * @return string String cleaned (a-zA-Z_) + * + * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName() + */ +function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1) +{ + $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°'); + return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars); @@ -1446,11 +899,2 @@ - global $conf; - - if (is_null($str)) { - return ''; - } - - if (utf8_check($str)) { - if (extension_loaded('intl') && getDolGlobalString('MAIN_UNACCENT_USE_TRANSLITERATOR')) { - $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD); - return $transliterator->transliterate($str); - } + if (utf8_check($str)) + { @@ -1461 +904,0 @@ - '%C3%87' => 'C', @@ -1464 +906,0 @@ - '%C3%91' => 'N', @@ -1466 +907,0 @@ - '%C5%A0' => 'S', @@ -1468 +908,0 @@ - '%C3%9D' => 'Y', '%C5%B8' => 'y', @@ -1475 +914,0 @@ - '%C5%A1' => 's', @@ -1477 +916 @@ - '%C3%BD' => 'y', '%C3%BF' => 'y' + '%C3%BF' => 'y' @@ -1481 +920,3 @@ - } else { + } + else + { @@ -1483 +924 @@ - $string = strtr( + $string = strtr( @@ -1505,17 +946,12 @@ - * This is a more complete function than dol_sanitizeFileName(). - * - * @param string $str String to clean - * @param string $newstr String to replace forbidden chars with - * @param array|string $badcharstoreplace Array of forbidden characters to replace. Use '' to keep default list. - * @param array|string $badcharstoremove Array of forbidden characters to remove. Use '' to keep default list. - * @param int $keepspaces 1=Do not treat space as a special char to replace or remove - * @return string Cleaned string - * - * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii() - */ -function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0) -{ - $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName - if (empty($keepspaces)) { - $forbidden_chars_to_replace[] = " "; - } + * This is a more complete function than dol_sanitizeFileName. + * + * @param string $str String to clean + * @param string $newstr String to replace forbidden chars with + * @param array $badcharstoreplace List of forbidden characters + * @return string Cleaned string + * + * @see dol_sanitizeFilename(), dol_string_unaccent() + */ +function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '') +{ + $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName @@ -1522,0 +959 @@ + if (is_array($badcharstoreplace)) $forbidden_chars_to_replace = $badcharstoreplace; @@ -1525,7 +961,0 @@ - if (is_array($badcharstoreplace)) { - $forbidden_chars_to_replace = $badcharstoreplace; - } - if (is_array($badcharstoremove)) { - $forbidden_chars_to_remove = $badcharstoremove; - } - @@ -1537,22 +966,0 @@ - * 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 - } -} - -/** @@ -1561,4 +969,4 @@ - * @param string $stringtoescape String to escape - * @param int $mode 0=Escape also ' and " into ', 1=Escape ' but not " for usage into 'string', 2=Escape " but not ' for usage into "string", 3=Escape ' and " with \ - * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n. - * @return string Escaped string. Both ' and " are escaped into ' if they are escaped. + * @param string $stringtoescape String to escape + * @param int $mode 0=Escape also ' and " into ', 1=Escape ' but not " for usage into 'string', 2=Escape " but not ' for usage into "string", 3=Escape ' and " with \ + * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n. + * @return string Escaped string. Both ' and " are escaped into ' if they are escaped. @@ -1568,4 +975,0 @@ - if (is_null($stringtoescape)) { - return ''; - } - @@ -1575,15 +979,5 @@ - if (empty($noescapebackslashn)) { - $substitjs["\n"] = '\\n'; - $substitjs['\\'] = '\\\\'; - } - if (empty($mode)) { - $substitjs["'"] = "\\'"; - $substitjs['"'] = "\\'"; - } elseif ($mode == 1) { - $substitjs["'"] = "\\'"; - } elseif ($mode == 2) { - $substitjs['"'] = '\\"'; - } elseif ($mode == 3) { - $substitjs["'"] = "\\'"; - $substitjs['"'] = "\\\""; - } + if (empty($noescapebackslashn)) { $substitjs["\n"] = '\\n'; $substitjs['\\'] = '\\\\'; } + if (empty($mode)) { $substitjs["'"] = "\\'"; $substitjs['"'] = "\\'"; } + elseif ($mode == 1) $substitjs["'"] = "\\'"; + elseif ($mode == 2) { $substitjs['"'] = '\\"'; } + elseif ($mode == 3) { $substitjs["'"] = "\\'"; $substitjs['"'] = "\\\""; } @@ -1597 +991 @@ - * @return string Escaped string for JSON content. + * @return string Escaped string for json content. @@ -1605,102 +999 @@ - * Returns text escaped for inclusion into a php string, build with double quotes " or ' - * - * @param string $stringtoescape String to escape - * @param int<1,2> $stringforquotes 2=String for doublequotes, 1=String for simple quotes - * @return string Escaped string for PHP content. - */ -function dol_escape_php($stringtoescape, $stringforquotes = 2) -{ - if (is_null($stringtoescape)) { - return ''; - } - - if ($stringforquotes == 2) { - return str_replace('"', "'", $stringtoescape); - } - if ($stringforquotes == 1) { - return str_replace("'", "\'", str_replace('"', "'", $stringtoescape)); - } - - return 'Bad parameter for stringforquotes in dol_escape_php'; -} - -/** - * Returns text escaped for inclusion into a XML string - * - * @param string $stringtoescape String to escape - * @return string Escaped string for XML content. - */ -function dol_escape_xml($stringtoescape) -{ - return $stringtoescape; -} - -/** - * Return a string label (so on 1 line only and that should not contains any HTML) ready to be output on HTML page - * To use text that is not HTML content inside an attribute, use can simply only dol_escape_htmltag(). In doubt, use dolPrintHTMLForAttribute(). - * - * @param string $s String to print - * @return string String ready for HTML output - */ -function dolPrintLabel($s) -{ - return dol_escape_htmltag(dol_htmlentitiesbr($s)); -} - -/** - * Return a string ready to be output on HTML page - * To use text inside an attribute, you can simply use dolPrintHTMLForAttribute() or dol_escape_htmltag() - * - * @param string $s String to print - * @param int $allowiframe Allow iframe tags - * @return string String ready for HTML output - */ -function dolPrintHTML($s, $allowiframe = 0) -{ - return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, 'common', 0, 1); -} - -/** - * Return a string ready to be output on an HTML attribute (alt, title, data-html, ...) - * - * @param string $s String to print - * @return string String ready for HTML output - */ -function dolPrintHTMLForAttribute($s) -{ - // The dol_htmlentitiesbr will convert simple text into html - // The dol_escape_htmltag will escape html chars. - return dol_escape_htmltag(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 0, 0, 0, array('br', 'b', 'font', 'span')), 1, -1, '', 0, 1); -} - -/** - * Return a string ready to be output on input textarea - * To use text inside an attribute, use can use only dol_escape_htmltag() - * - * @param string $s String to print - * @param int $allowiframe Allow iframe tags - * @return string String ready for HTML output into a textarea - */ -function dolPrintHTMLForTextArea($s, $allowiframe = 0) -{ - return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, '', 0, 1); -} - -/** - * Return a string ready to be output on an HTML attribute (alt, title, ...) - * - * @param string $s String to print - * @return string String ready for HTML output - */ -function dolPrintPassword($s) -{ - return htmlspecialchars($s, ENT_COMPAT, 'UTF-8'); -} - - -/** - * Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input fields. - * When we need to output strings on pages, we should use: - * - dolPrintHTML... that is dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr(), 1, 1, 1)), 1, 1) for notes or descriptions into textarea, add 'common' if into a html content - * - dolPrintLabel... that is dol_escape_htmltag(dol_htmlentitiesbr()) for simple labels. - * - dolPrintPassword that is abelhtmlspecialchars( , ENT_COMPAT, 'UTF-8') for passwords. + * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields. @@ -1709,3 +1002,3 @@ - * @param int $keepb 1=Keep b tags, 0=remove them completely - * @param int $keepn 1=Preserve \r\n strings, 0=Replace them with escaped value, -1=Remove them. Set to 1 when escaping for a