/** * Get the HTML fragment corresponding to the linkset editing widget * @param WebPage $oP The web page used for all the output * @param Hash $aArgs Extra context arguments * @return string The HTML fragment to be inserted into the page */ public function Display(WebPage $oPage, $aArgs = array()) { $sCode = $this->sAttCode . $this->sNameSuffix; $iWidgetIndex = self::$iWidgetIndex; $aPasswordValues = utils::ReadPostedParam("attr_{$sCode}", null, 'raw_data'); $sPasswordValue = $aPasswordValues ? $aPasswordValues['value'] : '*****'; $sConfirmPasswordValue = $aPasswordValues ? $aPasswordValues['confirm'] : '*****'; $sChangedValue = $sPasswordValue != '*****' || $sConfirmPasswordValue != '*****' ? 1 : 0; $sHtmlValue = ''; $sHtmlValue = '<input type="password" maxlength="255" name="attr_' . $sCode . '[value]" id="' . $this->iId . '" value="' . htmlentities($sPasswordValue, ENT_QUOTES, 'UTF-8') . '"/> <span class="form_validation" id="v_' . $this->iId . '"></span><br/>'; $sHtmlValue .= '<input type="password" maxlength="255" id="' . $this->iId . '_confirm" value="' . htmlentities($sConfirmPasswordValue, ENT_QUOTES, 'UTF-8') . '" name="attr_' . $sCode . '[confirm]"/> ' . Dict::S('UI:PasswordConfirm') . ' <input id="' . $this->iId . '_reset" type="button" value="' . Dict::S('UI:Button:ResetPassword') . '" onClick="ResetPwd(\'' . $this->iId . '\');">'; $sHtmlValue .= '<input type="hidden" id="' . $this->iId . '_changed" name="attr_' . $sCode . '[changed]" value="' . $sChangedValue . '"/>'; $oPage->add_ready_script("\$('#{$this->iId}').bind('keyup change', function(evt) { return PasswordFieldChanged('{$this->iId}') } );"); // Bind to a custom event: validate $oPage->add_ready_script("\$('#{$this->iId}').bind('keyup change validate', function(evt, sFormId) { return ValidatePasswordField('{$this->iId}', sFormId) } );"); // Bind to a custom event: validate $oPage->add_ready_script("\$('#{$this->iId}_confirm').bind('keyup change', function(evt, sFormId) { return ValidatePasswordField('{$this->iId}', sFormId) } );"); // Bind to a custom event: validate $oPage->add_ready_script("\$('#{$this->iId}').bind('update', function(evt, sFormId)\n\t\t\t{\n\t\t\t\tif (\$(this).attr('disabled'))\n\t\t\t\t{\n\t\t\t\t\t\$('#{$this->iId}_confirm').attr('disabled', 'disabled');\n\t\t\t\t\t\$('#{$this->iId}_changed').attr('disabled', 'disabled');\n\t\t\t\t\t\$('#{$this->iId}_reset').attr('disabled', 'disabled');\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\$('#{$this->iId}_confirm').removeAttr('disabled');\n\t\t\t\t\t\$('#{$this->iId}_changed').removeAttr('disabled');\n\t\t\t\t\t\$('#{$this->iId}_reset').removeAttr('disabled');\n\t\t\t\t}\n\t\t\t}\n\t\t);"); // Bind to a custom event: update to handle enabling/disabling return $sHtmlValue; }
/** * Updates the object form POSTED arguments, and writes it into the DB (applies a stimuli if requested) * @param DBObject $oObj The object to update * $param array $aAttList If set, this will limit the list of updated attributes * @return void */ public function DoUpdateObjectFromPostedForm(DBObject $oObj, $aAttList = null) { $sTransactionId = utils::ReadPostedParam('transaction_id', ''); if (!utils::IsTransactionValid($sTransactionId)) { throw new TransactionException(); } $sClass = get_class($oObj); $sStimulus = trim(utils::ReadPostedParam('apply_stimulus', '')); $sTargetState = ''; if (!empty($sStimulus)) { // Compute the target state $aTransitions = $oObj->EnumTransitions(); if (!isset($aTransitions[$sStimulus])) { throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel())); } $sTargetState = $aTransitions[$sStimulus]['target_state']; } $oObj->UpdateObjectFromPostedForm('', $aAttList, $sTargetState); // Optional: apply a stimulus // if (!empty($sStimulus)) { if (!$oObj->ApplyStimulus($sStimulus)) { throw new Exception("Cannot apply stimulus '{$sStimulus}' to {$oObj->GetName()}"); } } if ($oObj->IsModified()) { // Record the change // $oObj->DBUpdate(); // Trigger ? // $aClasses = MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL); $sClassList = implode(", ", CMDBSource::Quote($aClasses)); $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnPortalUpdate AS t WHERE t.target_class IN ({$sClassList})")); while ($oTrigger = $oSet->Fetch()) { $oTrigger->DoActivate($oObj->ToArgs('this')); } $this->p("<h1>" . Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()) . "</h1>\n"); } $bLockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled'); if ($bLockEnabled) { // Release the concurrent lock, if any $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, false, 'raw_data'); if ($sOwnershipToken !== null) { // We're done, let's release the lock iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken); } } }
/** * Process the reply made from a form built with DisplayBulkModifyForm */ public static function DoBulkModify($oP, $sClass, $aSelectedObj, $sCustomOperation, $bPreview, $sCancelUrl, $aContextData = array()) { $aHeaders = array('form::select' => array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList:not(:disabled)', this.checked);\"></input>", 'description' => Dict::S('UI:SelectAllToggle+')), 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')), 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')), 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+'))); $aRows = array(); $oP->add("<div class=\"page_header\">\n"); $oP->add("<h1>" . MetaModel::GetClassIcon($sClass) . " " . Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), MetaModel::GetName($sClass)) . "</h1>\n"); $oP->add("</div>\n"); $oP->set_title(Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass)); if (!$bPreview) { // Not in preview mode, do the update for real $sTransactionId = utils::ReadPostedParam('transaction_id', ''); if (!utils::IsTransactionValid($sTransactionId, false)) { throw new Exception(Dict::S('UI:Error:ObjectAlreadyUpdated')); } utils::RemoveTransaction($sTransactionId); } $iPreviousTimeLimit = ini_get('max_execution_time'); $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop'); foreach ($aSelectedObj as $iId) { set_time_limit($iLoopTimeLimit); $oObj = MetaModel::GetObject($sClass, $iId); $aErrors = $oObj->UpdateObjectFromPostedForm(''); $bResult = count($aErrors) == 0; if ($bResult) { list($bResult, $aErrors) = $oObj->CheckToWrite(true); } if ($bPreview) { $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusOk') : Dict::S('UI:BulkModifyStatusError'); } else { $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped'); } $sCSSClass = $bResult ? HILIGHT_CLASS_NONE : HILIGHT_CLASS_CRITICAL; $sChecked = $bResult ? 'checked' : ''; $sDisabled = $bResult ? '' : 'disabled'; $aRows[] = array('form::select' => "<input type=\"checkbox\" class=\"selectList\" {$sChecked} {$sDisabled}\"></input>", 'object' => $oObj->GetHyperlink(), 'status' => $sStatus, 'errors' => '<p>' . ($bResult ? '' : implode('</p><p>', $aErrors)) . '</p>', '@class' => $sCSSClass); if ($bResult && !$bPreview) { $oObj->DBUpdate(); } } set_time_limit($iPreviousTimeLimit); $oP->Table($aHeaders, $aRows); if ($bPreview) { $sFormAction = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php'; // No parameter in the URL, the only parameter will be the ones passed through the form // Form to submit: $oP->add("<form method=\"post\" action=\"{$sFormAction}\" enctype=\"multipart/form-data\">\n"); $aDefaults = utils::ReadParam('default', array()); $oAppContext = new ApplicationContext(); $oP->add($oAppContext->GetForForm()); foreach ($aContextData as $sKey => $value) { $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"{$value}\">\n"); } $oP->add("<input type=\"hidden\" name=\"operation\" value=\"{$sCustomOperation}\">\n"); $oP->add("<input type=\"hidden\" name=\"class\" value=\"{$sClass}\">\n"); $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"0\">\n"); $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"" . utils::GetNewTransactionId() . "\">\n"); $oP->add("<button type=\"button\" class=\"action cancel\" onClick=\"window.location.href='{$sCancelUrl}'\">" . Dict::S('UI:Button:Cancel') . "</button> \n"); $oP->add("<button type=\"submit\" class=\"action\"><span>" . Dict::S('UI:Button:ModifyAll') . "</span></button>\n"); foreach ($_POST as $sKey => $value) { if (preg_match('/attr_(.+)/', $sKey, $aMatches)) { // Beware: some values (like durations) are passed as arrays if (is_array($value)) { foreach ($value as $vKey => $vValue) { $oP->add("<input type=\"hidden\" name=\"{$sKey}[{$vKey}]\" value=\"" . htmlentities($vValue, ENT_QUOTES, 'UTF-8') . "\">\n"); } } else { $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"" . htmlentities($value, ENT_QUOTES, 'UTF-8') . "\">\n"); } } } $oP->add("</form>\n"); } else { $oP->add("<button type=\"button\" onClick=\"window.location.href='{$sCancelUrl}'\" class=\"action\"><span>" . Dict::S('UI:Button:Done') . "</span></button>\n"); } }
protected static function HandleOperations($operation) { $sMessage = ''; // most of the operations never return, but some can return a message to be displayed if ($operation == 'logoff') { if (isset($_SESSION['login_mode'])) { $sLoginMode = $_SESSION['login_mode']; } else { $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes(); if (count($aAllowedLoginTypes) > 0) { $sLoginMode = $aAllowedLoginTypes[0]; } else { $sLoginMode = 'form'; } } self::ResetSession(); $oPage = self::NewLoginWebPage(); $oPage->DisplayLoginForm($sLoginMode, false); $oPage->output(); exit; } else { if ($operation == 'forgot_pwd') { $oPage = self::NewLoginWebPage(); $oPage->DisplayForgotPwdForm(); $oPage->output(); exit; } else { if ($operation == 'forgot_pwd_go') { $oPage = self::NewLoginWebPage(); $oPage->ForgotPwdGo(); $oPage->output(); exit; } else { if ($operation == 'reset_pwd') { $oPage = self::NewLoginWebPage(); $oPage->DisplayResetPwdForm(); $oPage->output(); exit; } else { if ($operation == 'do_reset_pwd') { $oPage = self::NewLoginWebPage(); $oPage->DoResetPassword(); $oPage->output(); exit; } else { if ($operation == 'change_pwd') { $sAuthUser = $_SESSION['auth_user']; UserRights::Login($sAuthUser); // Set the user's language $oPage = self::NewLoginWebPage(); $oPage->DisplayChangePwdForm(); $oPage->output(); exit; } } } } } } if ($operation == 'do_change_pwd') { $sAuthUser = $_SESSION['auth_user']; UserRights::Login($sAuthUser); // Set the user's language $sOldPwd = utils::ReadPostedParam('old_pwd', '', false, 'raw_data'); $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data'); if (UserRights::CanChangePassword() && (!UserRights::CheckCredentials($sAuthUser, $sOldPwd) || !UserRights::ChangePassword($sOldPwd, $sNewPwd))) { $oPage = self::NewLoginWebPage(); $oPage->DisplayChangePwdForm(true); // old pwd was wrong $oPage->output(); exit; } $sMessage = Dict::S('UI:Login:PasswordChanged'); } return $sMessage; }
break; case 'search_form': $oPage->SetContentType('text/html'); $sClass = utils::ReadParam('className', '', false, 'class'); $sRootClass = utils::ReadParam('baseClass', '', false, 'class'); $currentId = utils::ReadParam('currentId', ''); $sTableId = utils::ReadParam('_table_id_', null, false, 'raw_data'); $sAction = utils::ReadParam('action', ''); $oFilter = new DBObjectSearch($sClass); $oSet = new CMDBObjectSet($oFilter); $sHtml = cmdbAbstractObject::GetSearchForm($oPage, $oSet, array('currentId' => $currentId, 'baseClass' => $sRootClass, 'action' => $sAction, 'table_id' => $sTableId)); $oPage->add($sHtml); break; case 'set_pref': $sCode = utils::ReadPostedParam('code', ''); $sValue = utils::ReadPostedParam('value', '', 'raw_data'); appUserPreferences::SetPref($sCode, $sValue); break; case 'erase_all_pref': // Can be useful in case a user got some corrupted prefs... appUserPreferences::ClearPreferences(); break; case 'on_form_cancel': // Called when a creation/modification form is cancelled by the end-user // Let's take this opportunity to inform the plug-ins so that they can perform some cleanup $iTransactionId = utils::ReadParam('transaction_id', 0); $sTempId = session_id() . '_' . $iTransactionId; foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) { $oExtensionInstance->OnFormCancel($sTempId); } break;
public function UpdateObjectFromPostedForm($sFormPrefix = '', $sAttList = null, $sTargetState = '') { parent::UpdateObjectFromPostedForm($sFormPrefix, $sAttList, $sTargetState); // And now read the other post parameters... $oAttributeSet = $this->Get('attribute_list'); $aAttributes = array(); while ($oAttribute = $oAttributeSet->Fetch()) { $aAttributes[$oAttribute->Get('attcode')] = $oAttribute; } $aReconcile = utils::ReadPostedParam('reconciliation', array()); $aUpdate = utils::ReadPostedParam('update', array()); $aUpdatePolicy = utils::ReadPostedParam('attr_update_policy', array()); $aReconciliation = utils::ReadPostedParam('attr_reconciliation_attcode', array()); // update_policy cannot be empty, so there is one entry per attribute, use this to iterate // through all the writable attributes foreach ($aUpdatePolicy as $sAttCode => $sValue) { if (!isset($aAttributes[$sAttCode])) { $oAttribute = $this->CreateSynchroAtt($sAttCode); } else { $oAttribute = $aAttributes[$sAttCode]; } $bReconcile = 0; if (isset($aReconcile[$sAttCode])) { $bReconcile = $aReconcile[$sAttCode] == 'on' ? 1 : 0; } $bUpdate = 0; // Default / initial value if (isset($aUpdate[$sAttCode])) { $bUpdate = $aUpdate[$sAttCode] == 'on' ? 1 : 0; } $oAttribute->Set('reconcile', $bReconcile); $oAttribute->Set('update', $bUpdate); $oAttribute->Set('update_policy', $sValue); if ($oAttribute instanceof SynchroAttExtKey) { $oAttribute->Set('reconciliation_attcode', $aReconciliation[$sAttCode]); } elseif ($oAttribute instanceof SynchroAttLinkSet) { } $oAttributeSet->AddObject($oAttribute); } $this->Set('attribute_list', $oAttributeSet); }
/** * Makes the string representation out of the values given by the form defined in GetDisplayForm */ public function ReadValueFromPostedForm($sFormPrefix) { $sHtmlNamesPrefix = 'rddcy_' . $this->Get('relation_code') . '_' . $this->Get('from_class') . '_' . $this->Get('neighbour_id'); $iMinUpCount = (int) utils::ReadPostedParam($sHtmlNamesPrefix . '_min_up_count', null, 'raw_data'); $iMinUpPercent = (int) utils::ReadPostedParam($sHtmlNamesPrefix . '_min_up_percent', null, 'raw_data'); $sSelectedOption = utils::ReadPostedParam($sHtmlNamesPrefix . '_user_option', null, 'raw_data'); switch ($sSelectedOption) { case self::USER_OPTION_ENABLED_COUNT: $sRet = $iMinUpCount; break; case self::USER_OPTION_ENABLED_PERCENT: $sRet = $iMinUpPercent . '%'; break; case self::USER_OPTION_DISABLED: default: $sRet = 'disabled'; break; } return $sRet; }
/** * Validate the parameters and create the ticket object (based on the page's POSTed parameters) * @param WebPage $oP The current web page for the output * @param Organization $oUserOrg The organization of the current user * @return void */ function DoCreateRequest($oP, $oUserOrg) { $aParameters = $oP->ReadAllParams(PORTAL_ALL_PARAMS . ',template_id'); $sTransactionId = utils::ReadPostedParam('transaction_id', ''); if (!utils::IsTransactionValid($sTransactionId)) { $oP->add("<h1>" . Dict::S('UI:Error:ObjectAlreadyCreated') . "</h1>\n"); //ShowOngoingTickets($oP); return; } // Validate the parameters // 1) ServiceCategory $oSearch = DBObjectSearch::FromOQL(PORTAL_VALIDATE_SERVICECATEGORY_QUERY); $oSearch->AllowAllData(); // In case the user has the rights on his org only $oSet = new CMDBObjectSet($oSearch, array(), array('id' => $aParameters['service_id'], 'org_id' => $oUserOrg->GetKey())); if ($oSet->Count() != 1) { // Invalid service for the current user ! throw new Exception("Invalid Service Category: id={$aParameters['service_id']} - count: " . $oSet->Count()); } $oServiceCategory = $oSet->Fetch(); // 2) Service Subcategory $oSearch = DBObjectSearch::FromOQL(PORTAL_VALIDATE_SERVICESUBCATEGORY_QUERY); RestrictSubcategories($oSearch); $oSearch->AllowAllData(); // In case the user has the rights on his org only $oSet = new CMDBObjectSet($oSearch, array(), array('service_id' => $aParameters['service_id'], 'id' => $aParameters['servicesubcategory_id'], 'org_id' => $oUserOrg->GetKey())); if ($oSet->Count() != 1) { // Invalid subcategory throw new Exception("Invalid ServiceSubcategory: id={$aParameters['servicesubcategory_id']} for service category " . $oServiceCategory->GetName() . "({$aParameters['service_id']}) - count: " . $oSet->Count()); } $oServiceSubCategory = $oSet->Fetch(); $sClass = ComputeClass($oServiceSubCategory->GetKey()); $oRequest = MetaModel::NewObject($sClass); $aAttList = array_merge(explode(',', GetConstant($sClass, 'FORM_ATTRIBUTES')), array('service_id', 'servicesubcategory_id')); $oRequest->UpdateObjectFromPostedForm('', $aAttList); $oRequest->Set('org_id', $oUserOrg->GetKey()); $oRequest->Set('caller_id', UserRights::GetContactId()); if (isset($aParameters['moreinfo'])) { // There is a template, insert it into the description $sLogAttCode = GetConstant($sClass, 'PUBLIC_LOG'); $oRequest->Set($sLogAttCode, $aParameters['moreinfo']); } $sTypeAttCode = GetConstant($sClass, 'TYPE'); if ($sTypeAttCode != '' && PORTAL_SET_TYPE_FROM != '') { $oRequest->Set($sTypeAttCode, $oServiceSubCategory->Get(PORTAL_SET_TYPE_FROM)); } if (MetaModel::IsValidAttCode($sClass, 'origin')) { $oRequest->Set('origin', 'portal'); } $oAttPlugin = new AttachmentPlugIn(); $oAttPlugin->OnFormSubmit($oRequest); list($bRes, $aIssues) = $oRequest->CheckToWrite(); if ($bRes) { if (isset($aParameters['template_id'])) { $oTemplate = MetaModel::GetObject('Template', $aParameters['template_id']); $sLogAttCode = GetConstant($sClass, 'PUBLIC_LOG'); $oRequest->Set($sLogAttCode, $oTemplate->GetPostedValuesAsText($oRequest) . "\n"); $oRequest->DBInsertNoReload(); $oTemplate->RecordExtraDataFromPostedForm($oRequest); } else { $oRequest->DBInsertNoReload(); } $oP->add("<h1>" . Dict::Format('UI:Title:Object_Of_Class_Created', $oRequest->GetName(), MetaModel::GetName($sClass)) . "</h1>\n"); //DisplayObject($oP, $oRequest, $oUserOrg); ShowOngoingTickets($oP); } else { RequestCreationForm($oP, $oUserOrg); $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues)); $oP->add_ready_script("alert('" . addslashes($sIssueDesc) . "');"); } }
$oP->p("Access restricted or wrong credentials ('{$sAuthUser}')"); $oP->output(); exit - 1; } if (!is_readable($sCsvFile)) { $oP->p("Input file could not be found or could not be read: '{$sCsvFile}'"); $oP->output(); exit - 1; } $sCSVData = file_get_contents($sCsvFile); } else { $_SESSION['login_mode'] = 'basic'; require_once APPROOT . '/application/loginwebpage.class.inc.php'; LoginWebPage::DoLogin(); // Check user rights and prompt if needed $sCSVData = utils::ReadPostedParam('csvdata', '', false, 'raw_data'); } try { ////////////////////////////////////////////////// // // Read parameters // $iDataSourceId = ReadMandatoryParam($oP, 'data_source_id', 'raw_data'); $sSynchronize = ReadParam($oP, 'synchronize'); $sSep = ReadParam($oP, 'separator', 'raw_data'); $sQualifier = ReadParam($oP, 'qualifier', 'raw_data'); $sCharSet = ReadParam($oP, 'charset', 'raw_data'); $sDateFormat = ReadParam($oP, 'date_format', 'raw_data'); $sOutput = ReadParam($oP, 'output'); // $sReportLevel = ReadParam($oP, 'reportlevel'); $sSimulate = ReadParam($oP, 'simulate');
/** * Select the options of the CSV load and check for CSV parsing errors * @param WebPage $oPage The current web page * @return void */ function SelectOptions(WebPage $oPage) { $sOperation = utils::ReadParam('operation', 'csv_data'); $sCSVData = ''; switch ($sOperation) { case 'file_upload': $oDocument = utils::ReadPostedDocument('csvdata'); if (!$oDocument->IsEmpty()) { $sCSVData = $oDocument->GetData(); } break; default: $sCSVData = utils::ReadPostedParam('csvdata', '', 'raw_data'); } $sEncoding = utils::ReadParam('encoding', 'UTF-8'); // Compute a subset of the data set, now that we know the charset if ($sEncoding == 'UTF-8') { // Remove the BOM if any if (substr($sCSVData, 0, 3) == UTF8_BOM) { $sCSVData = substr($sCSVData, 3); } // Clean the input // Todo: warn the user if some characters are lost/substituted $sUTF8Data = iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData); } else { $sUTF8Data = iconv($sEncoding, 'UTF-8//IGNORE//TRANSLIT', $sCSVData); } $aGuesses = GuessParameters($sUTF8Data); // Try to predict the parameters, based on the input data $sSeparator = utils::ReadParam('separator', '', false, 'raw_data'); if ($sSeparator == '') { $sSeparator = $aGuesses['separator']; } $iSkippedLines = utils::ReadParam('nb_skipped_lines', ''); $bBoxSkipLines = utils::ReadParam('box_skiplines', 0); if ($sSeparator == 'tab') { $sSeparator = "\t"; } $sOtherSeparator = in_array($sSeparator, array(',', ';', "\t")) ? '' : $sSeparator; $sTextQualifier = utils::ReadParam('text_qualifier', '', false, 'raw_data'); if ($sTextQualifier == '') { $sTextQualifier = $aGuesses['qualifier']; } $sOtherTextQualifier = in_array($sTextQualifier, array('"', "'")) ? '' : $sTextQualifier; $bHeaderLine = utils::ReadParam('header_line', 0); $sClassName = utils::ReadParam('class_name', '', false, 'class'); $bAdvanced = utils::ReadParam('advanced', 0); $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data'); $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name'); // Create a truncated version of the data used for the fast preview // Take about 20 lines of data... knowing that some lines may contain carriage returns $iMaxLen = strlen($sUTF8Data); if ($iMaxLen > 0) { $iMaxLines = 20; $iCurPos = true; while ($iCurPos > 0 && $iMaxLines > 0) { $pos = strpos($sUTF8Data, "\n", $iCurPos); if ($pos !== false) { $iCurPos = 1 + $pos; } else { $iCurPos = strlen($sUTF8Data); $iMaxLines = 1; } $iMaxLines--; } $sCSVDataTruncated = substr($sUTF8Data, 0, $iCurPos); } else { $sCSVDataTruncated = ''; } $sSynchroScope = utils::ReadParam('synchro_scope', '', false, 'raw_data'); if (!empty($sSynchroScope)) { $oSearch = DBObjectSearch::FromOQL($sSynchroScope); $sClassName = $oSearch->GetClass(); $oSet = new DBObjectSet($oSearch); $iCount = $oSet->Count(); DisplaySynchroBanner($oPage, $sClassName, $iCount); $aSynchroUpdate = utils::ReadParam('synchro_update', array()); } $oPage->add('<h2>' . Dict::S('UI:Title:CSVImportStep2') . '</h2>'); $oPage->add('<div class="wizContainer">'); $oPage->add('<table><tr><td style="vertical-align:top;padding-right:50px;">'); $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" id="csv_options">'); $oPage->add('<h3>' . Dict::S('UI:CSVImport:SeparatorCharacter') . '</h3>'); $oPage->add('<p><input type="radio" name="separator" value="," onClick="DoPreview()"' . IsChecked($sSeparator, ',') . '/> ' . Dict::S('UI:CSVImport:SeparatorComma+') . '<br/>'); $oPage->add('<input type="radio" name="separator" value=";" onClick="DoPreview()"' . IsChecked($sSeparator, ';') . '/> ' . Dict::S('UI:CSVImport:SeparatorSemicolon+') . '<br/>'); $oPage->add('<input type="radio" name="separator" value="tab" onClick="DoPreview()"' . IsChecked($sSeparator, "\t") . '/> ' . Dict::S('UI:CSVImport:SeparatorTab+') . '<br/>'); $oPage->add('<input type="radio" name="separator" value="other" onClick="DoPreview()"' . IsChecked($sOtherSeparator, '', true) . '/> ' . Dict::S('UI:CSVImport:SeparatorOther') . ' <input type="text" size="3" maxlength="1" name="other_separator" id="other_separator" value="' . $sOtherSeparator . '" onClick="DoPreview()"/>'); $oPage->add('</p>'); $oPage->add('</td><td style="vertical-align:top;padding-right:50px;">'); $oPage->add('<h3>' . Dict::S('UI:CSVImport:TextQualifierCharacter') . '</h3>'); $oPage->add('<p><input type="radio" name="text_qualifier" value=""" onClick="DoPreview()"' . IsChecked($sTextQualifier, '"') . '/> ' . Dict::S('UI:CSVImport:QualifierDoubleQuote+') . '<br/>'); $oPage->add('<input type="radio" name="text_qualifier" value="'" onClick="DoPreview()"' . IsChecked($sTextQualifier, "'") . '/> ' . Dict::S('UI:CSVImport:QualifierSimpleQuote+') . '<br/>'); $oPage->add('<input type="radio" name="text_qualifier" value="other" onClick="DoPreview()"' . IsChecked($sOtherTextQualifier, '', true) . '/> ' . Dict::S('UI:CSVImport:QualifierOther') . ' <input type="text" size="3" maxlength="1" name="other_qualifier" value="' . htmlentities($sOtherTextQualifier, ENT_QUOTES, 'UTF-8') . '" onChange="DoPreview()"/>'); $oPage->add('</p>'); $oPage->add('</td><td style="vertical-align:top;">'); $oPage->add('<h3>' . Dict::S('UI:CSVImport:CommentsAndHeader') . '</h3>'); $oPage->add('<p><input type="checkbox" name="header_line" id="box_header" value="1" onClick="DoPreview()"' . IsChecked($bHeaderLine, 1) . '/> ' . Dict::S('UI:CSVImport:TreatFirstLineAsHeader') . '<p>'); $oPage->add('<p><input type="checkbox" name="box_skiplines" value="1" id="box_skiplines" onClick="DoPreview()"' . IsChecked($bBoxSkipLines, 1) . '/> ' . Dict::Format('UI:CSVImport:Skip_N_LinesAtTheBeginning', '<input type="text" size=2 name="nb_skipped_lines" id="nb_skipped_lines" onChange="DoPreview()" value="' . $iSkippedLines . '">') . '<p>'); $oPage->add('</td></tr></table>'); $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="' . htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8') . '"/>'); $oPage->add('<input type="hidden" name="csvdata" id="csvdata" value="' . htmlentities($sUTF8Data, ENT_QUOTES, 'UTF-8') . '"/>'); // The encoding has changed, keep that information within the wizard $oPage->add('<input type="hidden" name="encoding" value="UTF-8">'); $oPage->add('<input type="hidden" name="class_name" value="' . $sClassName . '"/>'); $oPage->add('<input type="hidden" name="advanced" value="' . $bAdvanced . '"/>'); $oPage->add('<input type="hidden" name="synchro_scope" value="' . $sSynchroScope . '"/>'); foreach ($aFieldsMapping as $iNumber => $sAttCode) { $oPage->add('<input type="hidden" name="field[' . $iNumber . ']" value="' . $sAttCode . '"/>'); } foreach ($aSearchFields as $index => $sDummy) { $oPage->add('<input type="hidden" name="search_field[' . $index . ']" value="1"/>'); } $oPage->add('<input type="hidden" name="step" value="3"/>'); if (!empty($sSynchroScope)) { foreach ($aSynchroUpdate as $sKey => $value) { $oPage->add('<input type="hidden" name="synchro_update[' . $sKey . ']" value="' . $value . '"/>'); } } $oPage->add('<div id="preview">'); $oPage->add('<p style="text-align:center">' . Dict::S('UI:CSVImport:CSVDataPreview') . '</p>'); $oPage->add('</div>'); $oPage->add('<input type="button" value="' . Dict::S('UI:Button:Back') . '" onClick="GoBack()"/>'); $oPage->add('<input type="submit" value="' . Dict::S('UI:Button:Next') . '"/>'); $oPage->add('</form>'); $oPage->add('</div>'); $oPage->add_script(<<<EOF \tfunction GoBack() \t{ \t\t\$('input[name=step]').val(1); \t\t\$('#wizForm').submit(); \t\t \t} \t \tvar ajax_request = null; \t \tfunction DoPreview() \t{ \t\tvar separator = \$('input[name=separator]:checked').val(); \t\tif (separator == 'other') \t\t{ \t\t\tseparator = \$('#other_separator').val(); \t\t} \t\tvar text_qualifier = \$('input[name=text_qualifier]:checked').val(); \t\tif (text_qualifier == 'other') \t\t{ \t\t\ttext_qualifier = \$('#other_qualifier').val(); \t\t} \t\tvar do_skip_lines = 0; \t\tif (\$('#box_skiplines:checked').val() != null) \t\t{ \t\t\tdo_skip_lines = \$('#nb_skipped_lines').val(); \t\t} \t\tvar header_line = 0; \t\tif (\$('#box_header:checked').val() != null) \t\t{ \t\t\theader_line = 1; \t\t} \t\tvar encoding = \$('input[name=encoding]').val(); \t\t\$('#preview').block(); \t\t \t\t// Make sure that we cancel any pending request before issuing another \t\t// since responses may arrive in arbitrary order \t\tif (ajax_request != null) \t\t{ \t\t\tajax_request.abort(); \t\t\tajax_request = null; \t\t} \t\t \t\tajax_request = \$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php', \t\t\t { operation: 'parser_preview', enctype: 'multipart/form-data', csvdata: \$("#csvdata_truncated").val(), separator: separator, qualifier: text_qualifier, do_skip_lines: do_skip_lines, header_line: header_line, encoding: encoding }, \t\t\t function(data) { \t\t\t\t \$('#preview').empty(); \t\t\t\t \$('#preview').append(data); \t\t\t\t \$('#preview').unblock(); \t\t\t\t} \t\t\t ); \t} EOF ); $oPage->add_ready_script('DoPreview();'); }
$sMessage = Dict::S('UI:Error:ObjectAlreadyUpdated'); $sSeverity = 'info'; } else { $sActionLabel = $aStimuli[$sStimulus]->GetLabel(); $sActionDetails = $aStimuli[$sStimulus]->GetDescription(); $aTransition = $aTransitions[$sStimulus]; $sTargetState = $aTransition['target_state']; $aTargetStates = MetaModel::EnumStates($sClass); $aTargetState = $aTargetStates[$sTargetState]; $aExpectedAttributes = $aTargetState['attribute_list']; $aDetails = array(); $aErrors = array(); foreach ($aExpectedAttributes as $sAttCode => $iExpectCode) { $iFlags = $oObj->GetAttributeFlags($sAttCode); if ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT) || $oObj->Get($sAttCode) == '') { $paramValue = utils::ReadPostedParam("attr_{$sAttCode}", '', 'raw_data'); if ($iFlags & OPT_ATT_SLAVE && $paramValue != $oObj->Get($sAttCode)) { $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel()); unset($aExpectedAttributes[$sAttCode]); } } } $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $sTargetState); if (count($aErrors) == 0) { $sIssues = ''; $bApplyStimulus = true; list($bRes, $aIssues) = $oObj->CheckToWrite(); // Check before trying to write the object if ($bRes) { try {
} else { if ($sIssues != '') { $bDisplayDetails = false; // Found issues, explain and give the user a second chance // $oObj->DisplayStimulusForm($oP, $sStimulus); $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', $sIssues); $oP->add_ready_script("alert('" . addslashes($sIssueDesc) . "');"); } else { $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()); $sSeverity = 'ok'; utils::RemoveTransaction($sTransactionId); $bLockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled'); if ($bLockEnabled) { // Release the concurrent lock, if any $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, false, 'raw_data'); if ($sOwnershipToken !== null) { // We're done, let's release the lock iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken); } } } } } else { $sMessage = implode('</p><p>', $aErrors); $sSeverity = 'error'; } } if ($bDisplayDetails) { ReloadAndDisplay($oP, $oObj, 'apply_stimulus', $sMessage, $sSeverity); }
/** * Check if the user is already authentified, if yes, then performs some additional validations: * - if $bMustBeAdmin is true, then the user must be an administrator, otherwise an error is displayed * - if $bIsAllowedToPortalUsers is false and the user has only access to the portal, then the user is redirected to the portal * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...) */ static function DoLogin($bMustBeAdmin = false, $bIsAllowedToPortalUsers = false, $iOnExit = self::EXIT_PROMPT) { $sMessage = ''; // In case we need to return a message to the calling web page $operation = utils::ReadParam('loginop', ''); if ($operation == 'logoff') { if (isset($_SESSION['login_mode'])) { $sLoginMode = $_SESSION['login_mode']; } else { $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes(); if (count($aAllowedLoginTypes) > 0) { $sLoginMode = $aAllowedLoginTypes[0]; } else { $sLoginMode = 'form'; } } self::ResetSession(); $oPage = self::NewLoginWebPage(); $oPage->DisplayLoginForm($sLoginMode, false); $oPage->output(); exit; } else { if ($operation == 'forgot_pwd') { $oPage = self::NewLoginWebPage(); $oPage->DisplayForgotPwdForm(); $oPage->output(); exit; } else { if ($operation == 'forgot_pwd_go') { $oPage = self::NewLoginWebPage(); $oPage->ForgotPwdGo(); $oPage->output(); exit; } else { if ($operation == 'reset_pwd') { $oPage = self::NewLoginWebPage(); $oPage->DisplayResetPwdForm(); $oPage->output(); exit; } else { if ($operation == 'do_reset_pwd') { $oPage = self::NewLoginWebPage(); $oPage->DoResetPassword(); $oPage->output(); exit; } else { if ($operation == 'change_pwd') { $sAuthUser = $_SESSION['auth_user']; UserRights::Login($sAuthUser); // Set the user's language $oPage = self::NewLoginWebPage(); $oPage->DisplayChangePwdForm(); $oPage->output(); exit; } } } } } } if ($operation == 'do_change_pwd') { $sAuthUser = $_SESSION['auth_user']; UserRights::Login($sAuthUser); // Set the user's language $sOldPwd = utils::ReadPostedParam('old_pwd', '', false, 'raw_data'); $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data'); if (UserRights::CanChangePassword() && (!UserRights::CheckCredentials($sAuthUser, $sOldPwd) || !UserRights::ChangePassword($sOldPwd, $sNewPwd))) { $oPage = self::NewLoginWebPage(); $oPage->DisplayChangePwdForm(true); // old pwd was wrong $oPage->output(); exit; } $sMessage = Dict::S('UI:Login:PasswordChanged'); } $iRet = self::Login($iOnExit); if ($iRet == self::EXIT_CODE_OK) { if ($bMustBeAdmin && !UserRights::IsAdministrator()) { if ($iOnExit == self::EXIT_RETURN) { return self::EXIT_CODE_MUSTBEADMIN; } else { require_once APPROOT . '/setup/setuppage.class.inc.php'; $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError')); $oP->add("<h1>" . Dict::S('UI:Login:Error:AccessAdmin') . "</h1>\n"); $oP->p("<a href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/logoff.php\">" . Dict::S('UI:LogOffMenu') . "</a>"); $oP->output(); exit; } } $iRet = call_user_func(array(self::$sHandlerClass, 'ChangeLocation'), $bIsAllowedToPortalUsers, $iOnExit); } if ($iOnExit == self::EXIT_RETURN) { return $iRet; } else { return $sMessage; } }