Compare commits

..

2 Commits

92 changed files with 361 additions and 1403 deletions

View File

@@ -6,20 +6,19 @@ end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = false
max_line_length = 300
max_line_length = 140
tab_width = 4
ij_continuation_indent_size = 8
ij_formatter_off_tag = @formatter:off
ij_formatter_on_tag = @formatter:on
ij_formatter_tags_enabled = false
ij_smart_tabs = false
ij_visual_guides = 300
ij_visual_guides = 80,120
ij_wrap_on_typing = true
[*.css]
indent_style = tab
ij_smart_tabs = true
ij_visual_guides = none
ij_css_align_closing_brace_with_properties = false
ij_css_blank_lines_around_nested_selector = 1
ij_css_blank_lines_between_blocks = 1
@@ -39,9 +38,7 @@ ij_css_use_double_quotes = true
ij_css_value_alignment = do_not_align
[*.scss]
indent_size = 2
tab_width = 2
ij_visual_guides = none
indent_style = tab
ij_scss_align_closing_brace_with_properties = false
ij_scss_blank_lines_around_nested_selector = 1
ij_scss_blank_lines_between_blocks = 1
@@ -61,8 +58,8 @@ ij_scss_use_double_quotes = true
ij_scss_value_alignment = 0
[*.twig]
indent_style = tab
ij_smart_tabs = true
ij_visual_guides = none
ij_wrap_on_typing = false
ij_twig_keep_indents_on_empty_lines = false
ij_twig_spaces_inside_comments_delimiters = true
@@ -70,7 +67,6 @@ ij_twig_spaces_inside_delimiters = true
ij_twig_spaces_inside_variable_delimiters = true
[.editorconfig]
ij_visual_guides = none
ij_editorconfig_align_group_field_declarations = false
ij_editorconfig_space_after_colon = false
ij_editorconfig_space_after_comma = true
@@ -78,12 +74,10 @@ ij_editorconfig_space_before_colon = false
ij_editorconfig_space_before_comma = false
ij_editorconfig_spaces_around_assignment_operators = true
[{*.ant, *.fxml, *.jhm, *.jnlp, *.jrxml, *.rng, *.tld, *.wsdl, *.xml, *.xsd, *.xsl, *.xslt, *.xul, phpunit.xml.dist}]
[{*.ant,*.fxml,*.jhm,*.jnlp,*.jrxml,*.rng,*.tld,*.wsdl,*.xml,*.xsd,*.xsl,*.xslt,*.xul,phpunit.xml.dist}]
indent_size = 2
tab_width = 2
ij_smart_tabs = true
ij_visual_guides = none
ij_wrap_on_typing = false
ij_xml_align_attributes = true
ij_xml_align_text = false
ij_xml_attribute_wrap = normal
@@ -99,12 +93,11 @@ ij_xml_line_comment_at_first_column = true
ij_xml_space_after_tag_name = false
ij_xml_space_around_equals_in_attribute = false
ij_xml_space_inside_empty_tag = false
ij_xml_text_wrap = off
ij_xml_text_wrap = normal
[{*.bash,*.sh,*.zsh}]
indent_size = 2
tab_width = 2
ij_visual_guides = none
ij_shell_binary_ops_start_line = false
ij_shell_keep_column_alignment_padding = false
ij_shell_minify_program = false
@@ -115,7 +108,6 @@ ij_shell_switch_cases_indented = false
indent_style = tab
ij_continuation_indent_size = 4
ij_smart_tabs = true
ij_visual_guides = none
ij_javascript_align_imports = false
ij_javascript_align_multiline_array_initializer_expression = false
ij_javascript_align_multiline_binary_operation = false
@@ -149,7 +141,7 @@ ij_javascript_chained_call_dot_on_new_line = true
ij_javascript_class_brace_style = end_of_line
ij_javascript_comma_on_new_line = false
ij_javascript_do_while_brace_force = always
ij_javascript_else_on_new_line = false
ij_javascript_else_on_new_line = true
ij_javascript_enforce_trailing_comma = keep
ij_javascript_extends_keyword_wrap = off
ij_javascript_extends_list_wrap = off
@@ -305,7 +297,6 @@ ij_php_array_initializer_new_line_after_left_brace = true
ij_php_array_initializer_right_brace_on_new_line = true
ij_php_array_initializer_wrap = on_every_item
ij_php_assignment_wrap = off
ij_php_attributes_wrap = off
ij_php_author_weight = 8
ij_php_binary_operation_sign_on_next_line = false
ij_php_binary_operation_wrap = off
@@ -394,7 +385,6 @@ ij_php_new_line_after_php_opening_tag = false
ij_php_null_type_position = in_the_end
ij_php_package_weight = 28
ij_php_param_weight = 5
ij_php_parameters_attributes_wrap = off
ij_php_parentheses_expression_new_line_after_left_paren = false
ij_php_parentheses_expression_right_paren_on_new_line = false
ij_php_phpdoc_blank_line_before_tags = true
@@ -416,7 +406,6 @@ ij_php_see_weight = 3
ij_php_since_weight = 28
ij_php_sort_phpdoc_elements = true
ij_php_space_after_colon = true
ij_php_space_after_colon_in_named_argument = true
ij_php_space_after_colon_in_return_type = true
ij_php_space_after_comma = true
ij_php_space_after_for_semicolon = true
@@ -430,7 +419,6 @@ ij_php_space_before_catch_parentheses = true
ij_php_space_before_class_left_brace = true
ij_php_space_before_closure_left_parenthesis = true
ij_php_space_before_colon = true
ij_php_space_before_colon_in_named_argument = false
ij_php_space_before_colon_in_return_type = false
ij_php_space_before_comma = false
ij_php_space_before_do_left_brace = true
@@ -498,7 +486,6 @@ ij_php_while_on_new_line = false
[{*.har,*.jsb2,*.jsb3,*.json,.babelrc,.eslintrc,.stylelintrc,bowerrc,composer.lock,jest.config}]
indent_size = 2
ij_visual_guides = none
ij_json_keep_blank_lines_in_code = 0
ij_json_keep_indents_on_empty_lines = false
ij_json_keep_line_breaks = true
@@ -513,8 +500,7 @@ ij_json_wrap_long_lines = false
[{*.htm,*.html,*.sht,*.shtm,*.shtml}]
indent_style = tab
ij_smart_tabs = true
ij_visual_guides = none
ij_html_add_new_line_before_tags = body, div, p, form, h1, h2, h3
ij_html_add_new_line_before_tags = body,div,p,form,h1,h2,h3
ij_html_align_attributes = true
ij_html_align_text = false
ij_html_attribute_wrap = normal
@@ -541,16 +527,10 @@ ij_html_space_inside_empty_tag = false
ij_html_text_wrap = normal
ij_html_uniform_ident = false
[{*.yaml, *.yml}]
[{*.yaml,*.yml}]
indent_size = 2
ij_visual_guides = none
ij_yaml_align_values_properties = do_not_align
ij_yaml_autoinsert_sequence_marker = true
ij_yaml_block_mapping_on_new_line = false
ij_yaml_indent_sequence_value = true
ij_yaml_keep_indents_on_empty_lines = false
ij_yaml_keep_line_breaks = true
ij_yaml_sequence_on_new_line = false
ij_yaml_space_before_colon = false
ij_yaml_space_before_colon = true
ij_yaml_spaces_within_braces = true
ij_yaml_spaces_within_brackets = true

View File

@@ -3256,15 +3256,16 @@ EOF
*/
public function DisplayDocumentInline(WebPage $oPage, $sAttCode)
{
/** @var \ormDocument $oDoc */
$oDoc = $this->Get($sAttCode);
$sClass = get_class($this);
$Id = $this->GetKey();
switch ($oDoc->GetMainMimeType()) {
switch ($oDoc->GetMainMimeType())
{
case 'text':
case 'html':
$data = $oDoc->GetData();
switch ($oDoc->GetMimeType()) {
switch ($oDoc->GetMimeType())
{
case 'text/xml':
$oPage->add("<iframe id='preview_$sAttCode' src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" width=\"100%\" height=\"400\">Loading...</iframe>\n");
break;

View File

@@ -459,21 +459,17 @@ EOF
$sAttType = $aTargetAttCodes[$sTargetAttCode];
$sExtFieldAttCode = $sTargetAttCode;
}
$aForbidenAttType = [
'AttributeLinkedSet',
'AttributeFriendlyName',
'iAttributeNoGroupBy', //we cannot only use iAttributeNoGroupBy since this method is also used by the designer who do not have access to the classes' PHP reflection API. So the known classes has to be listed altogether
'AttributeOneWayPassword',
'AttributeEncryptedString',
'AttributePassword',
];
foreach ($aForbidenAttType as $sForbidenAttType) {
if (is_a($sAttType, $sForbidenAttType, true))
{
continue 2;
}
if (is_a($sAttType, 'AttributeLinkedSet', true))
{
continue;
}
if (is_a($sAttType, 'AttributeFriendlyName', true))
{
continue;
}
if (is_a($sAttType, 'AttributeOneWayPassword', true))
{
continue;
}
$sLabel = $this->oModelReflection->GetLabel($sClass, $sAttCode);

View File

@@ -446,21 +446,8 @@ class DisplayBlock
$this->m_oSet = new CMDBObjectSet($this->m_oFilter, $aOrderBy, $aQueryParams);
}
$this->m_oSet->SetShowObsoleteData($this->m_bShowObsoleteData);
switch($this->m_sStyle) {
case 'list_search':
case 'list':
break;
default:
// N°3473: except for 'list_search' and 'list' (which have more granularity, see the other switch below),
// refuse to render if the user is not allowed to see the class.
if (! UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) {
$sHtml .= $oPage->GetP(Dict::Format('UI:Error:ReadNotAllowedOn_Class', $this->m_oSet->GetClass()));
return $sHtml;
}
}
switch ($this->m_sStyle) {
switch($this->m_sStyle)
{
case 'count':
if (isset($aExtraParams['group_by']))
{

View File

@@ -685,7 +685,7 @@ class LoginWebPage extends NiceWebPage
public static function HTTPReload()
{
$sOriginURL = utils::GetCurrentAbsoluteUrl();
$sOriginURL = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (!utils::StartsWith($sOriginURL, utils::GetAbsoluteUrlAppRoot()))
{
// If the found URL does not start with the configured AppRoot URL

View File

@@ -297,19 +297,11 @@ class privUITransactionFile
* Cleanup old transactions which have been pending since more than 24 hours
* Use filemtime instead of filectime since filectime may be affected by operations on the directory (like changing the access rights)
*/
protected static function CleanupOldTransactions($sTransactionDir = null)
protected static function CleanupOldTransactions()
{
$iThreshold = (int) MetaModel::GetConfig()->Get('transactions_gc_threshold');
$iThreshold = min(100, $iThreshold);
$iThreshold = max(1, $iThreshold);
if ((100 != $iThreshold) && (rand(1, 100) > $iThreshold)) {
return;
}
clearstatcache();
$iLimit = time() - 24*3600;
$sPattern = $sTransactionDir ? "$sTransactionDir/*" : APPROOT.'data/transactions/*';
$aTransactions = glob($sPattern);
clearstatcache();
$aTransactions = glob(APPROOT.'data/transactions/*-*');
foreach($aTransactions as $sFileName)
{
if (filemtime($sFileName) < $iLimit)

View File

@@ -782,42 +782,22 @@ class utils
}
}
/**
* @return bool The boolean value of the conf. "behind_reverse_proxy" (except if there is no REMOTE_ADDR int his case, it return false)
*
* @since 2.7.4
*/
public static function IsProxyTrusted()
{
if (empty($_SERVER['REMOTE_ADDR'])) {
return false;
}
$bTrustProxies = (bool) self::GetConfig()->Get('behind_reverse_proxy');
return $bTrustProxies;
}
/**
* Returns the absolute URL to the application root path
*
* @param bool $bForceTrustProxy
*
* @return string The absolute URL to the application root, without the first slash
*
* @throws \Exception
*
* @since 2.7.4 $bForceTrustProxy param added
*/
public static function GetAbsoluteUrlAppRoot($bForceTrustProxy = false)
public static function GetAbsoluteUrlAppRoot()
{
static $sUrl = null;
if ($sUrl === null || $bForceTrustProxy)
if ($sUrl === null)
{
$sUrl = self::GetConfig()->Get('app_root_url');
if ($sUrl == '')
{
$sUrl = self::GetDefaultUrlAppRoot($bForceTrustProxy);
$sUrl = self::GetDefaultUrlAppRoot();
}
elseif (strpos($sUrl, SERVER_NAME_PLACEHOLDER) > -1)
{
@@ -841,116 +821,31 @@ class utils
* For most usages, when an root url is needed, use utils::GetAbsoluteUrlAppRoot() instead as uses this only as a fallback when the
* app_root_url conf parameter is not defined.
*
* @param bool $bForceTrustProxy
*
* @return string
*
* @throws \Exception
*
* @since 2.7.4 $bForceTrustProxy param added
*/
public static function GetDefaultUrlAppRoot($bForceTrustProxy = false)
{
$sAbsoluteUrl = self::GetCurrentAbsoluteUrl($bForceTrustProxy, true);
$sCurrentScript = realpath($_SERVER['SCRIPT_FILENAME']);
$sAppRoot = realpath(APPROOT);
return self::GetAppRootUrl($sCurrentScript, $sAppRoot, $sAbsoluteUrl);
}
/**
* Build the current absolute URL from the server's variables.
*
* For almost every usage, you should use the more secure utils::GetAbsoluteUrlAppRoot() : instead of reading the current uri, it provide you the configured application's root URL (this is done during the setup and chn be changed in the configuration file)
*
* @see utils::GetAbsoluteUrlAppRoot
*
* @param bool $bForceTrustProxy
* @param bool $bTrimQueryString
*
* @return string
*
* @since 2.7.4
*/
public static function GetCurrentAbsoluteUrl($bForceTrustProxy = false, $bTrimQueryString = false)
*/
public static function GetDefaultUrlAppRoot()
{
// Build an absolute URL to this page on this server/port
$sServerName = self::GetServerName($bForceTrustProxy);
$bIsSecure = self::IsConnectionSecure($bForceTrustProxy);
$sProtocol = $bIsSecure ? 'https' : 'http';
$iPort = self::GetServerPort($bForceTrustProxy);
if ($bIsSecure) {
$sPort = ($iPort == 443) ? '' : ':'.$iPort;
} else {
$sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
$sProtocol = self::IsConnectionSecure() ? 'https' : 'http';
$iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
if ($sProtocol == 'http')
{
$sPort = ($iPort == 80) ? '' : ':'.$iPort;
}
$sPath = self::GetRequestUri($bForceTrustProxy);
if ($bTrimQueryString) {
// remove all the parameters from the query string
$iQuestionMarkPos = strpos($sPath, '?');
if ($iQuestionMarkPos !== false) {
$sPath = substr($sPath, 0, $iQuestionMarkPos);
}
else
{
$sPort = ($iPort == 443) ? '' : ':'.$iPort;
}
$sAbsoluteUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
return $sAbsoluteUrl;
}
/**
* @param bool $bForceTrustProxy
*
* @return string
*
* @since 2.7.4
*/
public static function GetServerName($bForceTrustProxy = false)
{
$bTrustProxy = $bForceTrustProxy || self::IsProxyTrusted();
$sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
if ($bTrustProxy) {
$sServerName = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $sServerName;
}
return $sServerName;
}
/**
* @param bool $bForceTrustProxy
*
* @return int|mixed
* @since 2.7.4
*/
public static function GetServerPort($bForceTrustProxy = false)
{
$bTrustProxy = $bForceTrustProxy || self::IsProxyTrusted();
$sServerPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
if ($bTrustProxy) {
$sServerPort = isset($_SERVER['HTTP_X_FORWARDED_PORT']) ? $_SERVER['HTTP_X_FORWARDED_PORT'] : $sServerPort;
}
return $sServerPort;
}
/**
* @return string
*
* @since 2.7.4
*/
public static function GetRequestUri()
{
// $_SERVER['REQUEST_URI'] is empty when running on IIS
// Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
if (empty($_SERVER['REQUEST_URI']))
if (!empty($_SERVER['REQUEST_URI']))
{
$sPath = $_SERVER['REQUEST_URI'];
}
else
{
$sPath = $_SERVER['SCRIPT_NAME'];
if (!empty($_SERVER['QUERY_STRING']))
@@ -961,7 +856,18 @@ class utils
}
$sPath = $_SERVER['REQUEST_URI'];
return $sPath;
// remove all the parameters from the query string
$iQuestionMarkPos = strpos($sPath, '?');
if ($iQuestionMarkPos !== false)
{
$sPath = substr($sPath, 0, $iQuestionMarkPos);
}
$sAbsoluteUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
$sCurrentScript = realpath($_SERVER['SCRIPT_FILENAME']);
$sAppRoot = realpath(APPROOT);
return self::GetAppRootUrl($sCurrentScript, $sAppRoot, $sAbsoluteUrl);
}
/**
@@ -1005,36 +911,19 @@ class utils
/**
* Helper to handle the variety of HTTP servers
* See N°286 (fixed in [896]), and N°634 (this fix)
*
*
* Though the official specs says 'a non empty string', some servers like IIS do set it to 'off' !
* nginx set it to an empty string
* Others might leave it unset (no array entry)
*
* @param bool $bForceTrustProxy
*
* @return bool
*
* @since 2.7.4 reverse proxies handling
*/
public static function IsConnectionSecure($bForceTrustProxy = false)
* Others might leave it unset (no array entry)
*/
public static function IsConnectionSecure()
{
$bSecured = false;
$bTrustProxy = $bForceTrustProxy || self::IsProxyTrusted();
if ($bTrustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTO']))
{
$bSecured = ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
}
elseif ($bTrustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTOCOL']))
{
$bSecured = ($_SERVER['HTTP_X_FORWARDED_PROTOCOL'] === 'https');
}
elseif ((!empty($_SERVER['HTTPS'])) && (strtolower($_SERVER['HTTPS']) != 'off'))
if (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off'))
{
$bSecured = true;
}
return $bSecured;
}
@@ -2448,13 +2337,4 @@ class utils
$e = new CoreException($sMessage, null, '', $oException);
throw $e;
}
/**
* @return bool : indicate whether we run under a windows environnement or not
* @since 2.7.4 : N°3412
*/
public static function IsWindowsEnvironment(){
return (substr(PHP_OS,0,3) === 'WIN');
}
}

View File

@@ -485,7 +485,7 @@ class WebPage implements Page
/**
* @param string|null $sHeaderValue for example `SAMESITE`. If null will set the header using the config parameter value.
*
* @since 2.7.3 3.0.0 N°3416
* @since 2.7.2-2 3.0.0 N°3416
* @uses security_header_xframe config parameter
* @uses \utils::GetConfig()
* @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options

View File

@@ -103,14 +103,6 @@ define('LINKSET_EDITMODE_ACTIONS', 2); // Show the usual 'Actions' popup menu
define('LINKSET_EDITMODE_INPLACE', 3); // The "linked" objects can be created/modified/deleted in place
define('LINKSET_EDITMODE_ADDREMOVE', 4); // The "linked" objects can be added/removed in place
/**
* Attributes implementing this interface won't be accepted as `group by` field
* @since 2.7.4 N°3473
*/
interface iAttributeNoGroupBy
{
//no method, just a contract on implement
}
/**
* Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
@@ -3769,7 +3761,7 @@ class AttributeFinalClass extends AttributeString
*
* @package iTopORM
*/
class AttributePassword extends AttributeString implements iAttributeNoGroupBy
class AttributePassword extends AttributeString
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
@@ -3845,7 +3837,7 @@ class AttributePassword extends AttributeString implements iAttributeNoGroupBy
*
* @package iTopORM
*/
class AttributeEncryptedString extends AttributeString implements iAttributeNoGroupBy
class AttributeEncryptedString extends AttributeString
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
@@ -9225,7 +9217,7 @@ class AttributeSubItem extends AttributeDefinition
/**
* One way encrypted (hashed) password
*/
class AttributeOneWayPassword extends AttributeDefinition implements iAttributeNoGroupBy
class AttributeOneWayPassword extends AttributeDefinition
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;

View File

@@ -1181,24 +1181,17 @@ class CMDBSource
}
/**
* There may have some differences between DB ! For example in :
* * MySQL 5.7 we have `INT`
* * MariaDB >= 10.2 you get `int DEFAULT 'NULL'`
* There may have some differences between DB : for example in MySQL 5.7 we have "INT", while in MariaDB >= 10.2 you get "int DEFAULT 'NULL'"
*
* We still need to do a case sensitive comparison for enum values !
* We still do a case sensitive comparison for enum values !
*
* A better solution would be to generate SQL field definitions ({@link GetFieldSpec} method) based on the DB used... But for
* now (N°2490 / SF #1756 / PR #91) we did implement this simpler solution
*
* @see GetFieldDataTypeAndOptions extracts all info from the SQL field definition
*
* @param string $sItopGeneratedFieldType
* @param string $sDbFieldType
*
* @param string $sItopGeneratedFieldType
*
* @return bool true if same type and options (case sensitive comparison only for type options), false otherwise
*
* @throws \CoreException
* @since 2.7.0 N°2490
*/
public static function IsSameFieldTypes($sItopGeneratedFieldType, $sDbFieldType)
@@ -1246,68 +1239,24 @@ class CMDBSource
}
/**
* @see \self::GetEnumOptions() specific processing for ENUM fields
*
* @param string $sCompleteFieldType sql field type, for example `VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 0`
* @param string $sCompleteFieldType sql field type, for example 'VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 0'
*
* @return string[] consisting of 3 items :
* 1. data type : for example `VARCHAR`
* 2. type value : for example `255`
* 3. other options : for example `CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 0`
*
* @throws \CoreException
* 1. data type : for example 'VARCHAR'
* 2. type value : for example '255'
* 3. other options : for example ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 0'
*/
private static function GetFieldDataTypeAndOptions($sCompleteFieldType)
{
preg_match('/^([a-zA-Z]+)(\(([^\)]+)\))?( .+)?/', $sCompleteFieldType, $aMatches);
$sDataType = isset($aMatches[1]) ? $aMatches[1] : '';
if (strcasecmp($sDataType, 'ENUM') === 0){
try{
return self::GetEnumOptions($sDataType, $sCompleteFieldType);
}catch(CoreException $e){
//do nothing ; especially do not block setup.
IssueLog::Warning("enum was not parsed properly: $sCompleteFieldType. it should not happen during setup.");
}
}
$sTypeOptions = isset($aMatches[2]) ? $aMatches[3] : '';
$sOtherOptions = isset($aMatches[4]) ? $aMatches[4] : '';
return array($sDataType, $sTypeOptions, $sOtherOptions);
}
/**
* @param string $sDataType for example `ENUM`
* @param string $sCompleteFieldType Example:
* `ENUM('CSP A','CSP (aaaa) M','NA','OEM(ROC)','OPEN(VL)','RETAIL (Boite)') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`
*
* @return string[] consisting of 3 items :
* 1. data type : ENUM or enum here
* 2. type value : in-between EUM parenthesis
* 3. other options : for example ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 0'
* @throws \CoreException
* @since 2.7.4 N°3065 specific processing for enum fields : fix no alter table when enum values containing parenthesis
* Handle ENUM options
*/
private static function GetEnumOptions($sDataType, $sCompleteFieldType)
{
$iFirstOpeningParenthesis = strpos($sCompleteFieldType, '(');
$iLastEndingParenthesis = strrpos($sCompleteFieldType, ')');
if ($iFirstOpeningParenthesis === false || $iLastEndingParenthesis === false ){
//should never happen as GetFieldDataTypeAndOptions regexp matched.
//except if regexp is modiied/broken somehow one day...
throw new CoreException("GetEnumOptions issue with $sDataType parsing : " . $sCompleteFieldType);
}
$sTypeOptions = substr($sCompleteFieldType, $iFirstOpeningParenthesis + 1, $iLastEndingParenthesis - 1);
$sOtherOptions = substr($sCompleteFieldType, $iLastEndingParenthesis + 1);
return array($sDataType, $sTypeOptions, $sOtherOptions);
}
/**
* @param string $sTable
* @param string $sField

View File

@@ -1065,14 +1065,6 @@ class Config
'source_of_value' => '',
'show_in_conf_sample' => false,
),
'transactions_gc_threshold' => array(
'type' => 'integer',
'description' => 'probability in percent for the garbage collector to be triggered (100 mean always)',
'default' => 10, // added in itop 2.7.4, before the GC was always called
'value' => '',
'source_of_value' => '',
'show_in_conf_sample' => false,
),
'log_transactions' => array(
'type' => 'bool',
'description' => 'Whether or not to enable the debug log for the transactions.',
@@ -1265,14 +1257,6 @@ class Config
'source_of_value' => '',
'show_in_conf_sample' => false,
],
'behind_reverse_proxy' => [
'type' => 'bool',
'description' => 'If true, then proxies custom header (X-Forwarded-*) are taken into account. Use only if the webserver is not publicly accessible (reachable only by the reverse proxy)',
'default' => false,
'value' => false,
'source_of_value' => '',
'show_in_conf_sample' => true,
],
);

View File

@@ -1186,30 +1186,6 @@ abstract class DBSearch
}
}
}
if (is_array($aGroupByExpr))
{
foreach($aGroupByExpr as $sAlias => $oGroupByExp)
{
/** @var \Expression $oGroupByExp */
$aFields = $oGroupByExp->ListRequiredFields();
foreach($aFields as $sFieldAlias)
{
$aMatches = array();
if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches))
{
$sFieldClass = $this->GetClassName($aMatches[1]);
$oAttDef = MetaModel::GetAttributeDef($sFieldClass, $aMatches[2]);
if ( $oAttDef instanceof iAttributeNoGroupBy)
{
throw new Exception("Grouping on '$sFieldClass' fields is not supported.");
}
}
}
}
}
$oSQLQuery = $oSearch->GetSQLQueryStructure($aAttToLoad, $bGetCount, $aGroupByExpr, null, $aSelectExpr);
$oSQLQuery->SetSourceOQL($oSearch->ToOQL());

View File

@@ -2602,18 +2602,5 @@ class DBObjectSearch extends DBSearch
return $oExpression;
}
/**
* @param array $aAttCodes array of attCodes to search into
* @param string $sNeedle one word to be searched
*
* @throws \CoreException
*/
public function AddCondition_FullTextOnAttributes(array $aAttCodes, $sNeedle)
{
}
public function ListParameters()
{
return $this->GetCriteria()->ListParameters();
}
}

View File

@@ -5545,10 +5545,15 @@ abstract class MetaModel
// The field already exists, does it have the relevant properties?
//
$bToBeChanged = false;
$sActualFieldSpec = CMDBSource::GetFieldSpec($sTable, $sField);
if (!CMDBSource::IsSameFieldTypes($sDBFieldSpec, $sActualFieldSpec))
{
$bToBeChanged = true;
$aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found <code>$sActualFieldSpec</code> while expecting <code>$sDBFieldSpec</code>";
}
if ($bToBeChanged)
{
$aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
$aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
}

View File

@@ -1672,39 +1672,6 @@ class FieldExpression extends UnaryExpression
// Has been resolved into an SQL expression
class FieldExpressionResolved extends FieldExpression
{
protected $m_aAdditionalExpressions;
public function __construct($mExpression, $sParent = '')
{
$this->m_aAdditionalExpressions = array();
if (is_array($mExpression))
{
foreach ($mExpression as $sSuffix => $sExpression)
{
if ($sSuffix == '')
{
$sName = $sExpression;
}
$this->m_aAdditionalExpressions[$sSuffix] = new FieldExpressionResolved($sExpression, $sParent);
}
}
else
{
$sName = $mExpression;
}
parent::__construct($sName, $sParent);
}
/**
* @return array of additional expressions for muti-column attributes
* @since 2.7.4
*/
public function AdditionalExpressions()
{
return $this->m_aAdditionalExpressions;
}
public function GetUnresolvedFields($sAlias, &$aUnresolved)
{
}

View File

@@ -331,12 +331,4 @@ class OQLJoin
return $this->sRightField;
}
/**
* @return string
*/
public function GetLeftField()
{
return $this->sLeftField;
}
}

View File

@@ -50,15 +50,8 @@ class OQLClassTreeOptimizer
{
if ($oJoin->IsOutbound())
{
// If joined class in not the same class than the external key target class
// then the join cannot be removed because it is used to filter the request
$sJoinedClass = $oJoin->GetOOQLClassNode()->GetNodeClass();
$sExtKeyAttCode = $oJoin->GetLeftField();
$oExtKeyAttDef = MetaModel::GetAttributeDef($oCurrentClassNode->GetNodeClass(), $sExtKeyAttCode);
if ($sJoinedClass == $oExtKeyAttDef->GetTargetClass()) {
// The join is not used, remove from tree
$oCurrentClassNode->RemoveJoin($sLeftKey, $index);
}
// The join is not used, remove from tree
$oCurrentClassNode->RemoveJoin($sLeftKey, $index);
}
else
{

View File

@@ -178,14 +178,6 @@ class QueryBuilderExpressions
foreach ($this->m_aSelectExpr as $sColAlias => $oExpr)
{
$this->m_aSelectExpr[$sColAlias] = $oExpr->Translate($aTranslationData, $bMatchAll, $bMarkFieldsAsResolved);
if ($this->m_aSelectExpr[$sColAlias] instanceof FieldExpressionResolved)
{
// Split the field with the relevant alias
foreach ($this->m_aSelectExpr[$sColAlias]->AdditionalExpressions() as $sSuffix => $oAdditionalExpr)
{
$this->m_aSelectExpr[$sColAlias.$sSuffix] = $oAdditionalExpr->Translate($aTranslationData, $bMatchAll, $bMarkFieldsAsResolved);
}
}
}
if ($this->m_aGroupByExpr)
{

View File

@@ -239,16 +239,24 @@ class SQLObjectQueryBuilder
continue;
}
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
$oFieldSQLExp = new FieldExpressionResolved($oAttDef->GetSQLExpressions(), $sClassAlias);
/**
* @var string $sPluginClass
* @var iQueryModifier $oQueryModifier
*/
foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
{
$oFieldSQLExp = $oQueryModifier->GetFieldExpression($oBuild, $sClass, $sAttCode, '', $oFieldSQLExp, $oBaseSQLQuery);
if (!empty($sColId))
{
// Multi column attributes
$oBuild->m_oQBExpressions->AddSelect($sSelectedClassAlias.$sAttCode.$sColId, new FieldExpression($sAttCode.$sColId, $sClassAlias));
}
$oFieldSQLExp = new FieldExpressionResolved($sSQLExpr, $sClassAlias);
/**
* @var string $sPluginClass
* @var iQueryModifier $oQueryModifier
*/
foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
{
$oFieldSQLExp = $oQueryModifier->GetFieldExpression($oBuild, $sClass, $sAttCode, $sColId, $oFieldSQLExp, $oBaseSQLQuery);
}
$aTranslation[$sClassAlias][$sAttCode.$sColId] = $oFieldSQLExp;
}
$aTranslation[$sClassAlias][$sAttCode] = $oFieldSQLExp;
}
// Translate the selected columns

View File

@@ -17,7 +17,7 @@
*/
// Beware the version number MUST be enclosed with quotes otherwise v2.3.0 becomes v2 0.3 .0
$version: "v2.7.4";
$version: "v2.7.3";
$approot-relative: "../../../../../" !default; // relative to env-***/branding/themes/***/main.css
// Base colors

View File

@@ -5,7 +5,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'authent-cas/2.7.4',
'authent-cas/2.7.0',
array(
// Identification
//

View File

@@ -27,7 +27,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'authent-external/2.7.4',
'authent-external/2.7.0',
array(
// Identification
//

View File

@@ -9,7 +9,7 @@ if (function_exists('ldap_connect'))
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'authent-ldap/2.7.4',
'authent-ldap/2.7.0',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'authent-local/2.7.4',
'authent-local/2.7.1',
array(
// Identification
//

View File

@@ -24,7 +24,7 @@
/** @noinspection PhpUnhandledExceptionInspection */
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'combodo-db-tools/2.7.4',
'combodo-db-tools/2.7.1',
array(
// Identification
//

View File

@@ -19,7 +19,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-attachments/2.7.4',
'itop-attachments/2.7.1',
array(
// Identification
//
@@ -80,31 +80,6 @@ if (!class_exists('AttachmentInstaller'))
return $oConfiguration;
}
/**
* @since 2.7.4 N°3788
* @param string $sTableName
* @param int $iBulkSize
*
* @return array
* @throws \CoreException
* @throws \MySQLException
* @throws \MySQLHasGoneAwayException
*/
public static function GetOrphanAttachmentIds($sTableName, $iBulkSize){
$sSqlQuery = <<<SQL
SELECT id as attachment_id FROM `$sTableName` WHERE (`item_id`='' OR `item_id` IS NULL) LIMIT {$iBulkSize};
SQL;
/** @var \mysqli_result $oQueryResult */
$oQueryResult = CMDBSource::Query($sSqlQuery);
$aIds = [];
while($aRow = $oQueryResult->fetch_array()){
$aIds[] = $aRow['attachment_id'];
}
return $aIds;
}
/**
* Handler called before creating or upgrading the database schema
* @param $oConfiguration Config The new configuration of the application
@@ -122,32 +97,10 @@ SQL;
$iCount = CMDBSource::QueryToScalar($sCountQuery);
if ($iCount > 0)
{
SetupPage::log_info("Cleanup of orphan attachments that cannot be migrated to the new ObjKey model: $iCount record(s) must be deleted.");
$iBulkSize = 100;
$iMaxDuration = 30;
$iDeletedCount = 0;
$fStartTime = microtime(true);
$aIds = self::GetOrphanAttachmentIds($sTableName, $iBulkSize);
while (count($aIds) !== 0) {
$sCleanupQuery = sprintf("DELETE FROM `$sTableName` WHERE `id` IN (%s)", implode(",", $aIds));
CMDBSource::Query($sCleanupQuery); // Throws an exception in case of error
$iDeletedCount += count($aIds);
$fElapsed = microtime(true) - $fStartTime;
if ($fElapsed > $iMaxDuration){
SetupPage::log_info(sprintf("Cleanup of orphan attachments interrupted after %.3f s. $iDeletedCount records were deleted among $iCount.", $fElapsed));
break;
}
$aIds = self::GetOrphanAttachmentIds($sTableName, $iBulkSize);
}
if (count($aIds) === 0){
SetupPage::log_info("Cleanup of orphan attachments successfully completed.");
}
SetupPage::log_info("Cleanup of orphan attachments that cannot be migrated to the new ObjKey model: $iCount record(s) must be deleted.");
$sRepairQuery = "DELETE FROM `$sTableName` WHERE (`item_id`='' OR `item_id` IS NULL)";
$iRet = CMDBSource::Query($sRepairQuery); // Throws an exception in case of error
SetupPage::log_info("Cleanup of orphan attachments successfully completed.");
}
else
{
@@ -155,7 +108,7 @@ SQL;
}
}
}
/**
* Handler called after the creation/update of the database schema
* @param $oConfiguration Config The new configuration of the application
@@ -170,7 +123,6 @@ SQL;
// Prerequisite: change null into 0 (workaround to the fact that we cannot use IS NULL in OQL)
SetupPage::log_info("Initializing attachment/item_org_id - null to zero");
$sTableName = MetaModel::DBGetTable('Attachment');
$sRepair = "UPDATE `$sTableName` SET `item_org_id` = 0 WHERE `item_org_id` IS NULL";
CMDBSource::Query($sRepair);
@@ -180,13 +132,7 @@ SQL;
$iUpdated = 0;
while ($oAttachment = $oSet->Fetch())
{
if (empty($oAttachment->Get('item_class'))) {
//do not treat orphan attachment
continue;
}
$oContainer = MetaModel::GetObject($oAttachment->Get('item_class'), $oAttachment->Get('item_id'), false /* must be found */, true /* allow all data */);
if ($oContainer)
{
$oAttachment->SetItem($oContainer, true /*updateonchange*/);

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-backup/2.7.4',
'itop-backup/2.7.1',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-bridge-virtualization-storage/2.7.4',
'itop-bridge-virtualization-storage/2.7.0',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-change-mgmt-itil/2.7.4',
'itop-change-mgmt-itil/2.7.0',
array(
// Identification
//

View File

@@ -237,9 +237,9 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array(
Dict::Add('NL NL', 'Dutch', 'Nederlands', array(
'Class:NormalChange' => 'Normale Change',
'Class:NormalChange+' => '',
'Class:NormalChange/Attribute:acceptance_date' => 'Datum acceptatie',
'Class:NormalChange/Attribute:acceptance_date' => 'Datum goedkeuring',
'Class:NormalChange/Attribute:acceptance_date+' => '',
'Class:NormalChange/Attribute:acceptance_comment' => 'Commentaar acceptatie',
'Class:NormalChange/Attribute:acceptance_comment' => 'Commentaar goedkeuring',
'Class:NormalChange/Attribute:acceptance_comment+' => '',
'Class:NormalChange/Stimulus:ev_validate' => 'Valideer',
'Class:NormalChange/Stimulus:ev_validate+' => '',

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-change-mgmt/2.7.4',
'itop-change-mgmt/2.7.0',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-config-mgmt/2.7.4',
'itop-config-mgmt/2.7.1',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-config/2.7.4',
'itop-config/2.7.0',
array(
// Identification
//

View File

@@ -75,7 +75,6 @@ Dict::Add('EN US', 'English', 'English', array(
'iTopUpdate:UI:CanCoreUpdate:Yes' => 'Application can be updated',
'iTopUpdate:UI:CanCoreUpdate:No' => 'Application cannot be updated: %1$s',
'iTopUpdate:UI:CanCoreUpdate:Warning' => 'Warning: application update can fail: %1$s',
'iTopUpdate:UI:CannotUpdateUseSetup' => 'You must use the <a href="%1$s">setup</a> to update the application.<br />Some modified files were detected, a partial update cannot be executed.',
// Setup Messages
'iTopUpdate:UI:SetupMessage:Ready' => 'Ready to start',

View File

@@ -75,7 +75,6 @@ Dict::Add('FR FR', 'French', 'Français', array(
'iTopUpdate:UI:CanCoreUpdate:Yes' => 'L\'application peut être mise à jour',
'iTopUpdate:UI:CanCoreUpdate:No' => 'L\'application ne peut pas être mise à jour : %1$s',
'iTopUpdate:UI:CanCoreUpdate:Warning' => 'Attention : la mise à jour de l\'application peut échouer : %1$s',
'iTopUpdate:UI:CannotUpdateUseSetup' => 'Vous devez utiliser la page <a href="%1$s">d\'installation</a> pour mettre à jour l\'application.<br />Des fichiers modifiés ont été détectés, une mise à jour partielle ne peut pas être effectuée.',
// Setup Messages
'iTopUpdate:UI:SetupMessage:Ready' => 'Prêt pour l\\installation',

View File

@@ -24,7 +24,7 @@
/** @noinspection PhpUnhandledExceptionInspection */
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-core-update/2.7.4',
'itop-core-update/2.7.1',
array(
// Identification
//

View File

@@ -37,8 +37,7 @@ class AjaxController extends Controller
}
else
{
$sLink = utils::GetAbsoluteUrlAppRoot().'setup/';
$aParams['sMessage'] = Dict::Format('iTopUpdate:UI:CannotUpdateUseSetup', $sLink);
$aParams['sMessage'] = Dict::Format("iTopUpdate:UI:CanCoreUpdate:{$sCanUpdateCore}", $sMessage);
}
} catch (FileNotExistException $e)
{

View File

@@ -54,7 +54,7 @@
</fieldset>
<fieldset id="form-update-outer">
<fieldset>
<legend>{{ 'iTopUpdate:UI:SelectUpdateFile'|dict_s }}</legend>
<div class="details">

View File

@@ -22,9 +22,6 @@ $.ajax({
}
else
{
$("#check-update").prop("disabled", true);
$("#file").prop("disabled", true);
$('#form-update-outer').slideUp(600);
oRequirements.addClass("message_error");
}
}

View File

@@ -18,7 +18,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-datacenter-mgmt/2.7.4',
'itop-datacenter-mgmt/2.7.0',
array(
// Identification
//

View File

@@ -25,7 +25,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-endusers-devices/2.7.4',
'itop-endusers-devices/2.7.0',
array(
// Identification
//

View File

@@ -24,7 +24,7 @@
/** @noinspection PhpUnhandledExceptionInspection */
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-files-information/2.7.4',
'itop-files-information/2.7.1',
array(
// Identification
//

View File

@@ -6,7 +6,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-full-itil/2.7.4',
'itop-full-itil/2.7.0',
array(
// Identification
//

View File

@@ -5,7 +5,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-hub-connector/2.7.4',
'itop-hub-connector/2.7.0',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-incident-mgmt-itil/2.7.4',
'itop-incident-mgmt-itil/2.7.0',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-knownerror-mgmt/2.7.4',
'itop-knownerror-mgmt/2.7.0',
array(
// Identification
//

View File

@@ -20,7 +20,7 @@
/** @noinspection PhpUnhandledExceptionInspection */
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-portal-base/2.7.4', array(
'itop-portal-base/2.7.1', array(
// Identification
'label' => 'Portal Development Library',
'category' => 'Portal',

View File

@@ -33,7 +33,6 @@ $(function()
category: 'redirect',
url: null,
modal: false,
timeout_duration: 400,
},
cancel_rule: {
category: 'close',
@@ -57,7 +56,7 @@ $(function()
this.options.submit_rule.url = this.options.submit_url;
if((this.options.cancel_url !== null) && (this.options.cancel_url !== ''))
this.options.cancel_rule.url = this.options.cancel_url;
this._super();
},
@@ -144,14 +143,12 @@ $(function()
// Determine where we go in case validation is successful
var sRuleType = me.options.submit_rule.category;
var bRedirectInModal = me.options.submit_rule.modal;
var iRedirectTimeout = me.options.submit_rule.timeout_duration;
var sRedirectUrl = me.options.submit_rule.url;
// - The validation might want us to be redirect elsewhere
if(oValidation.valid)
{
// Checking if we have to redirect to another page
// Typically this happens when applying a stimulus, we redirect to the transition form
// This code let the ajax response override the initial parameters
if(oValidation.redirection !== undefined)
{
var oRedirection = oValidation.redirection;
@@ -163,10 +160,6 @@ $(function()
{
sRedirectUrl = oRedirection.url;
}
if(oRedirection.timeout_duration !== undefined)
{
iRedirectTimeout = oRedirection.timeout_duration;
}
sRuleType = 'redirect';
}
}
@@ -248,7 +241,7 @@ $(function()
// Checking if we have to redirect to another page
if(sRuleType === 'redirect')
{
me._applyRedirectRule(sRedirectUrl, bRedirectInModal, iRedirectTimeout);
me._applyRedirectRule(sRedirectUrl, bRedirectInModal);
}
// Close rule only needs to be applied to non modal forms (modal is always closed on submit)
else if(sRuleType === 'close')
@@ -367,13 +360,10 @@ $(function()
{
$('#page_overlay').fadeOut(200);
},
_applyRedirectRule: function(sRedirectUrl, bRedirectInModal, iRedirectTimeout)
_applyRedirectRule: function(sRedirectUrl, bRedirectInModal)
{
var me = this;
//optional argument
iRedirectTimeout = (typeof iRedirectTimeout !== 'undefined' && iRedirectTimeout != null ) ? iRedirectTimeout : 400;
// Always close current modal
if(this.options.is_modal)
{
@@ -401,8 +391,8 @@ $(function()
// Showing loader while redirecting, otherwise user tend to click somewhere in the page.
// Note: We use a timeout because .always() is called right after here and will hide the loader
setTimeout(function(){ me._disableFormBeforeLoading(); }, 50);
// Redirecting after a few ms so the user can see what happened
setTimeout(function() { location.href = sRedirectUrl; }, iRedirectTimeout);
// Redirecting after a few ms so the user can see what happend
setTimeout(function() { location.href = sRedirectUrl; }, 400);
}
}
},

View File

@@ -252,7 +252,6 @@ class ManageBrickController extends BrickController
$oExporter->SetObjectList($oSearch);
$oExporter->SetFormat($sFormat);
$oExporter->SetChunkSize(EXPORTER_DEFAULT_CHUNK_SIZE);
$oExporter->SetLocalizeOutput(true);
$oExporter->SetFields($sFields);
$aData = array(

View File

@@ -639,7 +639,7 @@ class ObjectController extends BrickController
$oSet = new DBObjectSet($oSearch, array(), array('this' => $oHostObject, 'ac_query' => '%'.$sQuery.'%'));
$oSet->OptimizeColumnLoad(array($oSearch->GetClassAlias() => array('friendlyname')));
// Note : This limit is also used in the field renderer by typeahead to determine how many suggestions to display
$oSet->SetLimit(MetaModel::GetConfig()->Get('max_display_limit'));
$oSet->SetLimit(MetaModel::GetConfig()->GetMaxDisplayLimit());
// - Retrieving objects
while ($oItem = $oSet->Fetch())

View File

@@ -211,7 +211,6 @@ class UserProfileBrickController extends BrickController
{
$aFormData['validation']['redirection'] = array(
'url' => $oUrlGenerator->generate('p_user_profile_brick'),
'timeout_duration' => 1000, //since there are several ajax request, we use a longer timeout in hope that they will all be finished in time. A promise would have been more reliable, but since this change is made in a minor version, this approach is less error prone.
);
}
}

View File

@@ -1048,26 +1048,6 @@ class ObjectFormManager extends FormManager
$this->CancelAttachments();
}
/**
* @inheritDoc
*/
public function CheckTransaction(&$aData)
{
$isTransactionValid = \utils::IsTransactionValid($this->oForm->GetTransactionId(), false); //The transaction token is kept in order to preserve BC with ajax forms (the second call would fail if the token is deleted). (The GC will take care of cleaning the token for us later on)
if (!$isTransactionValid) {
if ($this->oObject->IsNew()) {
$sError = Dict::S('UI:Error:ObjectAlreadyCreated');
} else {
$sError = Dict::S('UI:Error:ObjectAlreadyUpdated');
}
$aData['messages']['error'] += [
'_main' => [$sError]
];
$aData['valid'] = false;
}
}
/**
* Validates the form and returns an array with the validation status and the messages.
* If the form is valid, creates/updates the object.
@@ -1090,116 +1070,124 @@ class ObjectFormManager extends FormManager
*/
public function OnSubmit($aArgs = null)
{
$aData = parent::OnSubmit($aArgs);
if (! $aData['valid']) {
return $aData;
}
$aData = array(
'valid' => true,
'messages' => array(
'success' => array(),
'warnings' => array(), // Not used as of today, just to show that the structure is ready for change like this.
'error' => array(),
),
);
// Update object and form
$this->OnUpdate($aArgs);
// Check if form valid
if (! $this->oForm->Validate())
if ($this->oForm->Validate())
{
// The try catch is essentially to start a MySQL transaction in order to ensure that all or none objects are persisted when creating an object with links
try
{
$sObjectClass = get_class($this->oObject);
// Starting transaction
CMDBSource::Query('START TRANSACTION');
// Forcing allowed writing on the object if necessary. This is used in some particular cases.
$bAllowWrite = ($sObjectClass === 'Person' && $this->oObject->GetKey() == UserRights::GetContactId());
if ($bAllowWrite)
{
$this->oObject->AllowWrite(true);
}
// Writing object to DB
$bActivateTriggers = (!$this->oObject->IsNew() && $this->oObject->IsModified());
$bWasModified = $this->oObject->IsModified();
try
{
$this->oObject->DBWrite();
}
catch (CoreCannotSaveObjectException $e)
{
throw new Exception($e->getHtmlMessage());
}
// Finalizing images link to object, otherwise it will be cleaned by the GC
InlineImage::FinalizeInlineImages($this->oObject);
// Finalizing attachments link to object
// TODO : This has to be refactored when the function from itop-attachments has been migrated into the core
if (isset($aArgs['attachmentIds']))
{
$this->FinalizeAttachments($aArgs['attachmentIds']);
}
// Ending transaction with a commit as everything was fine
CMDBSource::Query('COMMIT');
// Checking if we have to apply a stimulus
if (isset($aArgs['applyStimulus']))
{
$this->oObject->ApplyStimulus($aArgs['applyStimulus']['code']);
}
// Activating triggers only on update
if ($bActivateTriggers)
{
$sTriggersQuery = $this->oContainer->getParameter('combodo.portal.instance.conf')['properties']['triggers_query'];
if ($sTriggersQuery !== null)
{
$aParentClasses = MetaModel::EnumParentClasses($sObjectClass, ENUM_PARENT_CLASSES_ALL);
$oTriggerSet = new DBObjectSet(DBObjectSearch::FromOQL($sTriggersQuery), array(),
array('parent_classes' => $aParentClasses));
/** @var \Trigger $oTrigger */
while ($oTrigger = $oTriggerSet->Fetch())
{
try
{
$oTrigger->DoActivate($this->oObject->ToArgs('this'));
}
catch(Exception $e)
{
utils::EnrichRaisedException($oTrigger, $e);
}
}
}
}
// Resetting caselog fields value, otherwise the value will stay in it after submit.
$this->oForm->ResetCaseLogFields();
if ($bWasModified)
{
//=if (isNew) because $bActivateTriggers = (!$this->oObject->IsNew() && $this->oObject->IsModified())
if(!$bActivateTriggers)
{
$aData['messages']['success'] += array( '_main' => array(Dict::Format('UI:Title:Object_Of_Class_Created', $this->oObject->GetName(),MetaModel::GetName(get_class($this->oObject)))));
}
else
{
$aData['messages']['success'] += array('_main' => array(Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($this->oObject)), $this->oObject->GetName())));
}
}
}
catch (Exception $e)
{
// End transaction with a rollback as something failed
CMDBSource::Query('ROLLBACK');
$aData['valid'] = false;
$aData['messages']['error'] += array('_main' => array($e->getMessage()));
IssueLog::Error(__METHOD__.' at line '.__LINE__.' : Rollback during submit ('.$e->getMessage().')');
}
finally
{
// Removing transaction id
utils::RemoveTransaction($this->oForm->GetTransactionId());
}
}
else
{
// Handle errors
$aData['valid'] = false;
$aData['messages']['error'] += $this->oForm->GetErrorMessages();
return $aData;
}
// The try catch is essentially to start a MySQL transaction in order to ensure that all or none objects are persisted when creating an object with links
try
{
$sObjectClass = get_class($this->oObject);
// Starting transaction
CMDBSource::Query('START TRANSACTION');
// Forcing allowed writing on the object if necessary. This is used in some particular cases.
$bAllowWrite = ($sObjectClass === 'Person' && $this->oObject->GetKey() == UserRights::GetContactId());
if ($bAllowWrite)
{
$this->oObject->AllowWrite(true);
}
// Writing object to DB
$bActivateTriggers = (!$this->oObject->IsNew() && $this->oObject->IsModified());
$bWasModified = $this->oObject->IsModified();
try
{
$this->oObject->DBWrite();
}
catch (CoreCannotSaveObjectException $e)
{
throw new Exception($e->getHtmlMessage());
}
// Finalizing images link to object, otherwise it will be cleaned by the GC
InlineImage::FinalizeInlineImages($this->oObject);
// Finalizing attachments link to object
// TODO : This has to be refactored when the function from itop-attachments has been migrated into the core
if (isset($aArgs['attachmentIds']))
{
$this->FinalizeAttachments($aArgs['attachmentIds']);
}
// Ending transaction with a commit as everything was fine
CMDBSource::Query('COMMIT');
// Checking if we have to apply a stimulus
if (isset($aArgs['applyStimulus']))
{
$this->oObject->ApplyStimulus($aArgs['applyStimulus']['code']);
}
// Activating triggers only on update
if ($bActivateTriggers)
{
$sTriggersQuery = $this->oContainer->getParameter('combodo.portal.instance.conf')['properties']['triggers_query'];
if ($sTriggersQuery !== null)
{
$aParentClasses = MetaModel::EnumParentClasses($sObjectClass, ENUM_PARENT_CLASSES_ALL);
$oTriggerSet = new DBObjectSet(DBObjectSearch::FromOQL($sTriggersQuery), array(),
array('parent_classes' => $aParentClasses));
/** @var \Trigger $oTrigger */
while ($oTrigger = $oTriggerSet->Fetch())
{
try
{
$oTrigger->DoActivate($this->oObject->ToArgs('this'));
}
catch(Exception $e)
{
utils::EnrichRaisedException($oTrigger, $e);
}
}
}
}
// Resetting caselog fields value, otherwise the value will stay in it after submit.
$this->oForm->ResetCaseLogFields();
if ($bWasModified)
{
//=if (isNew) because $bActivateTriggers = (!$this->oObject->IsNew() && $this->oObject->IsModified())
if(!$bActivateTriggers)
{
$aData['messages']['success'] += array( '_main' => array(Dict::Format('UI:Title:Object_Of_Class_Created', $this->oObject->GetName(),MetaModel::GetName(get_class($this->oObject)))));
}
else
{
$aData['messages']['success'] += array('_main' => array(Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($this->oObject)), $this->oObject->GetName())));
}
}
}
catch (Exception $e)
{
// End transaction with a rollback as something failed
CMDBSource::Query('ROLLBACK');
$aData['valid'] = false;
$aData['messages']['error'] += array('_main' => array($e->getMessage()));
IssueLog::Error(__METHOD__.' at line '.__LINE__.' : Rollback during submit ('.$e->getMessage().')');
}
return $aData;
}

View File

@@ -48,8 +48,6 @@ class PasswordFormManager extends FormManager
// Building the form
$oForm = new Form('change_password');
$oForm->SetTransactionId(\utils::GetNewTransactionId());
// Adding hidden field with form type
$oField = new HiddenField('form_type');
$oField->SetCurrentValue('change_password');
@@ -95,11 +93,14 @@ class PasswordFormManager extends FormManager
*/
public function OnSubmit($aArgs = null)
{
$aData = parent::OnSubmit($aArgs);
if (! $aData['valid']) {
return $aData;
}
$aData = array(
'valid' => true,
'messages' => array(
'success' => array(),
'warnings' => array(), // Not used as of today, just to show that the structure is ready for change like this.
'error' => array(),
),
);
// Update object and form
$this->OnUpdate($aArgs);

View File

@@ -49,8 +49,6 @@ class PreferencesFormManager extends FormManager
// Building the form
$oForm = new Form('preferences');
$oForm->SetTransactionId(\utils::GetNewTransactionId());
// Adding hidden field with form type
$oField = new HiddenField('form_type');
$oField->SetCurrentValue('preferences');
@@ -99,11 +97,14 @@ class PreferencesFormManager extends FormManager
*/
public function OnSubmit($aArgs = null)
{
$aData = parent::OnSubmit($aArgs);
if (! $aData['valid']) {
return $aData;
}
$aData = array(
'valid' => true,
'messages' => array(
'success' => array(),
'warnings' => array(), // Not used as of today, just to show that the structure is ready for change like this.
'error' => array(),
),
);
// Update object and form
$this->OnUpdate($aArgs);

View File

@@ -397,15 +397,16 @@
}
}
};
// N°3995: Loader is shown immediately, otherwise when we have a huge amount of items, we can have a bottleneck on the buildMosaic() function, blocking the display of the loader
showMosaicLoader();
$(document).ready(function(){
// Auto collapse item actions popup
$('body').click(function(){
$('#brick_content_mosaic .item-action-wrapper.collapse.in').collapse('hide');
});
// Build the tree (collapsed)
showMosaicLoader();
// Build the mosaic (collapsed)
buildMosaic(oRawDatas);
hideMosaicLoader();
registerFilterListeners();

View File

@@ -321,6 +321,8 @@
}
};
// N°3995: Loader is shown immediately, otherwise when we have a huge amount of items, we can have a bottleneck on the buildTree() function, blocking the display of the loader
showTreeLoader();
$(document).ready(function(){
// Init expand/collapse all buttons
$('#btn-collapse-all').on('click', function (oEvent) {
@@ -405,7 +407,6 @@
});
// Build the tree (collapsed)
showTreeLoader();
buildTree(oRawDatas);
hideTreeLoader();
registerFilterListeners();

View File

@@ -227,10 +227,16 @@
$('#user-profile-wrapper .form_field .help-block > p').remove();
// Submiting contact form through AJAX
$('#{{ oContactForm.id }}').portal_form_handler('submit', oEvent);
//if($('#{{ oContactForm.id }} .field_set').field_set('hasTouchedFields'))
//{
$('#{{ oContactForm.id }}').portal_form_handler('submit', oEvent);
//}
// Submiting preferences form through AJAX
$('#{{ oPreferencesForm.id }}').portal_form_handler('submit', oEvent);
//if($('#{{ oPreferencesForm.id }} .field_set').field_set('hasTouchedFields'))
//{
$('#{{ oPreferencesForm.id }}').portal_form_handler('submit', oEvent);
//}
{% if oPasswordForm is not null %}
// Submiting password form through AJAX

View File

@@ -20,7 +20,7 @@
/** @noinspection PhpUnhandledExceptionInspection */
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-portal/2.7.4', array(
'itop-portal/2.7.0', array(
// Identification
'label' => 'Enhanced Customer Portal',
'category' => 'Portal',

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-problem-mgmt/2.7.4',
'itop-problem-mgmt/2.7.0',
array(
// Identification
//

View File

@@ -19,7 +19,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-profiles-itil/2.7.4',
'itop-profiles-itil/2.7.0',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-request-mgmt-itil/2.7.4',
'itop-request-mgmt-itil/2.7.0',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-request-mgmt/2.7.4',
'itop-request-mgmt/2.7.0',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-service-mgmt-provider/2.7.4',
'itop-service-mgmt-provider/2.7.1',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-service-mgmt/2.7.4',
'itop-service-mgmt/2.7.1',
array(
// Identification
//

View File

@@ -18,7 +18,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-sla-computation/2.7.4',
'itop-sla-computation/2.7.0',
array(
// Identification
//

View File

@@ -25,7 +25,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-storage-mgmt/2.7.4',
'itop-storage-mgmt/2.7.0',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__,
'itop-tickets/2.7.4',
'itop-tickets/2.7.0',
array(
// Identification
//

View File

@@ -16,7 +16,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-virtualization-mgmt/2.7.4',
'itop-virtualization-mgmt/2.7.0',
array(
// Identification
//

View File

@@ -3,7 +3,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-welcome-itil/2.7.4',
'itop-welcome-itil/2.7.1',
array(
// Identification
//

View File

@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<information>
<version>2.7.4</version>
<version>2.7.2</version>
</information>

View File

@@ -1045,14 +1045,4 @@ Dict::Add('EN US', 'English', 'English', array(
'Class:AsyncTask/Attribute:event_id+' => '',
'Class:AsyncTask/Attribute:finalclass' => 'Final class',
'Class:AsyncTask/Attribute:finalclass+' => '',
'Class:AsyncTask/Attribute:status' => 'Status',
'Class:AsyncTask/Attribute:status+' => '',
'Class:AsyncTask/Attribute:remaining_retries' => 'Remaining retries',
'Class:AsyncTask/Attribute:remaining_retries+' => '',
'Class:AsyncTask/Attribute:last_error_code' => 'Last error code',
'Class:AsyncTask/Attribute:last_error_code+' => '',
'Class:AsyncTask/Attribute:last_error' => 'Last error',
'Class:AsyncTask/Attribute:last_error+' => '',
'Class:AsyncTask/Attribute:last_attempt' => 'Last attempt',
'Class:AsyncTask/Attribute:last_attempt+' => '',
));

View File

@@ -457,7 +457,6 @@ Dict::Add('EN US', 'English', 'English', array(
'UI:Error:ObjectsAlreadyDeleted' => 'Error: objects have already been deleted!',
'UI:Error:BulkDeleteNotAllowedOn_Class' => 'You are not allowed to perform a bulk delete of objects of class %1$s',
'UI:Error:DeleteNotAllowedOn_Class' => 'You are not allowed to delete objects of class %1$s',
'UI:Error:ReadNotAllowedOn_Class' => 'You are not allowed to view objects of class %1$s',
'UI:Error:BulkModifyNotAllowedOn_Class' => 'You are not allowed to perform a bulk update of objects of class %1$s',
'UI:Error:ObjectAlreadyCloned' => 'Error: the object has already been cloned!',
'UI:Error:ObjectAlreadyCreated' => 'Error: the object has already been created!',
@@ -466,7 +465,6 @@ Dict::Add('EN US', 'English', 'English', array(
'UI:Error:InvalidDashboard' => 'Error: invalid dashboard',
'UI:Error:MaintenanceMode' => 'Application is currently in maintenance',
'UI:Error:MaintenanceTitle' => 'Maintenance',
'UI:Error:InvalidToken' => 'Error: the requested operation has already been performed (CSRF token not found)',
'UI:GroupBy:Count' => 'Count',
'UI:GroupBy:Count+' => 'Number of elements',
@@ -1561,8 +1559,6 @@ When associated with a trigger, each action is given an "order" number, specifyi
'UI:Search:Criteria:Raw:Filtered' => 'Filtered',
'UI:Search:Criteria:Raw:FilteredOn' => 'Filtered on %1$s',
'UI:StateChanged' => 'State changed',
));
//

View File

@@ -1043,18 +1043,6 @@ Dict::Add('FR FR', 'French', 'Français', array(
'Class:AsyncTask/Attribute:event_id+' => '',
'Class:AsyncTask/Attribute:finalclass' => 'Sous-classe de tâche asynchrone',
'Class:AsyncTask/Attribute:finalclass+' => '',
'Class:AsyncTask/Attribute:status' => 'Statut',
'Class:AsyncTask/Attribute:status+' => '',
'Class:AsyncTask/Attribute:remaining_retries' => 'Essais restants',
'Class:AsyncTask/Attribute:remaining_retries+' => '',
'Class:AsyncTask/Attribute:last_error_code' => 'Dernier code d\'erreur',
'Class:AsyncTask/Attribute:last_error_code+' => '',
'Class:AsyncTask/Attribute:last_error' => 'Dernière erreur',
'Class:AsyncTask/Attribute:last_error+' => '',
'Class:AsyncTask/Attribute:last_attempt' => 'Dernière tentative',
'Class:AsyncTask/Attribute:last_attempt+' => '',
));
// Additional language entries not present in English dict

View File

@@ -439,8 +439,7 @@ Dict::Add('FR FR', 'French', 'Français', array(
'UI:Error:ObjectCannotBeUpdated' => 'Erreur: l\'objet ne peut pas être mis à jour.',
'UI:Error:ObjectsAlreadyDeleted' => 'Erreur: les objets ont déjà été supprimés !',
'UI:Error:BulkDeleteNotAllowedOn_Class' => 'Vous n\'êtes pas autorisé à faire une suppression massive sur les objets de type %1$s',
'UI:Error:DeleteNotAllowedOn_Class' => 'Vous n\'êtes pas autorisé à supprimer des objets de type %1$s',
'UI:Error:ReadNotAllowedOn_Class' => 'Vous n\'êtes pas autorisé à voir des objets de type %1$s',
'UI:Error:DeleteNotAllowedOn_Class' => 'Vous n\'êtes pas autorisé supprimer des objets de type %1$s',
'UI:Error:BulkModifyNotAllowedOn_Class' => 'Vous n\'êtes pas autorisé à faire une modification massive sur les objets de type %1$s',
'UI:Error:ObjectAlreadyCloned' => 'Erreur: l\'objet a déjà été dupliqué !',
'UI:Error:ObjectAlreadyCreated' => 'Erreur: l\'objet a déjà été créé !',
@@ -449,7 +448,6 @@ Dict::Add('FR FR', 'French', 'Français', array(
'UI:Error:InvalidDashboard' => 'Erreur: Le tableau de bord est invalide',
'UI:Error:MaintenanceMode' => 'L\'application est en maintenance',
'UI:Error:MaintenanceTitle' => 'Maintenance',
'UI:Error:InvalidToken' => 'Erreur: l\'opération a déjà été effectuée (CSRF token not found)',
'UI:GroupBy:Count' => 'Nombre',
'UI:GroupBy:Count+' => 'Nombre d\'éléments',
@@ -1541,8 +1539,6 @@ Lors de l\'association à un déclencheur, on attribue à chaque action un numé
'UI:Search:Criteria:Raw:Filtered' => 'Filtré',
'UI:Search:Criteria:Raw:FilteredOn' => 'Filtré sur %1$s',
'UI:StateChanged' => 'Etat modifié',
));
//

View File

@@ -813,7 +813,7 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array(
'UI:Delete:WillBeDeletedAutomatically' => 'Zal automatisch verwijderd worden',
'UI:Delete:MustBeDeletedManually' => 'Moet handmatig verwijderd worden',
'UI:Delete:CannotUpdateBecause_Issue' => 'Zou automatisch moeten geüpdatet worden, maar: %1$s',
'UI:Delete:WillAutomaticallyUpdate_Fields' => 'Zal automatisch aangepast worden (reset: %1$s)',
'UI:Delete:WillAutomaticallyUpdate_Fields' => 'Zal automatisch aangeapst worden (reset: %1$s)',
'UI:Delete:Count_Objects/LinksReferencing_Object' => '%1$d objecten/links verwijzen naar %2$s',
'UI:Delete:Count_Objects/LinksReferencingTheObjects' => '%1$d objecten/links verwijzen naar sommige objecten die verwijderd worden',
'UI:Delete:ReferencesMustBeDeletedToEnsureIntegrity' => 'Elke verdere verwijzing moet verwijderd worden om de integriteit van de database te verzekeren',

View File

@@ -1210,7 +1210,7 @@ HTML
$sOrigState = utils::ReadPostedParam('obj_state_orig', '');
if ($sTargetState != $sOrigState)
{
$aWarnings[] = Dict::S('UI:StateChanged');
$aWarnings[] = 'State changed';
}
$oObj->Set($sStateAttCode, $sTargetState);
}

View File

@@ -727,16 +727,10 @@ class ApplicationInstaller
SetupPage::log_info("There are $iOrphanCount useless records in {$sDBPrefix}priv_change (".sprintf('%.2f', ((100.0*$iOrphanCount)/$iTotalCount))."%)");
if ($iOrphanCount > 0)
{
//N°3793
if ($iOrphanCount > 100000)
{
SetupPage::log_warning("There are too much useless records ($iOrphanCount) in {$sDBPrefix}priv_change. Cleanup cannot be done during setup.");
} else {
SetupPage::log_info("Removing the orphan records...");
$sCleanup = "DELETE FROM `{$sDBPrefix}priv_change` USING `{$sDBPrefix}priv_change` LEFT JOIN `{$sDBPrefix}priv_changeop` ON `{$sDBPrefix}priv_change`.id = `{$sDBPrefix}priv_changeop`.changeid WHERE `{$sDBPrefix}priv_changeop`.id IS NULL;";
CMDBSource::Query($sCleanup);
SetupPage::log_info("Cleanup completed successfully.");
}
SetupPage::log_info("Removing the orphan records...");
$sCleanup = "DELETE FROM `{$sDBPrefix}priv_change` USING `{$sDBPrefix}priv_change` LEFT JOIN `{$sDBPrefix}priv_changeop` ON `{$sDBPrefix}priv_change`.id = `{$sDBPrefix}priv_changeop`.changeid WHERE `{$sDBPrefix}priv_changeop`.id IS NULL;";
CMDBSource::Query($sCleanup);
SetupPage::log_info("Cleanup completed successfully.");
}
else
{

View File

@@ -61,29 +61,24 @@ class iTopExtension
* @var bool
*/
public $bVisible;
/**
* @var string[]
*/
public $aModules;
/**
* @var string[]
*/
public $aModuleVersion;
/**
* @var string[]
*/
public $aModuleInfo;
/**
* @var string
*/
public $sSourceDir;
/**
*
*
* @var string[]
*/
public $aMissingDependencies;
@@ -101,7 +96,6 @@ class iTopExtension
$this->sInstalledVersion = '';
$this->aModules = array();
$this->aModuleVersion = array();
$this->aModuleInfo = array();
$this->sSourceDir = '';
$this->bVisible = true;
$this->aMissingDependencies = array();
@@ -316,11 +310,11 @@ class iTopExtensionsMap
$sModuleVersion = '0.0.1';
}
if (($sParentExtensionId !== null) && (array_key_exists($sParentExtensionId, $this->aExtensions)) && ($this->aExtensions[$sParentExtensionId] instanceof iTopExtension)) {
if (($sParentExtensionId !== null) && (array_key_exists($sParentExtensionId, $this->aExtensions)) && ($this->aExtensions[$sParentExtensionId] instanceof iTopExtension))
{
// Already inside an extension, let's add this module the list of modules belonging to this extension
$this->aExtensions[$sParentExtensionId]->aModules[] = $sModuleName;
$this->aExtensions[$sParentExtensionId]->aModuleVersion[$sModuleName] = $sModuleVersion;
$this->aExtensions[$sParentExtensionId]->aModuleInfo[$sModuleName] = $aModuleInfo[2];
}
else
{
@@ -335,6 +329,8 @@ class iTopExtensionsMap
}
// Let's create a "fake" extension from this module (containing just this module) for backwards compatibility
$sExtensionId = $sModuleId;
$oExtension = new iTopExtension();
$oExtension->sCode = $sModuleName;
$oExtension->sLabel = $aModuleInfo[2]['label'];
@@ -345,10 +341,9 @@ class iTopExtensionsMap
$oExtension->sMoreInfoUrl = $aModuleInfo[2]['doc.more_information'];
$oExtension->aModules = array($sModuleName);
$oExtension->aModuleVersion[$sModuleName] = $sModuleVersion;
$oExtension->aModuleInfo[$sModuleName] = $aModuleInfo[2];
$oExtension->sSourceDir = $sSearchDir;
$oExtension->bVisible = $bVisible;
$this->AddExtension($oExtension);
$this->AddExtension($oExtension);
}
closedir($hDir);

View File

@@ -54,7 +54,5 @@ if (!function_exists('json_decode'))
}
/////////////////////////////////////////////////////////////////////
//N°3671 setup context: force $bForceTrustProxy to be persisted in next calls
utils::GetAbsoluteUrlAppRoot(true);
$oWizard = new WizardController('WizStepWelcome');
$oWizard->Run();

View File

@@ -551,25 +551,14 @@ class SetupUtils
SetupPage::log('Info - PHP functions disabled: '.implode(', ', $aDisabled));
if (in_array('exec', $aDisabled))
{
return new CheckResult(CheckResult::ERROR, "The PHP exec() function has been disabled on this server");
$aResult[] = new CheckResult(CheckResult::ERROR, "The PHP exec() function has been disabled on this server");
}
// availability of dot / dot.exe
if (empty($sGraphvizPath))
{
$sGraphvizPath = 'dot';
} else {
clearstatcache();
if (!is_file($sGraphvizPath) || !is_executable($sGraphvizPath)) {
//N°3412 avoid shell injection
return new CheckResult(CheckResult::WARNING, "$sGraphvizPath could not be executed: Please make sure it is installed and in the path");
}
if (!utils::IsWindowsEnvironment()){
$sGraphvizPath = escapeshellcmd($sGraphvizPath);
}
}
$sCommand = "\"$sGraphvizPath\" -V 2>&1";
$aOutput = array();
@@ -579,6 +568,10 @@ class SetupUtils
{
$oResult = new CheckResult(CheckResult::INFO, "dot is present: ".$aOutput[0]);
}
elseif ($iRetCode == 1)
{
$oResult = new CheckResult(CheckResult::WARNING, "dot could not be found: ".implode(' ', $aOutput)." - Please make sure it is installed and in the path.");
}
else
{
$oResult = new CheckResult(CheckResult::WARNING, "dot could not be executed (retcode=$iRetCode): Please make sure it is installed and in the path");

View File

@@ -978,7 +978,7 @@ class WizStepMiscParams extends WizardStep
public function Display(WebPage $oPage)
{
$sDefaultLanguage = $this->oWizard->GetParameter('default_language', $this->oWizard->GetParameter('admin_language'));
$sApplicationURL = $this->oWizard->GetParameter('application_url', utils::GetDefaultUrlAppRoot(true));
$sApplicationURL = $this->oWizard->GetParameter('application_url', utils::GetDefaultUrlAppRoot());
$sDefaultGraphvizPath = (strtolower(substr(PHP_OS, 0, 3)) === 'win') ? 'C:\\Program Files\\Graphviz\\bin\\dot.exe' : '/usr/bin/dot';
$sGraphvizPath = $this->oWizard->GetParameter('graphviz_path', $sDefaultGraphvizPath);
$sSampleData = $this->oWizard->GetParameter('sample_data', 'yes');
@@ -996,14 +996,14 @@ class WizStepMiscParams extends WizardStep
$oPage->add('<fieldset>');
$oPage->add('<legend>Application URL</legend>');
$oPage->add('<table>');
$oPage->add('<tr><td>URL: </td><td><input id="application_url" name="application_url" type="text" size="35" maxlength="1024" value="'.htmlentities($sApplicationURL, ENT_QUOTES, 'UTF-8').'" style="width: 100%;box-sizing: border-box;"><span id="v_application_url"/></td><tr>');
$oPage->add('<tr><td colspan="2"><div class="message message-warning">Change the value above if the end-users will be accessing the application by another path due to a specific configuration of the web server.</div></td><tr>');
$oPage->add('<tr><td>URL: </td><td><input id="application_url" name="application_url" type="text" size="35" maxlength="1024" value="'.htmlentities($sApplicationURL, ENT_QUOTES, 'UTF-8').'"><span id="v_application_url"/></td><tr>');
$oPage->add('<tr><td colspan="2">Change the value above if the end-users will be accessing the application by another path due to a specific configuration of the web server.</td><tr>');
$oPage->add('</table>');
$oPage->add('</fieldset>');
$oPage->add('<fieldset>');
$oPage->add('<legend>Path to Graphviz\' dot application</legend>');
$oPage->add('<table style="width: 100%;">');
$oPage->add('<tr><td>Path: </td><td><input id="graphviz_path" name="graphviz_path" type="text" size="35" maxlength="1024" value="'.htmlentities($sGraphvizPath, ENT_QUOTES, 'UTF-8').'" style="width: 100%;box-sizing: border-box;"><span id="v_graphviz_path"/></td><tr>');
$oPage->add('<tr><td>Path: </td><td><input id="graphviz_path" name="graphviz_path" type="text" size="35" maxlength="1024" value="'.htmlentities($sGraphvizPath, ENT_QUOTES, 'UTF-8').'"><span id="v_graphviz_path"/></td><tr>');
$oPage->add('<tr><td colspan="2"><a href="http://www.graphviz.org" target="_blank">Graphviz</a> is required to display the impact analysis graph (i.e. impacts / depends on).</td><tr>');
$oPage->add('<tr><td colspan="2"><span id="graphviz_status"></span></td><tr>');
$oPage->add('</table>');
@@ -1125,21 +1125,21 @@ class WizStepUpgradeMiscParams extends WizardStep
public function Display(WebPage $oPage)
{
$sApplicationURL = $this->oWizard->GetParameter('application_url', utils::GetAbsoluteUrlAppRoot(true)); //Preserve existing configuration.
$sApplicationURL = $this->oWizard->GetParameter('application_url', utils::GetDefaultUrlAppRoot());
$sDefaultGraphvizPath = (strtolower(substr(PHP_OS, 0, 3)) === 'win') ? 'C:\\Program Files\\Graphviz\\bin\\dot.exe' : '/usr/bin/dot';
$sGraphvizPath = $this->oWizard->GetParameter('graphviz_path', $sDefaultGraphvizPath);
$oPage->add('<h2>Additional parameters</h2>');
$oPage->add('<fieldset>');
$oPage->add('<legend>Application URL</legend>');
$oPage->add('<table>');
$oPage->add('<tr><td>URL: </td><td><input id="application_url" name="application_url" type="text" size="35" maxlength="1024" value="'.htmlentities($sApplicationURL, ENT_QUOTES, 'UTF-8').'" style="width: 100%;box-sizing: border-box;"><span id="v_application_url"/></td><tr>');
$oPage->add('<tr><td colspan="2"><div class="message message-warning">Change the value above if the end-users will be accessing the application by another path due to a specific configuration of the web server.</div></td><tr>');
$oPage->add('<tr><td>URL: </td><td><input id="application_url" name="application_url" type="text" size="35" maxlength="1024" value="'.htmlentities($sApplicationURL, ENT_QUOTES, 'UTF-8').'"><span id="v_application_url"/></td><tr>');
$oPage->add('<tr><td colspan="2">Change the value above if the end-users will be accessing the application by another path due to a specific configuration of the web server.</td><tr>');
$oPage->add('</table>');
$oPage->add('</fieldset>');
$oPage->add('<fieldset>');
$oPage->add('<legend>Path to Graphviz\' dot application</legend>');
$oPage->add('<table style="width: 100%;">');
$oPage->add('<tr><td>Path: </td><td><input id="graphviz_path" name="graphviz_path" type="text" size="35" maxlength="1024" value="'.htmlentities($sGraphvizPath, ENT_QUOTES, 'UTF-8').'" style="width: 100%;box-sizing: border-box;"><span id="v_graphviz_path"/></td><tr>');
$oPage->add('<tr><td>Path: </td><td><input id="graphviz_path" name="graphviz_path" type="text" size="35" maxlength="1024" value="'.htmlentities($sGraphvizPath, ENT_QUOTES, 'UTF-8').'"><span id="v_graphviz_path"/></td><tr>');
$oPage->add('<tr><td colspan="2"><a href="http://www.graphviz.org" target="_blank">Graphviz</a> is required to display the impact analysis graph (i.e. impacts / depends on).</td><tr>');
$oPage->add('<tr><td colspan="2"><span id="graphviz_status"></span></td><tr>');
$oPage->add('</table>');
@@ -1376,14 +1376,14 @@ class WizStepModulesChoice extends WizardStep
if (substr($sBannerPath, 0, 1) == '/')
{
// absolute path, means relative to APPROOT
$sBannerUrl = utils::GetDefaultUrlAppRoot(true).$sBannerPath;
$sBannerUrl = utils::GetDefaultUrlAppRoot().$sBannerPath;
}
else
{
// relative path: i.e. relative to the directory containing the XML file
$sFullPath = dirname($this->GetSourceFilePath()).'/'.$sBannerPath;
$sRealPath = realpath($sFullPath);
$sBannerUrl = utils::GetDefaultUrlAppRoot(true).str_replace(realpath(APPROOT), '', $sRealPath);
$sBannerUrl = utils::GetDefaultUrlAppRoot().str_replace(realpath(APPROOT), '', $sRealPath);
}
$oPage->add('<td><img src="'.$sBannerUrl.'"/><td>');
}
@@ -1666,12 +1666,10 @@ EOF
/**
* Converts the list of selected "choices" into a list of "modules": take into account the selected and the mandatory modules
*
* @param array $aInfo Info about the "choice" array('options' => array(...), 'alternatives' => array(...))
* @param array $aSelectedChoices List of selected choices array('name' => 'selected_value_id')
* @param array $aModules Return parameter: List of selected modules array('module_id' => true)
* @param hash $aInfo Info about the "choice" array('options' => array(...), 'alternatives' => array(...))
* @param hash $aSelectedChoices List of selected choices array('name' => 'selected_value_id')
* @param hash $aModules Return parameter: List of selected modules array('module_id' => true)
* @param string $sParentId Used for recursion
*
* @return string A text representation of what will be installed
*/
protected function GetSelectedModules($aInfo, $aSelectedChoices, &$aModules, $sParentId = '', $sDisplayChoices = '', &$aSelectedExtensions = null)
@@ -1692,55 +1690,35 @@ EOF
}
}
$aOptions = isset($aInfo['options']) ? $aInfo['options'] : array();
foreach($aOptions as $index => $aChoice) {
foreach($aOptions as $index => $aChoice)
{
$sChoiceId = $sParentId.self::$SEP.$index;
$aModuleInfo = [];
// Get the extension corresponding to the choice
foreach ($this->oExtensionsMap->GetAllExtensions() as $sExtensionVersion => $oExtension) {
if (utils::StartsWith($sExtensionVersion, $aChoice['extension_code'].'/')) {
$aModuleInfo = $oExtension->aModuleInfo;
break;
}
}
if ((isset($aChoice['mandatory']) && $aChoice['mandatory']) ||
(isset($aSelectedChoices[$sChoiceId]) && ($aSelectedChoices[$sChoiceId] == $sChoiceId))) {
if ( (isset($aChoice['mandatory']) && $aChoice['mandatory']) ||
(isset($aSelectedChoices[$sChoiceId]) && ($aSelectedChoices[$sChoiceId] == $sChoiceId)) )
{
$sDisplayChoices .= '<li>'.$aChoice['title'].'</li>';
if (isset($aChoice['modules'])) {
foreach ($aChoice['modules'] as $sModuleId) {
$bSelected = true;
if (isset($aModuleInfo[$sModuleId])) {
// Test if module has 'auto_select'
$aInfo = $aModuleInfo[$sModuleId];
if (isset($aInfo['auto_select'])) {
// Check the module selection
try {
$bSelected = false;
SetupInfo::SetSelectedModules($aModules);
eval('$bSelected = ('.$aInfo['auto_select'].');');
}
catch (Exception $e) {
$bSelected = false;
}
}
}
if ($bSelected) {
$aModules[$sModuleId] = true; // store the Id of the selected module
SetupInfo::SetSelectedModules($aModules);
}
if (isset($aChoice['modules']))
{
foreach($aChoice['modules'] as $sModuleId)
{
$aModules[$sModuleId] = true; // store the Id of the selected module
}
}
$sChoiceType = isset($aChoice['type']) ? $aChoice['type'] : 'wizard_option';
if ($aSelectedExtensions !== null) {
if ($aSelectedExtensions !== null)
{
$aSelectedExtensions[] = $aChoice['extension_code'];
}
// Recurse only for selected choices
if (isset($aChoice['sub_options'])) {
if (isset($aChoice['sub_options']))
{
$sDisplayChoices .= '<ul>';
$sDisplayChoices = $this->GetSelectedModules($aChoice['sub_options'], $aSelectedChoices, $aModules, $sChoiceId, $sDisplayChoices, $aSelectedExtensions);
$sDisplayChoices .= '</ul>';
}
$sDisplayChoices .= '</li>';
}
$index++;
}
$aAlternatives = isset($aInfo['alternatives']) ? $aInfo['alternatives'] : array();
@@ -1776,6 +1754,7 @@ EOF
}
$sDisplayChoices .= '</li>';
}
$index++;
}
if ($sParentId == '')
{
@@ -2515,7 +2494,7 @@ class WizStepDone extends WizardStep
$aManualSteps = array();
$aAvailableModules = SetupUtils::AnalyzeInstallation($this->oWizard);
$sRootUrl = utils::GetAbsoluteUrlAppRoot(true);
$sRootUrl = utils::GetAbsoluteUrlAppRoot();
$aSelectedModules = json_decode($this->oWizard->GetParameter('selected_modules'), true);
foreach($aSelectedModules as $sModuleId)
{
@@ -2547,7 +2526,7 @@ class WizStepDone extends WizardStep
{
// To mitigate security risks: pass only the filename without the extension, the download will add the extension itself
$oPage->p('Your backup is ready');
$oPage->p('<a style="background:transparent;" href="'.utils::GetAbsoluteUrlAppRoot(true).'setup/ajax.dataloader.php?operation=async_action&step_class=WizStepDone&params[backup]='.urlencode($sBackupDestination).'&authent='.$this->oWizard->GetParameter('authent','').'" target="_blank"><img src="../images/tar.png" style="border:0;vertical-align:middle;">&nbsp;Download '.basename($sBackupDestination).'</a>');
$oPage->p('<a style="background:transparent;" href="'.utils::GetAbsoluteUrlAppRoot().'setup/ajax.dataloader.php?operation=async_action&step_class=WizStepDone&params[backup]='.urlencode($sBackupDestination).'&authent='.$this->oWizard->GetParameter('authent','').'" target="_blank"><img src="../images/tar.png" style="border:0;vertical-align:middle;">&nbsp;Download '.basename($sBackupDestination).'</a>');
}
else
{

View File

@@ -160,41 +160,9 @@ abstract class FormManager
/**
* @param array|null $aArgs
*
* @return array
*
* @since 2.7.4 3.0.0 N°3430
* @return mixed
*/
public function OnSubmit($aArgs = null)
{
$aData = array(
'valid' => true,
'messages' => array(
'success' => array(),
'warnings' => array(), // Not used as of today, just to show that the structure is ready for change like this.
'error' => array(),
),
);
$this->CheckTransaction($aData);
return $aData;
}
/**
* @param array $aData
*
* @since 2.7.4 3.0.0 N°3430
*/
public function CheckTransaction(&$aData)
{
$isTransactionValid = \utils::IsTransactionValid($this->oForm->GetTransactionId(), false); //The transaction token is kept in order to preserve BC with ajax forms (the second call would fail if the token is deleted). (The GC will take care of cleaning the token for us later on)
if (!$isTransactionValid) {
$aData['messages']['error'] += [
'_main' => [\Dict::S('UI:Error:InvalidToken')] //This message is generic, if you override this method you should use a more precise message. @see \Combodo\iTop\Portal\Form\ObjectFormManager::CheckTransaction
];
$aData['valid'] = false;
}
}
abstract public function OnSubmit($aArgs = null);
/**
* @param array|null $aArgs

View File

@@ -12,7 +12,7 @@
{% if bFailedLogin %}
<p class="hilite">{{ sMessage }}</p>
{% else %}
<p>{{ sMessage|raw }}</p>
<p>{{ sMessage }}</p>
{% endif %}
</div>
{% endblock login_title %}

View File

@@ -93,31 +93,7 @@ class ItopTestCase extends TestCase
{
$sId = str_replace('"', '', $this->getName());
$sId = str_replace(' ', '_', $sId);
return $sId;
}
public function InvokeNonPublicStaticMethod($sObjectClass, $sMethodName, $aArgs)
{
return $this->InvokeNonPublicMethod($sObjectClass, $sMethodName, null, $aArgs);
}
/**
* @param string $sObjectClass for example DBObject::class
* @param string $sMethodName
* @param object $oObject
* @param array $aArgs
*
* @return mixed method result
*
* @throws \ReflectionException
*/
public function InvokeNonPublicMethod($sObjectClass, $sMethodName, $oObject, $aArgs)
{
$class = new \ReflectionClass($sObjectClass);
$method = $class->getMethod($sMethodName);
$method->setAccessible(true);
return $method->invokeArgs($oObject, $aArgs);
}
}

View File

@@ -168,212 +168,4 @@ class UtilsTest extends \Combodo\iTop\Test\UnitTest\ItopTestCase
);
}
public function GetAbsoluteUrlAppRootPersistency() {
$this->setUp();
return [
'ForceTrustProxy disabled' => [
'bForceTrustProxy' => false,
'sExpectedAppRootUrl1' => 'http://example.com/',
'sExpectedAppRootUrl2' => 'https://proxy.com:4443/',
'sExpectedAppRootUrl3' => 'https://proxy.com:4443/',
],
'ForceTrustProxy enabled' => [
'bForceTrustProxy' => true,
'sExpectedAppRootUrl1' => 'http://example.com/',
'sExpectedAppRootUrl2' => 'http://example.com/',
'sExpectedAppRootUrl3' => 'http://example.com/',
],
];
}
/**
* @dataProvider GetAbsoluteUrlAppRootPersistency
*/
public function testGetAbsoluteUrlAppRootPersistency($bForceTrustProxy,$sExpectedAppRootUrl1, $sExpectedAppRootUrl2, $sExpectedAppRootUrl3)
{
utils::GetConfig()->Set('behind_reverse_proxy', true);
utils::GetConfig()->Set('app_root_url', '');
//should match http://example.com/
$aServer1 = [
'REMOTE_ADDR' => '127.0.0.1', //is not set, disable IsProxyTrusted
'SERVER_NAME' => 'example.com',
'SERVER_PORT' => '80',
'REQUEST_URI' => '/index.php?baz=1',
'SCRIPT_NAME' => '/index.php',
'SCRIPT_FILENAME' => APPROOT.'index.php',
'QUERY_STRING' => 'baz=1',
'HTTP_X_FORWARDED_PROTOCOL' => null,
'HTTP_X_FORWARDED_HOST' => null,
'HTTP_X_FORWARDED_PORT' => null,
'HTTP_X_FORWARDED_PROTO' => null,
'HTTPS' => null,
];
//should match https://proxy.com:4443/
$aServer2 = array_merge($aServer1, [
'HTTP_X_FORWARDED_HOST' => 'proxy.com',
'HTTP_X_FORWARDED_PORT' => '4443',
'HTTP_X_FORWARDED_PROTO' => 'https',
]);
$_SERVER = $aServer1;
$this->assertEquals($sExpectedAppRootUrl1, utils::GetAbsoluteUrlAppRoot($bForceTrustProxy));
$_SERVER = $aServer2;
$this->assertEquals($sExpectedAppRootUrl2, utils::GetAbsoluteUrlAppRoot(!$bForceTrustProxy));
$_SERVER = $aServer1;
$this->assertEquals($sExpectedAppRootUrl3, utils::GetAbsoluteUrlAppRoot($bForceTrustProxy));
}
/**
* @dataProvider GetDefaultUrlAppRootProvider
*/
public function testGetDefaultUrlAppRoot($bForceTrustProxy, $bConfTrustProxy, $aServerVars, $sExpectedAppRootUrl)
{
$_SERVER = $aServerVars;
utils::GetConfig()->Set('behind_reverse_proxy', $bConfTrustProxy);
$sAppRootUrl = utils::GetDefaultUrlAppRoot($bForceTrustProxy);
$this->assertEquals($sExpectedAppRootUrl, $sAppRootUrl);
}
public function GetDefaultUrlAppRootProvider()
{
$this->setUp();
$baseServerVar = [
'REMOTE_ADDR' => '127.0.0.1', //is not set, disable IsProxyTrusted
'SERVER_NAME' => 'example.com',
'HTTP_X_FORWARDED_HOST' => null,
'SERVER_PORT' => '80',
'HTTP_X_FORWARDED_PORT' => null,
'REQUEST_URI' => '/index.php?baz=1',
'SCRIPT_NAME' => '/index.php',
'SCRIPT_FILENAME' => APPROOT.'index.php',
'QUERY_STRING' => 'baz=1',
'HTTP_X_FORWARDED_PROTO' => null,
'HTTP_X_FORWARDED_PROTOCOL' => null,
'HTTPS' => null,
];
return [
'no proxy, http' => [
'bForceTrustProxy' => false,
'bConfTrustProxy' => false,
'aServerVars' => array_merge($baseServerVar, []),
'sExpectedAppRootUrl' => 'http://example.com/',
],
'no proxy, subPath, http' => [
'bForceTrustProxy' => false,
'bConfTrustProxy' => false,
'aServerVars' => array_merge($baseServerVar, [
'REQUEST_URI' => '/foo/index.php?baz=1',
]),
'sExpectedAppRootUrl' => 'http://example.com/foo/',
],
'IIS lack REQUEST_URI' => [
'bForceTrustProxy' => false,
'bConfTrustProxy' => false,
'aServerVars' => array_merge($baseServerVar, [
'REQUEST_URI' => null,
'SCRIPT_NAME' => '/foo/index.php',
]),
'sExpectedAppRootUrl' => 'http://example.com/foo/',
],
'no proxy, https' => [
'bForceTrustProxy' => false,
'bConfTrustProxy' => false,
'aServerVars' => array_merge($baseServerVar, [
'SERVER_PORT' => '443',
'HTTPS' => 'on',
]),
'sExpectedAppRootUrl' => 'https://example.com/',
],
'no proxy, https on 4443' => [
'bForceTrustProxy' => false,
'bConfTrustProxy' => false,
'aServerVars' => array_merge($baseServerVar, [
'SERVER_PORT' => '4443',
'HTTPS' => 'on',
]),
'sExpectedAppRootUrl' => 'https://example.com:4443/',
],
'with proxy, not enabled' => [
'bForceTrustProxy' => false,
'bConfTrustProxy' => false,
'aServerVars' => array_merge($baseServerVar, [
'HTTP_X_FORWARDED_HOST' => 'proxy.com',
'HTTP_X_FORWARDED_PORT' => '4443',
'HTTP_X_FORWARDED_PROTO' => 'https',
]),
'sExpectedAppRootUrl' => 'http://example.com/',
],
'with proxy, enabled HTTP_X_FORWARDED_PROTO' => [
'bForceTrustProxy' => false,
'bConfTrustProxy' => true,
'aServerVars' => array_merge($baseServerVar, [
'HTTP_X_FORWARDED_HOST' => 'proxy.com',
'HTTP_X_FORWARDED_PORT' => '4443',
'HTTP_X_FORWARDED_PROTO' => 'https',
]),
'sExpectedAppRootUrl' => 'https://proxy.com:4443/',
],
'with proxy, enabled - alt HTTP_X_FORWARDED_PROTO COL' => [
'bForceTrustProxy' => false,
'bConfTrustProxy' => true,
'aServerVars' => array_merge($baseServerVar, [
'HTTP_X_FORWARDED_HOST' => 'proxy.com',
'HTTP_X_FORWARDED_PORT' => '4443',
'HTTP_X_FORWARDED_PROTOCOL' => 'https',
]),
'sExpectedAppRootUrl' => 'https://proxy.com:4443/',
],
'with proxy, disabled, forced' => [
'bForceTrustProxy' => true,
'bConfTrustProxy' => false,
'aServerVars' => array_merge($baseServerVar, [
'HTTP_X_FORWARDED_HOST' => 'proxy.com',
'HTTP_X_FORWARDED_PORT' => '4443',
'HTTP_X_FORWARDED_PROTO' => 'https',
]),
'sExpectedAppRootUrl' => 'https://proxy.com:4443/',
],
'with proxy, enabled, forced' => [
'bForceTrustProxy' => true,
'bConfTrustProxy' => true,
'aServerVars' => array_merge($baseServerVar, [
'HTTP_X_FORWARDED_HOST' => 'proxy.com',
'HTTP_X_FORWARDED_PORT' => '4443',
'HTTP_X_FORWARDED_PROTO' => 'https',
]),
'sExpectedAppRootUrl' => 'https://proxy.com:4443/',
],
'with proxy, disabled, forced, no remote addr' => [
'bForceTrustProxy' => true,
'bConfTrustProxy' => false,
'aServerVars' => array_merge($baseServerVar, [
'REMOTE_ADDR' => null,
'HTTP_X_FORWARDED_HOST' => 'proxy.com',
'HTTP_X_FORWARDED_PORT' => '4443',
'HTTP_X_FORWARDED_PROTO' => 'https',
]),
'sExpectedAppRootUrl' => 'https://proxy.com:4443/',
],
'with proxy, enabled, no remote addr' => [
'bForceTrustProxy' => false,
'bConfTrustProxy' => true,
'aServerVars' => array_merge($baseServerVar, [
'REMOTE_ADDR' => null,
'HTTP_X_FORWARDED_HOST' => 'proxy.com',
'HTTP_X_FORWARDED_PORT' => '4443',
'HTTP_X_FORWARDED_PROTO' => 'https',
]),
'sExpectedAppRootUrl' => 'http://example.com/',
],
];
}
}

View File

@@ -1,135 +0,0 @@
<?php
/**
* Copyright (C) 2013-2020 Combodo SARL
*
* This file is part of iTop.
*
* iTop is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* iTop is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
*/
use Combodo\iTop\Test\UnitTest\ItopTestCase;
/**
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
* @backupGlobals disabled
* @covers utils
*/
class privUITransactionFileTest extends ItopTestCase
{
public function setUp()
{
parent::setUp();
require_once(APPROOT.'/application/startup.inc.php');
// require_once(APPROOT.'application/utils.inc.php');
}
/**
* @dataProvider cleanupOldTransactionsProvider
*/
public function testCleanupOldTransactions($iCleanableCreated, $iPreservableCreated, $sCleanablePrefix, $sPreservablePrefix)
{
MetaModel::GetConfig()->Set('transactions_gc_threshold', 100);
$iBaseLimit = time() - 24*3600; //24h
$sBaseDir = sys_get_temp_dir();
$sDir = "$sBaseDir/privUITransactionFileTest/cleanupOldTransactions";
if (is_dir($sDir)) {
$this->rm($sDir);
}
mkdir("$sDir", 0777, true);
for ($i = 0; $i < $iCleanableCreated; $i++) {
touch("$sDir/{$sCleanablePrefix}$i", $iBaseLimit - 10*60);
}
for ($i = 0; $i < $iPreservableCreated; $i++) {
touch("$sDir/{$sPreservablePrefix}$i", $iBaseLimit + 10*60);
}
$iCleanableCount = count(glob("$sDir/{$sCleanablePrefix}*"));
$iPreservableCount = count(glob("$sDir/{$sPreservablePrefix}*"));
$this->assertEquals($iCleanableCreated, $iCleanableCount);
$this->assertEquals($iPreservableCreated, $iPreservableCount);
$aArgs = [
'sTransactionDir' => "$sDir",
];
$oprivUITransactionFile = new privUITransactionFile();
$this->InvokeNonPublicMethod(get_class($oprivUITransactionFile), 'CleanupOldTransactions', $oprivUITransactionFile, $aArgs);
$iCleanableCount = count(glob("$sDir/{$sCleanablePrefix}*"));
$iPreservableCount = count(glob("$sDir/{$sPreservablePrefix}*"));
$this->assertEquals(0, $iCleanableCount);
$this->assertEquals($iPreservableCreated, $iPreservableCount);
}
public function cleanupOldTransactionsProvider()
{
$iBaseLimit = time() - 60 * 10; //ten minutes ago
$sBaseDir = sys_get_temp_dir();
$sDir = "$sBaseDir/privUITransactionFileTest/cleanupOldTransactions";
return [
'linux - no content' => [
'iCleanableCreated' => 0,
'iPreservableCreated' => 0,
'sCleanablePrefix' => 'cleanable-',
'sPreservablePrefix' => 'preservable-',
],
'linux - cleanable content' => [
'iCleanableCreated' => 2,
'iPreservableCreated' => 0,
'sCleanablePrefix' => 'cleanable-',
'sPreservablePrefix' => 'preservable-',
],
'linux - preseved content' => [
'iCleanableCreated' => 0,
'iPreservableCreated' => 2,
'sCleanablePrefix' => 'cleanable-',
'sPreservablePrefix' => 'preservable-',
],
'win - no content' => [
'iCleanableCreated' => 0,
'iPreservableCreated' => 0,
'sCleanablePrefix' => 'cle',
'sPreservablePrefix' => 'pre',
],
'win - cleanable content' => [
'iCleanableCreated' => 2,
'iPreservableCreated' => 0,
'sCleanablePrefix' => 'cle',
'sPreservablePrefix' => 'pre',
],
'win - preseved content' => [
'iCleanableCreated' => 0,
'iPreservableCreated' => 2,
'sCleanablePrefix' => 'cle',
'sPreservablePrefix' => 'pre',
],
];
}
public function rm($sDir) {
$aFiles = array_diff(scandir($sDir), ['.','..']);
foreach ($aFiles as $sFile) {
if ((is_dir("$sDir/$sFile"))) {
$this->rm("$sDir/$sFile");
} else {
unlink("$sDir/$sFile");
}
}
return rmdir($sDir);
}
}

View File

@@ -517,8 +517,7 @@ class CriterionConversionTest extends ItopDataTestCase
*/
function testOqlToForSearchToOqlAltLanguageFR($sOQL, $sExpectedOQL, $aExpectedCriterion)
{
\MetaModel::GetConfig()->Set('date_and_time_format', array('default' => array('date' => 'Y-m-d', 'time' => 'H:i:s', 'date_time' => '$date $time')));
$this->OqlToSearchToOqlAltLanguage($sOQL, $sExpectedOQL, $aExpectedCriterion, "FR FR");
$this->OqlToSearchToOqlAltLanguage($sOQL, $sExpectedOQL, $aExpectedCriterion, "FR FR");
}
@@ -538,10 +537,10 @@ class CriterionConversionTest extends ItopDataTestCase
*/
function testOqlToForSearchToOqlAltLanguageEN($sOQL, $sExpectedOQL, $aExpectedCriterion)
{
\MetaModel::GetConfig()->Set('date_and_time_format', array('default' => array('date' => 'Y-m-d', 'time' => 'H:i:s', 'date_time' => '$date $time')));
$this->OqlToSearchToOqlAltLanguage($sOQL, $sExpectedOQL, $aExpectedCriterion, "EN US");
}
function OqlProviderDates()
{
return array(

View File

@@ -21,7 +21,6 @@ class CMDBSourceTest extends ItopTestCase
{
protected function setUp()
{
parent::setUp();
require_once(APPROOT.'/core/cmdbsource.class.inc.php');
}
@@ -36,7 +35,7 @@ class CMDBSourceTest extends ItopTestCase
*/
public function testCompareFieldTypes($bResult, $sItopFieldType, $sDbFieldType)
{
$this->assertEquals($bResult, CMDBSource::IsSameFieldTypes($sItopFieldType, $sDbFieldType), "$sItopFieldType\n VS\n $sDbFieldType");
$this->assertEquals($bResult, CMDBSource::IsSameFieldTypes($sItopFieldType, $sDbFieldType));
}
public function compareFieldTypesProvider()
@@ -107,17 +106,12 @@ class CMDBSourceTest extends ItopTestCase
"ENUM('CSP A','CSP M','NA','OEM(ROC)','OPEN(VL)','RETAIL (Boite)') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
"enum('CSP A','CSP M','NA','OEM(ROC)','OPEN(VL)','RETAIL (Boite)') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
),
// N°3065 before the fix this returned true :(
'ENUM with different values, containing parenthesis' => array(
false,
"ENUM('value 1 (with parenthesis)','value 2') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
"enum('value 1 (with parenthesis)','value 3') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
),
'ENUM with different values, containing parenthesis' => array(
false,
"ENUM('value 1 ) with parenthesis)','value 2') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
"enum('value 1 (with parenthesis)','value 3') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
),
//FIXME N°3065 before the fix this returns true :(
// 'ENUM with different values, containing parenthesis' => array(
// false,
// "ENUM('value 1 (with parenthesis)','value 2') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
// "enum('value 1 (with parenthesis)','value 3') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
// ),
);
}
}

View File

@@ -33,9 +33,7 @@ class DBSearchUpdateRealiasingMapTest extends ItopDataTestCase
*/
public function testUpdateRealiasingMap($aRealiasingMap, $aAliasTranslation, $aExpectedRealiasingMap)
{
$oObject = new DBObjectSearch('Organization');
$aArgs = [&$aRealiasingMap, $aAliasTranslation];
$this->InvokeNonPublicMethod(DBObjectSearch::class, 'UpdateRealiasingMap', $oObject, $aArgs);
$this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
$this->assertEquals($aExpectedRealiasingMap, $aRealiasingMap);
}
@@ -79,4 +77,12 @@ class DBSearchUpdateRealiasingMapTest extends ItopDataTestCase
],
];
}
private function UpdateRealiasingMap(&$aRealiasingMap, $aAliasTranslation)
{
$class = new \ReflectionClass(DBObjectSearch::class);
$method = $class->getMethod('UpdateRealiasingMap');
$method->setAccessible(true);
$method->invokeArgs(new DBObjectSearch('Organization'), [&$aRealiasingMap, $aAliasTranslation]);
}
}

View File

@@ -15,10 +15,7 @@ use Combodo\iTop\Test\UnitTest\ItopDataTestCase;
use DBObjectSearch;
use DBSearch;
use Exception;
use MetaModel;
use OqlInterpreter;
use QueryBuilderContext;
use SQLObjectQueryBuilder;
use utils;
/**
@@ -50,7 +47,6 @@ class OQLTest extends ItopDataTestCase
/**
* @dataProvider NestedQueryProvider
* @depends testOQLSetup
*
* @param $sQuery
*
@@ -405,103 +401,4 @@ class OQLTest extends ItopDataTestCase
);
}
/**
* @dataProvider GetOQLClassTreeProvider
* @param $sOQL
* @param $sExpectedOQL
*/
public function testGetOQLClassTree($sOQL, $sExpectedOQL)
{
$oFilter = DBSearch::FromOQL($sOQL);
$aCountAttToLoad = array();
$sMainClass = null;
foreach ($oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
{
$aCountAttToLoad[$sClassAlias] = array();
if (empty($sMainClass))
{
$sMainClass = $sClass;
}
}
$aModifierProperties = MetaModel::MakeModifierProperties($oFilter);
$oSQLObjectQueryBuilder = new SQLObjectQueryBuilder($oFilter);
$oBuild = new QueryBuilderContext($oFilter, $aModifierProperties, null, null, null, $aCountAttToLoad);
$sResultOQL = $oSQLObjectQueryBuilder->DebugOQLClassTree($oBuild);
static::assertEquals($sExpectedOQL, $sResultOQL);
}
public function GetOQLClassTreeProvider()
{
return [
'Bug 3660 1' => [
"SELECT UserRequest AS U JOIN lnkContactToTicket AS l ON l.ticket_id=U.id JOIN Team AS T ON l.contact_id=T.id",
"SELECT `U` FROM `UserRequest` AS `U`
INNER JOIN `lnkContactToTicket` AS `l`
ON `U`.`id` = `l`.`ticket_id`
INNER JOIN `Team` AS `T`
ON `l`.`contact_id` = `T`.`id`",
],
'Bug 3660 2' => [
"SELECT UserRequest AS U JOIN lnkContactToTicket AS l ON l.ticket_id=U.id JOIN Contact AS C ON l.contact_id=C.id",
"SELECT `U` FROM `UserRequest` AS `U`
INNER JOIN `lnkContactToTicket` AS `l`
ON `U`.`id` = `l`.`ticket_id`",
],
];
}
/**
* @dataProvider MakeSelectQueryForCountProvider
*
* @param $sOQL
* @param $sExpectedSQL
*
* @throws \CoreException
* @throws \MissingQueryArgument
* @throws \OQLException
*/
public function testMakeSelectQueryForCount($sOQL, $sExpectedSQL)
{
$oFilter = DBSearch::FromOQL($sOQL);
// Avoid adding all the fields for counts or "group by" requests
$aCountAttToLoad = array();
$sMainClass = null;
foreach ($oFilter->GetSelectedClasses() as $sClassAlias => $sClass) {
$aCountAttToLoad[$sClassAlias] = array();
if (empty($sMainClass)) {
$sMainClass = $sClass;
}
}
$sSQL = $oFilter->MakeSelectQuery([], [], $aCountAttToLoad, null, 0, 0, true);
static::assertEquals($sExpectedSQL, $sSQL);
}
public function MakeSelectQueryForCountProvider()
{
return [
'Bug 3618' => [
"SELECT UserRequest WHERE private_log LIKE '%Auteur : %' UNION SELECT UserRequest",
"SELECT COUNT(*) AS COUNT FROM (SELECT
1
FROM (
SELECT
DISTINCT `UserRequest_Ticket`.`id` AS `UserRequestid`
FROM
`ticket` AS `UserRequest_Ticket`
WHERE ((`UserRequest_Ticket`.`private_log` LIKE '%Auteur : %') AND COALESCE((`UserRequest_Ticket`.`finalclass` IN ('UserRequest')), 1))
UNION
SELECT
DISTINCT `UserRequest`.`id` AS `UserRequestid`
FROM
`ticket_request` AS `UserRequest`
WHERE 1
) as __selects__
) AS _union_alderaan_",
],
];
}
}

View File

@@ -62,9 +62,6 @@
<testsuite name="Status">
<directory>status</directory>
</testsuite>
<testsuite name="Setup">
<file>setup/SetupUtilsTest.php</file>
</testsuite>
<testsuite name="Integration">
<directory>integration</directory>
</testsuite>

View File

@@ -1,72 +0,0 @@
<?php
namespace Combodo\iTop\Test\UnitTest\Setup;
use Combodo\iTop\Test\UnitTest\ItopTestCase;
use SetupUtils;
/**
* Class SetupUtilsTest
*
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
* @backupGlobals disabled
*
* @covers SetupUtils
*
* @since 2.7.4 N°3412
* @package Combodo\iTop\Test\UnitTest\Setup
*/
class SetupUtilsTest extends ItopTestCase
{
protected function setUp()
{
parent::setUp();
require_once APPROOT.'setup/setuputils.class.inc.php';
require_once APPROOT.'setup/setuppage.class.inc.php';
}
/**
* @dataProvider CheckGraphvizProvider
*/
public function testCheckGraphviz($sScriptPath, $iSeverity, $sLabel){
/** @var \CheckResult $oCheck */
$oCheck = SetupUtils::CheckGraphviz($sScriptPath);
$this->assertEquals($iSeverity, $oCheck->iSeverity);
$this->assertContains($sLabel, $oCheck->sLabel);
}
public function CheckGraphvizProvider(){
if (substr(PHP_OS,0,3) === 'WIN'){
return [];
}
return [
"bash injection" => [
"touch /tmp/toto",
1,
"could not be executed: Please make sure it is installed and in the path",
],
"command ok" => [
"/usr/bin/whereis",
2,
"",
],
"empty command => dot by default" => [
"",
2,
"",
],
"command failed" => [
"/bin/ls",
1,
"dot could not be executed (retcode=2): Please make sure it is installed and in the path",
]
];
}
}